1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71 const X86Subtarget &STI)
72 : TargetLowering(TM), Subtarget(&STI) {
73 X86ScalarSSEf64 = Subtarget->hasSSE2();
74 X86ScalarSSEf32 = Subtarget->hasSSE1();
75 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77 // Set up the TargetLowering object.
78 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
80 // X86 is weird. It always uses i8 for shift amounts and setcc results.
81 setBooleanContents(ZeroOrOneBooleanContent);
82 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85 // For 64-bit, since we have so many registers, use the ILP scheduler.
86 // For 32-bit, use the register pressure specific scheduling.
87 // For Atom, always use ILP scheduling.
88 if (Subtarget->isAtom())
89 setSchedulingPreference(Sched::ILP);
90 else if (Subtarget->is64Bit())
91 setSchedulingPreference(Sched::ILP);
93 setSchedulingPreference(Sched::RegPressure);
94 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97 // Bypass expensive divides on Atom when compiling with O2.
98 if (TM.getOptLevel() >= CodeGenOpt::Default) {
99 if (Subtarget->hasSlowDivide32())
100 addBypassSlowDiv(32, 8);
101 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102 addBypassSlowDiv(64, 16);
105 if (Subtarget->isTargetKnownWindowsMSVC()) {
106 // Setup Windows compiler runtime calls.
107 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109 setLibcallName(RTLIB::SREM_I64, "_allrem");
110 setLibcallName(RTLIB::UREM_I64, "_aullrem");
111 setLibcallName(RTLIB::MUL_I64, "_allmul");
112 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
119 if (Subtarget->isTargetDarwin()) {
120 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121 setUseUnderscoreSetJmp(false);
122 setUseUnderscoreLongJmp(false);
123 } else if (Subtarget->isTargetWindowsGNU()) {
124 // MS runtime is weird: it exports _setjmp, but longjmp!
125 setUseUnderscoreSetJmp(true);
126 setUseUnderscoreLongJmp(false);
128 setUseUnderscoreSetJmp(true);
129 setUseUnderscoreLongJmp(true);
132 // Set up the register classes.
133 addRegisterClass(MVT::i8, &X86::GR8RegClass);
134 addRegisterClass(MVT::i16, &X86::GR16RegClass);
135 addRegisterClass(MVT::i32, &X86::GR32RegClass);
136 if (Subtarget->is64Bit())
137 addRegisterClass(MVT::i64, &X86::GR64RegClass);
139 for (MVT VT : MVT::integer_valuetypes())
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 // We don't accept any truncstore of integer registers.
143 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
150 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 // SETOEQ and SETUNE require checking two conditions.
153 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
163 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
166 if (Subtarget->is64Bit()) {
167 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
168 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
169 } else if (!Subtarget->useSoftFloat()) {
170 // We have an algorithm for SSE2->double, and we turn this into a
171 // 64-bit FILD followed by conditional FADD for other targets.
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 // We have an algorithm for SSE2, and we turn this into a 64-bit
174 // FILD for other targets.
175 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
178 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
180 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
183 if (!Subtarget->useSoftFloat()) {
184 // SSE has no i16 to fp conversion, only i32
185 if (X86ScalarSSEf32) {
186 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
187 // f32 and f64 cases are Legal, f80 case is not
188 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
191 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
198 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
199 // are Legal, f80 is custom lowered.
200 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
203 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
205 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
206 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
208 if (X86ScalarSSEf32) {
209 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
210 // f32 and f64 cases are Legal, f80 case is not
211 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
213 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
214 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
217 // Handle FP_TO_UINT by promoting the destination to a larger signed
219 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
220 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
221 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
223 if (Subtarget->is64Bit()) {
224 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
227 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
229 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
230 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
232 } else if (!Subtarget->useSoftFloat()) {
233 // Since AVX is a superset of SSE3, only check for SSE here.
234 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235 // Expand FP_TO_UINT into a select.
236 // FIXME: We would like to use a Custom expander here eventually to do
237 // the optimal thing for SSE vs. the default expansion in the legalizer.
238 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
240 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
241 // With SSE3 we can use fisttpll to convert to a signed i64; without
242 // SSE, we're stuck with a fistpll.
243 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
245 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
248 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249 if (!X86ScalarSSEf64) {
250 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
251 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
252 if (Subtarget->is64Bit()) {
253 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
254 // Without SSE, i64->f64 goes through memory.
255 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
259 // Scalar integer divide and remainder are lowered to use operations that
260 // produce two results, to match the available instructions. This exposes
261 // the two-result form to trivial CSE, which is able to combine x/y and x%y
262 // into a single instruction.
264 // Scalar integer multiply-high is also lowered to use two-result
265 // operations, to match the available instructions. However, plain multiply
266 // (low) operations are left as Legal, as there are single-result
267 // instructions for this in x86. Using the two-result multiply instructions
268 // when both high and low results are needed must be arranged by dagcombine.
269 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
271 setOperationAction(ISD::MULHS, VT, Expand);
272 setOperationAction(ISD::MULHU, VT, Expand);
273 setOperationAction(ISD::SDIV, VT, Expand);
274 setOperationAction(ISD::UDIV, VT, Expand);
275 setOperationAction(ISD::SREM, VT, Expand);
276 setOperationAction(ISD::UREM, VT, Expand);
278 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279 setOperationAction(ISD::ADDC, VT, Custom);
280 setOperationAction(ISD::ADDE, VT, Custom);
281 setOperationAction(ISD::SUBC, VT, Custom);
282 setOperationAction(ISD::SUBE, VT, Custom);
285 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
286 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
287 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
288 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
289 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
290 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
291 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
292 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
293 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
294 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
295 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
296 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
297 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
301 if (Subtarget->is64Bit())
302 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
304 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
305 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
306 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
307 setOperationAction(ISD::FREM , MVT::f32 , Expand);
308 setOperationAction(ISD::FREM , MVT::f64 , Expand);
309 setOperationAction(ISD::FREM , MVT::f80 , Expand);
310 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
312 // Promote the i8 variants and force them on up to i32 which has a shorter
314 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
315 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
316 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
317 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
318 if (Subtarget->hasBMI()) {
319 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
320 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
321 if (Subtarget->is64Bit())
322 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
324 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
325 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
326 if (Subtarget->is64Bit())
327 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
330 if (Subtarget->hasLZCNT()) {
331 // When promoting the i8 variants, force them to i32 for a shorter
333 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
334 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
335 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
336 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
337 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
338 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
339 if (Subtarget->is64Bit())
340 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
342 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
343 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
344 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
346 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
347 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
348 if (Subtarget->is64Bit()) {
349 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
350 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
354 // Special handling for half-precision floating point conversions.
355 // If we don't have F16C support, then lower half float conversions
356 // into library calls.
357 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
358 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
359 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
362 // There's never any support for operations beyond MVT::f32.
363 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
364 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
365 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
366 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
368 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
369 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
370 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
371 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
372 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
375 if (Subtarget->hasPOPCNT()) {
376 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
378 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
379 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
380 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
381 if (Subtarget->is64Bit())
382 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
385 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
387 if (!Subtarget->hasMOVBE())
388 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
390 // These should be promoted to a larger select which is supported.
391 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
392 // X86 wants to expand cmov itself.
393 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
394 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
395 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
396 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
397 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
398 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
399 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
400 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
401 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
402 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
403 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
404 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
405 if (Subtarget->is64Bit()) {
406 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
407 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
409 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
410 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
411 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
412 // support continuation, user-level threading, and etc.. As a result, no
413 // other SjLj exception interfaces are implemented and please don't build
414 // your own exception handling based on them.
415 // LLVM/Clang supports zero-cost DWARF exception handling.
416 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
417 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
420 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
421 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
422 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
423 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
424 if (Subtarget->is64Bit())
425 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
426 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
427 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
428 if (Subtarget->is64Bit()) {
429 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
430 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
431 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
432 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
433 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
435 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
436 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
437 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
438 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
439 if (Subtarget->is64Bit()) {
440 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
441 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
442 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
445 if (Subtarget->hasSSE1())
446 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
448 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
450 // Expand certain atomics
451 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
453 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
454 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
455 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
458 if (Subtarget->hasCmpxchg16b()) {
459 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
462 // FIXME - use subtarget debug flags
463 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
464 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
465 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
468 if (Subtarget->isTarget64BitLP64()) {
469 setExceptionPointerRegister(X86::RAX);
470 setExceptionSelectorRegister(X86::RDX);
472 setExceptionPointerRegister(X86::EAX);
473 setExceptionSelectorRegister(X86::EDX);
475 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
476 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
478 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
479 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
481 setOperationAction(ISD::TRAP, MVT::Other, Legal);
482 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
484 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
485 setOperationAction(ISD::VASTART , MVT::Other, Custom);
486 setOperationAction(ISD::VAEND , MVT::Other, Expand);
487 if (Subtarget->is64Bit()) {
488 setOperationAction(ISD::VAARG , MVT::Other, Custom);
489 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
491 // TargetInfo::CharPtrBuiltinVaList
492 setOperationAction(ISD::VAARG , MVT::Other, Expand);
493 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
496 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
497 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
499 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
501 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
502 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
503 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
505 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
506 // f32 and f64 use SSE.
507 // Set up the FP register classes.
508 addRegisterClass(MVT::f32, &X86::FR32RegClass);
509 addRegisterClass(MVT::f64, &X86::FR64RegClass);
511 // Use ANDPD to simulate FABS.
512 setOperationAction(ISD::FABS , MVT::f64, Custom);
513 setOperationAction(ISD::FABS , MVT::f32, Custom);
515 // Use XORP to simulate FNEG.
516 setOperationAction(ISD::FNEG , MVT::f64, Custom);
517 setOperationAction(ISD::FNEG , MVT::f32, Custom);
519 // Use ANDPD and ORPD to simulate FCOPYSIGN.
520 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
521 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
523 // Lower this to FGETSIGNx86 plus an AND.
524 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
525 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
527 // We don't support sin/cos/fmod
528 setOperationAction(ISD::FSIN , MVT::f64, Expand);
529 setOperationAction(ISD::FCOS , MVT::f64, Expand);
530 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
531 setOperationAction(ISD::FSIN , MVT::f32, Expand);
532 setOperationAction(ISD::FCOS , MVT::f32, Expand);
533 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
535 // Expand FP immediates into loads from the stack, except for the special
537 addLegalFPImmediate(APFloat(+0.0)); // xorpd
538 addLegalFPImmediate(APFloat(+0.0f)); // xorps
539 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
540 // Use SSE for f32, x87 for f64.
541 // Set up the FP register classes.
542 addRegisterClass(MVT::f32, &X86::FR32RegClass);
543 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
545 // Use ANDPS to simulate FABS.
546 setOperationAction(ISD::FABS , MVT::f32, Custom);
548 // Use XORP to simulate FNEG.
549 setOperationAction(ISD::FNEG , MVT::f32, Custom);
551 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
553 // Use ANDPS and ORPS to simulate FCOPYSIGN.
554 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
555 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
557 // We don't support sin/cos/fmod
558 setOperationAction(ISD::FSIN , MVT::f32, Expand);
559 setOperationAction(ISD::FCOS , MVT::f32, Expand);
560 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
562 // Special cases we handle for FP constants.
563 addLegalFPImmediate(APFloat(+0.0f)); // xorps
564 addLegalFPImmediate(APFloat(+0.0)); // FLD0
565 addLegalFPImmediate(APFloat(+1.0)); // FLD1
566 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
567 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
569 if (!TM.Options.UnsafeFPMath) {
570 setOperationAction(ISD::FSIN , MVT::f64, Expand);
571 setOperationAction(ISD::FCOS , MVT::f64, Expand);
572 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
574 } else if (!Subtarget->useSoftFloat()) {
575 // f32 and f64 in x87.
576 // Set up the FP register classes.
577 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
578 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
580 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
581 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
582 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
583 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
585 if (!TM.Options.UnsafeFPMath) {
586 setOperationAction(ISD::FSIN , MVT::f64, Expand);
587 setOperationAction(ISD::FSIN , MVT::f32, Expand);
588 setOperationAction(ISD::FCOS , MVT::f64, Expand);
589 setOperationAction(ISD::FCOS , MVT::f32, Expand);
590 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
591 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
593 addLegalFPImmediate(APFloat(+0.0)); // FLD0
594 addLegalFPImmediate(APFloat(+1.0)); // FLD1
595 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
596 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
597 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
598 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
599 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
600 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
603 // We don't support FMA.
604 setOperationAction(ISD::FMA, MVT::f64, Expand);
605 setOperationAction(ISD::FMA, MVT::f32, Expand);
607 // Long double always uses X87.
608 if (!Subtarget->useSoftFloat()) {
609 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
610 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
611 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
613 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
614 addLegalFPImmediate(TmpFlt); // FLD0
616 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
619 APFloat TmpFlt2(+1.0);
620 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
622 addLegalFPImmediate(TmpFlt2); // FLD1
623 TmpFlt2.changeSign();
624 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
627 if (!TM.Options.UnsafeFPMath) {
628 setOperationAction(ISD::FSIN , MVT::f80, Expand);
629 setOperationAction(ISD::FCOS , MVT::f80, Expand);
630 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
633 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
634 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
635 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
636 setOperationAction(ISD::FRINT, MVT::f80, Expand);
637 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
638 setOperationAction(ISD::FMA, MVT::f80, Expand);
641 // Always use a library call for pow.
642 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
643 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
644 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
646 setOperationAction(ISD::FLOG, MVT::f80, Expand);
647 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
648 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
649 setOperationAction(ISD::FEXP, MVT::f80, Expand);
650 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
651 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
652 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
654 // First set operation action for all vector types to either promote
655 // (for widening) or expand (for scalarization). Then we will selectively
656 // turn on ones that can be effectively codegen'd.
657 for (MVT VT : MVT::vector_valuetypes()) {
658 setOperationAction(ISD::ADD , VT, Expand);
659 setOperationAction(ISD::SUB , VT, Expand);
660 setOperationAction(ISD::FADD, VT, Expand);
661 setOperationAction(ISD::FNEG, VT, Expand);
662 setOperationAction(ISD::FSUB, VT, Expand);
663 setOperationAction(ISD::MUL , VT, Expand);
664 setOperationAction(ISD::FMUL, VT, Expand);
665 setOperationAction(ISD::SDIV, VT, Expand);
666 setOperationAction(ISD::UDIV, VT, Expand);
667 setOperationAction(ISD::FDIV, VT, Expand);
668 setOperationAction(ISD::SREM, VT, Expand);
669 setOperationAction(ISD::UREM, VT, Expand);
670 setOperationAction(ISD::LOAD, VT, Expand);
671 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
672 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
673 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
674 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
675 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
676 setOperationAction(ISD::FABS, VT, Expand);
677 setOperationAction(ISD::FSIN, VT, Expand);
678 setOperationAction(ISD::FSINCOS, VT, Expand);
679 setOperationAction(ISD::FCOS, VT, Expand);
680 setOperationAction(ISD::FSINCOS, VT, Expand);
681 setOperationAction(ISD::FREM, VT, Expand);
682 setOperationAction(ISD::FMA, VT, Expand);
683 setOperationAction(ISD::FPOWI, VT, Expand);
684 setOperationAction(ISD::FSQRT, VT, Expand);
685 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
686 setOperationAction(ISD::FFLOOR, VT, Expand);
687 setOperationAction(ISD::FCEIL, VT, Expand);
688 setOperationAction(ISD::FTRUNC, VT, Expand);
689 setOperationAction(ISD::FRINT, VT, Expand);
690 setOperationAction(ISD::FNEARBYINT, VT, Expand);
691 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
692 setOperationAction(ISD::MULHS, VT, Expand);
693 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
694 setOperationAction(ISD::MULHU, VT, Expand);
695 setOperationAction(ISD::SDIVREM, VT, Expand);
696 setOperationAction(ISD::UDIVREM, VT, Expand);
697 setOperationAction(ISD::FPOW, VT, Expand);
698 setOperationAction(ISD::CTPOP, VT, Expand);
699 setOperationAction(ISD::CTTZ, VT, Expand);
700 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
701 setOperationAction(ISD::CTLZ, VT, Expand);
702 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
703 setOperationAction(ISD::SHL, VT, Expand);
704 setOperationAction(ISD::SRA, VT, Expand);
705 setOperationAction(ISD::SRL, VT, Expand);
706 setOperationAction(ISD::ROTL, VT, Expand);
707 setOperationAction(ISD::ROTR, VT, Expand);
708 setOperationAction(ISD::BSWAP, VT, Expand);
709 setOperationAction(ISD::SETCC, VT, Expand);
710 setOperationAction(ISD::FLOG, VT, Expand);
711 setOperationAction(ISD::FLOG2, VT, Expand);
712 setOperationAction(ISD::FLOG10, VT, Expand);
713 setOperationAction(ISD::FEXP, VT, Expand);
714 setOperationAction(ISD::FEXP2, VT, Expand);
715 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
716 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
717 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
718 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
719 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
720 setOperationAction(ISD::TRUNCATE, VT, Expand);
721 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
722 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
723 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
724 setOperationAction(ISD::VSELECT, VT, Expand);
725 setOperationAction(ISD::SELECT_CC, VT, Expand);
726 for (MVT InnerVT : MVT::vector_valuetypes()) {
727 setTruncStoreAction(InnerVT, VT, Expand);
729 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
730 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
732 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
733 // types, we have to deal with them whether we ask for Expansion or not.
734 // Setting Expand causes its own optimisation problems though, so leave
736 if (VT.getVectorElementType() == MVT::i1)
737 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
739 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
740 // split/scalarized right now.
741 if (VT.getVectorElementType() == MVT::f16)
742 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
746 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
747 // with -msoft-float, disable use of MMX as well.
748 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
749 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
750 // No operations on x86mmx supported, everything uses intrinsics.
753 // MMX-sized vectors (other than x86mmx) are expected to be expanded
754 // into smaller operations.
755 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
756 setOperationAction(ISD::MULHS, MMXTy, Expand);
757 setOperationAction(ISD::AND, MMXTy, Expand);
758 setOperationAction(ISD::OR, MMXTy, Expand);
759 setOperationAction(ISD::XOR, MMXTy, Expand);
760 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
761 setOperationAction(ISD::SELECT, MMXTy, Expand);
762 setOperationAction(ISD::BITCAST, MMXTy, Expand);
764 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
766 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
767 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
769 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
770 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
771 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
772 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
773 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
774 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
775 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
776 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
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);
785 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
786 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
788 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
789 // registers cannot be used even for integer operations.
790 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
791 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
792 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
793 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
795 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
796 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
797 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
798 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
799 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
800 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
801 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
802 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
803 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
804 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
805 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
806 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
807 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
808 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
809 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
810 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
811 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
812 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
813 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
814 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
815 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
816 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
817 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
819 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
820 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
821 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
822 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
824 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
825 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
826 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
827 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
831 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
835 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
836 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
837 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
838 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
840 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
841 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
842 MVT VT = (MVT::SimpleValueType)i;
843 // Do not attempt to custom lower non-power-of-2 vectors
844 if (!isPowerOf2_32(VT.getVectorNumElements()))
846 // Do not attempt to custom lower non-128-bit vectors
847 if (!VT.is128BitVector())
849 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
850 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
851 setOperationAction(ISD::VSELECT, VT, Custom);
852 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
855 // We support custom legalizing of sext and anyext loads for specific
856 // memory vector types which we can load as a scalar (or sequence of
857 // scalars) and extend in-register to a legal 128-bit vector type. For sext
858 // loads these must work with a single scalar load.
859 for (MVT VT : MVT::integer_vector_valuetypes()) {
860 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
861 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
862 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
863 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
864 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
865 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
866 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
867 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
868 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
871 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
872 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
873 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
874 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
875 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
876 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
877 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
878 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
880 if (Subtarget->is64Bit()) {
881 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
882 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
885 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
886 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
887 MVT VT = (MVT::SimpleValueType)i;
889 // Do not attempt to promote non-128-bit vectors
890 if (!VT.is128BitVector())
893 setOperationAction(ISD::AND, VT, Promote);
894 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
895 setOperationAction(ISD::OR, VT, Promote);
896 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
897 setOperationAction(ISD::XOR, VT, Promote);
898 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
899 setOperationAction(ISD::LOAD, VT, Promote);
900 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
901 setOperationAction(ISD::SELECT, VT, Promote);
902 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
905 // Custom lower v2i64 and v2f64 selects.
906 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
907 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
908 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
909 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
911 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
912 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
914 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
916 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
917 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
918 // As there is no 64-bit GPR available, we need build a special custom
919 // sequence to convert from v2i32 to v2f32.
920 if (!Subtarget->is64Bit())
921 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
923 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
924 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
926 for (MVT VT : MVT::fp_vector_valuetypes())
927 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
929 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
930 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
931 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
934 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
935 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
936 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
937 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
938 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
939 setOperationAction(ISD::FRINT, RoundedTy, Legal);
940 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
943 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
944 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
945 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
946 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
947 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
948 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
949 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
950 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
952 // FIXME: Do we need to handle scalar-to-vector here?
953 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
955 // We directly match byte blends in the backend as they match the VSELECT
957 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
959 // SSE41 brings specific instructions for doing vector sign extend even in
960 // cases where we don't have SRA.
961 for (MVT VT : MVT::integer_vector_valuetypes()) {
962 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
963 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
964 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
967 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
968 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
969 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
970 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
971 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
972 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
973 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
975 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
976 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
977 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
978 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
979 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
980 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
982 // i8 and i16 vectors are custom because the source register and source
983 // source memory operand types are not the same width. f32 vectors are
984 // custom since the immediate controlling the insert encodes additional
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
996 // FIXME: these should be Legal, but that's only for the case where
997 // the index is constant. For now custom expand to deal with that.
998 if (Subtarget->is64Bit()) {
999 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1004 if (Subtarget->hasSSE2()) {
1005 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1006 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1007 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1009 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1010 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1012 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1013 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1015 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1016 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1018 // In the customized shift lowering, the legal cases in AVX2 will be
1020 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1021 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1023 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1024 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1026 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1027 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1030 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1031 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1032 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1033 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1034 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1035 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1036 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1038 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1039 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1040 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1042 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1043 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1053 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1055 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1059 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1060 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1063 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1064 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1066 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1068 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1069 // even though v8i16 is a legal type.
1070 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1071 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1072 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1074 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1075 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1076 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1078 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1079 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1081 for (MVT VT : MVT::fp_vector_valuetypes())
1082 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1084 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1085 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1087 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1088 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1090 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1091 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1093 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1094 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1095 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1096 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1098 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1099 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1100 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1102 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1103 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1104 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1105 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1106 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1107 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1108 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1109 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1110 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1111 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1112 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1113 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1115 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1116 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1117 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1118 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1120 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1121 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1122 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1123 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1124 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1125 setOperationAction(ISD::FMA, MVT::f32, Legal);
1126 setOperationAction(ISD::FMA, MVT::f64, Legal);
1129 if (Subtarget->hasInt256()) {
1130 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1131 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1132 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1133 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1135 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1136 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1137 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1138 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1140 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1141 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1142 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1143 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1145 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1146 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1147 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1148 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1150 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1151 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1152 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1153 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1154 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1155 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1156 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1157 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1158 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1159 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1160 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1161 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1163 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1164 // when we have a 256bit-wide blend with immediate.
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1167 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1168 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1169 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1170 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1171 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1172 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1173 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1175 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1176 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1177 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1178 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1179 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1180 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1182 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1183 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1184 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1185 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1187 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1188 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1189 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1190 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1192 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1193 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1194 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1195 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1197 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1198 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1199 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1200 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1201 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1202 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1203 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1204 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1205 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1206 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1207 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1208 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1211 // In the customized shift lowering, the legal cases in AVX2 will be
1213 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1214 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1216 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1217 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1219 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1220 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1222 // Custom lower several nodes for 256-bit types.
1223 for (MVT VT : MVT::vector_valuetypes()) {
1224 if (VT.getScalarSizeInBits() >= 32) {
1225 setOperationAction(ISD::MLOAD, VT, Legal);
1226 setOperationAction(ISD::MSTORE, VT, Legal);
1228 // Extract subvector is special because the value type
1229 // (result) is 128-bit but the source is 256-bit wide.
1230 if (VT.is128BitVector()) {
1231 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1233 // Do not attempt to custom lower other non-256-bit vectors
1234 if (!VT.is256BitVector())
1237 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1238 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1239 setOperationAction(ISD::VSELECT, VT, Custom);
1240 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1241 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1242 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1243 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1244 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1247 if (Subtarget->hasInt256())
1248 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1251 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1252 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1253 MVT VT = (MVT::SimpleValueType)i;
1255 // Do not attempt to promote non-256-bit vectors
1256 if (!VT.is256BitVector())
1259 setOperationAction(ISD::AND, VT, Promote);
1260 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1261 setOperationAction(ISD::OR, VT, Promote);
1262 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1263 setOperationAction(ISD::XOR, VT, Promote);
1264 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1265 setOperationAction(ISD::LOAD, VT, Promote);
1266 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1267 setOperationAction(ISD::SELECT, VT, Promote);
1268 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1272 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1273 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1274 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1275 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1276 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1278 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1279 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1280 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1282 for (MVT VT : MVT::fp_vector_valuetypes())
1283 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1285 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1286 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1287 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1288 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1289 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1290 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1291 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1292 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1293 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1294 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1295 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1296 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1298 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1299 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1300 setOperationAction(ISD::XOR, MVT::i1, Legal);
1301 setOperationAction(ISD::OR, MVT::i1, Legal);
1302 setOperationAction(ISD::AND, MVT::i1, Legal);
1303 setOperationAction(ISD::SUB, MVT::i1, Custom);
1304 setOperationAction(ISD::ADD, MVT::i1, Custom);
1305 setOperationAction(ISD::MUL, MVT::i1, Custom);
1306 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1307 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1308 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1309 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1310 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1312 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1313 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1314 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1315 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1316 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1317 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1319 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1320 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1321 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1322 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1323 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1324 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1325 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1326 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1328 // FIXME: [US]INT_TO_FP are not legal for f80.
1329 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1330 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1331 if (Subtarget->is64Bit()) {
1332 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1333 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1335 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1336 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1337 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1338 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1339 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1340 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1341 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1342 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1343 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1344 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1346 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1347 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1348 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1349 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1350 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1352 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1353 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1354 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1355 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1356 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1357 if (Subtarget->hasVLX()){
1358 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1359 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1360 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1361 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1362 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1364 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1365 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1366 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1367 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1368 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1370 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1373 if (Subtarget->hasDQI()) {
1374 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1375 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1377 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1378 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1379 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1380 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1381 if (Subtarget->hasVLX()) {
1382 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1383 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1384 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1385 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1386 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1387 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1388 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1389 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1392 if (Subtarget->hasVLX()) {
1393 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1394 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1395 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1396 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1397 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1398 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1399 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1400 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1402 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1403 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1404 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1405 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1406 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1407 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1408 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1409 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1410 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1411 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1412 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1413 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1414 if (Subtarget->hasDQI()) {
1415 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1416 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1418 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1419 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1420 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1421 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1422 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1423 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1424 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1425 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1426 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1427 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1429 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1430 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1431 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1432 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1433 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1435 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1436 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1438 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1440 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1441 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1442 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1443 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1444 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1445 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1446 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1447 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1448 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1449 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1450 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1452 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1453 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1454 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1455 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1456 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1457 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1458 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1459 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1461 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1462 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1465 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1467 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1469 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1470 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1472 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1473 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1475 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1476 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1478 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1479 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1481 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1482 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1483 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1485 if (Subtarget->hasCDI()) {
1486 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1487 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1489 if (Subtarget->hasDQI()) {
1490 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1491 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1492 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1494 // Custom lower several nodes.
1495 for (MVT VT : MVT::vector_valuetypes()) {
1496 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1498 setOperationAction(ISD::AND, VT, Legal);
1499 setOperationAction(ISD::OR, VT, Legal);
1500 setOperationAction(ISD::XOR, VT, Legal);
1502 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1503 setOperationAction(ISD::MGATHER, VT, Custom);
1504 setOperationAction(ISD::MSCATTER, VT, Custom);
1506 // Extract subvector is special because the value type
1507 // (result) is 256/128-bit but the source is 512-bit wide.
1508 if (VT.is128BitVector() || VT.is256BitVector()) {
1509 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1511 if (VT.getVectorElementType() == MVT::i1)
1512 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1514 // Do not attempt to custom lower other non-512-bit vectors
1515 if (!VT.is512BitVector())
1518 if (EltSize >= 32) {
1519 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1520 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1521 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1522 setOperationAction(ISD::VSELECT, VT, Legal);
1523 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1524 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1525 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1526 setOperationAction(ISD::MLOAD, VT, Legal);
1527 setOperationAction(ISD::MSTORE, VT, Legal);
1530 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1531 MVT VT = (MVT::SimpleValueType)i;
1533 // Do not attempt to promote non-512-bit vectors.
1534 if (!VT.is512BitVector())
1537 setOperationAction(ISD::SELECT, VT, Promote);
1538 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1542 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1543 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1544 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1546 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1547 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1549 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1550 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1551 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1552 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1553 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1554 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1555 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1556 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1557 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1558 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1559 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1560 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1561 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1562 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1563 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1564 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1565 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1566 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1567 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1568 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1569 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1570 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1571 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1572 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1573 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1574 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1575 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1576 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1577 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1578 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1580 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1581 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1582 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1583 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1584 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1585 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1586 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1587 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1589 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1590 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1591 if (Subtarget->hasVLX())
1592 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1594 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1595 const MVT VT = (MVT::SimpleValueType)i;
1597 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1599 // Do not attempt to promote non-512-bit vectors.
1600 if (!VT.is512BitVector())
1604 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1605 setOperationAction(ISD::VSELECT, VT, Legal);
1610 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1611 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1612 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1614 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1615 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1616 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1617 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1618 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1619 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1620 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1621 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1622 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1623 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1625 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1626 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1627 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1628 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1629 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1630 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1631 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1632 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1634 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1635 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1636 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1637 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1638 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1639 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1640 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1641 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1644 // We want to custom lower some of our intrinsics.
1645 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1646 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1647 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1648 if (!Subtarget->is64Bit())
1649 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1651 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1652 // handle type legalization for these operations here.
1654 // FIXME: We really should do custom legalization for addition and
1655 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1656 // than generic legalization for 64-bit multiplication-with-overflow, though.
1657 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1658 // Add/Sub/Mul with overflow operations are custom lowered.
1660 setOperationAction(ISD::SADDO, VT, Custom);
1661 setOperationAction(ISD::UADDO, VT, Custom);
1662 setOperationAction(ISD::SSUBO, VT, Custom);
1663 setOperationAction(ISD::USUBO, VT, Custom);
1664 setOperationAction(ISD::SMULO, VT, Custom);
1665 setOperationAction(ISD::UMULO, VT, Custom);
1669 if (!Subtarget->is64Bit()) {
1670 // These libcalls are not available in 32-bit.
1671 setLibcallName(RTLIB::SHL_I128, nullptr);
1672 setLibcallName(RTLIB::SRL_I128, nullptr);
1673 setLibcallName(RTLIB::SRA_I128, nullptr);
1676 // Combine sin / cos into one node or libcall if possible.
1677 if (Subtarget->hasSinCos()) {
1678 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1679 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1680 if (Subtarget->isTargetDarwin()) {
1681 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1682 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1683 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1684 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1688 if (Subtarget->isTargetWin64()) {
1689 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1690 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1691 setOperationAction(ISD::SREM, MVT::i128, Custom);
1692 setOperationAction(ISD::UREM, MVT::i128, Custom);
1693 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1694 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1697 // We have target-specific dag combine patterns for the following nodes:
1698 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1699 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1700 setTargetDAGCombine(ISD::BITCAST);
1701 setTargetDAGCombine(ISD::VSELECT);
1702 setTargetDAGCombine(ISD::SELECT);
1703 setTargetDAGCombine(ISD::SHL);
1704 setTargetDAGCombine(ISD::SRA);
1705 setTargetDAGCombine(ISD::SRL);
1706 setTargetDAGCombine(ISD::OR);
1707 setTargetDAGCombine(ISD::AND);
1708 setTargetDAGCombine(ISD::ADD);
1709 setTargetDAGCombine(ISD::FADD);
1710 setTargetDAGCombine(ISD::FSUB);
1711 setTargetDAGCombine(ISD::FMA);
1712 setTargetDAGCombine(ISD::SUB);
1713 setTargetDAGCombine(ISD::LOAD);
1714 setTargetDAGCombine(ISD::MLOAD);
1715 setTargetDAGCombine(ISD::STORE);
1716 setTargetDAGCombine(ISD::MSTORE);
1717 setTargetDAGCombine(ISD::ZERO_EXTEND);
1718 setTargetDAGCombine(ISD::ANY_EXTEND);
1719 setTargetDAGCombine(ISD::SIGN_EXTEND);
1720 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1721 setTargetDAGCombine(ISD::SINT_TO_FP);
1722 setTargetDAGCombine(ISD::UINT_TO_FP);
1723 setTargetDAGCombine(ISD::SETCC);
1724 setTargetDAGCombine(ISD::BUILD_VECTOR);
1725 setTargetDAGCombine(ISD::MUL);
1726 setTargetDAGCombine(ISD::XOR);
1728 computeRegisterProperties(Subtarget->getRegisterInfo());
1730 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1731 MaxStoresPerMemsetOptSize = 8;
1732 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1733 MaxStoresPerMemcpyOptSize = 4;
1734 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1735 MaxStoresPerMemmoveOptSize = 4;
1736 setPrefLoopAlignment(4); // 2^4 bytes.
1738 // Predictable cmov don't hurt on atom because it's in-order.
1739 PredictableSelectIsExpensive = !Subtarget->isAtom();
1740 EnableExtLdPromotion = true;
1741 setPrefFunctionAlignment(4); // 2^4 bytes.
1743 verifyIntrinsicTables();
1746 // This has so far only been implemented for 64-bit MachO.
1747 bool X86TargetLowering::useLoadStackGuardNode() const {
1748 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1751 TargetLoweringBase::LegalizeTypeAction
1752 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1753 if (ExperimentalVectorWideningLegalization &&
1754 VT.getVectorNumElements() != 1 &&
1755 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1756 return TypeWidenVector;
1758 return TargetLoweringBase::getPreferredVectorAction(VT);
1761 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1764 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1766 const unsigned NumElts = VT.getVectorNumElements();
1767 const EVT EltVT = VT.getVectorElementType();
1768 if (VT.is512BitVector()) {
1769 if (Subtarget->hasAVX512())
1770 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1771 EltVT == MVT::f32 || EltVT == MVT::f64)
1773 case 8: return MVT::v8i1;
1774 case 16: return MVT::v16i1;
1776 if (Subtarget->hasBWI())
1777 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1779 case 32: return MVT::v32i1;
1780 case 64: return MVT::v64i1;
1784 if (VT.is256BitVector() || VT.is128BitVector()) {
1785 if (Subtarget->hasVLX())
1786 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1787 EltVT == MVT::f32 || EltVT == MVT::f64)
1789 case 2: return MVT::v2i1;
1790 case 4: return MVT::v4i1;
1791 case 8: return MVT::v8i1;
1793 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1794 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1796 case 8: return MVT::v8i1;
1797 case 16: return MVT::v16i1;
1798 case 32: return MVT::v32i1;
1802 return VT.changeVectorElementTypeToInteger();
1805 /// Helper for getByValTypeAlignment to determine
1806 /// the desired ByVal argument alignment.
1807 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1810 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1811 if (VTy->getBitWidth() == 128)
1813 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1814 unsigned EltAlign = 0;
1815 getMaxByValAlign(ATy->getElementType(), EltAlign);
1816 if (EltAlign > MaxAlign)
1817 MaxAlign = EltAlign;
1818 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1819 for (auto *EltTy : STy->elements()) {
1820 unsigned EltAlign = 0;
1821 getMaxByValAlign(EltTy, EltAlign);
1822 if (EltAlign > MaxAlign)
1823 MaxAlign = EltAlign;
1830 /// Return the desired alignment for ByVal aggregate
1831 /// function arguments in the caller parameter area. For X86, aggregates
1832 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1833 /// are at 4-byte boundaries.
1834 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1835 const DataLayout &DL) const {
1836 if (Subtarget->is64Bit()) {
1837 // Max of 8 and alignment of type.
1838 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1845 if (Subtarget->hasSSE1())
1846 getMaxByValAlign(Ty, Align);
1850 /// Returns the target specific optimal type for load
1851 /// and store operations as a result of memset, memcpy, and memmove
1852 /// lowering. If DstAlign is zero that means it's safe to destination
1853 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1854 /// means there isn't a need to check it against alignment requirement,
1855 /// probably because the source does not need to be loaded. If 'IsMemset' is
1856 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1857 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1858 /// source is constant so it does not need to be loaded.
1859 /// It returns EVT::Other if the type should be determined using generic
1860 /// target-independent logic.
1862 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1863 unsigned DstAlign, unsigned SrcAlign,
1864 bool IsMemset, bool ZeroMemset,
1866 MachineFunction &MF) const {
1867 const Function *F = MF.getFunction();
1868 if ((!IsMemset || ZeroMemset) &&
1869 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1871 (!Subtarget->isUnalignedMemUnder32Slow() ||
1872 ((DstAlign == 0 || DstAlign >= 16) &&
1873 (SrcAlign == 0 || SrcAlign >= 16)))) {
1875 // FIXME: Check if unaligned 32-byte accesses are slow.
1876 if (Subtarget->hasInt256())
1878 if (Subtarget->hasFp256())
1881 if (Subtarget->hasSSE2())
1883 if (Subtarget->hasSSE1())
1885 } else if (!MemcpyStrSrc && Size >= 8 &&
1886 !Subtarget->is64Bit() &&
1887 Subtarget->hasSSE2()) {
1888 // Do not use f64 to lower memcpy if source is string constant. It's
1889 // better to use i32 to avoid the loads.
1893 // This is a compromise. If we reach here, unaligned accesses may be slow on
1894 // this target. However, creating smaller, aligned accesses could be even
1895 // slower and would certainly be a lot more code.
1896 if (Subtarget->is64Bit() && Size >= 8)
1901 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1903 return X86ScalarSSEf32;
1904 else if (VT == MVT::f64)
1905 return X86ScalarSSEf64;
1910 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1915 if (VT.getSizeInBits() == 256)
1916 *Fast = !Subtarget->isUnalignedMem32Slow();
1918 *Fast = !Subtarget->isUnalignedMemUnder32Slow();
1923 /// Return the entry encoding for a jump table in the
1924 /// current function. The returned value is a member of the
1925 /// MachineJumpTableInfo::JTEntryKind enum.
1926 unsigned X86TargetLowering::getJumpTableEncoding() const {
1927 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1929 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1930 Subtarget->isPICStyleGOT())
1931 return MachineJumpTableInfo::EK_Custom32;
1933 // Otherwise, use the normal jump table encoding heuristics.
1934 return TargetLowering::getJumpTableEncoding();
1937 bool X86TargetLowering::useSoftFloat() const {
1938 return Subtarget->useSoftFloat();
1942 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1943 const MachineBasicBlock *MBB,
1944 unsigned uid,MCContext &Ctx) const{
1945 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1946 Subtarget->isPICStyleGOT());
1947 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1949 return MCSymbolRefExpr::create(MBB->getSymbol(),
1950 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1953 /// Returns relocation base for the given PIC jumptable.
1954 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1955 SelectionDAG &DAG) const {
1956 if (!Subtarget->is64Bit())
1957 // This doesn't have SDLoc associated with it, but is not really the
1958 // same as a Register.
1959 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1960 getPointerTy(DAG.getDataLayout()));
1964 /// This returns the relocation base for the given PIC jumptable,
1965 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1966 const MCExpr *X86TargetLowering::
1967 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1968 MCContext &Ctx) const {
1969 // X86-64 uses RIP relative addressing based on the jump table label.
1970 if (Subtarget->isPICStyleRIPRel())
1971 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1973 // Otherwise, the reference is relative to the PIC base.
1974 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1977 std::pair<const TargetRegisterClass *, uint8_t>
1978 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1980 const TargetRegisterClass *RRC = nullptr;
1982 switch (VT.SimpleTy) {
1984 return TargetLowering::findRepresentativeClass(TRI, VT);
1985 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1986 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1989 RRC = &X86::VR64RegClass;
1991 case MVT::f32: case MVT::f64:
1992 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1993 case MVT::v4f32: case MVT::v2f64:
1994 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1996 RRC = &X86::VR128RegClass;
1999 return std::make_pair(RRC, Cost);
2002 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2003 unsigned &Offset) const {
2004 if (!Subtarget->isTargetLinux())
2007 if (Subtarget->is64Bit()) {
2008 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2010 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2022 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2023 unsigned DestAS) const {
2024 assert(SrcAS != DestAS && "Expected different address spaces!");
2026 return SrcAS < 256 && DestAS < 256;
2029 //===----------------------------------------------------------------------===//
2030 // Return Value Calling Convention Implementation
2031 //===----------------------------------------------------------------------===//
2033 #include "X86GenCallingConv.inc"
2036 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2037 MachineFunction &MF, bool isVarArg,
2038 const SmallVectorImpl<ISD::OutputArg> &Outs,
2039 LLVMContext &Context) const {
2040 SmallVector<CCValAssign, 16> RVLocs;
2041 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2042 return CCInfo.CheckReturn(Outs, RetCC_X86);
2045 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2046 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2051 X86TargetLowering::LowerReturn(SDValue Chain,
2052 CallingConv::ID CallConv, bool isVarArg,
2053 const SmallVectorImpl<ISD::OutputArg> &Outs,
2054 const SmallVectorImpl<SDValue> &OutVals,
2055 SDLoc dl, SelectionDAG &DAG) const {
2056 MachineFunction &MF = DAG.getMachineFunction();
2057 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2059 SmallVector<CCValAssign, 16> RVLocs;
2060 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2061 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2064 SmallVector<SDValue, 6> RetOps;
2065 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2066 // Operand #1 = Bytes To Pop
2067 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2070 // Copy the result values into the output registers.
2071 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2072 CCValAssign &VA = RVLocs[i];
2073 assert(VA.isRegLoc() && "Can only return in registers!");
2074 SDValue ValToCopy = OutVals[i];
2075 EVT ValVT = ValToCopy.getValueType();
2077 // Promote values to the appropriate types.
2078 if (VA.getLocInfo() == CCValAssign::SExt)
2079 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2080 else if (VA.getLocInfo() == CCValAssign::ZExt)
2081 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2082 else if (VA.getLocInfo() == CCValAssign::AExt) {
2083 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2084 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2086 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2088 else if (VA.getLocInfo() == CCValAssign::BCvt)
2089 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2091 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2092 "Unexpected FP-extend for return value.");
2094 // If this is x86-64, and we disabled SSE, we can't return FP values,
2095 // or SSE or MMX vectors.
2096 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2097 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2098 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2099 report_fatal_error("SSE register return with SSE disabled");
2101 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2102 // llvm-gcc has never done it right and no one has noticed, so this
2103 // should be OK for now.
2104 if (ValVT == MVT::f64 &&
2105 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2106 report_fatal_error("SSE2 register return with SSE2 disabled");
2108 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2109 // the RET instruction and handled by the FP Stackifier.
2110 if (VA.getLocReg() == X86::FP0 ||
2111 VA.getLocReg() == X86::FP1) {
2112 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2113 // change the value to the FP stack register class.
2114 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2115 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2116 RetOps.push_back(ValToCopy);
2117 // Don't emit a copytoreg.
2121 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2122 // which is returned in RAX / RDX.
2123 if (Subtarget->is64Bit()) {
2124 if (ValVT == MVT::x86mmx) {
2125 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2126 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2127 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2129 // If we don't have SSE2 available, convert to v4f32 so the generated
2130 // register is legal.
2131 if (!Subtarget->hasSSE2())
2132 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2137 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2138 Flag = Chain.getValue(1);
2139 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2142 // All x86 ABIs require that for returning structs by value we copy
2143 // the sret argument into %rax/%eax (depending on ABI) for the return.
2144 // We saved the argument into a virtual register in the entry block,
2145 // so now we copy the value out and into %rax/%eax.
2147 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2148 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2149 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2150 // either case FuncInfo->setSRetReturnReg() will have been called.
2151 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2152 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2153 getPointerTy(MF.getDataLayout()));
2156 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2157 X86::RAX : X86::EAX;
2158 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2159 Flag = Chain.getValue(1);
2161 // RAX/EAX now acts like a return value.
2163 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2166 RetOps[0] = Chain; // Update chain.
2168 // Add the flag if we have it.
2170 RetOps.push_back(Flag);
2172 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2175 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2176 if (N->getNumValues() != 1)
2178 if (!N->hasNUsesOfValue(1, 0))
2181 SDValue TCChain = Chain;
2182 SDNode *Copy = *N->use_begin();
2183 if (Copy->getOpcode() == ISD::CopyToReg) {
2184 // If the copy has a glue operand, we conservatively assume it isn't safe to
2185 // perform a tail call.
2186 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2188 TCChain = Copy->getOperand(0);
2189 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2192 bool HasRet = false;
2193 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2195 if (UI->getOpcode() != X86ISD::RET_FLAG)
2197 // If we are returning more than one value, we can definitely
2198 // not make a tail call see PR19530
2199 if (UI->getNumOperands() > 4)
2201 if (UI->getNumOperands() == 4 &&
2202 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2215 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2216 ISD::NodeType ExtendKind) const {
2218 // TODO: Is this also valid on 32-bit?
2219 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2220 ReturnMVT = MVT::i8;
2222 ReturnMVT = MVT::i32;
2224 EVT MinVT = getRegisterType(Context, ReturnMVT);
2225 return VT.bitsLT(MinVT) ? MinVT : VT;
2228 /// Lower the result values of a call into the
2229 /// appropriate copies out of appropriate physical registers.
2232 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2233 CallingConv::ID CallConv, bool isVarArg,
2234 const SmallVectorImpl<ISD::InputArg> &Ins,
2235 SDLoc dl, SelectionDAG &DAG,
2236 SmallVectorImpl<SDValue> &InVals) const {
2238 // Assign locations to each value returned by this call.
2239 SmallVector<CCValAssign, 16> RVLocs;
2240 bool Is64Bit = Subtarget->is64Bit();
2241 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2243 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2245 // Copy all of the result registers out of their specified physreg.
2246 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2247 CCValAssign &VA = RVLocs[i];
2248 EVT CopyVT = VA.getLocVT();
2250 // If this is x86-64, and we disabled SSE, we can't return FP values
2251 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2252 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2253 report_fatal_error("SSE register return with SSE disabled");
2256 // If we prefer to use the value in xmm registers, copy it out as f80 and
2257 // use a truncate to move it from fp stack reg to xmm reg.
2258 bool RoundAfterCopy = false;
2259 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2260 isScalarFPTypeInSSEReg(VA.getValVT())) {
2262 RoundAfterCopy = (CopyVT != VA.getLocVT());
2265 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2266 CopyVT, InFlag).getValue(1);
2267 SDValue Val = Chain.getValue(0);
2270 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2271 // This truncation won't change the value.
2272 DAG.getIntPtrConstant(1, dl));
2274 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2275 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2277 InFlag = Chain.getValue(2);
2278 InVals.push_back(Val);
2284 //===----------------------------------------------------------------------===//
2285 // C & StdCall & Fast Calling Convention implementation
2286 //===----------------------------------------------------------------------===//
2287 // StdCall calling convention seems to be standard for many Windows' API
2288 // routines and around. It differs from C calling convention just a little:
2289 // callee should clean up the stack, not caller. Symbols should be also
2290 // decorated in some fancy way :) It doesn't support any vector arguments.
2291 // For info on fast calling convention see Fast Calling Convention (tail call)
2292 // implementation LowerX86_32FastCCCallTo.
2294 /// CallIsStructReturn - Determines whether a call uses struct return
2296 enum StructReturnType {
2301 static StructReturnType
2302 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2304 return NotStructReturn;
2306 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2307 if (!Flags.isSRet())
2308 return NotStructReturn;
2309 if (Flags.isInReg())
2310 return RegStructReturn;
2311 return StackStructReturn;
2314 /// Determines whether a function uses struct return semantics.
2315 static StructReturnType
2316 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2318 return NotStructReturn;
2320 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2321 if (!Flags.isSRet())
2322 return NotStructReturn;
2323 if (Flags.isInReg())
2324 return RegStructReturn;
2325 return StackStructReturn;
2328 /// Make a copy of an aggregate at address specified by "Src" to address
2329 /// "Dst" with size and alignment information specified by the specific
2330 /// parameter attribute. The copy will be passed as a byval function parameter.
2332 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2333 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2335 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2337 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2338 /*isVolatile*/false, /*AlwaysInline=*/true,
2339 /*isTailCall*/false,
2340 MachinePointerInfo(), MachinePointerInfo());
2343 /// Return true if the calling convention is one that
2344 /// supports tail call optimization.
2345 static bool IsTailCallConvention(CallingConv::ID CC) {
2346 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2347 CC == CallingConv::HiPE);
2350 /// \brief Return true if the calling convention is a C calling convention.
2351 static bool IsCCallConvention(CallingConv::ID CC) {
2352 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2353 CC == CallingConv::X86_64_SysV);
2356 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2358 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2359 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2363 CallingConv::ID CalleeCC = CS.getCallingConv();
2364 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2370 /// Return true if the function is being made into
2371 /// a tailcall target by changing its ABI.
2372 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2373 bool GuaranteedTailCallOpt) {
2374 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2378 X86TargetLowering::LowerMemArgument(SDValue Chain,
2379 CallingConv::ID CallConv,
2380 const SmallVectorImpl<ISD::InputArg> &Ins,
2381 SDLoc dl, SelectionDAG &DAG,
2382 const CCValAssign &VA,
2383 MachineFrameInfo *MFI,
2385 // Create the nodes corresponding to a load from this parameter slot.
2386 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2387 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2388 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2389 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2392 // If value is passed by pointer we have address passed instead of the value
2394 bool ExtendedInMem = VA.isExtInLoc() &&
2395 VA.getValVT().getScalarType() == MVT::i1;
2397 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2398 ValVT = VA.getLocVT();
2400 ValVT = VA.getValVT();
2402 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2403 // changed with more analysis.
2404 // In case of tail call optimization mark all arguments mutable. Since they
2405 // could be overwritten by lowering of arguments in case of a tail call.
2406 if (Flags.isByVal()) {
2407 unsigned Bytes = Flags.getByValSize();
2408 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2409 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2410 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2412 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2413 VA.getLocMemOffset(), isImmutable);
2414 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2415 SDValue Val = DAG.getLoad(
2416 ValVT, dl, Chain, FIN,
2417 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2419 return ExtendedInMem ?
2420 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2424 // FIXME: Get this from tablegen.
2425 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2426 const X86Subtarget *Subtarget) {
2427 assert(Subtarget->is64Bit());
2429 if (Subtarget->isCallingConvWin64(CallConv)) {
2430 static const MCPhysReg GPR64ArgRegsWin64[] = {
2431 X86::RCX, X86::RDX, X86::R8, X86::R9
2433 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2436 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2437 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2439 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2442 // FIXME: Get this from tablegen.
2443 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2444 CallingConv::ID CallConv,
2445 const X86Subtarget *Subtarget) {
2446 assert(Subtarget->is64Bit());
2447 if (Subtarget->isCallingConvWin64(CallConv)) {
2448 // The XMM registers which might contain var arg parameters are shadowed
2449 // in their paired GPR. So we only need to save the GPR to their home
2451 // TODO: __vectorcall will change this.
2455 const Function *Fn = MF.getFunction();
2456 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2457 bool isSoftFloat = Subtarget->useSoftFloat();
2458 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2459 "SSE register cannot be used when SSE is disabled!");
2460 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2461 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2465 static const MCPhysReg XMMArgRegs64Bit[] = {
2466 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2467 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2469 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2473 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2474 CallingConv::ID CallConv,
2476 const SmallVectorImpl<ISD::InputArg> &Ins,
2479 SmallVectorImpl<SDValue> &InVals)
2481 MachineFunction &MF = DAG.getMachineFunction();
2482 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2483 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2485 const Function* Fn = MF.getFunction();
2486 if (Fn->hasExternalLinkage() &&
2487 Subtarget->isTargetCygMing() &&
2488 Fn->getName() == "main")
2489 FuncInfo->setForceFramePointer(true);
2491 MachineFrameInfo *MFI = MF.getFrameInfo();
2492 bool Is64Bit = Subtarget->is64Bit();
2493 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2495 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2496 "Var args not supported with calling convention fastcc, ghc or hipe");
2498 // Assign locations to all of the incoming arguments.
2499 SmallVector<CCValAssign, 16> ArgLocs;
2500 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2502 // Allocate shadow area for Win64
2504 CCInfo.AllocateStack(32, 8);
2506 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2508 unsigned LastVal = ~0U;
2510 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2511 CCValAssign &VA = ArgLocs[i];
2512 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2514 assert(VA.getValNo() != LastVal &&
2515 "Don't support value assigned to multiple locs yet");
2517 LastVal = VA.getValNo();
2519 if (VA.isRegLoc()) {
2520 EVT RegVT = VA.getLocVT();
2521 const TargetRegisterClass *RC;
2522 if (RegVT == MVT::i32)
2523 RC = &X86::GR32RegClass;
2524 else if (Is64Bit && RegVT == MVT::i64)
2525 RC = &X86::GR64RegClass;
2526 else if (RegVT == MVT::f32)
2527 RC = &X86::FR32RegClass;
2528 else if (RegVT == MVT::f64)
2529 RC = &X86::FR64RegClass;
2530 else if (RegVT.is512BitVector())
2531 RC = &X86::VR512RegClass;
2532 else if (RegVT.is256BitVector())
2533 RC = &X86::VR256RegClass;
2534 else if (RegVT.is128BitVector())
2535 RC = &X86::VR128RegClass;
2536 else if (RegVT == MVT::x86mmx)
2537 RC = &X86::VR64RegClass;
2538 else if (RegVT == MVT::i1)
2539 RC = &X86::VK1RegClass;
2540 else if (RegVT == MVT::v8i1)
2541 RC = &X86::VK8RegClass;
2542 else if (RegVT == MVT::v16i1)
2543 RC = &X86::VK16RegClass;
2544 else if (RegVT == MVT::v32i1)
2545 RC = &X86::VK32RegClass;
2546 else if (RegVT == MVT::v64i1)
2547 RC = &X86::VK64RegClass;
2549 llvm_unreachable("Unknown argument type!");
2551 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2552 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2554 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2555 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2557 if (VA.getLocInfo() == CCValAssign::SExt)
2558 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2559 DAG.getValueType(VA.getValVT()));
2560 else if (VA.getLocInfo() == CCValAssign::ZExt)
2561 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2562 DAG.getValueType(VA.getValVT()));
2563 else if (VA.getLocInfo() == CCValAssign::BCvt)
2564 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2566 if (VA.isExtInLoc()) {
2567 // Handle MMX values passed in XMM regs.
2568 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2569 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2571 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2574 assert(VA.isMemLoc());
2575 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2578 // If value is passed via pointer - do a load.
2579 if (VA.getLocInfo() == CCValAssign::Indirect)
2580 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2581 MachinePointerInfo(), false, false, false, 0);
2583 InVals.push_back(ArgValue);
2586 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2587 // All x86 ABIs require that for returning structs by value we copy the
2588 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2589 // the argument into a virtual register so that we can access it from the
2591 if (Ins[i].Flags.isSRet()) {
2592 unsigned Reg = FuncInfo->getSRetReturnReg();
2594 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2595 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2596 FuncInfo->setSRetReturnReg(Reg);
2598 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2599 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2604 unsigned StackSize = CCInfo.getNextStackOffset();
2605 // Align stack specially for tail calls.
2606 if (FuncIsMadeTailCallSafe(CallConv,
2607 MF.getTarget().Options.GuaranteedTailCallOpt))
2608 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2610 // If the function takes variable number of arguments, make a frame index for
2611 // the start of the first vararg value... for expansion of llvm.va_start. We
2612 // can skip this if there are no va_start calls.
2613 if (MFI->hasVAStart() &&
2614 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2615 CallConv != CallingConv::X86_ThisCall))) {
2616 FuncInfo->setVarArgsFrameIndex(
2617 MFI->CreateFixedObject(1, StackSize, true));
2620 MachineModuleInfo &MMI = MF.getMMI();
2621 const Function *WinEHParent = nullptr;
2622 if (MMI.hasWinEHFuncInfo(Fn))
2623 WinEHParent = MMI.getWinEHParent(Fn);
2624 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2625 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2627 // Figure out if XMM registers are in use.
2628 assert(!(Subtarget->useSoftFloat() &&
2629 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2630 "SSE register cannot be used when SSE is disabled!");
2632 // 64-bit calling conventions support varargs and register parameters, so we
2633 // have to do extra work to spill them in the prologue.
2634 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2635 // Find the first unallocated argument registers.
2636 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2637 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2638 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2639 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2640 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2641 "SSE register cannot be used when SSE is disabled!");
2643 // Gather all the live in physical registers.
2644 SmallVector<SDValue, 6> LiveGPRs;
2645 SmallVector<SDValue, 8> LiveXMMRegs;
2647 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2648 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2650 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2652 if (!ArgXMMs.empty()) {
2653 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2654 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2655 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2656 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2657 LiveXMMRegs.push_back(
2658 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2663 // Get to the caller-allocated home save location. Add 8 to account
2664 // for the return address.
2665 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2666 FuncInfo->setRegSaveFrameIndex(
2667 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2668 // Fixup to set vararg frame on shadow area (4 x i64).
2670 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2672 // For X86-64, if there are vararg parameters that are passed via
2673 // registers, then we must store them to their spots on the stack so
2674 // they may be loaded by deferencing the result of va_next.
2675 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2676 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2677 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2678 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2681 // Store the integer parameter registers.
2682 SmallVector<SDValue, 8> MemOps;
2683 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2684 getPointerTy(DAG.getDataLayout()));
2685 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2686 for (SDValue Val : LiveGPRs) {
2687 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2688 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2690 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2691 MachinePointerInfo::getFixedStack(
2692 DAG.getMachineFunction(),
2693 FuncInfo->getRegSaveFrameIndex(), Offset),
2695 MemOps.push_back(Store);
2699 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2700 // Now store the XMM (fp + vector) parameter registers.
2701 SmallVector<SDValue, 12> SaveXMMOps;
2702 SaveXMMOps.push_back(Chain);
2703 SaveXMMOps.push_back(ALVal);
2704 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2705 FuncInfo->getRegSaveFrameIndex(), dl));
2706 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2707 FuncInfo->getVarArgsFPOffset(), dl));
2708 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2710 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2711 MVT::Other, SaveXMMOps));
2714 if (!MemOps.empty())
2715 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2716 } else if (IsWin64 && IsWinEHOutlined) {
2717 // Get to the caller-allocated home save location. Add 8 to account
2718 // for the return address.
2719 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2720 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2721 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2723 MMI.getWinEHFuncInfo(Fn)
2724 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2725 FuncInfo->getRegSaveFrameIndex();
2727 // Store the second integer parameter (rdx) into rsp+16 relative to the
2728 // stack pointer at the entry of the function.
2729 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2730 getPointerTy(DAG.getDataLayout()));
2731 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2732 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2733 Chain = DAG.getStore(
2734 Val.getValue(1), dl, Val, RSFIN,
2735 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2736 FuncInfo->getRegSaveFrameIndex()),
2737 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2740 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2741 // Find the largest legal vector type.
2742 MVT VecVT = MVT::Other;
2743 // FIXME: Only some x86_32 calling conventions support AVX512.
2744 if (Subtarget->hasAVX512() &&
2745 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2746 CallConv == CallingConv::Intel_OCL_BI)))
2747 VecVT = MVT::v16f32;
2748 else if (Subtarget->hasAVX())
2750 else if (Subtarget->hasSSE2())
2753 // We forward some GPRs and some vector types.
2754 SmallVector<MVT, 2> RegParmTypes;
2755 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2756 RegParmTypes.push_back(IntVT);
2757 if (VecVT != MVT::Other)
2758 RegParmTypes.push_back(VecVT);
2760 // Compute the set of forwarded registers. The rest are scratch.
2761 SmallVectorImpl<ForwardedRegister> &Forwards =
2762 FuncInfo->getForwardedMustTailRegParms();
2763 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2765 // Conservatively forward AL on x86_64, since it might be used for varargs.
2766 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2767 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2768 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2771 // Copy all forwards from physical to virtual registers.
2772 for (ForwardedRegister &F : Forwards) {
2773 // FIXME: Can we use a less constrained schedule?
2774 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2775 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2776 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2780 // Some CCs need callee pop.
2781 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2782 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2783 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2785 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2786 // If this is an sret function, the return should pop the hidden pointer.
2787 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2788 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2789 argsAreStructReturn(Ins) == StackStructReturn)
2790 FuncInfo->setBytesToPopOnReturn(4);
2794 // RegSaveFrameIndex is X86-64 only.
2795 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2796 if (CallConv == CallingConv::X86_FastCall ||
2797 CallConv == CallingConv::X86_ThisCall)
2798 // fastcc functions can't have varargs.
2799 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2802 FuncInfo->setArgumentStackSize(StackSize);
2804 if (IsWinEHParent) {
2806 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2807 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2808 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2809 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2810 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2811 MachinePointerInfo::getFixedStack(
2812 DAG.getMachineFunction(), UnwindHelpFI),
2813 /*isVolatile=*/true,
2814 /*isNonTemporal=*/false, /*Alignment=*/0);
2816 // Functions using Win32 EH are considered to have opaque SP adjustments
2817 // to force local variables to be addressed from the frame or base
2819 MFI->setHasOpaqueSPAdjustment(true);
2827 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2828 SDValue StackPtr, SDValue Arg,
2829 SDLoc dl, SelectionDAG &DAG,
2830 const CCValAssign &VA,
2831 ISD::ArgFlagsTy Flags) const {
2832 unsigned LocMemOffset = VA.getLocMemOffset();
2833 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2834 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2836 if (Flags.isByVal())
2837 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2839 return DAG.getStore(
2840 Chain, dl, Arg, PtrOff,
2841 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2845 /// Emit a load of return address if tail call
2846 /// optimization is performed and it is required.
2848 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2849 SDValue &OutRetAddr, SDValue Chain,
2850 bool IsTailCall, bool Is64Bit,
2851 int FPDiff, SDLoc dl) const {
2852 // Adjust the Return address stack slot.
2853 EVT VT = getPointerTy(DAG.getDataLayout());
2854 OutRetAddr = getReturnAddressFrameIndex(DAG);
2856 // Load the "old" Return address.
2857 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2858 false, false, false, 0);
2859 return SDValue(OutRetAddr.getNode(), 1);
2862 /// Emit a store of the return address if tail call
2863 /// optimization is performed and it is required (FPDiff!=0).
2864 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2865 SDValue Chain, SDValue RetAddrFrIdx,
2866 EVT PtrVT, unsigned SlotSize,
2867 int FPDiff, SDLoc dl) {
2868 // Store the return address to the appropriate stack slot.
2869 if (!FPDiff) return Chain;
2870 // Calculate the new stack slot for the return address.
2871 int NewReturnAddrFI =
2872 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2874 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2875 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2876 MachinePointerInfo::getFixedStack(
2877 DAG.getMachineFunction(), NewReturnAddrFI),
2882 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2883 /// operation of specified width.
2884 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2886 unsigned NumElems = VT.getVectorNumElements();
2887 SmallVector<int, 8> Mask;
2888 Mask.push_back(NumElems);
2889 for (unsigned i = 1; i != NumElems; ++i)
2891 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2895 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2896 SmallVectorImpl<SDValue> &InVals) const {
2897 SelectionDAG &DAG = CLI.DAG;
2899 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2900 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2901 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2902 SDValue Chain = CLI.Chain;
2903 SDValue Callee = CLI.Callee;
2904 CallingConv::ID CallConv = CLI.CallConv;
2905 bool &isTailCall = CLI.IsTailCall;
2906 bool isVarArg = CLI.IsVarArg;
2908 MachineFunction &MF = DAG.getMachineFunction();
2909 bool Is64Bit = Subtarget->is64Bit();
2910 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2911 StructReturnType SR = callIsStructReturn(Outs);
2912 bool IsSibcall = false;
2913 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2914 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2916 if (Attr.getValueAsString() == "true")
2919 if (Subtarget->isPICStyleGOT() &&
2920 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2921 // If we are using a GOT, disable tail calls to external symbols with
2922 // default visibility. Tail calling such a symbol requires using a GOT
2923 // relocation, which forces early binding of the symbol. This breaks code
2924 // that require lazy function symbol resolution. Using musttail or
2925 // GuaranteedTailCallOpt will override this.
2926 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2927 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2928 G->getGlobal()->hasDefaultVisibility()))
2932 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2934 // Force this to be a tail call. The verifier rules are enough to ensure
2935 // that we can lower this successfully without moving the return address
2938 } else if (isTailCall) {
2939 // Check if it's really possible to do a tail call.
2940 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2941 isVarArg, SR != NotStructReturn,
2942 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2943 Outs, OutVals, Ins, DAG);
2945 // Sibcalls are automatically detected tailcalls which do not require
2947 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2954 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2955 "Var args not supported with calling convention fastcc, ghc or hipe");
2957 // Analyze operands of the call, assigning locations to each operand.
2958 SmallVector<CCValAssign, 16> ArgLocs;
2959 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2961 // Allocate shadow area for Win64
2963 CCInfo.AllocateStack(32, 8);
2965 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2967 // Get a count of how many bytes are to be pushed on the stack.
2968 unsigned NumBytes = CCInfo.getNextStackOffset();
2970 // This is a sibcall. The memory operands are available in caller's
2971 // own caller's stack.
2973 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2974 IsTailCallConvention(CallConv))
2975 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2978 if (isTailCall && !IsSibcall && !IsMustTail) {
2979 // Lower arguments at fp - stackoffset + fpdiff.
2980 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2982 FPDiff = NumBytesCallerPushed - NumBytes;
2984 // Set the delta of movement of the returnaddr stackslot.
2985 // But only set if delta is greater than previous delta.
2986 if (FPDiff < X86Info->getTCReturnAddrDelta())
2987 X86Info->setTCReturnAddrDelta(FPDiff);
2990 unsigned NumBytesToPush = NumBytes;
2991 unsigned NumBytesToPop = NumBytes;
2993 // If we have an inalloca argument, all stack space has already been allocated
2994 // for us and be right at the top of the stack. We don't support multiple
2995 // arguments passed in memory when using inalloca.
2996 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2998 if (!ArgLocs.back().isMemLoc())
2999 report_fatal_error("cannot use inalloca attribute on a register "
3001 if (ArgLocs.back().getLocMemOffset() != 0)
3002 report_fatal_error("any parameter with the inalloca attribute must be "
3003 "the only memory argument");
3007 Chain = DAG.getCALLSEQ_START(
3008 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3010 SDValue RetAddrFrIdx;
3011 // Load return address for tail calls.
3012 if (isTailCall && FPDiff)
3013 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3014 Is64Bit, FPDiff, dl);
3016 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3017 SmallVector<SDValue, 8> MemOpChains;
3020 // Walk the register/memloc assignments, inserting copies/loads. In the case
3021 // of tail call optimization arguments are handle later.
3022 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3023 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3024 // Skip inalloca arguments, they have already been written.
3025 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3026 if (Flags.isInAlloca())
3029 CCValAssign &VA = ArgLocs[i];
3030 EVT RegVT = VA.getLocVT();
3031 SDValue Arg = OutVals[i];
3032 bool isByVal = Flags.isByVal();
3034 // Promote the value if needed.
3035 switch (VA.getLocInfo()) {
3036 default: llvm_unreachable("Unknown loc info!");
3037 case CCValAssign::Full: break;
3038 case CCValAssign::SExt:
3039 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3041 case CCValAssign::ZExt:
3042 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3044 case CCValAssign::AExt:
3045 if (Arg.getValueType().isVector() &&
3046 Arg.getValueType().getScalarType() == MVT::i1)
3047 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3048 else if (RegVT.is128BitVector()) {
3049 // Special case: passing MMX values in XMM registers.
3050 Arg = DAG.getBitcast(MVT::i64, Arg);
3051 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3052 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3054 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3056 case CCValAssign::BCvt:
3057 Arg = DAG.getBitcast(RegVT, Arg);
3059 case CCValAssign::Indirect: {
3060 // Store the argument.
3061 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3062 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3063 Chain = DAG.getStore(
3064 Chain, dl, Arg, SpillSlot,
3065 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3072 if (VA.isRegLoc()) {
3073 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3074 if (isVarArg && IsWin64) {
3075 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3076 // shadow reg if callee is a varargs function.
3077 unsigned ShadowReg = 0;
3078 switch (VA.getLocReg()) {
3079 case X86::XMM0: ShadowReg = X86::RCX; break;
3080 case X86::XMM1: ShadowReg = X86::RDX; break;
3081 case X86::XMM2: ShadowReg = X86::R8; break;
3082 case X86::XMM3: ShadowReg = X86::R9; break;
3085 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3087 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3088 assert(VA.isMemLoc());
3089 if (!StackPtr.getNode())
3090 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3091 getPointerTy(DAG.getDataLayout()));
3092 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3093 dl, DAG, VA, Flags));
3097 if (!MemOpChains.empty())
3098 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3100 if (Subtarget->isPICStyleGOT()) {
3101 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3104 RegsToPass.push_back(std::make_pair(
3105 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3106 getPointerTy(DAG.getDataLayout()))));
3108 // If we are tail calling and generating PIC/GOT style code load the
3109 // address of the callee into ECX. The value in ecx is used as target of
3110 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3111 // for tail calls on PIC/GOT architectures. Normally we would just put the
3112 // address of GOT into ebx and then call target@PLT. But for tail calls
3113 // ebx would be restored (since ebx is callee saved) before jumping to the
3116 // Note: The actual moving to ECX is done further down.
3117 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3118 if (G && !G->getGlobal()->hasLocalLinkage() &&
3119 G->getGlobal()->hasDefaultVisibility())
3120 Callee = LowerGlobalAddress(Callee, DAG);
3121 else if (isa<ExternalSymbolSDNode>(Callee))
3122 Callee = LowerExternalSymbol(Callee, DAG);
3126 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3127 // From AMD64 ABI document:
3128 // For calls that may call functions that use varargs or stdargs
3129 // (prototype-less calls or calls to functions containing ellipsis (...) in
3130 // the declaration) %al is used as hidden argument to specify the number
3131 // of SSE registers used. The contents of %al do not need to match exactly
3132 // the number of registers, but must be an ubound on the number of SSE
3133 // registers used and is in the range 0 - 8 inclusive.
3135 // Count the number of XMM registers allocated.
3136 static const MCPhysReg XMMArgRegs[] = {
3137 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3138 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3140 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3141 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3142 && "SSE registers cannot be used when SSE is disabled");
3144 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3145 DAG.getConstant(NumXMMRegs, dl,
3149 if (isVarArg && IsMustTail) {
3150 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3151 for (const auto &F : Forwards) {
3152 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3153 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3157 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3158 // don't need this because the eligibility check rejects calls that require
3159 // shuffling arguments passed in memory.
3160 if (!IsSibcall && isTailCall) {
3161 // Force all the incoming stack arguments to be loaded from the stack
3162 // before any new outgoing arguments are stored to the stack, because the
3163 // outgoing stack slots may alias the incoming argument stack slots, and
3164 // the alias isn't otherwise explicit. This is slightly more conservative
3165 // than necessary, because it means that each store effectively depends
3166 // on every argument instead of just those arguments it would clobber.
3167 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3169 SmallVector<SDValue, 8> MemOpChains2;
3172 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3173 CCValAssign &VA = ArgLocs[i];
3176 assert(VA.isMemLoc());
3177 SDValue Arg = OutVals[i];
3178 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3179 // Skip inalloca arguments. They don't require any work.
3180 if (Flags.isInAlloca())
3182 // Create frame index.
3183 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3184 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3185 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3186 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3188 if (Flags.isByVal()) {
3189 // Copy relative to framepointer.
3190 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3191 if (!StackPtr.getNode())
3192 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3193 getPointerTy(DAG.getDataLayout()));
3194 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3197 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3201 // Store relative to framepointer.
3202 MemOpChains2.push_back(DAG.getStore(
3203 ArgChain, dl, Arg, FIN,
3204 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3209 if (!MemOpChains2.empty())
3210 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3212 // Store the return address to the appropriate stack slot.
3213 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3214 getPointerTy(DAG.getDataLayout()),
3215 RegInfo->getSlotSize(), FPDiff, dl);
3218 // Build a sequence of copy-to-reg nodes chained together with token chain
3219 // and flag operands which copy the outgoing args into registers.
3221 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3222 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3223 RegsToPass[i].second, InFlag);
3224 InFlag = Chain.getValue(1);
3227 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3228 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3229 // In the 64-bit large code model, we have to make all calls
3230 // through a register, since the call instruction's 32-bit
3231 // pc-relative offset may not be large enough to hold the whole
3233 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3234 // If the callee is a GlobalAddress node (quite common, every direct call
3235 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3237 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3239 // We should use extra load for direct calls to dllimported functions in
3241 const GlobalValue *GV = G->getGlobal();
3242 if (!GV->hasDLLImportStorageClass()) {
3243 unsigned char OpFlags = 0;
3244 bool ExtraLoad = false;
3245 unsigned WrapperKind = ISD::DELETED_NODE;
3247 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3248 // external symbols most go through the PLT in PIC mode. If the symbol
3249 // has hidden or protected visibility, or if it is static or local, then
3250 // we don't need to use the PLT - we can directly call it.
3251 if (Subtarget->isTargetELF() &&
3252 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3253 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3254 OpFlags = X86II::MO_PLT;
3255 } else if (Subtarget->isPICStyleStubAny() &&
3256 !GV->isStrongDefinitionForLinker() &&
3257 (!Subtarget->getTargetTriple().isMacOSX() ||
3258 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3259 // PC-relative references to external symbols should go through $stub,
3260 // unless we're building with the leopard linker or later, which
3261 // automatically synthesizes these stubs.
3262 OpFlags = X86II::MO_DARWIN_STUB;
3263 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3264 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3265 // If the function is marked as non-lazy, generate an indirect call
3266 // which loads from the GOT directly. This avoids runtime overhead
3267 // at the cost of eager binding (and one extra byte of encoding).
3268 OpFlags = X86II::MO_GOTPCREL;
3269 WrapperKind = X86ISD::WrapperRIP;
3273 Callee = DAG.getTargetGlobalAddress(
3274 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3276 // Add a wrapper if needed.
3277 if (WrapperKind != ISD::DELETED_NODE)
3278 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3279 getPointerTy(DAG.getDataLayout()), Callee);
3280 // Add extra indirection if needed.
3282 Callee = DAG.getLoad(
3283 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3284 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3287 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3288 unsigned char OpFlags = 0;
3290 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3291 // external symbols should go through the PLT.
3292 if (Subtarget->isTargetELF() &&
3293 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3294 OpFlags = X86II::MO_PLT;
3295 } else if (Subtarget->isPICStyleStubAny() &&
3296 (!Subtarget->getTargetTriple().isMacOSX() ||
3297 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3298 // PC-relative references to external symbols should go through $stub,
3299 // unless we're building with the leopard linker or later, which
3300 // automatically synthesizes these stubs.
3301 OpFlags = X86II::MO_DARWIN_STUB;
3304 Callee = DAG.getTargetExternalSymbol(
3305 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3306 } else if (Subtarget->isTarget64BitILP32() &&
3307 Callee->getValueType(0) == MVT::i32) {
3308 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3309 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3312 // Returns a chain & a flag for retval copy to use.
3313 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3314 SmallVector<SDValue, 8> Ops;
3316 if (!IsSibcall && isTailCall) {
3317 Chain = DAG.getCALLSEQ_END(Chain,
3318 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3319 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3320 InFlag = Chain.getValue(1);
3323 Ops.push_back(Chain);
3324 Ops.push_back(Callee);
3327 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3329 // Add argument registers to the end of the list so that they are known live
3331 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3332 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3333 RegsToPass[i].second.getValueType()));
3335 // Add a register mask operand representing the call-preserved registers.
3336 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3337 assert(Mask && "Missing call preserved mask for calling convention");
3339 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3340 // the function clobbers all registers. If an exception is thrown, the runtime
3341 // will not restore CSRs.
3342 // FIXME: Model this more precisely so that we can register allocate across
3343 // the normal edge and spill and fill across the exceptional edge.
3344 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3345 const Function *CallerFn = MF.getFunction();
3346 EHPersonality Pers =
3347 CallerFn->hasPersonalityFn()
3348 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3349 : EHPersonality::Unknown;
3350 if (isMSVCEHPersonality(Pers))
3351 Mask = RegInfo->getNoPreservedMask();
3354 Ops.push_back(DAG.getRegisterMask(Mask));
3356 if (InFlag.getNode())
3357 Ops.push_back(InFlag);
3361 //// If this is the first return lowered for this function, add the regs
3362 //// to the liveout set for the function.
3363 // This isn't right, although it's probably harmless on x86; liveouts
3364 // should be computed from returns not tail calls. Consider a void
3365 // function making a tail call to a function returning int.
3366 MF.getFrameInfo()->setHasTailCall();
3367 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3370 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3371 InFlag = Chain.getValue(1);
3373 // Create the CALLSEQ_END node.
3374 unsigned NumBytesForCalleeToPop;
3375 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3376 DAG.getTarget().Options.GuaranteedTailCallOpt))
3377 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3378 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3379 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3380 SR == StackStructReturn)
3381 // If this is a call to a struct-return function, the callee
3382 // pops the hidden struct pointer, so we have to push it back.
3383 // This is common for Darwin/X86, Linux & Mingw32 targets.
3384 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3385 NumBytesForCalleeToPop = 4;
3387 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3389 // Returns a flag for retval copy to use.
3391 Chain = DAG.getCALLSEQ_END(Chain,
3392 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3393 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3396 InFlag = Chain.getValue(1);
3399 // Handle result values, copying them out of physregs into vregs that we
3401 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3402 Ins, dl, DAG, InVals);
3405 //===----------------------------------------------------------------------===//
3406 // Fast Calling Convention (tail call) implementation
3407 //===----------------------------------------------------------------------===//
3409 // Like std call, callee cleans arguments, convention except that ECX is
3410 // reserved for storing the tail called function address. Only 2 registers are
3411 // free for argument passing (inreg). Tail call optimization is performed
3413 // * tailcallopt is enabled
3414 // * caller/callee are fastcc
3415 // On X86_64 architecture with GOT-style position independent code only local
3416 // (within module) calls are supported at the moment.
3417 // To keep the stack aligned according to platform abi the function
3418 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3419 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3420 // If a tail called function callee has more arguments than the caller the
3421 // caller needs to make sure that there is room to move the RETADDR to. This is
3422 // achieved by reserving an area the size of the argument delta right after the
3423 // original RETADDR, but before the saved framepointer or the spilled registers
3424 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3436 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3439 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3440 SelectionDAG& DAG) const {
3441 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3442 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3443 unsigned StackAlignment = TFI.getStackAlignment();
3444 uint64_t AlignMask = StackAlignment - 1;
3445 int64_t Offset = StackSize;
3446 unsigned SlotSize = RegInfo->getSlotSize();
3447 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3448 // Number smaller than 12 so just add the difference.
3449 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3451 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3452 Offset = ((~AlignMask) & Offset) + StackAlignment +
3453 (StackAlignment-SlotSize);
3458 /// Return true if the given stack call argument is already available in the
3459 /// same position (relatively) of the caller's incoming argument stack.
3461 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3462 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3463 const X86InstrInfo *TII) {
3464 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3466 if (Arg.getOpcode() == ISD::CopyFromReg) {
3467 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3468 if (!TargetRegisterInfo::isVirtualRegister(VR))
3470 MachineInstr *Def = MRI->getVRegDef(VR);
3473 if (!Flags.isByVal()) {
3474 if (!TII->isLoadFromStackSlot(Def, FI))
3477 unsigned Opcode = Def->getOpcode();
3478 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3479 Opcode == X86::LEA64_32r) &&
3480 Def->getOperand(1).isFI()) {
3481 FI = Def->getOperand(1).getIndex();
3482 Bytes = Flags.getByValSize();
3486 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3487 if (Flags.isByVal())
3488 // ByVal argument is passed in as a pointer but it's now being
3489 // dereferenced. e.g.
3490 // define @foo(%struct.X* %A) {
3491 // tail call @bar(%struct.X* byval %A)
3494 SDValue Ptr = Ld->getBasePtr();
3495 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3498 FI = FINode->getIndex();
3499 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3500 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3501 FI = FINode->getIndex();
3502 Bytes = Flags.getByValSize();
3506 assert(FI != INT_MAX);
3507 if (!MFI->isFixedObjectIndex(FI))
3509 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3512 /// Check whether the call is eligible for tail call optimization. Targets
3513 /// that want to do tail call optimization should implement this function.
3515 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3516 CallingConv::ID CalleeCC,
3518 bool isCalleeStructRet,
3519 bool isCallerStructRet,
3521 const SmallVectorImpl<ISD::OutputArg> &Outs,
3522 const SmallVectorImpl<SDValue> &OutVals,
3523 const SmallVectorImpl<ISD::InputArg> &Ins,
3524 SelectionDAG &DAG) const {
3525 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3528 // If -tailcallopt is specified, make fastcc functions tail-callable.
3529 const MachineFunction &MF = DAG.getMachineFunction();
3530 const Function *CallerF = MF.getFunction();
3532 // If the function return type is x86_fp80 and the callee return type is not,
3533 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3534 // perform a tailcall optimization here.
3535 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3538 CallingConv::ID CallerCC = CallerF->getCallingConv();
3539 bool CCMatch = CallerCC == CalleeCC;
3540 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3541 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3543 // Win64 functions have extra shadow space for argument homing. Don't do the
3544 // sibcall if the caller and callee have mismatched expectations for this
3546 if (IsCalleeWin64 != IsCallerWin64)
3549 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3550 if (IsTailCallConvention(CalleeCC) && CCMatch)
3555 // Look for obvious safe cases to perform tail call optimization that do not
3556 // require ABI changes. This is what gcc calls sibcall.
3558 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3559 // emit a special epilogue.
3560 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3561 if (RegInfo->needsStackRealignment(MF))
3564 // Also avoid sibcall optimization if either caller or callee uses struct
3565 // return semantics.
3566 if (isCalleeStructRet || isCallerStructRet)
3569 // An stdcall/thiscall caller is expected to clean up its arguments; the
3570 // callee isn't going to do that.
3571 // FIXME: this is more restrictive than needed. We could produce a tailcall
3572 // when the stack adjustment matches. For example, with a thiscall that takes
3573 // only one argument.
3574 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3575 CallerCC == CallingConv::X86_ThisCall))
3578 // Do not sibcall optimize vararg calls unless all arguments are passed via
3580 if (isVarArg && !Outs.empty()) {
3582 // Optimizing for varargs on Win64 is unlikely to be safe without
3583 // additional testing.
3584 if (IsCalleeWin64 || IsCallerWin64)
3587 SmallVector<CCValAssign, 16> ArgLocs;
3588 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3591 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3592 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3593 if (!ArgLocs[i].isRegLoc())
3597 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3598 // stack. Therefore, if it's not used by the call it is not safe to optimize
3599 // this into a sibcall.
3600 bool Unused = false;
3601 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3608 SmallVector<CCValAssign, 16> RVLocs;
3609 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3611 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3612 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3613 CCValAssign &VA = RVLocs[i];
3614 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3619 // If the calling conventions do not match, then we'd better make sure the
3620 // results are returned in the same way as what the caller expects.
3622 SmallVector<CCValAssign, 16> RVLocs1;
3623 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3625 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3627 SmallVector<CCValAssign, 16> RVLocs2;
3628 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3630 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3632 if (RVLocs1.size() != RVLocs2.size())
3634 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3635 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3637 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3639 if (RVLocs1[i].isRegLoc()) {
3640 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3643 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3649 // If the callee takes no arguments then go on to check the results of the
3651 if (!Outs.empty()) {
3652 // Check if stack adjustment is needed. For now, do not do this if any
3653 // argument is passed on the stack.
3654 SmallVector<CCValAssign, 16> ArgLocs;
3655 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3658 // Allocate shadow area for Win64
3660 CCInfo.AllocateStack(32, 8);
3662 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3663 if (CCInfo.getNextStackOffset()) {
3664 MachineFunction &MF = DAG.getMachineFunction();
3665 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3668 // Check if the arguments are already laid out in the right way as
3669 // the caller's fixed stack objects.
3670 MachineFrameInfo *MFI = MF.getFrameInfo();
3671 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3672 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3673 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3674 CCValAssign &VA = ArgLocs[i];
3675 SDValue Arg = OutVals[i];
3676 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3677 if (VA.getLocInfo() == CCValAssign::Indirect)
3679 if (!VA.isRegLoc()) {
3680 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3687 // If the tailcall address may be in a register, then make sure it's
3688 // possible to register allocate for it. In 32-bit, the call address can
3689 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3690 // callee-saved registers are restored. These happen to be the same
3691 // registers used to pass 'inreg' arguments so watch out for those.
3692 if (!Subtarget->is64Bit() &&
3693 ((!isa<GlobalAddressSDNode>(Callee) &&
3694 !isa<ExternalSymbolSDNode>(Callee)) ||
3695 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3696 unsigned NumInRegs = 0;
3697 // In PIC we need an extra register to formulate the address computation
3699 unsigned MaxInRegs =
3700 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3702 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3703 CCValAssign &VA = ArgLocs[i];
3706 unsigned Reg = VA.getLocReg();
3709 case X86::EAX: case X86::EDX: case X86::ECX:
3710 if (++NumInRegs == MaxInRegs)
3722 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3723 const TargetLibraryInfo *libInfo) const {
3724 return X86::createFastISel(funcInfo, libInfo);
3727 //===----------------------------------------------------------------------===//
3728 // Other Lowering Hooks
3729 //===----------------------------------------------------------------------===//
3731 static bool MayFoldLoad(SDValue Op) {
3732 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3735 static bool MayFoldIntoStore(SDValue Op) {
3736 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3739 static bool isTargetShuffle(unsigned Opcode) {
3741 default: return false;
3742 case X86ISD::BLENDI:
3743 case X86ISD::PSHUFB:
3744 case X86ISD::PSHUFD:
3745 case X86ISD::PSHUFHW:
3746 case X86ISD::PSHUFLW:
3748 case X86ISD::PALIGNR:
3749 case X86ISD::MOVLHPS:
3750 case X86ISD::MOVLHPD:
3751 case X86ISD::MOVHLPS:
3752 case X86ISD::MOVLPS:
3753 case X86ISD::MOVLPD:
3754 case X86ISD::MOVSHDUP:
3755 case X86ISD::MOVSLDUP:
3756 case X86ISD::MOVDDUP:
3759 case X86ISD::UNPCKL:
3760 case X86ISD::UNPCKH:
3761 case X86ISD::VPERMILPI:
3762 case X86ISD::VPERM2X128:
3763 case X86ISD::VPERMI:
3768 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3769 SDValue V1, unsigned TargetMask,
3770 SelectionDAG &DAG) {
3772 default: llvm_unreachable("Unknown x86 shuffle node");
3773 case X86ISD::PSHUFD:
3774 case X86ISD::PSHUFHW:
3775 case X86ISD::PSHUFLW:
3776 case X86ISD::VPERMILPI:
3777 case X86ISD::VPERMI:
3778 return DAG.getNode(Opc, dl, VT, V1,
3779 DAG.getConstant(TargetMask, dl, MVT::i8));
3783 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3784 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3786 default: llvm_unreachable("Unknown x86 shuffle node");
3787 case X86ISD::MOVLHPS:
3788 case X86ISD::MOVLHPD:
3789 case X86ISD::MOVHLPS:
3790 case X86ISD::MOVLPS:
3791 case X86ISD::MOVLPD:
3794 case X86ISD::UNPCKL:
3795 case X86ISD::UNPCKH:
3796 return DAG.getNode(Opc, dl, VT, V1, V2);
3800 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3801 MachineFunction &MF = DAG.getMachineFunction();
3802 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3803 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3804 int ReturnAddrIndex = FuncInfo->getRAIndex();
3806 if (ReturnAddrIndex == 0) {
3807 // Set up a frame object for the return address.
3808 unsigned SlotSize = RegInfo->getSlotSize();
3809 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3812 FuncInfo->setRAIndex(ReturnAddrIndex);
3815 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3818 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3819 bool hasSymbolicDisplacement) {
3820 // Offset should fit into 32 bit immediate field.
3821 if (!isInt<32>(Offset))
3824 // If we don't have a symbolic displacement - we don't have any extra
3826 if (!hasSymbolicDisplacement)
3829 // FIXME: Some tweaks might be needed for medium code model.
3830 if (M != CodeModel::Small && M != CodeModel::Kernel)
3833 // For small code model we assume that latest object is 16MB before end of 31
3834 // bits boundary. We may also accept pretty large negative constants knowing
3835 // that all objects are in the positive half of address space.
3836 if (M == CodeModel::Small && Offset < 16*1024*1024)
3839 // For kernel code model we know that all object resist in the negative half
3840 // of 32bits address space. We may not accept negative offsets, since they may
3841 // be just off and we may accept pretty large positive ones.
3842 if (M == CodeModel::Kernel && Offset >= 0)
3848 /// Determines whether the callee is required to pop its own arguments.
3849 /// Callee pop is necessary to support tail calls.
3850 bool X86::isCalleePop(CallingConv::ID CallingConv,
3851 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3852 switch (CallingConv) {
3855 case CallingConv::X86_StdCall:
3856 case CallingConv::X86_FastCall:
3857 case CallingConv::X86_ThisCall:
3859 case CallingConv::Fast:
3860 case CallingConv::GHC:
3861 case CallingConv::HiPE:
3868 /// \brief Return true if the condition is an unsigned comparison operation.
3869 static bool isX86CCUnsigned(unsigned X86CC) {
3871 default: llvm_unreachable("Invalid integer condition!");
3872 case X86::COND_E: return true;
3873 case X86::COND_G: return false;
3874 case X86::COND_GE: return false;
3875 case X86::COND_L: return false;
3876 case X86::COND_LE: return false;
3877 case X86::COND_NE: return true;
3878 case X86::COND_B: return true;
3879 case X86::COND_A: return true;
3880 case X86::COND_BE: return true;
3881 case X86::COND_AE: return true;
3883 llvm_unreachable("covered switch fell through?!");
3886 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3887 /// condition code, returning the condition code and the LHS/RHS of the
3888 /// comparison to make.
3889 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3890 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3892 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3893 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3894 // X > -1 -> X == 0, jump !sign.
3895 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3896 return X86::COND_NS;
3898 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3899 // X < 0 -> X == 0, jump on sign.
3902 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3904 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3905 return X86::COND_LE;
3909 switch (SetCCOpcode) {
3910 default: llvm_unreachable("Invalid integer condition!");
3911 case ISD::SETEQ: return X86::COND_E;
3912 case ISD::SETGT: return X86::COND_G;
3913 case ISD::SETGE: return X86::COND_GE;
3914 case ISD::SETLT: return X86::COND_L;
3915 case ISD::SETLE: return X86::COND_LE;
3916 case ISD::SETNE: return X86::COND_NE;
3917 case ISD::SETULT: return X86::COND_B;
3918 case ISD::SETUGT: return X86::COND_A;
3919 case ISD::SETULE: return X86::COND_BE;
3920 case ISD::SETUGE: return X86::COND_AE;
3924 // First determine if it is required or is profitable to flip the operands.
3926 // If LHS is a foldable load, but RHS is not, flip the condition.
3927 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3928 !ISD::isNON_EXTLoad(RHS.getNode())) {
3929 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3930 std::swap(LHS, RHS);
3933 switch (SetCCOpcode) {
3939 std::swap(LHS, RHS);
3943 // On a floating point condition, the flags are set as follows:
3945 // 0 | 0 | 0 | X > Y
3946 // 0 | 0 | 1 | X < Y
3947 // 1 | 0 | 0 | X == Y
3948 // 1 | 1 | 1 | unordered
3949 switch (SetCCOpcode) {
3950 default: llvm_unreachable("Condcode should be pre-legalized away");
3952 case ISD::SETEQ: return X86::COND_E;
3953 case ISD::SETOLT: // flipped
3955 case ISD::SETGT: return X86::COND_A;
3956 case ISD::SETOLE: // flipped
3958 case ISD::SETGE: return X86::COND_AE;
3959 case ISD::SETUGT: // flipped
3961 case ISD::SETLT: return X86::COND_B;
3962 case ISD::SETUGE: // flipped
3964 case ISD::SETLE: return X86::COND_BE;
3966 case ISD::SETNE: return X86::COND_NE;
3967 case ISD::SETUO: return X86::COND_P;
3968 case ISD::SETO: return X86::COND_NP;
3970 case ISD::SETUNE: return X86::COND_INVALID;
3974 /// Is there a floating point cmov for the specific X86 condition code?
3975 /// Current x86 isa includes the following FP cmov instructions:
3976 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3977 static bool hasFPCMov(unsigned X86CC) {
3993 /// Returns true if the target can instruction select the
3994 /// specified FP immediate natively. If false, the legalizer will
3995 /// materialize the FP immediate as a load from a constant pool.
3996 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3997 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3998 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4004 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4005 ISD::LoadExtType ExtTy,
4007 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4008 // relocation target a movq or addq instruction: don't let the load shrink.
4009 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4010 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4011 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4012 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4016 /// \brief Returns true if it is beneficial to convert a load of a constant
4017 /// to just the constant itself.
4018 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4020 assert(Ty->isIntegerTy());
4022 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4023 if (BitSize == 0 || BitSize > 64)
4028 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4029 unsigned Index) const {
4030 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4033 return (Index == 0 || Index == ResVT.getVectorNumElements());
4036 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4037 // Speculate cttz only if we can directly use TZCNT.
4038 return Subtarget->hasBMI();
4041 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4042 // Speculate ctlz only if we can directly use LZCNT.
4043 return Subtarget->hasLZCNT();
4046 /// Return true if every element in Mask, beginning
4047 /// from position Pos and ending in Pos+Size is undef.
4048 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4049 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4055 /// Return true if Val is undef or if its value falls within the
4056 /// specified range (L, H].
4057 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4058 return (Val < 0) || (Val >= Low && Val < Hi);
4061 /// Val is either less than zero (undef) or equal to the specified value.
4062 static bool isUndefOrEqual(int Val, int CmpVal) {
4063 return (Val < 0 || Val == CmpVal);
4066 /// Return true if every element in Mask, beginning
4067 /// from position Pos and ending in Pos+Size, falls within the specified
4068 /// sequential range (Low, Low+Size]. or is undef.
4069 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4070 unsigned Pos, unsigned Size, int Low) {
4071 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4072 if (!isUndefOrEqual(Mask[i], Low))
4077 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4078 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4079 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4080 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4081 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4084 // The index should be aligned on a vecWidth-bit boundary.
4086 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4088 MVT VT = N->getSimpleValueType(0);
4089 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4090 bool Result = (Index * ElSize) % vecWidth == 0;
4095 /// Return true if the specified INSERT_SUBVECTOR
4096 /// operand specifies a subvector insert that is suitable for input to
4097 /// insertion of 128 or 256-bit subvectors
4098 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4099 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4100 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4102 // The index should be aligned on a vecWidth-bit boundary.
4104 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4106 MVT VT = N->getSimpleValueType(0);
4107 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4108 bool Result = (Index * ElSize) % vecWidth == 0;
4113 bool X86::isVINSERT128Index(SDNode *N) {
4114 return isVINSERTIndex(N, 128);
4117 bool X86::isVINSERT256Index(SDNode *N) {
4118 return isVINSERTIndex(N, 256);
4121 bool X86::isVEXTRACT128Index(SDNode *N) {
4122 return isVEXTRACTIndex(N, 128);
4125 bool X86::isVEXTRACT256Index(SDNode *N) {
4126 return isVEXTRACTIndex(N, 256);
4129 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4130 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4131 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4132 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4135 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4137 MVT VecVT = N->getOperand(0).getSimpleValueType();
4138 MVT ElVT = VecVT.getVectorElementType();
4140 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4141 return Index / NumElemsPerChunk;
4144 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4145 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4146 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4147 llvm_unreachable("Illegal insert subvector for VINSERT");
4150 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4152 MVT VecVT = N->getSimpleValueType(0);
4153 MVT ElVT = VecVT.getVectorElementType();
4155 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4156 return Index / NumElemsPerChunk;
4159 /// Return the appropriate immediate to extract the specified
4160 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4161 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4162 return getExtractVEXTRACTImmediate(N, 128);
4165 /// Return the appropriate immediate to extract the specified
4166 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4167 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4168 return getExtractVEXTRACTImmediate(N, 256);
4171 /// Return the appropriate immediate to insert at the specified
4172 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4173 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4174 return getInsertVINSERTImmediate(N, 128);
4177 /// Return the appropriate immediate to insert at the specified
4178 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4179 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4180 return getInsertVINSERTImmediate(N, 256);
4183 /// Returns true if Elt is a constant integer zero
4184 static bool isZero(SDValue V) {
4185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4186 return C && C->isNullValue();
4189 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4190 bool X86::isZeroNode(SDValue Elt) {
4193 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4194 return CFP->getValueAPF().isPosZero();
4198 /// Returns a vector of specified type with all zero elements.
4199 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4200 SelectionDAG &DAG, SDLoc dl) {
4201 assert(VT.isVector() && "Expected a vector type");
4203 // Always build SSE zero vectors as <4 x i32> bitcasted
4204 // to their dest type. This ensures they get CSE'd.
4206 if (VT.is128BitVector()) { // SSE
4207 if (Subtarget->hasSSE2()) { // SSE2
4208 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4209 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4211 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4212 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4214 } else if (VT.is256BitVector()) { // AVX
4215 if (Subtarget->hasInt256()) { // AVX2
4216 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4217 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4218 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4220 // 256-bit logic and arithmetic instructions in AVX are all
4221 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4222 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4223 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4224 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4226 } else if (VT.is512BitVector()) { // AVX-512
4227 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4228 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4229 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4230 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4231 } else if (VT.getScalarType() == MVT::i1) {
4233 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4234 && "Unexpected vector type");
4235 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4236 && "Unexpected vector type");
4237 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4238 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4239 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4241 llvm_unreachable("Unexpected vector type");
4243 return DAG.getBitcast(VT, Vec);
4246 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4247 SelectionDAG &DAG, SDLoc dl,
4248 unsigned vectorWidth) {
4249 assert((vectorWidth == 128 || vectorWidth == 256) &&
4250 "Unsupported vector width");
4251 EVT VT = Vec.getValueType();
4252 EVT ElVT = VT.getVectorElementType();
4253 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4254 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4255 VT.getVectorNumElements()/Factor);
4257 // Extract from UNDEF is UNDEF.
4258 if (Vec.getOpcode() == ISD::UNDEF)
4259 return DAG.getUNDEF(ResultVT);
4261 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4262 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4264 // This is the index of the first element of the vectorWidth-bit chunk
4266 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4269 // If the input is a buildvector just emit a smaller one.
4270 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4271 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4272 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4275 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4276 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4279 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4280 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4281 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4282 /// instructions or a simple subregister reference. Idx is an index in the
4283 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4284 /// lowering EXTRACT_VECTOR_ELT operations easier.
4285 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4286 SelectionDAG &DAG, SDLoc dl) {
4287 assert((Vec.getValueType().is256BitVector() ||
4288 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4289 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4292 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4293 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4294 SelectionDAG &DAG, SDLoc dl) {
4295 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4296 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4299 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4300 unsigned IdxVal, SelectionDAG &DAG,
4301 SDLoc dl, unsigned vectorWidth) {
4302 assert((vectorWidth == 128 || vectorWidth == 256) &&
4303 "Unsupported vector width");
4304 // Inserting UNDEF is Result
4305 if (Vec.getOpcode() == ISD::UNDEF)
4307 EVT VT = Vec.getValueType();
4308 EVT ElVT = VT.getVectorElementType();
4309 EVT ResultVT = Result.getValueType();
4311 // Insert the relevant vectorWidth bits.
4312 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4314 // This is the index of the first element of the vectorWidth-bit chunk
4316 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4319 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4320 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4323 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4324 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4325 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4326 /// simple superregister reference. Idx is an index in the 128 bits
4327 /// we want. It need not be aligned to a 128-bit boundary. That makes
4328 /// lowering INSERT_VECTOR_ELT operations easier.
4329 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4330 SelectionDAG &DAG, SDLoc dl) {
4331 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4333 // For insertion into the zero index (low half) of a 256-bit vector, it is
4334 // more efficient to generate a blend with immediate instead of an insert*128.
4335 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4336 // extend the subvector to the size of the result vector. Make sure that
4337 // we are not recursing on that node by checking for undef here.
4338 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4339 Result.getOpcode() != ISD::UNDEF) {
4340 EVT ResultVT = Result.getValueType();
4341 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4342 SDValue Undef = DAG.getUNDEF(ResultVT);
4343 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4346 // The blend instruction, and therefore its mask, depend on the data type.
4347 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4348 if (ScalarType.isFloatingPoint()) {
4349 // Choose either vblendps (float) or vblendpd (double).
4350 unsigned ScalarSize = ScalarType.getSizeInBits();
4351 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4352 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4353 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4354 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4357 const X86Subtarget &Subtarget =
4358 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4360 // AVX2 is needed for 256-bit integer blend support.
4361 // Integers must be cast to 32-bit because there is only vpblendd;
4362 // vpblendw can't be used for this because it has a handicapped mask.
4364 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4365 // is still more efficient than using the wrong domain vinsertf128 that
4366 // will be created by InsertSubVector().
4367 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4369 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4370 Vec256 = DAG.getBitcast(CastVT, Vec256);
4371 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4372 return DAG.getBitcast(ResultVT, Vec256);
4375 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4378 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4379 SelectionDAG &DAG, SDLoc dl) {
4380 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4381 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4384 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4385 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4386 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4387 /// large BUILD_VECTORS.
4388 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4389 unsigned NumElems, SelectionDAG &DAG,
4391 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4392 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4395 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4396 unsigned NumElems, SelectionDAG &DAG,
4398 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4399 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4402 /// Returns a vector of specified type with all bits set.
4403 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4404 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4405 /// Then bitcast to their original type, ensuring they get CSE'd.
4406 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4408 assert(VT.isVector() && "Expected a vector type");
4410 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4412 if (VT.is256BitVector()) {
4413 if (HasInt256) { // AVX2
4414 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4415 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4417 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4418 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4420 } else if (VT.is128BitVector()) {
4421 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4423 llvm_unreachable("Unexpected vector type");
4425 return DAG.getBitcast(VT, Vec);
4428 /// Returns a vector_shuffle node for an unpackl operation.
4429 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4431 unsigned NumElems = VT.getVectorNumElements();
4432 SmallVector<int, 8> Mask;
4433 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4435 Mask.push_back(i + NumElems);
4437 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4440 /// Returns a vector_shuffle node for an unpackh operation.
4441 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4443 unsigned NumElems = VT.getVectorNumElements();
4444 SmallVector<int, 8> Mask;
4445 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4446 Mask.push_back(i + Half);
4447 Mask.push_back(i + NumElems + Half);
4449 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4452 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4453 /// This produces a shuffle where the low element of V2 is swizzled into the
4454 /// zero/undef vector, landing at element Idx.
4455 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4456 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4458 const X86Subtarget *Subtarget,
4459 SelectionDAG &DAG) {
4460 MVT VT = V2.getSimpleValueType();
4462 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4463 unsigned NumElems = VT.getVectorNumElements();
4464 SmallVector<int, 16> MaskVec;
4465 for (unsigned i = 0; i != NumElems; ++i)
4466 // If this is the insertion idx, put the low elt of V2 here.
4467 MaskVec.push_back(i == Idx ? NumElems : i);
4468 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4471 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4472 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4473 /// uses one source. Note that this will set IsUnary for shuffles which use a
4474 /// single input multiple times, and in those cases it will
4475 /// adjust the mask to only have indices within that single input.
4476 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4477 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4478 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4479 unsigned NumElems = VT.getVectorNumElements();
4483 bool IsFakeUnary = false;
4484 switch(N->getOpcode()) {
4485 case X86ISD::BLENDI:
4486 ImmN = N->getOperand(N->getNumOperands()-1);
4487 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4490 ImmN = N->getOperand(N->getNumOperands()-1);
4491 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4492 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4494 case X86ISD::UNPCKH:
4495 DecodeUNPCKHMask(VT, Mask);
4496 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4498 case X86ISD::UNPCKL:
4499 DecodeUNPCKLMask(VT, Mask);
4500 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4502 case X86ISD::MOVHLPS:
4503 DecodeMOVHLPSMask(NumElems, Mask);
4504 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4506 case X86ISD::MOVLHPS:
4507 DecodeMOVLHPSMask(NumElems, Mask);
4508 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4510 case X86ISD::PALIGNR:
4511 ImmN = N->getOperand(N->getNumOperands()-1);
4512 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4514 case X86ISD::PSHUFD:
4515 case X86ISD::VPERMILPI:
4516 ImmN = N->getOperand(N->getNumOperands()-1);
4517 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4520 case X86ISD::PSHUFHW:
4521 ImmN = N->getOperand(N->getNumOperands()-1);
4522 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4525 case X86ISD::PSHUFLW:
4526 ImmN = N->getOperand(N->getNumOperands()-1);
4527 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4530 case X86ISD::PSHUFB: {
4532 SDValue MaskNode = N->getOperand(1);
4533 while (MaskNode->getOpcode() == ISD::BITCAST)
4534 MaskNode = MaskNode->getOperand(0);
4536 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4537 // If we have a build-vector, then things are easy.
4538 EVT VT = MaskNode.getValueType();
4539 assert(VT.isVector() &&
4540 "Can't produce a non-vector with a build_vector!");
4541 if (!VT.isInteger())
4544 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4546 SmallVector<uint64_t, 32> RawMask;
4547 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4548 SDValue Op = MaskNode->getOperand(i);
4549 if (Op->getOpcode() == ISD::UNDEF) {
4550 RawMask.push_back((uint64_t)SM_SentinelUndef);
4553 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4556 APInt MaskElement = CN->getAPIntValue();
4558 // We now have to decode the element which could be any integer size and
4559 // extract each byte of it.
4560 for (int j = 0; j < NumBytesPerElement; ++j) {
4561 // Note that this is x86 and so always little endian: the low byte is
4562 // the first byte of the mask.
4563 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4564 MaskElement = MaskElement.lshr(8);
4567 DecodePSHUFBMask(RawMask, Mask);
4571 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4575 SDValue Ptr = MaskLoad->getBasePtr();
4576 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4577 Ptr->getOpcode() == X86ISD::WrapperRIP)
4578 Ptr = Ptr->getOperand(0);
4580 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4581 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4584 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4585 DecodePSHUFBMask(C, Mask);
4593 case X86ISD::VPERMI:
4594 ImmN = N->getOperand(N->getNumOperands()-1);
4595 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4600 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4602 case X86ISD::VPERM2X128:
4603 ImmN = N->getOperand(N->getNumOperands()-1);
4604 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4605 if (Mask.empty()) return false;
4606 // Mask only contains negative index if an element is zero.
4607 if (std::any_of(Mask.begin(), Mask.end(),
4608 [](int M){ return M == SM_SentinelZero; }))
4611 case X86ISD::MOVSLDUP:
4612 DecodeMOVSLDUPMask(VT, Mask);
4615 case X86ISD::MOVSHDUP:
4616 DecodeMOVSHDUPMask(VT, Mask);
4619 case X86ISD::MOVDDUP:
4620 DecodeMOVDDUPMask(VT, Mask);
4623 case X86ISD::MOVLHPD:
4624 case X86ISD::MOVLPD:
4625 case X86ISD::MOVLPS:
4626 // Not yet implemented
4628 default: llvm_unreachable("unknown target shuffle node");
4631 // If we have a fake unary shuffle, the shuffle mask is spread across two
4632 // inputs that are actually the same node. Re-map the mask to always point
4633 // into the first input.
4636 if (M >= (int)Mask.size())
4642 /// Returns the scalar element that will make up the ith
4643 /// element of the result of the vector shuffle.
4644 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4647 return SDValue(); // Limit search depth.
4649 SDValue V = SDValue(N, 0);
4650 EVT VT = V.getValueType();
4651 unsigned Opcode = V.getOpcode();
4653 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4654 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4655 int Elt = SV->getMaskElt(Index);
4658 return DAG.getUNDEF(VT.getVectorElementType());
4660 unsigned NumElems = VT.getVectorNumElements();
4661 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4662 : SV->getOperand(1);
4663 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4666 // Recurse into target specific vector shuffles to find scalars.
4667 if (isTargetShuffle(Opcode)) {
4668 MVT ShufVT = V.getSimpleValueType();
4669 unsigned NumElems = ShufVT.getVectorNumElements();
4670 SmallVector<int, 16> ShuffleMask;
4673 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4676 int Elt = ShuffleMask[Index];
4678 return DAG.getUNDEF(ShufVT.getVectorElementType());
4680 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4682 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4686 // Actual nodes that may contain scalar elements
4687 if (Opcode == ISD::BITCAST) {
4688 V = V.getOperand(0);
4689 EVT SrcVT = V.getValueType();
4690 unsigned NumElems = VT.getVectorNumElements();
4692 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4696 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4697 return (Index == 0) ? V.getOperand(0)
4698 : DAG.getUNDEF(VT.getVectorElementType());
4700 if (V.getOpcode() == ISD::BUILD_VECTOR)
4701 return V.getOperand(Index);
4706 /// Custom lower build_vector of v16i8.
4707 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4708 unsigned NumNonZero, unsigned NumZero,
4710 const X86Subtarget* Subtarget,
4711 const TargetLowering &TLI) {
4719 // SSE4.1 - use PINSRB to insert each byte directly.
4720 if (Subtarget->hasSSE41()) {
4721 for (unsigned i = 0; i < 16; ++i) {
4722 bool isNonZero = (NonZeros & (1 << i)) != 0;
4726 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4728 V = DAG.getUNDEF(MVT::v16i8);
4731 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4732 MVT::v16i8, V, Op.getOperand(i),
4733 DAG.getIntPtrConstant(i, dl));
4740 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4741 for (unsigned i = 0; i < 16; ++i) {
4742 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4743 if (ThisIsNonZero && First) {
4745 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4747 V = DAG.getUNDEF(MVT::v8i16);
4752 SDValue ThisElt, LastElt;
4753 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4754 if (LastIsNonZero) {
4755 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4756 MVT::i16, Op.getOperand(i-1));
4758 if (ThisIsNonZero) {
4759 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4760 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4761 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4763 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4767 if (ThisElt.getNode())
4768 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4769 DAG.getIntPtrConstant(i/2, dl));
4773 return DAG.getBitcast(MVT::v16i8, V);
4776 /// Custom lower build_vector of v8i16.
4777 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4778 unsigned NumNonZero, unsigned NumZero,
4780 const X86Subtarget* Subtarget,
4781 const TargetLowering &TLI) {
4788 for (unsigned i = 0; i < 8; ++i) {
4789 bool isNonZero = (NonZeros & (1 << i)) != 0;
4793 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4795 V = DAG.getUNDEF(MVT::v8i16);
4798 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4799 MVT::v8i16, V, Op.getOperand(i),
4800 DAG.getIntPtrConstant(i, dl));
4807 /// Custom lower build_vector of v4i32 or v4f32.
4808 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4809 const X86Subtarget *Subtarget,
4810 const TargetLowering &TLI) {
4811 // Find all zeroable elements.
4812 std::bitset<4> Zeroable;
4813 for (int i=0; i < 4; ++i) {
4814 SDValue Elt = Op->getOperand(i);
4815 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4817 assert(Zeroable.size() - Zeroable.count() > 1 &&
4818 "We expect at least two non-zero elements!");
4820 // We only know how to deal with build_vector nodes where elements are either
4821 // zeroable or extract_vector_elt with constant index.
4822 SDValue FirstNonZero;
4823 unsigned FirstNonZeroIdx;
4824 for (unsigned i=0; i < 4; ++i) {
4827 SDValue Elt = Op->getOperand(i);
4828 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4829 !isa<ConstantSDNode>(Elt.getOperand(1)))
4831 // Make sure that this node is extracting from a 128-bit vector.
4832 MVT VT = Elt.getOperand(0).getSimpleValueType();
4833 if (!VT.is128BitVector())
4835 if (!FirstNonZero.getNode()) {
4837 FirstNonZeroIdx = i;
4841 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4842 SDValue V1 = FirstNonZero.getOperand(0);
4843 MVT VT = V1.getSimpleValueType();
4845 // See if this build_vector can be lowered as a blend with zero.
4847 unsigned EltMaskIdx, EltIdx;
4849 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4850 if (Zeroable[EltIdx]) {
4851 // The zero vector will be on the right hand side.
4852 Mask[EltIdx] = EltIdx+4;
4856 Elt = Op->getOperand(EltIdx);
4857 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4858 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4859 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4861 Mask[EltIdx] = EltIdx;
4865 // Let the shuffle legalizer deal with blend operations.
4866 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4867 if (V1.getSimpleValueType() != VT)
4868 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4869 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4872 // See if we can lower this build_vector to a INSERTPS.
4873 if (!Subtarget->hasSSE41())
4876 SDValue V2 = Elt.getOperand(0);
4877 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4880 bool CanFold = true;
4881 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4885 SDValue Current = Op->getOperand(i);
4886 SDValue SrcVector = Current->getOperand(0);
4889 CanFold = SrcVector == V1 &&
4890 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4896 assert(V1.getNode() && "Expected at least two non-zero elements!");
4897 if (V1.getSimpleValueType() != MVT::v4f32)
4898 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4899 if (V2.getSimpleValueType() != MVT::v4f32)
4900 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4902 // Ok, we can emit an INSERTPS instruction.
4903 unsigned ZMask = Zeroable.to_ulong();
4905 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4906 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4908 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4909 DAG.getIntPtrConstant(InsertPSMask, DL));
4910 return DAG.getBitcast(VT, Result);
4913 /// Return a vector logical shift node.
4914 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4915 unsigned NumBits, SelectionDAG &DAG,
4916 const TargetLowering &TLI, SDLoc dl) {
4917 assert(VT.is128BitVector() && "Unknown type for VShift");
4918 MVT ShVT = MVT::v2i64;
4919 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4920 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4921 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4922 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4923 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4924 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4928 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4930 // Check if the scalar load can be widened into a vector load. And if
4931 // the address is "base + cst" see if the cst can be "absorbed" into
4932 // the shuffle mask.
4933 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4934 SDValue Ptr = LD->getBasePtr();
4935 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4937 EVT PVT = LD->getValueType(0);
4938 if (PVT != MVT::i32 && PVT != MVT::f32)
4943 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4944 FI = FINode->getIndex();
4946 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4947 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4948 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4949 Offset = Ptr.getConstantOperandVal(1);
4950 Ptr = Ptr.getOperand(0);
4955 // FIXME: 256-bit vector instructions don't require a strict alignment,
4956 // improve this code to support it better.
4957 unsigned RequiredAlign = VT.getSizeInBits()/8;
4958 SDValue Chain = LD->getChain();
4959 // Make sure the stack object alignment is at least 16 or 32.
4960 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4961 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4962 if (MFI->isFixedObjectIndex(FI)) {
4963 // Can't change the alignment. FIXME: It's possible to compute
4964 // the exact stack offset and reference FI + adjust offset instead.
4965 // If someone *really* cares about this. That's the way to implement it.
4968 MFI->setObjectAlignment(FI, RequiredAlign);
4972 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4973 // Ptr + (Offset & ~15).
4976 if ((Offset % RequiredAlign) & 3)
4978 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
4981 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4982 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4985 int EltNo = (Offset - StartOffset) >> 2;
4986 unsigned NumElems = VT.getVectorNumElements();
4988 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4989 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4990 LD->getPointerInfo().getWithOffset(StartOffset),
4991 false, false, false, 0);
4993 SmallVector<int, 8> Mask(NumElems, EltNo);
4995 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5001 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5002 /// elements can be replaced by a single large load which has the same value as
5003 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5005 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5007 /// FIXME: we'd also like to handle the case where the last elements are zero
5008 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5009 /// There's even a handy isZeroNode for that purpose.
5010 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5011 SDLoc &DL, SelectionDAG &DAG,
5012 bool isAfterLegalize) {
5013 unsigned NumElems = Elts.size();
5015 LoadSDNode *LDBase = nullptr;
5016 unsigned LastLoadedElt = -1U;
5018 // For each element in the initializer, see if we've found a load or an undef.
5019 // If we don't find an initial load element, or later load elements are
5020 // non-consecutive, bail out.
5021 for (unsigned i = 0; i < NumElems; ++i) {
5022 SDValue Elt = Elts[i];
5023 // Look through a bitcast.
5024 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5025 Elt = Elt.getOperand(0);
5026 if (!Elt.getNode() ||
5027 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5030 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5032 LDBase = cast<LoadSDNode>(Elt.getNode());
5036 if (Elt.getOpcode() == ISD::UNDEF)
5039 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5040 EVT LdVT = Elt.getValueType();
5041 // Each loaded element must be the correct fractional portion of the
5042 // requested vector load.
5043 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5045 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5050 // If we have found an entire vector of loads and undefs, then return a large
5051 // load of the entire vector width starting at the base pointer. If we found
5052 // consecutive loads for the low half, generate a vzext_load node.
5053 if (LastLoadedElt == NumElems - 1) {
5054 assert(LDBase && "Did not find base load for merging consecutive loads");
5055 EVT EltVT = LDBase->getValueType(0);
5056 // Ensure that the input vector size for the merged loads matches the
5057 // cumulative size of the input elements.
5058 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5061 if (isAfterLegalize &&
5062 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5065 SDValue NewLd = SDValue();
5067 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5068 LDBase->getPointerInfo(), LDBase->isVolatile(),
5069 LDBase->isNonTemporal(), LDBase->isInvariant(),
5070 LDBase->getAlignment());
5072 if (LDBase->hasAnyUseOfValue(1)) {
5073 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5075 SDValue(NewLd.getNode(), 1));
5076 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5077 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5078 SDValue(NewLd.getNode(), 1));
5084 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5085 //of a v4i32 / v4f32. It's probably worth generalizing.
5086 EVT EltVT = VT.getVectorElementType();
5087 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5088 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5089 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5090 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5092 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5093 LDBase->getPointerInfo(),
5094 LDBase->getAlignment(),
5095 false/*isVolatile*/, true/*ReadMem*/,
5098 // Make sure the newly-created LOAD is in the same position as LDBase in
5099 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5100 // update uses of LDBase's output chain to use the TokenFactor.
5101 if (LDBase->hasAnyUseOfValue(1)) {
5102 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5103 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5104 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5105 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5106 SDValue(ResNode.getNode(), 1));
5109 return DAG.getBitcast(VT, ResNode);
5114 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5115 /// to generate a splat value for the following cases:
5116 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5117 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5118 /// a scalar load, or a constant.
5119 /// The VBROADCAST node is returned when a pattern is found,
5120 /// or SDValue() otherwise.
5121 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5122 SelectionDAG &DAG) {
5123 // VBROADCAST requires AVX.
5124 // TODO: Splats could be generated for non-AVX CPUs using SSE
5125 // instructions, but there's less potential gain for only 128-bit vectors.
5126 if (!Subtarget->hasAVX())
5129 MVT VT = Op.getSimpleValueType();
5132 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5133 "Unsupported vector type for broadcast.");
5138 switch (Op.getOpcode()) {
5140 // Unknown pattern found.
5143 case ISD::BUILD_VECTOR: {
5144 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5145 BitVector UndefElements;
5146 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5148 // We need a splat of a single value to use broadcast, and it doesn't
5149 // make any sense if the value is only in one element of the vector.
5150 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5154 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5155 Ld.getOpcode() == ISD::ConstantFP);
5157 // Make sure that all of the users of a non-constant load are from the
5158 // BUILD_VECTOR node.
5159 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5164 case ISD::VECTOR_SHUFFLE: {
5165 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5167 // Shuffles must have a splat mask where the first element is
5169 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5172 SDValue Sc = Op.getOperand(0);
5173 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5174 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5176 if (!Subtarget->hasInt256())
5179 // Use the register form of the broadcast instruction available on AVX2.
5180 if (VT.getSizeInBits() >= 256)
5181 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5182 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5185 Ld = Sc.getOperand(0);
5186 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5187 Ld.getOpcode() == ISD::ConstantFP);
5189 // The scalar_to_vector node and the suspected
5190 // load node must have exactly one user.
5191 // Constants may have multiple users.
5193 // AVX-512 has register version of the broadcast
5194 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5195 Ld.getValueType().getSizeInBits() >= 32;
5196 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5203 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5204 bool IsGE256 = (VT.getSizeInBits() >= 256);
5206 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5207 // instruction to save 8 or more bytes of constant pool data.
5208 // TODO: If multiple splats are generated to load the same constant,
5209 // it may be detrimental to overall size. There needs to be a way to detect
5210 // that condition to know if this is truly a size win.
5211 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5213 // Handle broadcasting a single constant scalar from the constant pool
5215 // On Sandybridge (no AVX2), it is still better to load a constant vector
5216 // from the constant pool and not to broadcast it from a scalar.
5217 // But override that restriction when optimizing for size.
5218 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5219 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5220 EVT CVT = Ld.getValueType();
5221 assert(!CVT.isVector() && "Must not broadcast a vector type");
5223 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5224 // For size optimization, also splat v2f64 and v2i64, and for size opt
5225 // with AVX2, also splat i8 and i16.
5226 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5227 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5228 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5229 const Constant *C = nullptr;
5230 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5231 C = CI->getConstantIntValue();
5232 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5233 C = CF->getConstantFPValue();
5235 assert(C && "Invalid constant type");
5237 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5239 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5240 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5242 CVT, dl, DAG.getEntryNode(), CP,
5243 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5244 false, false, Alignment);
5246 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5250 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5252 // Handle AVX2 in-register broadcasts.
5253 if (!IsLoad && Subtarget->hasInt256() &&
5254 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5255 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5257 // The scalar source must be a normal load.
5261 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5262 (Subtarget->hasVLX() && ScalarSize == 64))
5263 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5265 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5266 // double since there is no vbroadcastsd xmm
5267 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5268 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5269 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5272 // Unsupported broadcast.
5276 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5277 /// underlying vector and index.
5279 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5281 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5283 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5284 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5287 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5289 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5291 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5292 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5295 // In this case the vector is the extract_subvector expression and the index
5296 // is 2, as specified by the shuffle.
5297 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5298 SDValue ShuffleVec = SVOp->getOperand(0);
5299 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5300 assert(ShuffleVecVT.getVectorElementType() ==
5301 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5303 int ShuffleIdx = SVOp->getMaskElt(Idx);
5304 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5305 ExtractedFromVec = ShuffleVec;
5311 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5312 MVT VT = Op.getSimpleValueType();
5314 // Skip if insert_vec_elt is not supported.
5315 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5316 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5320 unsigned NumElems = Op.getNumOperands();
5324 SmallVector<unsigned, 4> InsertIndices;
5325 SmallVector<int, 8> Mask(NumElems, -1);
5327 for (unsigned i = 0; i != NumElems; ++i) {
5328 unsigned Opc = Op.getOperand(i).getOpcode();
5330 if (Opc == ISD::UNDEF)
5333 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5334 // Quit if more than 1 elements need inserting.
5335 if (InsertIndices.size() > 1)
5338 InsertIndices.push_back(i);
5342 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5343 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5344 // Quit if non-constant index.
5345 if (!isa<ConstantSDNode>(ExtIdx))
5347 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5349 // Quit if extracted from vector of different type.
5350 if (ExtractedFromVec.getValueType() != VT)
5353 if (!VecIn1.getNode())
5354 VecIn1 = ExtractedFromVec;
5355 else if (VecIn1 != ExtractedFromVec) {
5356 if (!VecIn2.getNode())
5357 VecIn2 = ExtractedFromVec;
5358 else if (VecIn2 != ExtractedFromVec)
5359 // Quit if more than 2 vectors to shuffle
5363 if (ExtractedFromVec == VecIn1)
5365 else if (ExtractedFromVec == VecIn2)
5366 Mask[i] = Idx + NumElems;
5369 if (!VecIn1.getNode())
5372 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5373 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5374 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5375 unsigned Idx = InsertIndices[i];
5376 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5377 DAG.getIntPtrConstant(Idx, DL));
5383 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5384 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5385 Op.getScalarValueSizeInBits() == 1 &&
5386 "Can not convert non-constant vector");
5387 uint64_t Immediate = 0;
5388 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5389 SDValue In = Op.getOperand(idx);
5390 if (In.getOpcode() != ISD::UNDEF)
5391 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5395 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5396 return DAG.getConstant(Immediate, dl, VT);
5398 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5400 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5402 MVT VT = Op.getSimpleValueType();
5403 assert((VT.getVectorElementType() == MVT::i1) &&
5404 "Unexpected type in LowerBUILD_VECTORvXi1!");
5407 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5408 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5409 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5410 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5413 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5414 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5415 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5416 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5419 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5420 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5421 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5422 return DAG.getBitcast(VT, Imm);
5423 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5424 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5425 DAG.getIntPtrConstant(0, dl));
5428 // Vector has one or more non-const elements
5429 uint64_t Immediate = 0;
5430 SmallVector<unsigned, 16> NonConstIdx;
5431 bool IsSplat = true;
5432 bool HasConstElts = false;
5434 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5435 SDValue In = Op.getOperand(idx);
5436 if (In.getOpcode() == ISD::UNDEF)
5438 if (!isa<ConstantSDNode>(In))
5439 NonConstIdx.push_back(idx);
5441 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5442 HasConstElts = true;
5446 else if (In != Op.getOperand(SplatIdx))
5450 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5452 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5453 DAG.getConstant(1, dl, VT),
5454 DAG.getConstant(0, dl, VT));
5456 // insert elements one by one
5460 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5461 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5463 else if (HasConstElts)
5464 Imm = DAG.getConstant(0, dl, VT);
5466 Imm = DAG.getUNDEF(VT);
5467 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5468 DstVec = DAG.getBitcast(VT, Imm);
5470 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5471 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5472 DAG.getIntPtrConstant(0, dl));
5475 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5476 unsigned InsertIdx = NonConstIdx[i];
5477 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5478 Op.getOperand(InsertIdx),
5479 DAG.getIntPtrConstant(InsertIdx, dl));
5484 /// \brief Return true if \p N implements a horizontal binop and return the
5485 /// operands for the horizontal binop into V0 and V1.
5487 /// This is a helper function of LowerToHorizontalOp().
5488 /// This function checks that the build_vector \p N in input implements a
5489 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5490 /// operation to match.
5491 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5492 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5493 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5496 /// This function only analyzes elements of \p N whose indices are
5497 /// in range [BaseIdx, LastIdx).
5498 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5500 unsigned BaseIdx, unsigned LastIdx,
5501 SDValue &V0, SDValue &V1) {
5502 EVT VT = N->getValueType(0);
5504 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5505 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5506 "Invalid Vector in input!");
5508 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5509 bool CanFold = true;
5510 unsigned ExpectedVExtractIdx = BaseIdx;
5511 unsigned NumElts = LastIdx - BaseIdx;
5512 V0 = DAG.getUNDEF(VT);
5513 V1 = DAG.getUNDEF(VT);
5515 // Check if N implements a horizontal binop.
5516 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5517 SDValue Op = N->getOperand(i + BaseIdx);
5520 if (Op->getOpcode() == ISD::UNDEF) {
5521 // Update the expected vector extract index.
5522 if (i * 2 == NumElts)
5523 ExpectedVExtractIdx = BaseIdx;
5524 ExpectedVExtractIdx += 2;
5528 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5533 SDValue Op0 = Op.getOperand(0);
5534 SDValue Op1 = Op.getOperand(1);
5536 // Try to match the following pattern:
5537 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5538 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5539 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5540 Op0.getOperand(0) == Op1.getOperand(0) &&
5541 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5542 isa<ConstantSDNode>(Op1.getOperand(1)));
5546 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5547 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5549 if (i * 2 < NumElts) {
5550 if (V0.getOpcode() == ISD::UNDEF) {
5551 V0 = Op0.getOperand(0);
5552 if (V0.getValueType() != VT)
5556 if (V1.getOpcode() == ISD::UNDEF) {
5557 V1 = Op0.getOperand(0);
5558 if (V1.getValueType() != VT)
5561 if (i * 2 == NumElts)
5562 ExpectedVExtractIdx = BaseIdx;
5565 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5566 if (I0 == ExpectedVExtractIdx)
5567 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5568 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5569 // Try to match the following dag sequence:
5570 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5571 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5575 ExpectedVExtractIdx += 2;
5581 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5582 /// a concat_vector.
5584 /// This is a helper function of LowerToHorizontalOp().
5585 /// This function expects two 256-bit vectors called V0 and V1.
5586 /// At first, each vector is split into two separate 128-bit vectors.
5587 /// Then, the resulting 128-bit vectors are used to implement two
5588 /// horizontal binary operations.
5590 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5592 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5593 /// the two new horizontal binop.
5594 /// When Mode is set, the first horizontal binop dag node would take as input
5595 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5596 /// horizontal binop dag node would take as input the lower 128-bit of V1
5597 /// and the upper 128-bit of V1.
5599 /// HADD V0_LO, V0_HI
5600 /// HADD V1_LO, V1_HI
5602 /// Otherwise, the first horizontal binop dag node takes as input the lower
5603 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5604 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5606 /// HADD V0_LO, V1_LO
5607 /// HADD V0_HI, V1_HI
5609 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5610 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5611 /// the upper 128-bits of the result.
5612 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5613 SDLoc DL, SelectionDAG &DAG,
5614 unsigned X86Opcode, bool Mode,
5615 bool isUndefLO, bool isUndefHI) {
5616 EVT VT = V0.getValueType();
5617 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5618 "Invalid nodes in input!");
5620 unsigned NumElts = VT.getVectorNumElements();
5621 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5622 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5623 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5624 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5625 EVT NewVT = V0_LO.getValueType();
5627 SDValue LO = DAG.getUNDEF(NewVT);
5628 SDValue HI = DAG.getUNDEF(NewVT);
5631 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5632 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5633 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5634 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5635 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5637 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5638 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5639 V1_LO->getOpcode() != ISD::UNDEF))
5640 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5642 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5643 V1_HI->getOpcode() != ISD::UNDEF))
5644 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5647 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5650 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5652 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5653 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5654 EVT VT = BV->getValueType(0);
5655 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5656 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5660 unsigned NumElts = VT.getVectorNumElements();
5661 SDValue InVec0 = DAG.getUNDEF(VT);
5662 SDValue InVec1 = DAG.getUNDEF(VT);
5664 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5665 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5667 // Odd-numbered elements in the input build vector are obtained from
5668 // adding two integer/float elements.
5669 // Even-numbered elements in the input build vector are obtained from
5670 // subtracting two integer/float elements.
5671 unsigned ExpectedOpcode = ISD::FSUB;
5672 unsigned NextExpectedOpcode = ISD::FADD;
5673 bool AddFound = false;
5674 bool SubFound = false;
5676 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5677 SDValue Op = BV->getOperand(i);
5679 // Skip 'undef' values.
5680 unsigned Opcode = Op.getOpcode();
5681 if (Opcode == ISD::UNDEF) {
5682 std::swap(ExpectedOpcode, NextExpectedOpcode);
5686 // Early exit if we found an unexpected opcode.
5687 if (Opcode != ExpectedOpcode)
5690 SDValue Op0 = Op.getOperand(0);
5691 SDValue Op1 = Op.getOperand(1);
5693 // Try to match the following pattern:
5694 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5695 // Early exit if we cannot match that sequence.
5696 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5697 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5698 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5699 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5700 Op0.getOperand(1) != Op1.getOperand(1))
5703 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5707 // We found a valid add/sub node. Update the information accordingly.
5713 // Update InVec0 and InVec1.
5714 if (InVec0.getOpcode() == ISD::UNDEF) {
5715 InVec0 = Op0.getOperand(0);
5716 if (InVec0.getValueType() != VT)
5719 if (InVec1.getOpcode() == ISD::UNDEF) {
5720 InVec1 = Op1.getOperand(0);
5721 if (InVec1.getValueType() != VT)
5725 // Make sure that operands in input to each add/sub node always
5726 // come from a same pair of vectors.
5727 if (InVec0 != Op0.getOperand(0)) {
5728 if (ExpectedOpcode == ISD::FSUB)
5731 // FADD is commutable. Try to commute the operands
5732 // and then test again.
5733 std::swap(Op0, Op1);
5734 if (InVec0 != Op0.getOperand(0))
5738 if (InVec1 != Op1.getOperand(0))
5741 // Update the pair of expected opcodes.
5742 std::swap(ExpectedOpcode, NextExpectedOpcode);
5745 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5746 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5747 InVec1.getOpcode() != ISD::UNDEF)
5748 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5753 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5754 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5755 const X86Subtarget *Subtarget,
5756 SelectionDAG &DAG) {
5757 EVT VT = BV->getValueType(0);
5758 unsigned NumElts = VT.getVectorNumElements();
5759 unsigned NumUndefsLO = 0;
5760 unsigned NumUndefsHI = 0;
5761 unsigned Half = NumElts/2;
5763 // Count the number of UNDEF operands in the build_vector in input.
5764 for (unsigned i = 0, e = Half; i != e; ++i)
5765 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5768 for (unsigned i = Half, e = NumElts; i != e; ++i)
5769 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5772 // Early exit if this is either a build_vector of all UNDEFs or all the
5773 // operands but one are UNDEF.
5774 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5778 SDValue InVec0, InVec1;
5779 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5780 // Try to match an SSE3 float HADD/HSUB.
5781 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5782 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5784 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5785 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5786 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5787 // Try to match an SSSE3 integer HADD/HSUB.
5788 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5789 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5791 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5792 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5795 if (!Subtarget->hasAVX())
5798 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5799 // Try to match an AVX horizontal add/sub of packed single/double
5800 // precision floating point values from 256-bit vectors.
5801 SDValue InVec2, InVec3;
5802 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5803 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5804 ((InVec0.getOpcode() == ISD::UNDEF ||
5805 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5806 ((InVec1.getOpcode() == ISD::UNDEF ||
5807 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5808 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5810 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5811 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5812 ((InVec0.getOpcode() == ISD::UNDEF ||
5813 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5814 ((InVec1.getOpcode() == ISD::UNDEF ||
5815 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5816 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5817 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5818 // Try to match an AVX2 horizontal add/sub of signed integers.
5819 SDValue InVec2, InVec3;
5821 bool CanFold = true;
5823 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5824 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5825 ((InVec0.getOpcode() == ISD::UNDEF ||
5826 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5827 ((InVec1.getOpcode() == ISD::UNDEF ||
5828 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5829 X86Opcode = X86ISD::HADD;
5830 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5831 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5832 ((InVec0.getOpcode() == ISD::UNDEF ||
5833 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5834 ((InVec1.getOpcode() == ISD::UNDEF ||
5835 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5836 X86Opcode = X86ISD::HSUB;
5841 // Fold this build_vector into a single horizontal add/sub.
5842 // Do this only if the target has AVX2.
5843 if (Subtarget->hasAVX2())
5844 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5846 // Do not try to expand this build_vector into a pair of horizontal
5847 // add/sub if we can emit a pair of scalar add/sub.
5848 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5851 // Convert this build_vector into a pair of horizontal binop followed by
5853 bool isUndefLO = NumUndefsLO == Half;
5854 bool isUndefHI = NumUndefsHI == Half;
5855 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5856 isUndefLO, isUndefHI);
5860 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5861 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5863 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5864 X86Opcode = X86ISD::HADD;
5865 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5866 X86Opcode = X86ISD::HSUB;
5867 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5868 X86Opcode = X86ISD::FHADD;
5869 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5870 X86Opcode = X86ISD::FHSUB;
5874 // Don't try to expand this build_vector into a pair of horizontal add/sub
5875 // if we can simply emit a pair of scalar add/sub.
5876 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5879 // Convert this build_vector into two horizontal add/sub followed by
5881 bool isUndefLO = NumUndefsLO == Half;
5882 bool isUndefHI = NumUndefsHI == Half;
5883 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5884 isUndefLO, isUndefHI);
5891 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5894 MVT VT = Op.getSimpleValueType();
5895 MVT ExtVT = VT.getVectorElementType();
5896 unsigned NumElems = Op.getNumOperands();
5898 // Generate vectors for predicate vectors.
5899 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5900 return LowerBUILD_VECTORvXi1(Op, DAG);
5902 // Vectors containing all zeros can be matched by pxor and xorps later
5903 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5904 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5905 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5906 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5909 return getZeroVector(VT, Subtarget, DAG, dl);
5912 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5913 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5914 // vpcmpeqd on 256-bit vectors.
5915 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5916 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5919 if (!VT.is512BitVector())
5920 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5923 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5924 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5926 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5927 return HorizontalOp;
5928 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5931 unsigned EVTBits = ExtVT.getSizeInBits();
5933 unsigned NumZero = 0;
5934 unsigned NumNonZero = 0;
5935 unsigned NonZeros = 0;
5936 bool IsAllConstants = true;
5937 SmallSet<SDValue, 8> Values;
5938 for (unsigned i = 0; i < NumElems; ++i) {
5939 SDValue Elt = Op.getOperand(i);
5940 if (Elt.getOpcode() == ISD::UNDEF)
5943 if (Elt.getOpcode() != ISD::Constant &&
5944 Elt.getOpcode() != ISD::ConstantFP)
5945 IsAllConstants = false;
5946 if (X86::isZeroNode(Elt))
5949 NonZeros |= (1 << i);
5954 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5955 if (NumNonZero == 0)
5956 return DAG.getUNDEF(VT);
5958 // Special case for single non-zero, non-undef, element.
5959 if (NumNonZero == 1) {
5960 unsigned Idx = countTrailingZeros(NonZeros);
5961 SDValue Item = Op.getOperand(Idx);
5963 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5964 // the value are obviously zero, truncate the value to i32 and do the
5965 // insertion that way. Only do this if the value is non-constant or if the
5966 // value is a constant being inserted into element 0. It is cheaper to do
5967 // a constant pool load than it is to do a movd + shuffle.
5968 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5969 (!IsAllConstants || Idx == 0)) {
5970 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5972 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5973 EVT VecVT = MVT::v4i32;
5975 // Truncate the value (which may itself be a constant) to i32, and
5976 // convert it to a vector with movd (S2V+shuffle to zero extend).
5977 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5978 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5979 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5980 Item, Idx * 2, true, Subtarget, DAG));
5984 // If we have a constant or non-constant insertion into the low element of
5985 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5986 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5987 // depending on what the source datatype is.
5990 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5992 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5993 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5994 if (VT.is512BitVector()) {
5995 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5996 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5997 Item, DAG.getIntPtrConstant(0, dl));
5999 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6000 "Expected an SSE value type!");
6001 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6002 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6003 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6006 // We can't directly insert an i8 or i16 into a vector, so zero extend
6008 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6009 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6010 if (VT.is256BitVector()) {
6011 if (Subtarget->hasAVX()) {
6012 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6013 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6015 // Without AVX, we need to extend to a 128-bit vector and then
6016 // insert into the 256-bit vector.
6017 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6018 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6019 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6022 assert(VT.is128BitVector() && "Expected an SSE value type!");
6023 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6024 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6026 return DAG.getBitcast(VT, Item);
6030 // Is it a vector logical left shift?
6031 if (NumElems == 2 && Idx == 1 &&
6032 X86::isZeroNode(Op.getOperand(0)) &&
6033 !X86::isZeroNode(Op.getOperand(1))) {
6034 unsigned NumBits = VT.getSizeInBits();
6035 return getVShift(true, VT,
6036 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6037 VT, Op.getOperand(1)),
6038 NumBits/2, DAG, *this, dl);
6041 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6044 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6045 // is a non-constant being inserted into an element other than the low one,
6046 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6047 // movd/movss) to move this into the low element, then shuffle it into
6049 if (EVTBits == 32) {
6050 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6051 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6055 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6056 if (Values.size() == 1) {
6057 if (EVTBits == 32) {
6058 // Instead of a shuffle like this:
6059 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6060 // Check if it's possible to issue this instead.
6061 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6062 unsigned Idx = countTrailingZeros(NonZeros);
6063 SDValue Item = Op.getOperand(Idx);
6064 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6065 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6070 // A vector full of immediates; various special cases are already
6071 // handled, so this is best done with a single constant-pool load.
6075 // For AVX-length vectors, see if we can use a vector load to get all of the
6076 // elements, otherwise build the individual 128-bit pieces and use
6077 // shuffles to put them in place.
6078 if (VT.is256BitVector() || VT.is512BitVector()) {
6079 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6081 // Check for a build vector of consecutive loads.
6082 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6085 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6087 // Build both the lower and upper subvector.
6088 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6089 makeArrayRef(&V[0], NumElems/2));
6090 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6091 makeArrayRef(&V[NumElems / 2], NumElems/2));
6093 // Recreate the wider vector with the lower and upper part.
6094 if (VT.is256BitVector())
6095 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6096 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6099 // Let legalizer expand 2-wide build_vectors.
6100 if (EVTBits == 64) {
6101 if (NumNonZero == 1) {
6102 // One half is zero or undef.
6103 unsigned Idx = countTrailingZeros(NonZeros);
6104 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6105 Op.getOperand(Idx));
6106 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6111 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6112 if (EVTBits == 8 && NumElems == 16)
6113 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6117 if (EVTBits == 16 && NumElems == 8)
6118 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6122 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6123 if (EVTBits == 32 && NumElems == 4)
6124 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6127 // If element VT is == 32 bits, turn it into a number of shuffles.
6128 SmallVector<SDValue, 8> V(NumElems);
6129 if (NumElems == 4 && NumZero > 0) {
6130 for (unsigned i = 0; i < 4; ++i) {
6131 bool isZero = !(NonZeros & (1 << i));
6133 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6135 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6138 for (unsigned i = 0; i < 2; ++i) {
6139 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6142 V[i] = V[i*2]; // Must be a zero vector.
6145 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6148 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6151 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6156 bool Reverse1 = (NonZeros & 0x3) == 2;
6157 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6161 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6162 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6164 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6167 if (Values.size() > 1 && VT.is128BitVector()) {
6168 // Check for a build vector of consecutive loads.
6169 for (unsigned i = 0; i < NumElems; ++i)
6170 V[i] = Op.getOperand(i);
6172 // Check for elements which are consecutive loads.
6173 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6176 // Check for a build vector from mostly shuffle plus few inserting.
6177 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6180 // For SSE 4.1, use insertps to put the high elements into the low element.
6181 if (Subtarget->hasSSE41()) {
6183 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6184 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6186 Result = DAG.getUNDEF(VT);
6188 for (unsigned i = 1; i < NumElems; ++i) {
6189 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6190 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6191 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6196 // Otherwise, expand into a number of unpckl*, start by extending each of
6197 // our (non-undef) elements to the full vector width with the element in the
6198 // bottom slot of the vector (which generates no code for SSE).
6199 for (unsigned i = 0; i < NumElems; ++i) {
6200 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6201 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6203 V[i] = DAG.getUNDEF(VT);
6206 // Next, we iteratively mix elements, e.g. for v4f32:
6207 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6208 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6209 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6210 unsigned EltStride = NumElems >> 1;
6211 while (EltStride != 0) {
6212 for (unsigned i = 0; i < EltStride; ++i) {
6213 // If V[i+EltStride] is undef and this is the first round of mixing,
6214 // then it is safe to just drop this shuffle: V[i] is already in the
6215 // right place, the one element (since it's the first round) being
6216 // inserted as undef can be dropped. This isn't safe for successive
6217 // rounds because they will permute elements within both vectors.
6218 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6219 EltStride == NumElems/2)
6222 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6231 // 256-bit AVX can use the vinsertf128 instruction
6232 // to create 256-bit vectors from two other 128-bit ones.
6233 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6235 MVT ResVT = Op.getSimpleValueType();
6237 assert((ResVT.is256BitVector() ||
6238 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6240 SDValue V1 = Op.getOperand(0);
6241 SDValue V2 = Op.getOperand(1);
6242 unsigned NumElems = ResVT.getVectorNumElements();
6243 if (ResVT.is256BitVector())
6244 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6246 if (Op.getNumOperands() == 4) {
6247 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6248 ResVT.getVectorNumElements()/2);
6249 SDValue V3 = Op.getOperand(2);
6250 SDValue V4 = Op.getOperand(3);
6251 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6252 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6254 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6257 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6258 const X86Subtarget *Subtarget,
6259 SelectionDAG & DAG) {
6261 MVT ResVT = Op.getSimpleValueType();
6262 unsigned NumOfOperands = Op.getNumOperands();
6264 assert(isPowerOf2_32(NumOfOperands) &&
6265 "Unexpected number of operands in CONCAT_VECTORS");
6267 if (NumOfOperands > 2) {
6268 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6269 ResVT.getVectorNumElements()/2);
6270 SmallVector<SDValue, 2> Ops;
6271 for (unsigned i = 0; i < NumOfOperands/2; i++)
6272 Ops.push_back(Op.getOperand(i));
6273 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6275 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6276 Ops.push_back(Op.getOperand(i));
6277 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6278 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6281 SDValue V1 = Op.getOperand(0);
6282 SDValue V2 = Op.getOperand(1);
6283 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6284 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6286 if (IsZeroV1 && IsZeroV2)
6287 return getZeroVector(ResVT, Subtarget, DAG, dl);
6289 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6290 SDValue Undef = DAG.getUNDEF(ResVT);
6291 unsigned NumElems = ResVT.getVectorNumElements();
6292 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6294 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6295 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6299 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6300 // Zero the upper bits of V1
6301 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6302 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6305 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6308 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6309 const X86Subtarget *Subtarget,
6310 SelectionDAG &DAG) {
6311 MVT VT = Op.getSimpleValueType();
6312 if (VT.getVectorElementType() == MVT::i1)
6313 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6315 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6316 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6317 Op.getNumOperands() == 4)));
6319 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6320 // from two other 128-bit ones.
6322 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6323 return LowerAVXCONCAT_VECTORS(Op, DAG);
6327 //===----------------------------------------------------------------------===//
6328 // Vector shuffle lowering
6330 // This is an experimental code path for lowering vector shuffles on x86. It is
6331 // designed to handle arbitrary vector shuffles and blends, gracefully
6332 // degrading performance as necessary. It works hard to recognize idiomatic
6333 // shuffles and lower them to optimal instruction patterns without leaving
6334 // a framework that allows reasonably efficient handling of all vector shuffle
6336 //===----------------------------------------------------------------------===//
6338 /// \brief Tiny helper function to identify a no-op mask.
6340 /// This is a somewhat boring predicate function. It checks whether the mask
6341 /// array input, which is assumed to be a single-input shuffle mask of the kind
6342 /// used by the X86 shuffle instructions (not a fully general
6343 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6344 /// in-place shuffle are 'no-op's.
6345 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6346 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6347 if (Mask[i] != -1 && Mask[i] != i)
6352 /// \brief Helper function to classify a mask as a single-input mask.
6354 /// This isn't a generic single-input test because in the vector shuffle
6355 /// lowering we canonicalize single inputs to be the first input operand. This
6356 /// means we can more quickly test for a single input by only checking whether
6357 /// an input from the second operand exists. We also assume that the size of
6358 /// mask corresponds to the size of the input vectors which isn't true in the
6359 /// fully general case.
6360 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6362 if (M >= (int)Mask.size())
6367 /// \brief Test whether there are elements crossing 128-bit lanes in this
6370 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6371 /// and we routinely test for these.
6372 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6373 int LaneSize = 128 / VT.getScalarSizeInBits();
6374 int Size = Mask.size();
6375 for (int i = 0; i < Size; ++i)
6376 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6381 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6383 /// This checks a shuffle mask to see if it is performing the same
6384 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6385 /// that it is also not lane-crossing. It may however involve a blend from the
6386 /// same lane of a second vector.
6388 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6389 /// non-trivial to compute in the face of undef lanes. The representation is
6390 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6391 /// entries from both V1 and V2 inputs to the wider mask.
6393 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6394 SmallVectorImpl<int> &RepeatedMask) {
6395 int LaneSize = 128 / VT.getScalarSizeInBits();
6396 RepeatedMask.resize(LaneSize, -1);
6397 int Size = Mask.size();
6398 for (int i = 0; i < Size; ++i) {
6401 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6402 // This entry crosses lanes, so there is no way to model this shuffle.
6405 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6406 if (RepeatedMask[i % LaneSize] == -1)
6407 // This is the first non-undef entry in this slot of a 128-bit lane.
6408 RepeatedMask[i % LaneSize] =
6409 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6410 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6411 // Found a mismatch with the repeated mask.
6417 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6420 /// This is a fast way to test a shuffle mask against a fixed pattern:
6422 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6424 /// It returns true if the mask is exactly as wide as the argument list, and
6425 /// each element of the mask is either -1 (signifying undef) or the value given
6426 /// in the argument.
6427 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6428 ArrayRef<int> ExpectedMask) {
6429 if (Mask.size() != ExpectedMask.size())
6432 int Size = Mask.size();
6434 // If the values are build vectors, we can look through them to find
6435 // equivalent inputs that make the shuffles equivalent.
6436 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6437 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6439 for (int i = 0; i < Size; ++i)
6440 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6441 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6442 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6443 if (!MaskBV || !ExpectedBV ||
6444 MaskBV->getOperand(Mask[i] % Size) !=
6445 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6452 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6454 /// This helper function produces an 8-bit shuffle immediate corresponding to
6455 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6456 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6459 /// NB: We rely heavily on "undef" masks preserving the input lane.
6460 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6461 SelectionDAG &DAG) {
6462 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6463 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6464 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6465 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6466 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6469 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6470 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6471 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6472 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6473 return DAG.getConstant(Imm, DL, MVT::i8);
6476 /// \brief Compute whether each element of a shuffle is zeroable.
6478 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6479 /// Either it is an undef element in the shuffle mask, the element of the input
6480 /// referenced is undef, or the element of the input referenced is known to be
6481 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6482 /// as many lanes with this technique as possible to simplify the remaining
6484 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6485 SDValue V1, SDValue V2) {
6486 SmallBitVector Zeroable(Mask.size(), false);
6488 while (V1.getOpcode() == ISD::BITCAST)
6489 V1 = V1->getOperand(0);
6490 while (V2.getOpcode() == ISD::BITCAST)
6491 V2 = V2->getOperand(0);
6493 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6494 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6496 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6498 // Handle the easy cases.
6499 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6504 // If this is an index into a build_vector node (which has the same number
6505 // of elements), dig out the input value and use it.
6506 SDValue V = M < Size ? V1 : V2;
6507 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6510 SDValue Input = V.getOperand(M % Size);
6511 // The UNDEF opcode check really should be dead code here, but not quite
6512 // worth asserting on (it isn't invalid, just unexpected).
6513 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6520 /// \brief Try to emit a bitmask instruction for a shuffle.
6522 /// This handles cases where we can model a blend exactly as a bitmask due to
6523 /// one of the inputs being zeroable.
6524 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6525 SDValue V2, ArrayRef<int> Mask,
6526 SelectionDAG &DAG) {
6527 MVT EltVT = VT.getScalarType();
6528 int NumEltBits = EltVT.getSizeInBits();
6529 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6530 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6531 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6533 if (EltVT.isFloatingPoint()) {
6534 Zero = DAG.getBitcast(EltVT, Zero);
6535 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6537 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6538 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6540 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6543 if (Mask[i] % Size != i)
6544 return SDValue(); // Not a blend.
6546 V = Mask[i] < Size ? V1 : V2;
6547 else if (V != (Mask[i] < Size ? V1 : V2))
6548 return SDValue(); // Can only let one input through the mask.
6550 VMaskOps[i] = AllOnes;
6553 return SDValue(); // No non-zeroable elements!
6555 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6556 V = DAG.getNode(VT.isFloatingPoint()
6557 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6562 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6564 /// This is used as a fallback approach when first class blend instructions are
6565 /// unavailable. Currently it is only suitable for integer vectors, but could
6566 /// be generalized for floating point vectors if desirable.
6567 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6568 SDValue V2, ArrayRef<int> Mask,
6569 SelectionDAG &DAG) {
6570 assert(VT.isInteger() && "Only supports integer vector types!");
6571 MVT EltVT = VT.getScalarType();
6572 int NumEltBits = EltVT.getSizeInBits();
6573 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6574 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6576 SmallVector<SDValue, 16> MaskOps;
6577 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6578 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6579 return SDValue(); // Shuffled input!
6580 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6583 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6584 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6585 // We have to cast V2 around.
6586 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6587 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6588 DAG.getBitcast(MaskVT, V1Mask),
6589 DAG.getBitcast(MaskVT, V2)));
6590 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6593 /// \brief Try to emit a blend instruction for a shuffle.
6595 /// This doesn't do any checks for the availability of instructions for blending
6596 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6597 /// be matched in the backend with the type given. What it does check for is
6598 /// that the shuffle mask is in fact a blend.
6599 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6600 SDValue V2, ArrayRef<int> Mask,
6601 const X86Subtarget *Subtarget,
6602 SelectionDAG &DAG) {
6603 unsigned BlendMask = 0;
6604 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6605 if (Mask[i] >= Size) {
6606 if (Mask[i] != i + Size)
6607 return SDValue(); // Shuffled V2 input!
6608 BlendMask |= 1u << i;
6611 if (Mask[i] >= 0 && Mask[i] != i)
6612 return SDValue(); // Shuffled V1 input!
6614 switch (VT.SimpleTy) {
6619 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6620 DAG.getConstant(BlendMask, DL, MVT::i8));
6624 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6628 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6629 // that instruction.
6630 if (Subtarget->hasAVX2()) {
6631 // Scale the blend by the number of 32-bit dwords per element.
6632 int Scale = VT.getScalarSizeInBits() / 32;
6634 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6635 if (Mask[i] >= Size)
6636 for (int j = 0; j < Scale; ++j)
6637 BlendMask |= 1u << (i * Scale + j);
6639 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6640 V1 = DAG.getBitcast(BlendVT, V1);
6641 V2 = DAG.getBitcast(BlendVT, V2);
6642 return DAG.getBitcast(
6643 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6644 DAG.getConstant(BlendMask, DL, MVT::i8)));
6648 // For integer shuffles we need to expand the mask and cast the inputs to
6649 // v8i16s prior to blending.
6650 int Scale = 8 / VT.getVectorNumElements();
6652 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6653 if (Mask[i] >= Size)
6654 for (int j = 0; j < Scale; ++j)
6655 BlendMask |= 1u << (i * Scale + j);
6657 V1 = DAG.getBitcast(MVT::v8i16, V1);
6658 V2 = DAG.getBitcast(MVT::v8i16, V2);
6659 return DAG.getBitcast(VT,
6660 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6661 DAG.getConstant(BlendMask, DL, MVT::i8)));
6665 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6666 SmallVector<int, 8> RepeatedMask;
6667 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6668 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6669 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6671 for (int i = 0; i < 8; ++i)
6672 if (RepeatedMask[i] >= 16)
6673 BlendMask |= 1u << i;
6674 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6675 DAG.getConstant(BlendMask, DL, MVT::i8));
6681 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6682 "256-bit byte-blends require AVX2 support!");
6684 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6685 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6688 // Scale the blend by the number of bytes per element.
6689 int Scale = VT.getScalarSizeInBits() / 8;
6691 // This form of blend is always done on bytes. Compute the byte vector
6693 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6695 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6696 // mix of LLVM's code generator and the x86 backend. We tell the code
6697 // generator that boolean values in the elements of an x86 vector register
6698 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6699 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6700 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6701 // of the element (the remaining are ignored) and 0 in that high bit would
6702 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6703 // the LLVM model for boolean values in vector elements gets the relevant
6704 // bit set, it is set backwards and over constrained relative to x86's
6706 SmallVector<SDValue, 32> VSELECTMask;
6707 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6708 for (int j = 0; j < Scale; ++j)
6709 VSELECTMask.push_back(
6710 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6711 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6714 V1 = DAG.getBitcast(BlendVT, V1);
6715 V2 = DAG.getBitcast(BlendVT, V2);
6716 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6717 DAG.getNode(ISD::BUILD_VECTOR, DL,
6718 BlendVT, VSELECTMask),
6723 llvm_unreachable("Not a supported integer vector type!");
6727 /// \brief Try to lower as a blend of elements from two inputs followed by
6728 /// a single-input permutation.
6730 /// This matches the pattern where we can blend elements from two inputs and
6731 /// then reduce the shuffle to a single-input permutation.
6732 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6735 SelectionDAG &DAG) {
6736 // We build up the blend mask while checking whether a blend is a viable way
6737 // to reduce the shuffle.
6738 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6739 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6741 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6745 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6747 if (BlendMask[Mask[i] % Size] == -1)
6748 BlendMask[Mask[i] % Size] = Mask[i];
6749 else if (BlendMask[Mask[i] % Size] != Mask[i])
6750 return SDValue(); // Can't blend in the needed input!
6752 PermuteMask[i] = Mask[i] % Size;
6755 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6756 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6759 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6760 /// blends and permutes.
6762 /// This matches the extremely common pattern for handling combined
6763 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6764 /// operations. It will try to pick the best arrangement of shuffles and
6766 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6770 SelectionDAG &DAG) {
6771 // Shuffle the input elements into the desired positions in V1 and V2 and
6772 // blend them together.
6773 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6774 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6775 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6776 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6777 if (Mask[i] >= 0 && Mask[i] < Size) {
6778 V1Mask[i] = Mask[i];
6780 } else if (Mask[i] >= Size) {
6781 V2Mask[i] = Mask[i] - Size;
6782 BlendMask[i] = i + Size;
6785 // Try to lower with the simpler initial blend strategy unless one of the
6786 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6787 // shuffle may be able to fold with a load or other benefit. However, when
6788 // we'll have to do 2x as many shuffles in order to achieve this, blending
6789 // first is a better strategy.
6790 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6791 if (SDValue BlendPerm =
6792 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6795 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6796 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6797 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6800 /// \brief Try to lower a vector shuffle as a byte rotation.
6802 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6803 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6804 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6805 /// try to generically lower a vector shuffle through such an pattern. It
6806 /// does not check for the profitability of lowering either as PALIGNR or
6807 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6808 /// This matches shuffle vectors that look like:
6810 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6812 /// Essentially it concatenates V1 and V2, shifts right by some number of
6813 /// elements, and takes the low elements as the result. Note that while this is
6814 /// specified as a *right shift* because x86 is little-endian, it is a *left
6815 /// rotate* of the vector lanes.
6816 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6819 const X86Subtarget *Subtarget,
6820 SelectionDAG &DAG) {
6821 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6823 int NumElts = Mask.size();
6824 int NumLanes = VT.getSizeInBits() / 128;
6825 int NumLaneElts = NumElts / NumLanes;
6827 // We need to detect various ways of spelling a rotation:
6828 // [11, 12, 13, 14, 15, 0, 1, 2]
6829 // [-1, 12, 13, 14, -1, -1, 1, -1]
6830 // [-1, -1, -1, -1, -1, -1, 1, 2]
6831 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6832 // [-1, 4, 5, 6, -1, -1, 9, -1]
6833 // [-1, 4, 5, 6, -1, -1, -1, -1]
6836 for (int l = 0; l < NumElts; l += NumLaneElts) {
6837 for (int i = 0; i < NumLaneElts; ++i) {
6838 if (Mask[l + i] == -1)
6840 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6842 // Get the mod-Size index and lane correct it.
6843 int LaneIdx = (Mask[l + i] % NumElts) - l;
6844 // Make sure it was in this lane.
6845 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6848 // Determine where a rotated vector would have started.
6849 int StartIdx = i - LaneIdx;
6851 // The identity rotation isn't interesting, stop.
6854 // If we found the tail of a vector the rotation must be the missing
6855 // front. If we found the head of a vector, it must be how much of the
6857 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6860 Rotation = CandidateRotation;
6861 else if (Rotation != CandidateRotation)
6862 // The rotations don't match, so we can't match this mask.
6865 // Compute which value this mask is pointing at.
6866 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6868 // Compute which of the two target values this index should be assigned
6869 // to. This reflects whether the high elements are remaining or the low
6870 // elements are remaining.
6871 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6873 // Either set up this value if we've not encountered it before, or check
6874 // that it remains consistent.
6877 else if (TargetV != MaskV)
6878 // This may be a rotation, but it pulls from the inputs in some
6879 // unsupported interleaving.
6884 // Check that we successfully analyzed the mask, and normalize the results.
6885 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6886 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6892 // The actual rotate instruction rotates bytes, so we need to scale the
6893 // rotation based on how many bytes are in the vector lane.
6894 int Scale = 16 / NumLaneElts;
6896 // SSSE3 targets can use the palignr instruction.
6897 if (Subtarget->hasSSSE3()) {
6898 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6899 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6900 Lo = DAG.getBitcast(AlignVT, Lo);
6901 Hi = DAG.getBitcast(AlignVT, Hi);
6903 return DAG.getBitcast(
6904 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6905 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6908 assert(VT.getSizeInBits() == 128 &&
6909 "Rotate-based lowering only supports 128-bit lowering!");
6910 assert(Mask.size() <= 16 &&
6911 "Can shuffle at most 16 bytes in a 128-bit vector!");
6913 // Default SSE2 implementation
6914 int LoByteShift = 16 - Rotation * Scale;
6915 int HiByteShift = Rotation * Scale;
6917 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6918 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6919 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6921 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6922 DAG.getConstant(LoByteShift, DL, MVT::i8));
6923 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6924 DAG.getConstant(HiByteShift, DL, MVT::i8));
6925 return DAG.getBitcast(VT,
6926 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6929 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6931 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6932 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6933 /// matches elements from one of the input vectors shuffled to the left or
6934 /// right with zeroable elements 'shifted in'. It handles both the strictly
6935 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6938 /// PSHL : (little-endian) left bit shift.
6939 /// [ zz, 0, zz, 2 ]
6940 /// [ -1, 4, zz, -1 ]
6941 /// PSRL : (little-endian) right bit shift.
6943 /// [ -1, -1, 7, zz]
6944 /// PSLLDQ : (little-endian) left byte shift
6945 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6946 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6947 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6948 /// PSRLDQ : (little-endian) right byte shift
6949 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6950 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6951 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6952 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6953 SDValue V2, ArrayRef<int> Mask,
6954 SelectionDAG &DAG) {
6955 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6957 int Size = Mask.size();
6958 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6960 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6961 for (int i = 0; i < Size; i += Scale)
6962 for (int j = 0; j < Shift; ++j)
6963 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6969 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6970 for (int i = 0; i != Size; i += Scale) {
6971 unsigned Pos = Left ? i + Shift : i;
6972 unsigned Low = Left ? i : i + Shift;
6973 unsigned Len = Scale - Shift;
6974 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6975 Low + (V == V1 ? 0 : Size)))
6979 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6980 bool ByteShift = ShiftEltBits > 64;
6981 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6982 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6983 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6985 // Normalize the scale for byte shifts to still produce an i64 element
6987 Scale = ByteShift ? Scale / 2 : Scale;
6989 // We need to round trip through the appropriate type for the shift.
6990 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6991 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6992 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6993 "Illegal integer vector type");
6994 V = DAG.getBitcast(ShiftVT, V);
6996 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6997 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6998 return DAG.getBitcast(VT, V);
7001 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7002 // keep doubling the size of the integer elements up to that. We can
7003 // then shift the elements of the integer vector by whole multiples of
7004 // their width within the elements of the larger integer vector. Test each
7005 // multiple to see if we can find a match with the moved element indices
7006 // and that the shifted in elements are all zeroable.
7007 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7008 for (int Shift = 1; Shift != Scale; ++Shift)
7009 for (bool Left : {true, false})
7010 if (CheckZeros(Shift, Scale, Left))
7011 for (SDValue V : {V1, V2})
7012 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7019 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7020 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7021 SDValue V2, ArrayRef<int> Mask,
7022 SelectionDAG &DAG) {
7023 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7024 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7026 int Size = Mask.size();
7027 int HalfSize = Size / 2;
7028 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7030 // Upper half must be undefined.
7031 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7034 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7035 // Remainder of lower half result is zero and upper half is all undef.
7036 auto LowerAsEXTRQ = [&]() {
7037 // Determine the extraction length from the part of the
7038 // lower half that isn't zeroable.
7040 for (; Len >= 0; --Len)
7041 if (!Zeroable[Len - 1])
7043 assert(Len > 0 && "Zeroable shuffle mask");
7045 // Attempt to match first Len sequential elements from the lower half.
7048 for (int i = 0; i != Len; ++i) {
7052 SDValue &V = (M < Size ? V1 : V2);
7055 // All mask elements must be in the lower half.
7059 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7070 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7071 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7072 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7073 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7074 DAG.getConstant(BitLen, DL, MVT::i8),
7075 DAG.getConstant(BitIdx, DL, MVT::i8));
7078 if (SDValue ExtrQ = LowerAsEXTRQ())
7081 // INSERTQ: Extract lowest Len elements from lower half of second source and
7082 // insert over first source, starting at Idx.
7083 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7084 auto LowerAsInsertQ = [&]() {
7085 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7088 // Attempt to match first source from mask before insertion point.
7089 if (isUndefInRange(Mask, 0, Idx)) {
7091 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7093 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7099 // Extend the extraction length looking to match both the insertion of
7100 // the second source and the remaining elements of the first.
7101 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7106 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7108 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7114 // Match the remaining elements of the lower half.
7115 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7117 } else if ((!Base || (Base == V1)) &&
7118 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7120 } else if ((!Base || (Base == V2)) &&
7121 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7128 // We may not have a base (first source) - this can safely be undefined.
7130 Base = DAG.getUNDEF(VT);
7132 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7133 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7134 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7135 DAG.getConstant(BitLen, DL, MVT::i8),
7136 DAG.getConstant(BitIdx, DL, MVT::i8));
7143 if (SDValue InsertQ = LowerAsInsertQ())
7149 /// \brief Lower a vector shuffle as a zero or any extension.
7151 /// Given a specific number of elements, element bit width, and extension
7152 /// stride, produce either a zero or any extension based on the available
7153 /// features of the subtarget.
7154 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7155 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7156 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7157 assert(Scale > 1 && "Need a scale to extend.");
7158 int NumElements = VT.getVectorNumElements();
7159 int EltBits = VT.getScalarSizeInBits();
7160 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7161 "Only 8, 16, and 32 bit elements can be extended.");
7162 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7164 // Found a valid zext mask! Try various lowering strategies based on the
7165 // input type and available ISA extensions.
7166 if (Subtarget->hasSSE41()) {
7167 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7168 NumElements / Scale);
7169 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7172 // For any extends we can cheat for larger element sizes and use shuffle
7173 // instructions that can fold with a load and/or copy.
7174 if (AnyExt && EltBits == 32) {
7175 int PSHUFDMask[4] = {0, -1, 1, -1};
7176 return DAG.getBitcast(
7177 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7178 DAG.getBitcast(MVT::v4i32, InputV),
7179 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7181 if (AnyExt && EltBits == 16 && Scale > 2) {
7182 int PSHUFDMask[4] = {0, -1, 0, -1};
7183 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7184 DAG.getBitcast(MVT::v4i32, InputV),
7185 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7186 int PSHUFHWMask[4] = {1, -1, -1, -1};
7187 return DAG.getBitcast(
7188 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7189 DAG.getBitcast(MVT::v8i16, InputV),
7190 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7193 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7195 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7196 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7197 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7199 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7200 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7201 DAG.getConstant(EltBits, DL, MVT::i8),
7202 DAG.getConstant(0, DL, MVT::i8)));
7203 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7204 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7207 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7208 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7209 DAG.getConstant(EltBits, DL, MVT::i8),
7210 DAG.getConstant(EltBits, DL, MVT::i8)));
7211 return DAG.getNode(ISD::BITCAST, DL, VT,
7212 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7215 // If this would require more than 2 unpack instructions to expand, use
7216 // pshufb when available. We can only use more than 2 unpack instructions
7217 // when zero extending i8 elements which also makes it easier to use pshufb.
7218 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7219 assert(NumElements == 16 && "Unexpected byte vector width!");
7220 SDValue PSHUFBMask[16];
7221 for (int i = 0; i < 16; ++i)
7223 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7224 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7225 return DAG.getBitcast(VT,
7226 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7227 DAG.getNode(ISD::BUILD_VECTOR, DL,
7228 MVT::v16i8, PSHUFBMask)));
7231 // Otherwise emit a sequence of unpacks.
7233 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7234 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7235 : getZeroVector(InputVT, Subtarget, DAG, DL);
7236 InputV = DAG.getBitcast(InputVT, InputV);
7237 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7241 } while (Scale > 1);
7242 return DAG.getBitcast(VT, InputV);
7245 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7247 /// This routine will try to do everything in its power to cleverly lower
7248 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7249 /// check for the profitability of this lowering, it tries to aggressively
7250 /// match this pattern. It will use all of the micro-architectural details it
7251 /// can to emit an efficient lowering. It handles both blends with all-zero
7252 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7253 /// masking out later).
7255 /// The reason we have dedicated lowering for zext-style shuffles is that they
7256 /// are both incredibly common and often quite performance sensitive.
7257 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7258 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7259 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7260 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7262 int Bits = VT.getSizeInBits();
7263 int NumElements = VT.getVectorNumElements();
7264 assert(VT.getScalarSizeInBits() <= 32 &&
7265 "Exceeds 32-bit integer zero extension limit");
7266 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7268 // Define a helper function to check a particular ext-scale and lower to it if
7270 auto Lower = [&](int Scale) -> SDValue {
7273 for (int i = 0; i < NumElements; ++i) {
7275 continue; // Valid anywhere but doesn't tell us anything.
7276 if (i % Scale != 0) {
7277 // Each of the extended elements need to be zeroable.
7281 // We no longer are in the anyext case.
7286 // Each of the base elements needs to be consecutive indices into the
7287 // same input vector.
7288 SDValue V = Mask[i] < NumElements ? V1 : V2;
7291 else if (InputV != V)
7292 return SDValue(); // Flip-flopping inputs.
7294 if (Mask[i] % NumElements != i / Scale)
7295 return SDValue(); // Non-consecutive strided elements.
7298 // If we fail to find an input, we have a zero-shuffle which should always
7299 // have already been handled.
7300 // FIXME: Maybe handle this here in case during blending we end up with one?
7304 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7305 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7308 // The widest scale possible for extending is to a 64-bit integer.
7309 assert(Bits % 64 == 0 &&
7310 "The number of bits in a vector must be divisible by 64 on x86!");
7311 int NumExtElements = Bits / 64;
7313 // Each iteration, try extending the elements half as much, but into twice as
7315 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7316 assert(NumElements % NumExtElements == 0 &&
7317 "The input vector size must be divisible by the extended size.");
7318 if (SDValue V = Lower(NumElements / NumExtElements))
7322 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7326 // Returns one of the source operands if the shuffle can be reduced to a
7327 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7328 auto CanZExtLowHalf = [&]() {
7329 for (int i = NumElements / 2; i != NumElements; ++i)
7332 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7334 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7339 if (SDValue V = CanZExtLowHalf()) {
7340 V = DAG.getBitcast(MVT::v2i64, V);
7341 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7342 return DAG.getBitcast(VT, V);
7345 // No viable ext lowering found.
7349 /// \brief Try to get a scalar value for a specific element of a vector.
7351 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7352 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7353 SelectionDAG &DAG) {
7354 MVT VT = V.getSimpleValueType();
7355 MVT EltVT = VT.getVectorElementType();
7356 while (V.getOpcode() == ISD::BITCAST)
7357 V = V.getOperand(0);
7358 // If the bitcasts shift the element size, we can't extract an equivalent
7360 MVT NewVT = V.getSimpleValueType();
7361 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7364 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7365 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7366 // Ensure the scalar operand is the same size as the destination.
7367 // FIXME: Add support for scalar truncation where possible.
7368 SDValue S = V.getOperand(Idx);
7369 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7370 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7376 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7378 /// This is particularly important because the set of instructions varies
7379 /// significantly based on whether the operand is a load or not.
7380 static bool isShuffleFoldableLoad(SDValue V) {
7381 while (V.getOpcode() == ISD::BITCAST)
7382 V = V.getOperand(0);
7384 return ISD::isNON_EXTLoad(V.getNode());
7387 /// \brief Try to lower insertion of a single element into a zero vector.
7389 /// This is a common pattern that we have especially efficient patterns to lower
7390 /// across all subtarget feature sets.
7391 static SDValue lowerVectorShuffleAsElementInsertion(
7392 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7393 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7394 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7396 MVT EltVT = VT.getVectorElementType();
7398 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7399 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7401 bool IsV1Zeroable = true;
7402 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7403 if (i != V2Index && !Zeroable[i]) {
7404 IsV1Zeroable = false;
7408 // Check for a single input from a SCALAR_TO_VECTOR node.
7409 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7410 // all the smarts here sunk into that routine. However, the current
7411 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7412 // vector shuffle lowering is dead.
7413 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7415 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7416 // We need to zext the scalar if it is smaller than an i32.
7417 V2S = DAG.getBitcast(EltVT, V2S);
7418 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7419 // Using zext to expand a narrow element won't work for non-zero
7424 // Zero-extend directly to i32.
7426 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7428 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7429 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7430 EltVT == MVT::i16) {
7431 // Either not inserting from the low element of the input or the input
7432 // element size is too small to use VZEXT_MOVL to clear the high bits.
7436 if (!IsV1Zeroable) {
7437 // If V1 can't be treated as a zero vector we have fewer options to lower
7438 // this. We can't support integer vectors or non-zero targets cheaply, and
7439 // the V1 elements can't be permuted in any way.
7440 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7441 if (!VT.isFloatingPoint() || V2Index != 0)
7443 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7444 V1Mask[V2Index] = -1;
7445 if (!isNoopShuffleMask(V1Mask))
7447 // This is essentially a special case blend operation, but if we have
7448 // general purpose blend operations, they are always faster. Bail and let
7449 // the rest of the lowering handle these as blends.
7450 if (Subtarget->hasSSE41())
7453 // Otherwise, use MOVSD or MOVSS.
7454 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7455 "Only two types of floating point element types to handle!");
7456 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7460 // This lowering only works for the low element with floating point vectors.
7461 if (VT.isFloatingPoint() && V2Index != 0)
7464 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7466 V2 = DAG.getBitcast(VT, V2);
7469 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7470 // the desired position. Otherwise it is more efficient to do a vector
7471 // shift left. We know that we can do a vector shift left because all
7472 // the inputs are zero.
7473 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7474 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7475 V2Shuffle[V2Index] = 0;
7476 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7478 V2 = DAG.getBitcast(MVT::v2i64, V2);
7480 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7481 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7482 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7483 DAG.getDataLayout(), VT)));
7484 V2 = DAG.getBitcast(VT, V2);
7490 /// \brief Try to lower broadcast of a single element.
7492 /// For convenience, this code also bundles all of the subtarget feature set
7493 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7494 /// a convenient way to factor it out.
7495 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7497 const X86Subtarget *Subtarget,
7498 SelectionDAG &DAG) {
7499 if (!Subtarget->hasAVX())
7501 if (VT.isInteger() && !Subtarget->hasAVX2())
7504 // Check that the mask is a broadcast.
7505 int BroadcastIdx = -1;
7507 if (M >= 0 && BroadcastIdx == -1)
7509 else if (M >= 0 && M != BroadcastIdx)
7512 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7513 "a sorted mask where the broadcast "
7516 // Go up the chain of (vector) values to find a scalar load that we can
7517 // combine with the broadcast.
7519 switch (V.getOpcode()) {
7520 case ISD::CONCAT_VECTORS: {
7521 int OperandSize = Mask.size() / V.getNumOperands();
7522 V = V.getOperand(BroadcastIdx / OperandSize);
7523 BroadcastIdx %= OperandSize;
7527 case ISD::INSERT_SUBVECTOR: {
7528 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7529 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7533 int BeginIdx = (int)ConstantIdx->getZExtValue();
7535 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7536 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7537 BroadcastIdx -= BeginIdx;
7548 // Check if this is a broadcast of a scalar. We special case lowering
7549 // for scalars so that we can more effectively fold with loads.
7550 // First, look through bitcast: if the original value has a larger element
7551 // type than the shuffle, the broadcast element is in essence truncated.
7552 // Make that explicit to ease folding.
7553 if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7554 EVT EltVT = VT.getVectorElementType();
7555 SDValue V0 = V.getOperand(0);
7556 EVT V0VT = V0.getValueType();
7558 if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7559 ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7560 (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7561 V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7566 // Also check the simpler case, where we can directly reuse the scalar.
7567 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7568 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7569 V = V.getOperand(BroadcastIdx);
7571 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7572 // Only AVX2 has register broadcasts.
7573 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7575 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7576 // We can't broadcast from a vector register without AVX2, and we can only
7577 // broadcast from the zero-element of a vector register.
7581 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7584 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7585 // INSERTPS when the V1 elements are already in the correct locations
7586 // because otherwise we can just always use two SHUFPS instructions which
7587 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7588 // perform INSERTPS if a single V1 element is out of place and all V2
7589 // elements are zeroable.
7590 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7592 SelectionDAG &DAG) {
7593 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7594 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7595 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7596 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7598 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7601 int V1DstIndex = -1;
7602 int V2DstIndex = -1;
7603 bool V1UsedInPlace = false;
7605 for (int i = 0; i < 4; ++i) {
7606 // Synthesize a zero mask from the zeroable elements (includes undefs).
7612 // Flag if we use any V1 inputs in place.
7614 V1UsedInPlace = true;
7618 // We can only insert a single non-zeroable element.
7619 if (V1DstIndex != -1 || V2DstIndex != -1)
7623 // V1 input out of place for insertion.
7626 // V2 input for insertion.
7631 // Don't bother if we have no (non-zeroable) element for insertion.
7632 if (V1DstIndex == -1 && V2DstIndex == -1)
7635 // Determine element insertion src/dst indices. The src index is from the
7636 // start of the inserted vector, not the start of the concatenated vector.
7637 unsigned V2SrcIndex = 0;
7638 if (V1DstIndex != -1) {
7639 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7640 // and don't use the original V2 at all.
7641 V2SrcIndex = Mask[V1DstIndex];
7642 V2DstIndex = V1DstIndex;
7645 V2SrcIndex = Mask[V2DstIndex] - 4;
7648 // If no V1 inputs are used in place, then the result is created only from
7649 // the zero mask and the V2 insertion - so remove V1 dependency.
7651 V1 = DAG.getUNDEF(MVT::v4f32);
7653 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7654 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7656 // Insert the V2 element into the desired position.
7658 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7659 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7662 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7663 /// UNPCK instruction.
7665 /// This specifically targets cases where we end up with alternating between
7666 /// the two inputs, and so can permute them into something that feeds a single
7667 /// UNPCK instruction. Note that this routine only targets integer vectors
7668 /// because for floating point vectors we have a generalized SHUFPS lowering
7669 /// strategy that handles everything that doesn't *exactly* match an unpack,
7670 /// making this clever lowering unnecessary.
7671 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7672 SDValue V2, ArrayRef<int> Mask,
7673 SelectionDAG &DAG) {
7674 assert(!VT.isFloatingPoint() &&
7675 "This routine only supports integer vectors.");
7676 assert(!isSingleInputShuffleMask(Mask) &&
7677 "This routine should only be used when blending two inputs.");
7678 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7680 int Size = Mask.size();
7682 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7683 return M >= 0 && M % Size < Size / 2;
7685 int NumHiInputs = std::count_if(
7686 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7688 bool UnpackLo = NumLoInputs >= NumHiInputs;
7690 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7691 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7692 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7694 for (int i = 0; i < Size; ++i) {
7698 // Each element of the unpack contains Scale elements from this mask.
7699 int UnpackIdx = i / Scale;
7701 // We only handle the case where V1 feeds the first slots of the unpack.
7702 // We rely on canonicalization to ensure this is the case.
7703 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7706 // Setup the mask for this input. The indexing is tricky as we have to
7707 // handle the unpack stride.
7708 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7709 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7713 // If we will have to shuffle both inputs to use the unpack, check whether
7714 // we can just unpack first and shuffle the result. If so, skip this unpack.
7715 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7716 !isNoopShuffleMask(V2Mask))
7719 // Shuffle the inputs into place.
7720 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7721 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7723 // Cast the inputs to the type we will use to unpack them.
7724 V1 = DAG.getBitcast(UnpackVT, V1);
7725 V2 = DAG.getBitcast(UnpackVT, V2);
7727 // Unpack the inputs and cast the result back to the desired type.
7728 return DAG.getBitcast(
7729 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7733 // We try each unpack from the largest to the smallest to try and find one
7734 // that fits this mask.
7735 int OrigNumElements = VT.getVectorNumElements();
7736 int OrigScalarSize = VT.getScalarSizeInBits();
7737 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7738 int Scale = ScalarSize / OrigScalarSize;
7739 int NumElements = OrigNumElements / Scale;
7740 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7741 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7745 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7747 if (NumLoInputs == 0 || NumHiInputs == 0) {
7748 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7749 "We have to have *some* inputs!");
7750 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7752 // FIXME: We could consider the total complexity of the permute of each
7753 // possible unpacking. Or at the least we should consider how many
7754 // half-crossings are created.
7755 // FIXME: We could consider commuting the unpacks.
7757 SmallVector<int, 32> PermMask;
7758 PermMask.assign(Size, -1);
7759 for (int i = 0; i < Size; ++i) {
7763 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7766 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7768 return DAG.getVectorShuffle(
7769 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7771 DAG.getUNDEF(VT), PermMask);
7777 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7779 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7780 /// support for floating point shuffles but not integer shuffles. These
7781 /// instructions will incur a domain crossing penalty on some chips though so
7782 /// it is better to avoid lowering through this for integer vectors where
7784 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7785 const X86Subtarget *Subtarget,
7786 SelectionDAG &DAG) {
7788 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7789 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7790 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7791 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7792 ArrayRef<int> Mask = SVOp->getMask();
7793 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7795 if (isSingleInputShuffleMask(Mask)) {
7796 // Use low duplicate instructions for masks that match their pattern.
7797 if (Subtarget->hasSSE3())
7798 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7799 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7801 // Straight shuffle of a single input vector. Simulate this by using the
7802 // single input as both of the "inputs" to this instruction..
7803 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7805 if (Subtarget->hasAVX()) {
7806 // If we have AVX, we can use VPERMILPS which will allow folding a load
7807 // into the shuffle.
7808 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7809 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7812 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7813 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7815 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7816 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7818 // If we have a single input, insert that into V1 if we can do so cheaply.
7819 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7820 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7821 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7823 // Try inverting the insertion since for v2 masks it is easy to do and we
7824 // can't reliably sort the mask one way or the other.
7825 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7826 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7827 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7828 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7832 // Try to use one of the special instruction patterns to handle two common
7833 // blend patterns if a zero-blend above didn't work.
7834 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7835 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7836 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7837 // We can either use a special instruction to load over the low double or
7838 // to move just the low double.
7840 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7842 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7844 if (Subtarget->hasSSE41())
7845 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7849 // Use dedicated unpack instructions for masks that match their pattern.
7850 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7851 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7852 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7853 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7855 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7856 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7857 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7860 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7862 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7863 /// the integer unit to minimize domain crossing penalties. However, for blends
7864 /// it falls back to the floating point shuffle operation with appropriate bit
7866 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7867 const X86Subtarget *Subtarget,
7868 SelectionDAG &DAG) {
7870 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7871 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7872 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7873 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7874 ArrayRef<int> Mask = SVOp->getMask();
7875 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7877 if (isSingleInputShuffleMask(Mask)) {
7878 // Check for being able to broadcast a single element.
7879 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7880 Mask, Subtarget, DAG))
7883 // Straight shuffle of a single input vector. For everything from SSE2
7884 // onward this has a single fast instruction with no scary immediates.
7885 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7886 V1 = DAG.getBitcast(MVT::v4i32, V1);
7887 int WidenedMask[4] = {
7888 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7889 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7890 return DAG.getBitcast(
7892 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7893 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7895 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7896 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7897 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7898 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7900 // If we have a blend of two PACKUS operations an the blend aligns with the
7901 // low and half halves, we can just merge the PACKUS operations. This is
7902 // particularly important as it lets us merge shuffles that this routine itself
7904 auto GetPackNode = [](SDValue V) {
7905 while (V.getOpcode() == ISD::BITCAST)
7906 V = V.getOperand(0);
7908 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7910 if (SDValue V1Pack = GetPackNode(V1))
7911 if (SDValue V2Pack = GetPackNode(V2))
7912 return DAG.getBitcast(MVT::v2i64,
7913 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7914 Mask[0] == 0 ? V1Pack.getOperand(0)
7915 : V1Pack.getOperand(1),
7916 Mask[1] == 2 ? V2Pack.getOperand(0)
7917 : V2Pack.getOperand(1)));
7919 // Try to use shift instructions.
7921 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7924 // When loading a scalar and then shuffling it into a vector we can often do
7925 // the insertion cheaply.
7926 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7927 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7929 // Try inverting the insertion since for v2 masks it is easy to do and we
7930 // can't reliably sort the mask one way or the other.
7931 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7932 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7933 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7936 // We have different paths for blend lowering, but they all must use the
7937 // *exact* same predicate.
7938 bool IsBlendSupported = Subtarget->hasSSE41();
7939 if (IsBlendSupported)
7940 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7944 // Use dedicated unpack instructions for masks that match their pattern.
7945 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7946 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7947 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7948 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7950 // Try to use byte rotation instructions.
7951 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7952 if (Subtarget->hasSSSE3())
7953 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7954 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7957 // If we have direct support for blends, we should lower by decomposing into
7958 // a permute. That will be faster than the domain cross.
7959 if (IsBlendSupported)
7960 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7963 // We implement this with SHUFPD which is pretty lame because it will likely
7964 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7965 // However, all the alternatives are still more cycles and newer chips don't
7966 // have this problem. It would be really nice if x86 had better shuffles here.
7967 V1 = DAG.getBitcast(MVT::v2f64, V1);
7968 V2 = DAG.getBitcast(MVT::v2f64, V2);
7969 return DAG.getBitcast(MVT::v2i64,
7970 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7973 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7975 /// This is used to disable more specialized lowerings when the shufps lowering
7976 /// will happen to be efficient.
7977 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7978 // This routine only handles 128-bit shufps.
7979 assert(Mask.size() == 4 && "Unsupported mask size!");
7981 // To lower with a single SHUFPS we need to have the low half and high half
7982 // each requiring a single input.
7983 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7985 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7991 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7993 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7994 /// It makes no assumptions about whether this is the *best* lowering, it simply
7996 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7997 ArrayRef<int> Mask, SDValue V1,
7998 SDValue V2, SelectionDAG &DAG) {
7999 SDValue LowV = V1, HighV = V2;
8000 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8003 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8005 if (NumV2Elements == 1) {
8007 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8010 // Compute the index adjacent to V2Index and in the same half by toggling
8012 int V2AdjIndex = V2Index ^ 1;
8014 if (Mask[V2AdjIndex] == -1) {
8015 // Handles all the cases where we have a single V2 element and an undef.
8016 // This will only ever happen in the high lanes because we commute the
8017 // vector otherwise.
8019 std::swap(LowV, HighV);
8020 NewMask[V2Index] -= 4;
8022 // Handle the case where the V2 element ends up adjacent to a V1 element.
8023 // To make this work, blend them together as the first step.
8024 int V1Index = V2AdjIndex;
8025 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8026 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8027 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8029 // Now proceed to reconstruct the final blend as we have the necessary
8030 // high or low half formed.
8037 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8038 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8040 } else if (NumV2Elements == 2) {
8041 if (Mask[0] < 4 && Mask[1] < 4) {
8042 // Handle the easy case where we have V1 in the low lanes and V2 in the
8046 } else if (Mask[2] < 4 && Mask[3] < 4) {
8047 // We also handle the reversed case because this utility may get called
8048 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8049 // arrange things in the right direction.
8055 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8056 // trying to place elements directly, just blend them and set up the final
8057 // shuffle to place them.
8059 // The first two blend mask elements are for V1, the second two are for
8061 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8062 Mask[2] < 4 ? Mask[2] : Mask[3],
8063 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8064 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8065 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8066 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8068 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8071 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8072 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8073 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8074 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8077 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8078 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8081 /// \brief Lower 4-lane 32-bit floating point shuffles.
8083 /// Uses instructions exclusively from the floating point unit to minimize
8084 /// domain crossing penalties, as these are sufficient to implement all v4f32
8086 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8087 const X86Subtarget *Subtarget,
8088 SelectionDAG &DAG) {
8090 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8091 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8092 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8093 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8094 ArrayRef<int> Mask = SVOp->getMask();
8095 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8098 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8100 if (NumV2Elements == 0) {
8101 // Check for being able to broadcast a single element.
8102 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8103 Mask, Subtarget, DAG))
8106 // Use even/odd duplicate instructions for masks that match their pattern.
8107 if (Subtarget->hasSSE3()) {
8108 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8109 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8110 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8111 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8114 if (Subtarget->hasAVX()) {
8115 // If we have AVX, we can use VPERMILPS which will allow folding a load
8116 // into the shuffle.
8117 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8118 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8121 // Otherwise, use a straight shuffle of a single input vector. We pass the
8122 // input vector to both operands to simulate this with a SHUFPS.
8123 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8124 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8127 // There are special ways we can lower some single-element blends. However, we
8128 // have custom ways we can lower more complex single-element blends below that
8129 // we defer to if both this and BLENDPS fail to match, so restrict this to
8130 // when the V2 input is targeting element 0 of the mask -- that is the fast
8132 if (NumV2Elements == 1 && Mask[0] >= 4)
8133 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8134 Mask, Subtarget, DAG))
8137 if (Subtarget->hasSSE41()) {
8138 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8142 // Use INSERTPS if we can complete the shuffle efficiently.
8143 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8146 if (!isSingleSHUFPSMask(Mask))
8147 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8148 DL, MVT::v4f32, V1, V2, Mask, DAG))
8152 // Use dedicated unpack instructions for masks that match their pattern.
8153 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8154 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8155 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8156 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8157 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8158 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8159 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8160 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8162 // Otherwise fall back to a SHUFPS lowering strategy.
8163 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8166 /// \brief Lower 4-lane i32 vector shuffles.
8168 /// We try to handle these with integer-domain shuffles where we can, but for
8169 /// blends we use the floating point domain blend instructions.
8170 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8171 const X86Subtarget *Subtarget,
8172 SelectionDAG &DAG) {
8174 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8175 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8176 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8177 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8178 ArrayRef<int> Mask = SVOp->getMask();
8179 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8181 // Whenever we can lower this as a zext, that instruction is strictly faster
8182 // than any alternative. It also allows us to fold memory operands into the
8183 // shuffle in many cases.
8184 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8185 Mask, Subtarget, DAG))
8189 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8191 if (NumV2Elements == 0) {
8192 // Check for being able to broadcast a single element.
8193 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8194 Mask, Subtarget, DAG))
8197 // Straight shuffle of a single input vector. For everything from SSE2
8198 // onward this has a single fast instruction with no scary immediates.
8199 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8200 // but we aren't actually going to use the UNPCK instruction because doing
8201 // so prevents folding a load into this instruction or making a copy.
8202 const int UnpackLoMask[] = {0, 0, 1, 1};
8203 const int UnpackHiMask[] = {2, 2, 3, 3};
8204 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8205 Mask = UnpackLoMask;
8206 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8207 Mask = UnpackHiMask;
8209 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8210 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8213 // Try to use shift instructions.
8215 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8218 // There are special ways we can lower some single-element blends.
8219 if (NumV2Elements == 1)
8220 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8221 Mask, Subtarget, DAG))
8224 // We have different paths for blend lowering, but they all must use the
8225 // *exact* same predicate.
8226 bool IsBlendSupported = Subtarget->hasSSE41();
8227 if (IsBlendSupported)
8228 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8232 if (SDValue Masked =
8233 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8236 // Use dedicated unpack instructions for masks that match their pattern.
8237 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8238 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8239 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8240 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8241 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8242 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8243 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8244 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8246 // Try to use byte rotation instructions.
8247 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8248 if (Subtarget->hasSSSE3())
8249 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8250 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8253 // If we have direct support for blends, we should lower by decomposing into
8254 // a permute. That will be faster than the domain cross.
8255 if (IsBlendSupported)
8256 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8259 // Try to lower by permuting the inputs into an unpack instruction.
8260 if (SDValue Unpack =
8261 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8264 // We implement this with SHUFPS because it can blend from two vectors.
8265 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8266 // up the inputs, bypassing domain shift penalties that we would encur if we
8267 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8269 return DAG.getBitcast(
8271 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8272 DAG.getBitcast(MVT::v4f32, V2), Mask));
8275 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8276 /// shuffle lowering, and the most complex part.
8278 /// The lowering strategy is to try to form pairs of input lanes which are
8279 /// targeted at the same half of the final vector, and then use a dword shuffle
8280 /// to place them onto the right half, and finally unpack the paired lanes into
8281 /// their final position.
8283 /// The exact breakdown of how to form these dword pairs and align them on the
8284 /// correct sides is really tricky. See the comments within the function for
8285 /// more of the details.
8287 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8288 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8289 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8290 /// vector, form the analogous 128-bit 8-element Mask.
8291 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8292 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8293 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8294 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8295 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8297 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8298 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8299 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8301 SmallVector<int, 4> LoInputs;
8302 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8303 [](int M) { return M >= 0; });
8304 std::sort(LoInputs.begin(), LoInputs.end());
8305 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8306 SmallVector<int, 4> HiInputs;
8307 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8308 [](int M) { return M >= 0; });
8309 std::sort(HiInputs.begin(), HiInputs.end());
8310 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8312 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8313 int NumHToL = LoInputs.size() - NumLToL;
8315 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8316 int NumHToH = HiInputs.size() - NumLToH;
8317 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8318 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8319 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8320 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8322 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8323 // such inputs we can swap two of the dwords across the half mark and end up
8324 // with <=2 inputs to each half in each half. Once there, we can fall through
8325 // to the generic code below. For example:
8327 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8328 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8330 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8331 // and an existing 2-into-2 on the other half. In this case we may have to
8332 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8333 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8334 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8335 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8336 // half than the one we target for fixing) will be fixed when we re-enter this
8337 // path. We will also combine away any sequence of PSHUFD instructions that
8338 // result into a single instruction. Here is an example of the tricky case:
8340 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8341 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8343 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8345 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8346 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8348 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8349 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8351 // The result is fine to be handled by the generic logic.
8352 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8353 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8354 int AOffset, int BOffset) {
8355 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8356 "Must call this with A having 3 or 1 inputs from the A half.");
8357 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8358 "Must call this with B having 1 or 3 inputs from the B half.");
8359 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8360 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8362 bool ThreeAInputs = AToAInputs.size() == 3;
8364 // Compute the index of dword with only one word among the three inputs in
8365 // a half by taking the sum of the half with three inputs and subtracting
8366 // the sum of the actual three inputs. The difference is the remaining
8369 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8370 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8371 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8372 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8373 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8374 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8375 int TripleNonInputIdx =
8376 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8377 TripleDWord = TripleNonInputIdx / 2;
8379 // We use xor with one to compute the adjacent DWord to whichever one the
8381 OneInputDWord = (OneInput / 2) ^ 1;
8383 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8384 // and BToA inputs. If there is also such a problem with the BToB and AToB
8385 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8386 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8387 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8388 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8389 // Compute how many inputs will be flipped by swapping these DWords. We
8391 // to balance this to ensure we don't form a 3-1 shuffle in the other
8393 int NumFlippedAToBInputs =
8394 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8395 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8396 int NumFlippedBToBInputs =
8397 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8398 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8399 if ((NumFlippedAToBInputs == 1 &&
8400 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8401 (NumFlippedBToBInputs == 1 &&
8402 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8403 // We choose whether to fix the A half or B half based on whether that
8404 // half has zero flipped inputs. At zero, we may not be able to fix it
8405 // with that half. We also bias towards fixing the B half because that
8406 // will more commonly be the high half, and we have to bias one way.
8407 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8408 ArrayRef<int> Inputs) {
8409 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8410 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8411 PinnedIdx ^ 1) != Inputs.end();
8412 // Determine whether the free index is in the flipped dword or the
8413 // unflipped dword based on where the pinned index is. We use this bit
8414 // in an xor to conditionally select the adjacent dword.
8415 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8416 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8417 FixFreeIdx) != Inputs.end();
8418 if (IsFixIdxInput == IsFixFreeIdxInput)
8420 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8421 FixFreeIdx) != Inputs.end();
8422 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8423 "We need to be changing the number of flipped inputs!");
8424 int PSHUFHalfMask[] = {0, 1, 2, 3};
8425 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8426 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8428 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8431 if (M != -1 && M == FixIdx)
8433 else if (M != -1 && M == FixFreeIdx)
8436 if (NumFlippedBToBInputs != 0) {
8438 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8439 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8441 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8442 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8443 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8448 int PSHUFDMask[] = {0, 1, 2, 3};
8449 PSHUFDMask[ADWord] = BDWord;
8450 PSHUFDMask[BDWord] = ADWord;
8453 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8454 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8456 // Adjust the mask to match the new locations of A and B.
8458 if (M != -1 && M/2 == ADWord)
8459 M = 2 * BDWord + M % 2;
8460 else if (M != -1 && M/2 == BDWord)
8461 M = 2 * ADWord + M % 2;
8463 // Recurse back into this routine to re-compute state now that this isn't
8464 // a 3 and 1 problem.
8465 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8468 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8469 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8470 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8471 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8473 // At this point there are at most two inputs to the low and high halves from
8474 // each half. That means the inputs can always be grouped into dwords and
8475 // those dwords can then be moved to the correct half with a dword shuffle.
8476 // We use at most one low and one high word shuffle to collect these paired
8477 // inputs into dwords, and finally a dword shuffle to place them.
8478 int PSHUFLMask[4] = {-1, -1, -1, -1};
8479 int PSHUFHMask[4] = {-1, -1, -1, -1};
8480 int PSHUFDMask[4] = {-1, -1, -1, -1};
8482 // First fix the masks for all the inputs that are staying in their
8483 // original halves. This will then dictate the targets of the cross-half
8485 auto fixInPlaceInputs =
8486 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8487 MutableArrayRef<int> SourceHalfMask,
8488 MutableArrayRef<int> HalfMask, int HalfOffset) {
8489 if (InPlaceInputs.empty())
8491 if (InPlaceInputs.size() == 1) {
8492 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8493 InPlaceInputs[0] - HalfOffset;
8494 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8497 if (IncomingInputs.empty()) {
8498 // Just fix all of the in place inputs.
8499 for (int Input : InPlaceInputs) {
8500 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8501 PSHUFDMask[Input / 2] = Input / 2;
8506 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8507 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8508 InPlaceInputs[0] - HalfOffset;
8509 // Put the second input next to the first so that they are packed into
8510 // a dword. We find the adjacent index by toggling the low bit.
8511 int AdjIndex = InPlaceInputs[0] ^ 1;
8512 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8513 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8514 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8516 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8517 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8519 // Now gather the cross-half inputs and place them into a free dword of
8520 // their target half.
8521 // FIXME: This operation could almost certainly be simplified dramatically to
8522 // look more like the 3-1 fixing operation.
8523 auto moveInputsToRightHalf = [&PSHUFDMask](
8524 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8525 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8526 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8528 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8529 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8531 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8533 int LowWord = Word & ~1;
8534 int HighWord = Word | 1;
8535 return isWordClobbered(SourceHalfMask, LowWord) ||
8536 isWordClobbered(SourceHalfMask, HighWord);
8539 if (IncomingInputs.empty())
8542 if (ExistingInputs.empty()) {
8543 // Map any dwords with inputs from them into the right half.
8544 for (int Input : IncomingInputs) {
8545 // If the source half mask maps over the inputs, turn those into
8546 // swaps and use the swapped lane.
8547 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8548 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8549 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8550 Input - SourceOffset;
8551 // We have to swap the uses in our half mask in one sweep.
8552 for (int &M : HalfMask)
8553 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8555 else if (M == Input)
8556 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8558 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8559 Input - SourceOffset &&
8560 "Previous placement doesn't match!");
8562 // Note that this correctly re-maps both when we do a swap and when
8563 // we observe the other side of the swap above. We rely on that to
8564 // avoid swapping the members of the input list directly.
8565 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8568 // Map the input's dword into the correct half.
8569 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8570 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8572 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8574 "Previous placement doesn't match!");
8577 // And just directly shift any other-half mask elements to be same-half
8578 // as we will have mirrored the dword containing the element into the
8579 // same position within that half.
8580 for (int &M : HalfMask)
8581 if (M >= SourceOffset && M < SourceOffset + 4) {
8582 M = M - SourceOffset + DestOffset;
8583 assert(M >= 0 && "This should never wrap below zero!");
8588 // Ensure we have the input in a viable dword of its current half. This
8589 // is particularly tricky because the original position may be clobbered
8590 // by inputs being moved and *staying* in that half.
8591 if (IncomingInputs.size() == 1) {
8592 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8593 int InputFixed = std::find(std::begin(SourceHalfMask),
8594 std::end(SourceHalfMask), -1) -
8595 std::begin(SourceHalfMask) + SourceOffset;
8596 SourceHalfMask[InputFixed - SourceOffset] =
8597 IncomingInputs[0] - SourceOffset;
8598 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8600 IncomingInputs[0] = InputFixed;
8602 } else if (IncomingInputs.size() == 2) {
8603 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8604 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8605 // We have two non-adjacent or clobbered inputs we need to extract from
8606 // the source half. To do this, we need to map them into some adjacent
8607 // dword slot in the source mask.
8608 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8609 IncomingInputs[1] - SourceOffset};
8611 // If there is a free slot in the source half mask adjacent to one of
8612 // the inputs, place the other input in it. We use (Index XOR 1) to
8613 // compute an adjacent index.
8614 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8615 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8616 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8617 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8618 InputsFixed[1] = InputsFixed[0] ^ 1;
8619 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8620 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8621 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8622 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8623 InputsFixed[0] = InputsFixed[1] ^ 1;
8624 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8625 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8626 // The two inputs are in the same DWord but it is clobbered and the
8627 // adjacent DWord isn't used at all. Move both inputs to the free
8629 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8630 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8631 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8632 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8634 // The only way we hit this point is if there is no clobbering
8635 // (because there are no off-half inputs to this half) and there is no
8636 // free slot adjacent to one of the inputs. In this case, we have to
8637 // swap an input with a non-input.
8638 for (int i = 0; i < 4; ++i)
8639 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8640 "We can't handle any clobbers here!");
8641 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8642 "Cannot have adjacent inputs here!");
8644 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8645 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8647 // We also have to update the final source mask in this case because
8648 // it may need to undo the above swap.
8649 for (int &M : FinalSourceHalfMask)
8650 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8651 M = InputsFixed[1] + SourceOffset;
8652 else if (M == InputsFixed[1] + SourceOffset)
8653 M = (InputsFixed[0] ^ 1) + SourceOffset;
8655 InputsFixed[1] = InputsFixed[0] ^ 1;
8658 // Point everything at the fixed inputs.
8659 for (int &M : HalfMask)
8660 if (M == IncomingInputs[0])
8661 M = InputsFixed[0] + SourceOffset;
8662 else if (M == IncomingInputs[1])
8663 M = InputsFixed[1] + SourceOffset;
8665 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8666 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8669 llvm_unreachable("Unhandled input size!");
8672 // Now hoist the DWord down to the right half.
8673 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8674 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8675 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8676 for (int &M : HalfMask)
8677 for (int Input : IncomingInputs)
8679 M = FreeDWord * 2 + Input % 2;
8681 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8682 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8683 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8684 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8686 // Now enact all the shuffles we've computed to move the inputs into their
8688 if (!isNoopShuffleMask(PSHUFLMask))
8689 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8690 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8691 if (!isNoopShuffleMask(PSHUFHMask))
8692 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8693 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8694 if (!isNoopShuffleMask(PSHUFDMask))
8697 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8698 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8700 // At this point, each half should contain all its inputs, and we can then
8701 // just shuffle them into their final position.
8702 assert(std::count_if(LoMask.begin(), LoMask.end(),
8703 [](int M) { return M >= 4; }) == 0 &&
8704 "Failed to lift all the high half inputs to the low mask!");
8705 assert(std::count_if(HiMask.begin(), HiMask.end(),
8706 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8707 "Failed to lift all the low half inputs to the high mask!");
8709 // Do a half shuffle for the low mask.
8710 if (!isNoopShuffleMask(LoMask))
8711 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8712 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8714 // Do a half shuffle with the high mask after shifting its values down.
8715 for (int &M : HiMask)
8718 if (!isNoopShuffleMask(HiMask))
8719 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8720 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8725 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8726 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8727 SDValue V2, ArrayRef<int> Mask,
8728 SelectionDAG &DAG, bool &V1InUse,
8730 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8736 int Size = Mask.size();
8737 int Scale = 16 / Size;
8738 for (int i = 0; i < 16; ++i) {
8739 if (Mask[i / Scale] == -1) {
8740 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8742 const int ZeroMask = 0x80;
8743 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8745 int V2Idx = Mask[i / Scale] < Size
8747 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8748 if (Zeroable[i / Scale])
8749 V1Idx = V2Idx = ZeroMask;
8750 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8751 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8752 V1InUse |= (ZeroMask != V1Idx);
8753 V2InUse |= (ZeroMask != V2Idx);
8758 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8759 DAG.getBitcast(MVT::v16i8, V1),
8760 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8762 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8763 DAG.getBitcast(MVT::v16i8, V2),
8764 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8766 // If we need shuffled inputs from both, blend the two.
8768 if (V1InUse && V2InUse)
8769 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8771 V = V1InUse ? V1 : V2;
8773 // Cast the result back to the correct type.
8774 return DAG.getBitcast(VT, V);
8777 /// \brief Generic lowering of 8-lane i16 shuffles.
8779 /// This handles both single-input shuffles and combined shuffle/blends with
8780 /// two inputs. The single input shuffles are immediately delegated to
8781 /// a dedicated lowering routine.
8783 /// The blends are lowered in one of three fundamental ways. If there are few
8784 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8785 /// of the input is significantly cheaper when lowered as an interleaving of
8786 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8787 /// halves of the inputs separately (making them have relatively few inputs)
8788 /// and then concatenate them.
8789 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8790 const X86Subtarget *Subtarget,
8791 SelectionDAG &DAG) {
8793 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8794 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8795 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8796 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8797 ArrayRef<int> OrigMask = SVOp->getMask();
8798 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8799 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8800 MutableArrayRef<int> Mask(MaskStorage);
8802 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8804 // Whenever we can lower this as a zext, that instruction is strictly faster
8805 // than any alternative.
8806 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8807 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8810 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8812 auto isV2 = [](int M) { return M >= 8; };
8814 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8816 if (NumV2Inputs == 0) {
8817 // Check for being able to broadcast a single element.
8818 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8819 Mask, Subtarget, DAG))
8822 // Try to use shift instructions.
8824 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8827 // Use dedicated unpack instructions for masks that match their pattern.
8828 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8829 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8830 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8831 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8833 // Try to use byte rotation instructions.
8834 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8835 Mask, Subtarget, DAG))
8838 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8842 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8843 "All single-input shuffles should be canonicalized to be V1-input "
8846 // Try to use shift instructions.
8848 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8851 // See if we can use SSE4A Extraction / Insertion.
8852 if (Subtarget->hasSSE4A())
8853 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8856 // There are special ways we can lower some single-element blends.
8857 if (NumV2Inputs == 1)
8858 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8859 Mask, Subtarget, DAG))
8862 // We have different paths for blend lowering, but they all must use the
8863 // *exact* same predicate.
8864 bool IsBlendSupported = Subtarget->hasSSE41();
8865 if (IsBlendSupported)
8866 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8870 if (SDValue Masked =
8871 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8874 // Use dedicated unpack instructions for masks that match their pattern.
8875 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8876 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8877 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8878 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8880 // Try to use byte rotation instructions.
8881 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8882 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8885 if (SDValue BitBlend =
8886 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8889 if (SDValue Unpack =
8890 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8893 // If we can't directly blend but can use PSHUFB, that will be better as it
8894 // can both shuffle and set up the inefficient blend.
8895 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8896 bool V1InUse, V2InUse;
8897 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8901 // We can always bit-blend if we have to so the fallback strategy is to
8902 // decompose into single-input permutes and blends.
8903 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8907 /// \brief Check whether a compaction lowering can be done by dropping even
8908 /// elements and compute how many times even elements must be dropped.
8910 /// This handles shuffles which take every Nth element where N is a power of
8911 /// two. Example shuffle masks:
8913 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8914 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8915 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8916 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8917 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8918 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8920 /// Any of these lanes can of course be undef.
8922 /// This routine only supports N <= 3.
8923 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8926 /// \returns N above, or the number of times even elements must be dropped if
8927 /// there is such a number. Otherwise returns zero.
8928 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8929 // Figure out whether we're looping over two inputs or just one.
8930 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8932 // The modulus for the shuffle vector entries is based on whether this is
8933 // a single input or not.
8934 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8935 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8936 "We should only be called with masks with a power-of-2 size!");
8938 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8940 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8941 // and 2^3 simultaneously. This is because we may have ambiguity with
8942 // partially undef inputs.
8943 bool ViableForN[3] = {true, true, true};
8945 for (int i = 0, e = Mask.size(); i < e; ++i) {
8946 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8951 bool IsAnyViable = false;
8952 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8953 if (ViableForN[j]) {
8956 // The shuffle mask must be equal to (i * 2^N) % M.
8957 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8960 ViableForN[j] = false;
8962 // Early exit if we exhaust the possible powers of two.
8967 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8971 // Return 0 as there is no viable power of two.
8975 /// \brief Generic lowering of v16i8 shuffles.
8977 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8978 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8979 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8980 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8982 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8983 const X86Subtarget *Subtarget,
8984 SelectionDAG &DAG) {
8986 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8987 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8988 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8989 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8990 ArrayRef<int> Mask = SVOp->getMask();
8991 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8993 // Try to use shift instructions.
8995 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8998 // Try to use byte rotation instructions.
8999 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9000 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9003 // Try to use a zext lowering.
9004 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9005 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9008 // See if we can use SSE4A Extraction / Insertion.
9009 if (Subtarget->hasSSE4A())
9010 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9014 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9016 // For single-input shuffles, there are some nicer lowering tricks we can use.
9017 if (NumV2Elements == 0) {
9018 // Check for being able to broadcast a single element.
9019 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9020 Mask, Subtarget, DAG))
9023 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9024 // Notably, this handles splat and partial-splat shuffles more efficiently.
9025 // However, it only makes sense if the pre-duplication shuffle simplifies
9026 // things significantly. Currently, this means we need to be able to
9027 // express the pre-duplication shuffle as an i16 shuffle.
9029 // FIXME: We should check for other patterns which can be widened into an
9030 // i16 shuffle as well.
9031 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9032 for (int i = 0; i < 16; i += 2)
9033 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9038 auto tryToWidenViaDuplication = [&]() -> SDValue {
9039 if (!canWidenViaDuplication(Mask))
9041 SmallVector<int, 4> LoInputs;
9042 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9043 [](int M) { return M >= 0 && M < 8; });
9044 std::sort(LoInputs.begin(), LoInputs.end());
9045 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9047 SmallVector<int, 4> HiInputs;
9048 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9049 [](int M) { return M >= 8; });
9050 std::sort(HiInputs.begin(), HiInputs.end());
9051 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9054 bool TargetLo = LoInputs.size() >= HiInputs.size();
9055 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9056 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9058 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9059 SmallDenseMap<int, int, 8> LaneMap;
9060 for (int I : InPlaceInputs) {
9061 PreDupI16Shuffle[I/2] = I/2;
9064 int j = TargetLo ? 0 : 4, je = j + 4;
9065 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9066 // Check if j is already a shuffle of this input. This happens when
9067 // there are two adjacent bytes after we move the low one.
9068 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9069 // If we haven't yet mapped the input, search for a slot into which
9071 while (j < je && PreDupI16Shuffle[j] != -1)
9075 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9078 // Map this input with the i16 shuffle.
9079 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9082 // Update the lane map based on the mapping we ended up with.
9083 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9085 V1 = DAG.getBitcast(
9087 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9088 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9090 // Unpack the bytes to form the i16s that will be shuffled into place.
9091 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9092 MVT::v16i8, V1, V1);
9094 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9095 for (int i = 0; i < 16; ++i)
9096 if (Mask[i] != -1) {
9097 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9098 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9099 if (PostDupI16Shuffle[i / 2] == -1)
9100 PostDupI16Shuffle[i / 2] = MappedMask;
9102 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9103 "Conflicting entrties in the original shuffle!");
9105 return DAG.getBitcast(
9107 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9108 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9110 if (SDValue V = tryToWidenViaDuplication())
9114 if (SDValue Masked =
9115 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9118 // Use dedicated unpack instructions for masks that match their pattern.
9119 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9120 0, 16, 1, 17, 2, 18, 3, 19,
9122 4, 20, 5, 21, 6, 22, 7, 23}))
9123 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9124 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9125 8, 24, 9, 25, 10, 26, 11, 27,
9127 12, 28, 13, 29, 14, 30, 15, 31}))
9128 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9130 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9131 // with PSHUFB. It is important to do this before we attempt to generate any
9132 // blends but after all of the single-input lowerings. If the single input
9133 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9134 // want to preserve that and we can DAG combine any longer sequences into
9135 // a PSHUFB in the end. But once we start blending from multiple inputs,
9136 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9137 // and there are *very* few patterns that would actually be faster than the
9138 // PSHUFB approach because of its ability to zero lanes.
9140 // FIXME: The only exceptions to the above are blends which are exact
9141 // interleavings with direct instructions supporting them. We currently don't
9142 // handle those well here.
9143 if (Subtarget->hasSSSE3()) {
9144 bool V1InUse = false;
9145 bool V2InUse = false;
9147 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9148 DAG, V1InUse, V2InUse);
9150 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9151 // do so. This avoids using them to handle blends-with-zero which is
9152 // important as a single pshufb is significantly faster for that.
9153 if (V1InUse && V2InUse) {
9154 if (Subtarget->hasSSE41())
9155 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9156 Mask, Subtarget, DAG))
9159 // We can use an unpack to do the blending rather than an or in some
9160 // cases. Even though the or may be (very minorly) more efficient, we
9161 // preference this lowering because there are common cases where part of
9162 // the complexity of the shuffles goes away when we do the final blend as
9164 // FIXME: It might be worth trying to detect if the unpack-feeding
9165 // shuffles will both be pshufb, in which case we shouldn't bother with
9167 if (SDValue Unpack =
9168 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9175 // There are special ways we can lower some single-element blends.
9176 if (NumV2Elements == 1)
9177 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9178 Mask, Subtarget, DAG))
9181 if (SDValue BitBlend =
9182 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9185 // Check whether a compaction lowering can be done. This handles shuffles
9186 // which take every Nth element for some even N. See the helper function for
9189 // We special case these as they can be particularly efficiently handled with
9190 // the PACKUSB instruction on x86 and they show up in common patterns of
9191 // rearranging bytes to truncate wide elements.
9192 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9193 // NumEvenDrops is the power of two stride of the elements. Another way of
9194 // thinking about it is that we need to drop the even elements this many
9195 // times to get the original input.
9196 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9198 // First we need to zero all the dropped bytes.
9199 assert(NumEvenDrops <= 3 &&
9200 "No support for dropping even elements more than 3 times.");
9201 // We use the mask type to pick which bytes are preserved based on how many
9202 // elements are dropped.
9203 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9204 SDValue ByteClearMask = DAG.getBitcast(
9205 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9206 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9208 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9210 // Now pack things back together.
9211 V1 = DAG.getBitcast(MVT::v8i16, V1);
9212 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9213 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9214 for (int i = 1; i < NumEvenDrops; ++i) {
9215 Result = DAG.getBitcast(MVT::v8i16, Result);
9216 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9222 // Handle multi-input cases by blending single-input shuffles.
9223 if (NumV2Elements > 0)
9224 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9227 // The fallback path for single-input shuffles widens this into two v8i16
9228 // vectors with unpacks, shuffles those, and then pulls them back together
9232 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9233 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9234 for (int i = 0; i < 16; ++i)
9236 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9238 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9240 SDValue VLoHalf, VHiHalf;
9241 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9242 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9244 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9245 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9246 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9247 [](int M) { return M >= 0 && M % 2 == 1; })) {
9248 // Use a mask to drop the high bytes.
9249 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9250 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9251 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9253 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9254 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9256 // Squash the masks to point directly into VLoHalf.
9257 for (int &M : LoBlendMask)
9260 for (int &M : HiBlendMask)
9264 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9265 // VHiHalf so that we can blend them as i16s.
9266 VLoHalf = DAG.getBitcast(
9267 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9268 VHiHalf = DAG.getBitcast(
9269 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9272 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9273 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9275 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9278 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9280 /// This routine breaks down the specific type of 128-bit shuffle and
9281 /// dispatches to the lowering routines accordingly.
9282 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9283 MVT VT, const X86Subtarget *Subtarget,
9284 SelectionDAG &DAG) {
9285 switch (VT.SimpleTy) {
9287 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9289 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9291 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9293 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9295 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9297 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9300 llvm_unreachable("Unimplemented!");
9304 /// \brief Helper function to test whether a shuffle mask could be
9305 /// simplified by widening the elements being shuffled.
9307 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9308 /// leaves it in an unspecified state.
9310 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9311 /// shuffle masks. The latter have the special property of a '-2' representing
9312 /// a zero-ed lane of a vector.
9313 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9314 SmallVectorImpl<int> &WidenedMask) {
9315 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9316 // If both elements are undef, its trivial.
9317 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9318 WidenedMask.push_back(SM_SentinelUndef);
9322 // Check for an undef mask and a mask value properly aligned to fit with
9323 // a pair of values. If we find such a case, use the non-undef mask's value.
9324 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9325 WidenedMask.push_back(Mask[i + 1] / 2);
9328 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9329 WidenedMask.push_back(Mask[i] / 2);
9333 // When zeroing, we need to spread the zeroing across both lanes to widen.
9334 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9335 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9336 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9337 WidenedMask.push_back(SM_SentinelZero);
9343 // Finally check if the two mask values are adjacent and aligned with
9345 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9346 WidenedMask.push_back(Mask[i] / 2);
9350 // Otherwise we can't safely widen the elements used in this shuffle.
9353 assert(WidenedMask.size() == Mask.size() / 2 &&
9354 "Incorrect size of mask after widening the elements!");
9359 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9361 /// This routine just extracts two subvectors, shuffles them independently, and
9362 /// then concatenates them back together. This should work effectively with all
9363 /// AVX vector shuffle types.
9364 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9365 SDValue V2, ArrayRef<int> Mask,
9366 SelectionDAG &DAG) {
9367 assert(VT.getSizeInBits() >= 256 &&
9368 "Only for 256-bit or wider vector shuffles!");
9369 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9370 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9372 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9373 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9375 int NumElements = VT.getVectorNumElements();
9376 int SplitNumElements = NumElements / 2;
9377 MVT ScalarVT = VT.getScalarType();
9378 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9380 // Rather than splitting build-vectors, just build two narrower build
9381 // vectors. This helps shuffling with splats and zeros.
9382 auto SplitVector = [&](SDValue V) {
9383 while (V.getOpcode() == ISD::BITCAST)
9384 V = V->getOperand(0);
9386 MVT OrigVT = V.getSimpleValueType();
9387 int OrigNumElements = OrigVT.getVectorNumElements();
9388 int OrigSplitNumElements = OrigNumElements / 2;
9389 MVT OrigScalarVT = OrigVT.getScalarType();
9390 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9394 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9396 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9397 DAG.getIntPtrConstant(0, DL));
9398 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9399 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9402 SmallVector<SDValue, 16> LoOps, HiOps;
9403 for (int i = 0; i < OrigSplitNumElements; ++i) {
9404 LoOps.push_back(BV->getOperand(i));
9405 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9407 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9408 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9410 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9411 DAG.getBitcast(SplitVT, HiV));
9414 SDValue LoV1, HiV1, LoV2, HiV2;
9415 std::tie(LoV1, HiV1) = SplitVector(V1);
9416 std::tie(LoV2, HiV2) = SplitVector(V2);
9418 // Now create two 4-way blends of these half-width vectors.
9419 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9420 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9421 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9422 for (int i = 0; i < SplitNumElements; ++i) {
9423 int M = HalfMask[i];
9424 if (M >= NumElements) {
9425 if (M >= NumElements + SplitNumElements)
9429 V2BlendMask.push_back(M - NumElements);
9430 V1BlendMask.push_back(-1);
9431 BlendMask.push_back(SplitNumElements + i);
9432 } else if (M >= 0) {
9433 if (M >= SplitNumElements)
9437 V2BlendMask.push_back(-1);
9438 V1BlendMask.push_back(M);
9439 BlendMask.push_back(i);
9441 V2BlendMask.push_back(-1);
9442 V1BlendMask.push_back(-1);
9443 BlendMask.push_back(-1);
9447 // Because the lowering happens after all combining takes place, we need to
9448 // manually combine these blend masks as much as possible so that we create
9449 // a minimal number of high-level vector shuffle nodes.
9451 // First try just blending the halves of V1 or V2.
9452 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9453 return DAG.getUNDEF(SplitVT);
9454 if (!UseLoV2 && !UseHiV2)
9455 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9456 if (!UseLoV1 && !UseHiV1)
9457 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9459 SDValue V1Blend, V2Blend;
9460 if (UseLoV1 && UseHiV1) {
9462 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9464 // We only use half of V1 so map the usage down into the final blend mask.
9465 V1Blend = UseLoV1 ? LoV1 : HiV1;
9466 for (int i = 0; i < SplitNumElements; ++i)
9467 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9468 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9470 if (UseLoV2 && UseHiV2) {
9472 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9474 // We only use half of V2 so map the usage down into the final blend mask.
9475 V2Blend = UseLoV2 ? LoV2 : HiV2;
9476 for (int i = 0; i < SplitNumElements; ++i)
9477 if (BlendMask[i] >= SplitNumElements)
9478 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9480 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9482 SDValue Lo = HalfBlend(LoMask);
9483 SDValue Hi = HalfBlend(HiMask);
9484 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9487 /// \brief Either split a vector in halves or decompose the shuffles and the
9490 /// This is provided as a good fallback for many lowerings of non-single-input
9491 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9492 /// between splitting the shuffle into 128-bit components and stitching those
9493 /// back together vs. extracting the single-input shuffles and blending those
9495 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9496 SDValue V2, ArrayRef<int> Mask,
9497 SelectionDAG &DAG) {
9498 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9499 "lower single-input shuffles as it "
9500 "could then recurse on itself.");
9501 int Size = Mask.size();
9503 // If this can be modeled as a broadcast of two elements followed by a blend,
9504 // prefer that lowering. This is especially important because broadcasts can
9505 // often fold with memory operands.
9506 auto DoBothBroadcast = [&] {
9507 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9510 if (V2BroadcastIdx == -1)
9511 V2BroadcastIdx = M - Size;
9512 else if (M - Size != V2BroadcastIdx)
9514 } else if (M >= 0) {
9515 if (V1BroadcastIdx == -1)
9517 else if (M != V1BroadcastIdx)
9522 if (DoBothBroadcast())
9523 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9526 // If the inputs all stem from a single 128-bit lane of each input, then we
9527 // split them rather than blending because the split will decompose to
9528 // unusually few instructions.
9529 int LaneCount = VT.getSizeInBits() / 128;
9530 int LaneSize = Size / LaneCount;
9531 SmallBitVector LaneInputs[2];
9532 LaneInputs[0].resize(LaneCount, false);
9533 LaneInputs[1].resize(LaneCount, false);
9534 for (int i = 0; i < Size; ++i)
9536 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9537 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9538 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9540 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9541 // that the decomposed single-input shuffles don't end up here.
9542 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9545 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9546 /// a permutation and blend of those lanes.
9548 /// This essentially blends the out-of-lane inputs to each lane into the lane
9549 /// from a permuted copy of the vector. This lowering strategy results in four
9550 /// instructions in the worst case for a single-input cross lane shuffle which
9551 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9552 /// of. Special cases for each particular shuffle pattern should be handled
9553 /// prior to trying this lowering.
9554 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9555 SDValue V1, SDValue V2,
9557 SelectionDAG &DAG) {
9558 // FIXME: This should probably be generalized for 512-bit vectors as well.
9559 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9560 int LaneSize = Mask.size() / 2;
9562 // If there are only inputs from one 128-bit lane, splitting will in fact be
9563 // less expensive. The flags track whether the given lane contains an element
9564 // that crosses to another lane.
9565 bool LaneCrossing[2] = {false, false};
9566 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9567 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9568 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9569 if (!LaneCrossing[0] || !LaneCrossing[1])
9570 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9572 if (isSingleInputShuffleMask(Mask)) {
9573 SmallVector<int, 32> FlippedBlendMask;
9574 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9575 FlippedBlendMask.push_back(
9576 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9578 : Mask[i] % LaneSize +
9579 (i / LaneSize) * LaneSize + Size));
9581 // Flip the vector, and blend the results which should now be in-lane. The
9582 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9583 // 5 for the high source. The value 3 selects the high half of source 2 and
9584 // the value 2 selects the low half of source 2. We only use source 2 to
9585 // allow folding it into a memory operand.
9586 unsigned PERMMask = 3 | 2 << 4;
9587 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9588 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9589 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9592 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9593 // will be handled by the above logic and a blend of the results, much like
9594 // other patterns in AVX.
9595 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9598 /// \brief Handle lowering 2-lane 128-bit shuffles.
9599 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9600 SDValue V2, ArrayRef<int> Mask,
9601 const X86Subtarget *Subtarget,
9602 SelectionDAG &DAG) {
9603 // TODO: If minimizing size and one of the inputs is a zero vector and the
9604 // the zero vector has only one use, we could use a VPERM2X128 to save the
9605 // instruction bytes needed to explicitly generate the zero vector.
9607 // Blends are faster and handle all the non-lane-crossing cases.
9608 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9612 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9613 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9615 // If either input operand is a zero vector, use VPERM2X128 because its mask
9616 // allows us to replace the zero input with an implicit zero.
9617 if (!IsV1Zero && !IsV2Zero) {
9618 // Check for patterns which can be matched with a single insert of a 128-bit
9620 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9621 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9622 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9623 VT.getVectorNumElements() / 2);
9624 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9625 DAG.getIntPtrConstant(0, DL));
9626 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9627 OnlyUsesV1 ? V1 : V2,
9628 DAG.getIntPtrConstant(0, DL));
9629 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9633 // Otherwise form a 128-bit permutation. After accounting for undefs,
9634 // convert the 64-bit shuffle mask selection values into 128-bit
9635 // selection bits by dividing the indexes by 2 and shifting into positions
9636 // defined by a vperm2*128 instruction's immediate control byte.
9638 // The immediate permute control byte looks like this:
9639 // [1:0] - select 128 bits from sources for low half of destination
9641 // [3] - zero low half of destination
9642 // [5:4] - select 128 bits from sources for high half of destination
9644 // [7] - zero high half of destination
9646 int MaskLO = Mask[0];
9647 if (MaskLO == SM_SentinelUndef)
9648 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9650 int MaskHI = Mask[2];
9651 if (MaskHI == SM_SentinelUndef)
9652 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9654 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9656 // If either input is a zero vector, replace it with an undef input.
9657 // Shuffle mask values < 4 are selecting elements of V1.
9658 // Shuffle mask values >= 4 are selecting elements of V2.
9659 // Adjust each half of the permute mask by clearing the half that was
9660 // selecting the zero vector and setting the zero mask bit.
9662 V1 = DAG.getUNDEF(VT);
9664 PermMask = (PermMask & 0xf0) | 0x08;
9666 PermMask = (PermMask & 0x0f) | 0x80;
9669 V2 = DAG.getUNDEF(VT);
9671 PermMask = (PermMask & 0xf0) | 0x08;
9673 PermMask = (PermMask & 0x0f) | 0x80;
9676 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9677 DAG.getConstant(PermMask, DL, MVT::i8));
9680 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9681 /// shuffling each lane.
9683 /// This will only succeed when the result of fixing the 128-bit lanes results
9684 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9685 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9686 /// the lane crosses early and then use simpler shuffles within each lane.
9688 /// FIXME: It might be worthwhile at some point to support this without
9689 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9690 /// in x86 only floating point has interesting non-repeating shuffles, and even
9691 /// those are still *marginally* more expensive.
9692 static SDValue lowerVectorShuffleByMerging128BitLanes(
9693 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9694 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9695 assert(!isSingleInputShuffleMask(Mask) &&
9696 "This is only useful with multiple inputs.");
9698 int Size = Mask.size();
9699 int LaneSize = 128 / VT.getScalarSizeInBits();
9700 int NumLanes = Size / LaneSize;
9701 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9703 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9704 // check whether the in-128-bit lane shuffles share a repeating pattern.
9705 SmallVector<int, 4> Lanes;
9706 Lanes.resize(NumLanes, -1);
9707 SmallVector<int, 4> InLaneMask;
9708 InLaneMask.resize(LaneSize, -1);
9709 for (int i = 0; i < Size; ++i) {
9713 int j = i / LaneSize;
9716 // First entry we've seen for this lane.
9717 Lanes[j] = Mask[i] / LaneSize;
9718 } else if (Lanes[j] != Mask[i] / LaneSize) {
9719 // This doesn't match the lane selected previously!
9723 // Check that within each lane we have a consistent shuffle mask.
9724 int k = i % LaneSize;
9725 if (InLaneMask[k] < 0) {
9726 InLaneMask[k] = Mask[i] % LaneSize;
9727 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9728 // This doesn't fit a repeating in-lane mask.
9733 // First shuffle the lanes into place.
9734 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9735 VT.getSizeInBits() / 64);
9736 SmallVector<int, 8> LaneMask;
9737 LaneMask.resize(NumLanes * 2, -1);
9738 for (int i = 0; i < NumLanes; ++i)
9739 if (Lanes[i] >= 0) {
9740 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9741 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9744 V1 = DAG.getBitcast(LaneVT, V1);
9745 V2 = DAG.getBitcast(LaneVT, V2);
9746 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9748 // Cast it back to the type we actually want.
9749 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9751 // Now do a simple shuffle that isn't lane crossing.
9752 SmallVector<int, 8> NewMask;
9753 NewMask.resize(Size, -1);
9754 for (int i = 0; i < Size; ++i)
9756 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9757 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9758 "Must not introduce lane crosses at this point!");
9760 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9763 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9766 /// This returns true if the elements from a particular input are already in the
9767 /// slot required by the given mask and require no permutation.
9768 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9769 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9770 int Size = Mask.size();
9771 for (int i = 0; i < Size; ++i)
9772 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9778 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9779 ArrayRef<int> Mask, SDValue V1,
9780 SDValue V2, SelectionDAG &DAG) {
9782 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9783 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9784 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9785 int NumElts = VT.getVectorNumElements();
9786 bool ShufpdMask = true;
9787 bool CommutableMask = true;
9788 unsigned Immediate = 0;
9789 for (int i = 0; i < NumElts; ++i) {
9792 int Val = (i & 6) + NumElts * (i & 1);
9793 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9794 if (Mask[i] < Val || Mask[i] > Val + 1)
9796 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9797 CommutableMask = false;
9798 Immediate |= (Mask[i] % 2) << i;
9801 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9802 DAG.getConstant(Immediate, DL, MVT::i8));
9804 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9805 DAG.getConstant(Immediate, DL, MVT::i8));
9809 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9811 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9812 /// isn't available.
9813 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9814 const X86Subtarget *Subtarget,
9815 SelectionDAG &DAG) {
9817 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9818 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9819 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9820 ArrayRef<int> Mask = SVOp->getMask();
9821 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9823 SmallVector<int, 4> WidenedMask;
9824 if (canWidenShuffleElements(Mask, WidenedMask))
9825 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9828 if (isSingleInputShuffleMask(Mask)) {
9829 // Check for being able to broadcast a single element.
9830 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9831 Mask, Subtarget, DAG))
9834 // Use low duplicate instructions for masks that match their pattern.
9835 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9836 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9838 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9839 // Non-half-crossing single input shuffles can be lowerid with an
9840 // interleaved permutation.
9841 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9842 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9843 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9844 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9847 // With AVX2 we have direct support for this permutation.
9848 if (Subtarget->hasAVX2())
9849 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9850 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9852 // Otherwise, fall back.
9853 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9857 // X86 has dedicated unpack instructions that can handle specific blend
9858 // operations: UNPCKH and UNPCKL.
9859 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9860 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9861 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9862 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9863 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9864 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9865 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9866 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9868 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9872 // Check if the blend happens to exactly fit that of SHUFPD.
9874 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9877 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9878 // shuffle. However, if we have AVX2 and either inputs are already in place,
9879 // we will be able to shuffle even across lanes the other input in a single
9880 // instruction so skip this pattern.
9881 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9882 isShuffleMaskInputInPlace(1, Mask))))
9883 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9884 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9887 // If we have AVX2 then we always want to lower with a blend because an v4 we
9888 // can fully permute the elements.
9889 if (Subtarget->hasAVX2())
9890 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9893 // Otherwise fall back on generic lowering.
9894 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9897 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9899 /// This routine is only called when we have AVX2 and thus a reasonable
9900 /// instruction set for v4i64 shuffling..
9901 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9902 const X86Subtarget *Subtarget,
9903 SelectionDAG &DAG) {
9905 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9906 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9907 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9908 ArrayRef<int> Mask = SVOp->getMask();
9909 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9910 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9912 SmallVector<int, 4> WidenedMask;
9913 if (canWidenShuffleElements(Mask, WidenedMask))
9914 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9917 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9921 // Check for being able to broadcast a single element.
9922 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9923 Mask, Subtarget, DAG))
9926 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9927 // use lower latency instructions that will operate on both 128-bit lanes.
9928 SmallVector<int, 2> RepeatedMask;
9929 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9930 if (isSingleInputShuffleMask(Mask)) {
9931 int PSHUFDMask[] = {-1, -1, -1, -1};
9932 for (int i = 0; i < 2; ++i)
9933 if (RepeatedMask[i] >= 0) {
9934 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9935 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9937 return DAG.getBitcast(
9939 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9940 DAG.getBitcast(MVT::v8i32, V1),
9941 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9945 // AVX2 provides a direct instruction for permuting a single input across
9947 if (isSingleInputShuffleMask(Mask))
9948 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9949 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9951 // Try to use shift instructions.
9953 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9956 // Use dedicated unpack instructions for masks that match their pattern.
9957 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9958 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9959 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9960 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9961 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9962 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9963 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9964 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9966 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9967 // shuffle. However, if we have AVX2 and either inputs are already in place,
9968 // we will be able to shuffle even across lanes the other input in a single
9969 // instruction so skip this pattern.
9970 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9971 isShuffleMaskInputInPlace(1, Mask))))
9972 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9973 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9976 // Otherwise fall back on generic blend lowering.
9977 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9981 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9983 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9984 /// isn't available.
9985 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9986 const X86Subtarget *Subtarget,
9987 SelectionDAG &DAG) {
9989 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9990 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9991 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9992 ArrayRef<int> Mask = SVOp->getMask();
9993 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9995 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9999 // Check for being able to broadcast a single element.
10000 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10001 Mask, Subtarget, DAG))
10004 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10005 // options to efficiently lower the shuffle.
10006 SmallVector<int, 4> RepeatedMask;
10007 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10008 assert(RepeatedMask.size() == 4 &&
10009 "Repeated masks must be half the mask width!");
10011 // Use even/odd duplicate instructions for masks that match their pattern.
10012 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10013 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10014 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10015 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10017 if (isSingleInputShuffleMask(Mask))
10018 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10019 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10021 // Use dedicated unpack instructions for masks that match their pattern.
10022 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10023 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10024 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10025 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10026 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10027 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10028 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10029 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10031 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10032 // have already handled any direct blends. We also need to squash the
10033 // repeated mask into a simulated v4f32 mask.
10034 for (int i = 0; i < 4; ++i)
10035 if (RepeatedMask[i] >= 8)
10036 RepeatedMask[i] -= 4;
10037 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10040 // If we have a single input shuffle with different shuffle patterns in the
10041 // two 128-bit lanes use the variable mask to VPERMILPS.
10042 if (isSingleInputShuffleMask(Mask)) {
10043 SDValue VPermMask[8];
10044 for (int i = 0; i < 8; ++i)
10045 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10046 : DAG.getConstant(Mask[i], DL, MVT::i32);
10047 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10048 return DAG.getNode(
10049 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10050 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10052 if (Subtarget->hasAVX2())
10053 return DAG.getNode(
10054 X86ISD::VPERMV, DL, MVT::v8f32,
10055 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10056 MVT::v8i32, VPermMask)),
10059 // Otherwise, fall back.
10060 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10064 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10066 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10067 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10070 // If we have AVX2 then we always want to lower with a blend because at v8 we
10071 // can fully permute the elements.
10072 if (Subtarget->hasAVX2())
10073 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10076 // Otherwise fall back on generic lowering.
10077 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10080 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10082 /// This routine is only called when we have AVX2 and thus a reasonable
10083 /// instruction set for v8i32 shuffling..
10084 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10085 const X86Subtarget *Subtarget,
10086 SelectionDAG &DAG) {
10088 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10089 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10090 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10091 ArrayRef<int> Mask = SVOp->getMask();
10092 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10093 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10095 // Whenever we can lower this as a zext, that instruction is strictly faster
10096 // than any alternative. It also allows us to fold memory operands into the
10097 // shuffle in many cases.
10098 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10099 Mask, Subtarget, DAG))
10102 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10106 // Check for being able to broadcast a single element.
10107 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10108 Mask, Subtarget, DAG))
10111 // If the shuffle mask is repeated in each 128-bit lane we can use more
10112 // efficient instructions that mirror the shuffles across the two 128-bit
10114 SmallVector<int, 4> RepeatedMask;
10115 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10116 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10117 if (isSingleInputShuffleMask(Mask))
10118 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10119 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10121 // Use dedicated unpack instructions for masks that match their pattern.
10122 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10123 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10124 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10125 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10126 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10127 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10128 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10129 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10132 // Try to use shift instructions.
10133 if (SDValue Shift =
10134 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10137 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10138 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10141 // If the shuffle patterns aren't repeated but it is a single input, directly
10142 // generate a cross-lane VPERMD instruction.
10143 if (isSingleInputShuffleMask(Mask)) {
10144 SDValue VPermMask[8];
10145 for (int i = 0; i < 8; ++i)
10146 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10147 : DAG.getConstant(Mask[i], DL, MVT::i32);
10148 return DAG.getNode(
10149 X86ISD::VPERMV, DL, MVT::v8i32,
10150 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10153 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10155 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10156 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10159 // Otherwise fall back on generic blend lowering.
10160 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10164 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10166 /// This routine is only called when we have AVX2 and thus a reasonable
10167 /// instruction set for v16i16 shuffling..
10168 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10169 const X86Subtarget *Subtarget,
10170 SelectionDAG &DAG) {
10172 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10173 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10174 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10175 ArrayRef<int> Mask = SVOp->getMask();
10176 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10177 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10179 // Whenever we can lower this as a zext, that instruction is strictly faster
10180 // than any alternative. It also allows us to fold memory operands into the
10181 // shuffle in many cases.
10182 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10183 Mask, Subtarget, DAG))
10186 // Check for being able to broadcast a single element.
10187 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10188 Mask, Subtarget, DAG))
10191 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10195 // Use dedicated unpack instructions for masks that match their pattern.
10196 if (isShuffleEquivalent(V1, V2, Mask,
10197 {// First 128-bit lane:
10198 0, 16, 1, 17, 2, 18, 3, 19,
10199 // Second 128-bit lane:
10200 8, 24, 9, 25, 10, 26, 11, 27}))
10201 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10202 if (isShuffleEquivalent(V1, V2, Mask,
10203 {// First 128-bit lane:
10204 4, 20, 5, 21, 6, 22, 7, 23,
10205 // Second 128-bit lane:
10206 12, 28, 13, 29, 14, 30, 15, 31}))
10207 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10209 // Try to use shift instructions.
10210 if (SDValue Shift =
10211 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10214 // Try to use byte rotation instructions.
10215 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10216 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10219 if (isSingleInputShuffleMask(Mask)) {
10220 // There are no generalized cross-lane shuffle operations available on i16
10222 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10223 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10226 SmallVector<int, 8> RepeatedMask;
10227 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10228 // As this is a single-input shuffle, the repeated mask should be
10229 // a strictly valid v8i16 mask that we can pass through to the v8i16
10230 // lowering to handle even the v16 case.
10231 return lowerV8I16GeneralSingleInputVectorShuffle(
10232 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10235 SDValue PSHUFBMask[32];
10236 for (int i = 0; i < 16; ++i) {
10237 if (Mask[i] == -1) {
10238 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10242 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10243 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10244 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10245 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10247 return DAG.getBitcast(MVT::v16i16,
10248 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10249 DAG.getBitcast(MVT::v32i8, V1),
10250 DAG.getNode(ISD::BUILD_VECTOR, DL,
10251 MVT::v32i8, PSHUFBMask)));
10254 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10256 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10257 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10260 // Otherwise fall back on generic lowering.
10261 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10264 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10266 /// This routine is only called when we have AVX2 and thus a reasonable
10267 /// instruction set for v32i8 shuffling..
10268 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10269 const X86Subtarget *Subtarget,
10270 SelectionDAG &DAG) {
10272 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10273 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10274 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10275 ArrayRef<int> Mask = SVOp->getMask();
10276 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10277 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10279 // Whenever we can lower this as a zext, that instruction is strictly faster
10280 // than any alternative. It also allows us to fold memory operands into the
10281 // shuffle in many cases.
10282 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10283 Mask, Subtarget, DAG))
10286 // Check for being able to broadcast a single element.
10287 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10288 Mask, Subtarget, DAG))
10291 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10295 // Use dedicated unpack instructions for masks that match their pattern.
10296 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10298 if (isShuffleEquivalent(
10300 {// First 128-bit lane:
10301 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10302 // Second 128-bit lane:
10303 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10304 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10305 if (isShuffleEquivalent(
10307 {// First 128-bit lane:
10308 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10309 // Second 128-bit lane:
10310 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10311 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10313 // Try to use shift instructions.
10314 if (SDValue Shift =
10315 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10318 // Try to use byte rotation instructions.
10319 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10320 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10323 if (isSingleInputShuffleMask(Mask)) {
10324 // There are no generalized cross-lane shuffle operations available on i8
10326 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10327 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10330 SDValue PSHUFBMask[32];
10331 for (int i = 0; i < 32; ++i)
10334 ? DAG.getUNDEF(MVT::i8)
10335 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10338 return DAG.getNode(
10339 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10340 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10343 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10345 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10346 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10349 // Otherwise fall back on generic lowering.
10350 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10353 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10355 /// This routine either breaks down the specific type of a 256-bit x86 vector
10356 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10357 /// together based on the available instructions.
10358 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10359 MVT VT, const X86Subtarget *Subtarget,
10360 SelectionDAG &DAG) {
10362 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10363 ArrayRef<int> Mask = SVOp->getMask();
10365 // If we have a single input to the zero element, insert that into V1 if we
10366 // can do so cheaply.
10367 int NumElts = VT.getVectorNumElements();
10368 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10369 return M >= NumElts;
10372 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10373 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10374 DL, VT, V1, V2, Mask, Subtarget, DAG))
10377 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10378 // check for those subtargets here and avoid much of the subtarget querying in
10379 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10380 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10381 // floating point types there eventually, just immediately cast everything to
10382 // a float and operate entirely in that domain.
10383 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10384 int ElementBits = VT.getScalarSizeInBits();
10385 if (ElementBits < 32)
10386 // No floating point type available, decompose into 128-bit vectors.
10387 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10389 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10390 VT.getVectorNumElements());
10391 V1 = DAG.getBitcast(FpVT, V1);
10392 V2 = DAG.getBitcast(FpVT, V2);
10393 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10396 switch (VT.SimpleTy) {
10398 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10400 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10402 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10404 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10406 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10408 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10411 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10415 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10416 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10417 const X86Subtarget *Subtarget,
10418 SelectionDAG &DAG) {
10420 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10421 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10422 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10423 ArrayRef<int> Mask = SVOp->getMask();
10424 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10426 // X86 has dedicated unpack instructions that can handle specific blend
10427 // operations: UNPCKH and UNPCKL.
10428 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10429 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10430 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10431 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10433 // FIXME: Implement direct support for this type!
10434 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10437 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10438 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10439 const X86Subtarget *Subtarget,
10440 SelectionDAG &DAG) {
10442 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10443 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10444 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10445 ArrayRef<int> Mask = SVOp->getMask();
10446 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10448 // Use dedicated unpack instructions for masks that match their pattern.
10449 if (isShuffleEquivalent(V1, V2, Mask,
10450 {// First 128-bit lane.
10451 0, 16, 1, 17, 4, 20, 5, 21,
10452 // Second 128-bit lane.
10453 8, 24, 9, 25, 12, 28, 13, 29}))
10454 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10455 if (isShuffleEquivalent(V1, V2, Mask,
10456 {// First 128-bit lane.
10457 2, 18, 3, 19, 6, 22, 7, 23,
10458 // Second 128-bit lane.
10459 10, 26, 11, 27, 14, 30, 15, 31}))
10460 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10462 // FIXME: Implement direct support for this type!
10463 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10466 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10467 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10468 const X86Subtarget *Subtarget,
10469 SelectionDAG &DAG) {
10471 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10472 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10473 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10474 ArrayRef<int> Mask = SVOp->getMask();
10475 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10477 // X86 has dedicated unpack instructions that can handle specific blend
10478 // operations: UNPCKH and UNPCKL.
10479 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10480 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10481 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10482 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10484 // FIXME: Implement direct support for this type!
10485 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10488 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10489 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10490 const X86Subtarget *Subtarget,
10491 SelectionDAG &DAG) {
10493 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10494 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10495 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10496 ArrayRef<int> Mask = SVOp->getMask();
10497 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10499 // Use dedicated unpack instructions for masks that match their pattern.
10500 if (isShuffleEquivalent(V1, V2, Mask,
10501 {// First 128-bit lane.
10502 0, 16, 1, 17, 4, 20, 5, 21,
10503 // Second 128-bit lane.
10504 8, 24, 9, 25, 12, 28, 13, 29}))
10505 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10506 if (isShuffleEquivalent(V1, V2, Mask,
10507 {// First 128-bit lane.
10508 2, 18, 3, 19, 6, 22, 7, 23,
10509 // Second 128-bit lane.
10510 10, 26, 11, 27, 14, 30, 15, 31}))
10511 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10513 // FIXME: Implement direct support for this type!
10514 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10517 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10518 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10519 const X86Subtarget *Subtarget,
10520 SelectionDAG &DAG) {
10522 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10523 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10524 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10525 ArrayRef<int> Mask = SVOp->getMask();
10526 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10527 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10529 // FIXME: Implement direct support for this type!
10530 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10533 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10534 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10535 const X86Subtarget *Subtarget,
10536 SelectionDAG &DAG) {
10538 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10539 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10540 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10541 ArrayRef<int> Mask = SVOp->getMask();
10542 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10543 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10545 // FIXME: Implement direct support for this type!
10546 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10549 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10551 /// This routine either breaks down the specific type of a 512-bit x86 vector
10552 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10553 /// together based on the available instructions.
10554 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10555 MVT VT, const X86Subtarget *Subtarget,
10556 SelectionDAG &DAG) {
10558 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10559 ArrayRef<int> Mask = SVOp->getMask();
10560 assert(Subtarget->hasAVX512() &&
10561 "Cannot lower 512-bit vectors w/ basic ISA!");
10563 // Check for being able to broadcast a single element.
10564 if (SDValue Broadcast =
10565 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10568 // Dispatch to each element type for lowering. If we don't have supprot for
10569 // specific element type shuffles at 512 bits, immediately split them and
10570 // lower them. Each lowering routine of a given type is allowed to assume that
10571 // the requisite ISA extensions for that element type are available.
10572 switch (VT.SimpleTy) {
10574 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10576 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10578 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10580 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10582 if (Subtarget->hasBWI())
10583 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10586 if (Subtarget->hasBWI())
10587 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10591 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10594 // Otherwise fall back on splitting.
10595 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10598 /// \brief Top-level lowering for x86 vector shuffles.
10600 /// This handles decomposition, canonicalization, and lowering of all x86
10601 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10602 /// above in helper routines. The canonicalization attempts to widen shuffles
10603 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10604 /// s.t. only one of the two inputs needs to be tested, etc.
10605 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10606 SelectionDAG &DAG) {
10607 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10608 ArrayRef<int> Mask = SVOp->getMask();
10609 SDValue V1 = Op.getOperand(0);
10610 SDValue V2 = Op.getOperand(1);
10611 MVT VT = Op.getSimpleValueType();
10612 int NumElements = VT.getVectorNumElements();
10615 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10617 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10618 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10619 if (V1IsUndef && V2IsUndef)
10620 return DAG.getUNDEF(VT);
10622 // When we create a shuffle node we put the UNDEF node to second operand,
10623 // but in some cases the first operand may be transformed to UNDEF.
10624 // In this case we should just commute the node.
10626 return DAG.getCommutedVectorShuffle(*SVOp);
10628 // Check for non-undef masks pointing at an undef vector and make the masks
10629 // undef as well. This makes it easier to match the shuffle based solely on
10633 if (M >= NumElements) {
10634 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10635 for (int &M : NewMask)
10636 if (M >= NumElements)
10638 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10641 // We actually see shuffles that are entirely re-arrangements of a set of
10642 // zero inputs. This mostly happens while decomposing complex shuffles into
10643 // simple ones. Directly lower these as a buildvector of zeros.
10644 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10645 if (Zeroable.all())
10646 return getZeroVector(VT, Subtarget, DAG, dl);
10648 // Try to collapse shuffles into using a vector type with fewer elements but
10649 // wider element types. We cap this to not form integers or floating point
10650 // elements wider than 64 bits, but it might be interesting to form i128
10651 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10652 SmallVector<int, 16> WidenedMask;
10653 if (VT.getScalarSizeInBits() < 64 &&
10654 canWidenShuffleElements(Mask, WidenedMask)) {
10655 MVT NewEltVT = VT.isFloatingPoint()
10656 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10657 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10658 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10659 // Make sure that the new vector type is legal. For example, v2f64 isn't
10661 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10662 V1 = DAG.getBitcast(NewVT, V1);
10663 V2 = DAG.getBitcast(NewVT, V2);
10664 return DAG.getBitcast(
10665 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10669 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10670 for (int M : SVOp->getMask())
10672 ++NumUndefElements;
10673 else if (M < NumElements)
10678 // Commute the shuffle as needed such that more elements come from V1 than
10679 // V2. This allows us to match the shuffle pattern strictly on how many
10680 // elements come from V1 without handling the symmetric cases.
10681 if (NumV2Elements > NumV1Elements)
10682 return DAG.getCommutedVectorShuffle(*SVOp);
10684 // When the number of V1 and V2 elements are the same, try to minimize the
10685 // number of uses of V2 in the low half of the vector. When that is tied,
10686 // ensure that the sum of indices for V1 is equal to or lower than the sum
10687 // indices for V2. When those are equal, try to ensure that the number of odd
10688 // indices for V1 is lower than the number of odd indices for V2.
10689 if (NumV1Elements == NumV2Elements) {
10690 int LowV1Elements = 0, LowV2Elements = 0;
10691 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10692 if (M >= NumElements)
10696 if (LowV2Elements > LowV1Elements) {
10697 return DAG.getCommutedVectorShuffle(*SVOp);
10698 } else if (LowV2Elements == LowV1Elements) {
10699 int SumV1Indices = 0, SumV2Indices = 0;
10700 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10701 if (SVOp->getMask()[i] >= NumElements)
10703 else if (SVOp->getMask()[i] >= 0)
10705 if (SumV2Indices < SumV1Indices) {
10706 return DAG.getCommutedVectorShuffle(*SVOp);
10707 } else if (SumV2Indices == SumV1Indices) {
10708 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10709 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10710 if (SVOp->getMask()[i] >= NumElements)
10711 NumV2OddIndices += i % 2;
10712 else if (SVOp->getMask()[i] >= 0)
10713 NumV1OddIndices += i % 2;
10714 if (NumV2OddIndices < NumV1OddIndices)
10715 return DAG.getCommutedVectorShuffle(*SVOp);
10720 // For each vector width, delegate to a specialized lowering routine.
10721 if (VT.getSizeInBits() == 128)
10722 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10724 if (VT.getSizeInBits() == 256)
10725 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10727 // Force AVX-512 vectors to be scalarized for now.
10728 // FIXME: Implement AVX-512 support!
10729 if (VT.getSizeInBits() == 512)
10730 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10732 llvm_unreachable("Unimplemented!");
10735 // This function assumes its argument is a BUILD_VECTOR of constants or
10736 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10738 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10739 unsigned &MaskValue) {
10741 unsigned NumElems = BuildVector->getNumOperands();
10742 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10743 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10744 unsigned NumElemsInLane = NumElems / NumLanes;
10746 // Blend for v16i16 should be symmetric for the both lanes.
10747 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10748 SDValue EltCond = BuildVector->getOperand(i);
10749 SDValue SndLaneEltCond =
10750 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10752 int Lane1Cond = -1, Lane2Cond = -1;
10753 if (isa<ConstantSDNode>(EltCond))
10754 Lane1Cond = !isZero(EltCond);
10755 if (isa<ConstantSDNode>(SndLaneEltCond))
10756 Lane2Cond = !isZero(SndLaneEltCond);
10758 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10759 // Lane1Cond != 0, means we want the first argument.
10760 // Lane1Cond == 0, means we want the second argument.
10761 // The encoding of this argument is 0 for the first argument, 1
10762 // for the second. Therefore, invert the condition.
10763 MaskValue |= !Lane1Cond << i;
10764 else if (Lane1Cond < 0)
10765 MaskValue |= !Lane2Cond << i;
10772 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10773 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10774 const X86Subtarget *Subtarget,
10775 SelectionDAG &DAG) {
10776 SDValue Cond = Op.getOperand(0);
10777 SDValue LHS = Op.getOperand(1);
10778 SDValue RHS = Op.getOperand(2);
10780 MVT VT = Op.getSimpleValueType();
10782 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10784 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10786 // Only non-legal VSELECTs reach this lowering, convert those into generic
10787 // shuffles and re-use the shuffle lowering path for blends.
10788 SmallVector<int, 32> Mask;
10789 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10790 SDValue CondElt = CondBV->getOperand(i);
10792 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10794 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10797 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10798 // A vselect where all conditions and data are constants can be optimized into
10799 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10800 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10801 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10802 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10805 // Try to lower this to a blend-style vector shuffle. This can handle all
10806 // constant condition cases.
10807 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10810 // Variable blends are only legal from SSE4.1 onward.
10811 if (!Subtarget->hasSSE41())
10814 // Only some types will be legal on some subtargets. If we can emit a legal
10815 // VSELECT-matching blend, return Op, and but if we need to expand, return
10817 switch (Op.getSimpleValueType().SimpleTy) {
10819 // Most of the vector types have blends past SSE4.1.
10823 // The byte blends for AVX vectors were introduced only in AVX2.
10824 if (Subtarget->hasAVX2())
10831 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10832 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10835 // FIXME: We should custom lower this by fixing the condition and using i8
10841 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10842 MVT VT = Op.getSimpleValueType();
10845 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10848 if (VT.getSizeInBits() == 8) {
10849 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10850 Op.getOperand(0), Op.getOperand(1));
10851 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10852 DAG.getValueType(VT));
10853 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10856 if (VT.getSizeInBits() == 16) {
10857 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10858 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10860 return DAG.getNode(
10861 ISD::TRUNCATE, dl, MVT::i16,
10862 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10863 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10864 Op.getOperand(1)));
10865 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10866 Op.getOperand(0), Op.getOperand(1));
10867 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10868 DAG.getValueType(VT));
10869 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10872 if (VT == MVT::f32) {
10873 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10874 // the result back to FR32 register. It's only worth matching if the
10875 // result has a single use which is a store or a bitcast to i32. And in
10876 // the case of a store, it's not worth it if the index is a constant 0,
10877 // because a MOVSSmr can be used instead, which is smaller and faster.
10878 if (!Op.hasOneUse())
10880 SDNode *User = *Op.getNode()->use_begin();
10881 if ((User->getOpcode() != ISD::STORE ||
10882 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10883 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10884 (User->getOpcode() != ISD::BITCAST ||
10885 User->getValueType(0) != MVT::i32))
10887 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10888 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10890 return DAG.getBitcast(MVT::f32, Extract);
10893 if (VT == MVT::i32 || VT == MVT::i64) {
10894 // ExtractPS/pextrq works with constant index.
10895 if (isa<ConstantSDNode>(Op.getOperand(1)))
10901 /// Extract one bit from mask vector, like v16i1 or v8i1.
10902 /// AVX-512 feature.
10904 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10905 SDValue Vec = Op.getOperand(0);
10907 MVT VecVT = Vec.getSimpleValueType();
10908 SDValue Idx = Op.getOperand(1);
10909 MVT EltVT = Op.getSimpleValueType();
10911 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10912 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10913 "Unexpected vector type in ExtractBitFromMaskVector");
10915 // variable index can't be handled in mask registers,
10916 // extend vector to VR512
10917 if (!isa<ConstantSDNode>(Idx)) {
10918 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10919 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10920 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10921 ExtVT.getVectorElementType(), Ext, Idx);
10922 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10925 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10926 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10927 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10928 rc = getRegClassFor(MVT::v16i1);
10929 unsigned MaxSift = rc->getSize()*8 - 1;
10930 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10931 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10932 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10933 DAG.getConstant(MaxSift, dl, MVT::i8));
10934 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10935 DAG.getIntPtrConstant(0, dl));
10939 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10940 SelectionDAG &DAG) const {
10942 SDValue Vec = Op.getOperand(0);
10943 MVT VecVT = Vec.getSimpleValueType();
10944 SDValue Idx = Op.getOperand(1);
10946 if (Op.getSimpleValueType() == MVT::i1)
10947 return ExtractBitFromMaskVector(Op, DAG);
10949 if (!isa<ConstantSDNode>(Idx)) {
10950 if (VecVT.is512BitVector() ||
10951 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10952 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10955 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10956 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10957 MaskEltVT.getSizeInBits());
10959 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10960 auto PtrVT = getPointerTy(DAG.getDataLayout());
10961 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10962 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10963 DAG.getConstant(0, dl, PtrVT));
10964 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10965 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10966 DAG.getConstant(0, dl, PtrVT));
10971 // If this is a 256-bit vector result, first extract the 128-bit vector and
10972 // then extract the element from the 128-bit vector.
10973 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10975 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10976 // Get the 128-bit vector.
10977 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10978 MVT EltVT = VecVT.getVectorElementType();
10980 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10982 //if (IdxVal >= NumElems/2)
10983 // IdxVal -= NumElems/2;
10984 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10985 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10986 DAG.getConstant(IdxVal, dl, MVT::i32));
10989 assert(VecVT.is128BitVector() && "Unexpected vector length");
10991 if (Subtarget->hasSSE41())
10992 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10995 MVT VT = Op.getSimpleValueType();
10996 // TODO: handle v16i8.
10997 if (VT.getSizeInBits() == 16) {
10998 SDValue Vec = Op.getOperand(0);
10999 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11001 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11002 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11003 DAG.getBitcast(MVT::v4i32, Vec),
11004 Op.getOperand(1)));
11005 // Transform it so it match pextrw which produces a 32-bit result.
11006 MVT EltVT = MVT::i32;
11007 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11008 Op.getOperand(0), Op.getOperand(1));
11009 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11010 DAG.getValueType(VT));
11011 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11014 if (VT.getSizeInBits() == 32) {
11015 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11019 // SHUFPS the element to the lowest double word, then movss.
11020 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11021 MVT VVT = Op.getOperand(0).getSimpleValueType();
11022 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11023 DAG.getUNDEF(VVT), Mask);
11024 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11025 DAG.getIntPtrConstant(0, dl));
11028 if (VT.getSizeInBits() == 64) {
11029 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11030 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11031 // to match extract_elt for f64.
11032 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11036 // UNPCKHPD the element to the lowest double word, then movsd.
11037 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11038 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11039 int Mask[2] = { 1, -1 };
11040 MVT VVT = Op.getOperand(0).getSimpleValueType();
11041 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11042 DAG.getUNDEF(VVT), Mask);
11043 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11044 DAG.getIntPtrConstant(0, dl));
11050 /// Insert one bit to mask vector, like v16i1 or v8i1.
11051 /// AVX-512 feature.
11053 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11055 SDValue Vec = Op.getOperand(0);
11056 SDValue Elt = Op.getOperand(1);
11057 SDValue Idx = Op.getOperand(2);
11058 MVT VecVT = Vec.getSimpleValueType();
11060 if (!isa<ConstantSDNode>(Idx)) {
11061 // Non constant index. Extend source and destination,
11062 // insert element and then truncate the result.
11063 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11064 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11065 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11066 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11067 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11068 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11071 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11072 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11074 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11075 DAG.getConstant(IdxVal, dl, MVT::i8));
11076 if (Vec.getOpcode() == ISD::UNDEF)
11078 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11081 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11082 SelectionDAG &DAG) const {
11083 MVT VT = Op.getSimpleValueType();
11084 MVT EltVT = VT.getVectorElementType();
11086 if (EltVT == MVT::i1)
11087 return InsertBitToMaskVector(Op, DAG);
11090 SDValue N0 = Op.getOperand(0);
11091 SDValue N1 = Op.getOperand(1);
11092 SDValue N2 = Op.getOperand(2);
11093 if (!isa<ConstantSDNode>(N2))
11095 auto *N2C = cast<ConstantSDNode>(N2);
11096 unsigned IdxVal = N2C->getZExtValue();
11098 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11099 // into that, and then insert the subvector back into the result.
11100 if (VT.is256BitVector() || VT.is512BitVector()) {
11101 // With a 256-bit vector, we can insert into the zero element efficiently
11102 // using a blend if we have AVX or AVX2 and the right data type.
11103 if (VT.is256BitVector() && IdxVal == 0) {
11104 // TODO: It is worthwhile to cast integer to floating point and back
11105 // and incur a domain crossing penalty if that's what we'll end up
11106 // doing anyway after extracting to a 128-bit vector.
11107 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11108 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11109 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11110 N2 = DAG.getIntPtrConstant(1, dl);
11111 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11115 // Get the desired 128-bit vector chunk.
11116 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11118 // Insert the element into the desired chunk.
11119 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11120 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11122 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11123 DAG.getConstant(IdxIn128, dl, MVT::i32));
11125 // Insert the changed part back into the bigger vector
11126 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11128 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11130 if (Subtarget->hasSSE41()) {
11131 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11133 if (VT == MVT::v8i16) {
11134 Opc = X86ISD::PINSRW;
11136 assert(VT == MVT::v16i8);
11137 Opc = X86ISD::PINSRB;
11140 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11142 if (N1.getValueType() != MVT::i32)
11143 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11144 if (N2.getValueType() != MVT::i32)
11145 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11146 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11149 if (EltVT == MVT::f32) {
11150 // Bits [7:6] of the constant are the source select. This will always be
11151 // zero here. The DAG Combiner may combine an extract_elt index into
11152 // these bits. For example (insert (extract, 3), 2) could be matched by
11153 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11154 // Bits [5:4] of the constant are the destination select. This is the
11155 // value of the incoming immediate.
11156 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11157 // combine either bitwise AND or insert of float 0.0 to set these bits.
11159 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11160 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11161 // If this is an insertion of 32-bits into the low 32-bits of
11162 // a vector, we prefer to generate a blend with immediate rather
11163 // than an insertps. Blends are simpler operations in hardware and so
11164 // will always have equal or better performance than insertps.
11165 // But if optimizing for size and there's a load folding opportunity,
11166 // generate insertps because blendps does not have a 32-bit memory
11168 N2 = DAG.getIntPtrConstant(1, dl);
11169 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11170 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11172 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11173 // Create this as a scalar to vector..
11174 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11175 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11178 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11179 // PINSR* works with constant index.
11184 if (EltVT == MVT::i8)
11187 if (EltVT.getSizeInBits() == 16) {
11188 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11189 // as its second argument.
11190 if (N1.getValueType() != MVT::i32)
11191 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11192 if (N2.getValueType() != MVT::i32)
11193 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11194 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11199 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11201 MVT OpVT = Op.getSimpleValueType();
11203 // If this is a 256-bit vector result, first insert into a 128-bit
11204 // vector and then insert into the 256-bit vector.
11205 if (!OpVT.is128BitVector()) {
11206 // Insert into a 128-bit vector.
11207 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11208 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11209 OpVT.getVectorNumElements() / SizeFactor);
11211 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11213 // Insert the 128-bit vector.
11214 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11217 if (OpVT == MVT::v1i64 &&
11218 Op.getOperand(0).getValueType() == MVT::i64)
11219 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11221 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11222 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11223 return DAG.getBitcast(
11224 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11227 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11228 // a simple subregister reference or explicit instructions to grab
11229 // upper bits of a vector.
11230 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11231 SelectionDAG &DAG) {
11233 SDValue In = Op.getOperand(0);
11234 SDValue Idx = Op.getOperand(1);
11235 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11236 MVT ResVT = Op.getSimpleValueType();
11237 MVT InVT = In.getSimpleValueType();
11239 if (Subtarget->hasFp256()) {
11240 if (ResVT.is128BitVector() &&
11241 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11242 isa<ConstantSDNode>(Idx)) {
11243 return Extract128BitVector(In, IdxVal, DAG, dl);
11245 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11246 isa<ConstantSDNode>(Idx)) {
11247 return Extract256BitVector(In, IdxVal, DAG, dl);
11253 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11254 // simple superregister reference or explicit instructions to insert
11255 // the upper bits of a vector.
11256 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11257 SelectionDAG &DAG) {
11258 if (!Subtarget->hasAVX())
11262 SDValue Vec = Op.getOperand(0);
11263 SDValue SubVec = Op.getOperand(1);
11264 SDValue Idx = Op.getOperand(2);
11266 if (!isa<ConstantSDNode>(Idx))
11269 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11270 MVT OpVT = Op.getSimpleValueType();
11271 MVT SubVecVT = SubVec.getSimpleValueType();
11273 // Fold two 16-byte subvector loads into one 32-byte load:
11274 // (insert_subvector (insert_subvector undef, (load addr), 0),
11275 // (load addr + 16), Elts/2)
11277 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11278 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11279 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11280 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11281 if (Idx2 && Idx2->getZExtValue() == 0) {
11282 SDValue SubVec2 = Vec.getOperand(1);
11283 // If needed, look through a bitcast to get to the load.
11284 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11285 SubVec2 = SubVec2.getOperand(0);
11287 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11289 unsigned Alignment = FirstLd->getAlignment();
11290 unsigned AS = FirstLd->getAddressSpace();
11291 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11292 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11293 OpVT, AS, Alignment, &Fast) && Fast) {
11294 SDValue Ops[] = { SubVec2, SubVec };
11295 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11302 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11303 SubVecVT.is128BitVector())
11304 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11306 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11307 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11309 if (OpVT.getVectorElementType() == MVT::i1) {
11310 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11312 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11313 SDValue Undef = DAG.getUNDEF(OpVT);
11314 unsigned NumElems = OpVT.getVectorNumElements();
11315 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11317 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11318 // Zero upper bits of the Vec
11319 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11320 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11322 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11324 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11325 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11328 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11330 // Zero upper bits of the Vec2
11331 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11332 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11333 // Zero lower bits of the Vec
11334 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11335 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11336 // Merge them together
11337 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11343 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11344 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11345 // one of the above mentioned nodes. It has to be wrapped because otherwise
11346 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11347 // be used to form addressing mode. These wrapped nodes will be selected
11350 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11351 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11353 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11354 // global base reg.
11355 unsigned char OpFlag = 0;
11356 unsigned WrapperKind = X86ISD::Wrapper;
11357 CodeModel::Model M = DAG.getTarget().getCodeModel();
11359 if (Subtarget->isPICStyleRIPRel() &&
11360 (M == CodeModel::Small || M == CodeModel::Kernel))
11361 WrapperKind = X86ISD::WrapperRIP;
11362 else if (Subtarget->isPICStyleGOT())
11363 OpFlag = X86II::MO_GOTOFF;
11364 else if (Subtarget->isPICStyleStubPIC())
11365 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11367 auto PtrVT = getPointerTy(DAG.getDataLayout());
11368 SDValue Result = DAG.getTargetConstantPool(
11369 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11371 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11372 // With PIC, the address is actually $g + Offset.
11375 DAG.getNode(ISD::ADD, DL, PtrVT,
11376 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11382 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11383 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11385 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11386 // global base reg.
11387 unsigned char OpFlag = 0;
11388 unsigned WrapperKind = X86ISD::Wrapper;
11389 CodeModel::Model M = DAG.getTarget().getCodeModel();
11391 if (Subtarget->isPICStyleRIPRel() &&
11392 (M == CodeModel::Small || M == CodeModel::Kernel))
11393 WrapperKind = X86ISD::WrapperRIP;
11394 else if (Subtarget->isPICStyleGOT())
11395 OpFlag = X86II::MO_GOTOFF;
11396 else if (Subtarget->isPICStyleStubPIC())
11397 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11399 auto PtrVT = getPointerTy(DAG.getDataLayout());
11400 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11402 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11404 // With PIC, the address is actually $g + Offset.
11407 DAG.getNode(ISD::ADD, DL, PtrVT,
11408 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11414 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11415 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11417 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11418 // global base reg.
11419 unsigned char OpFlag = 0;
11420 unsigned WrapperKind = X86ISD::Wrapper;
11421 CodeModel::Model M = DAG.getTarget().getCodeModel();
11423 if (Subtarget->isPICStyleRIPRel() &&
11424 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11425 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11426 OpFlag = X86II::MO_GOTPCREL;
11427 WrapperKind = X86ISD::WrapperRIP;
11428 } else if (Subtarget->isPICStyleGOT()) {
11429 OpFlag = X86II::MO_GOT;
11430 } else if (Subtarget->isPICStyleStubPIC()) {
11431 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11432 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11433 OpFlag = X86II::MO_DARWIN_NONLAZY;
11436 auto PtrVT = getPointerTy(DAG.getDataLayout());
11437 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11440 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11442 // With PIC, the address is actually $g + Offset.
11443 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11444 !Subtarget->is64Bit()) {
11446 DAG.getNode(ISD::ADD, DL, PtrVT,
11447 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11450 // For symbols that require a load from a stub to get the address, emit the
11452 if (isGlobalStubReference(OpFlag))
11453 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11454 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11455 false, false, false, 0);
11461 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11462 // Create the TargetBlockAddressAddress node.
11463 unsigned char OpFlags =
11464 Subtarget->ClassifyBlockAddressReference();
11465 CodeModel::Model M = DAG.getTarget().getCodeModel();
11466 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11467 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11469 auto PtrVT = getPointerTy(DAG.getDataLayout());
11470 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11472 if (Subtarget->isPICStyleRIPRel() &&
11473 (M == CodeModel::Small || M == CodeModel::Kernel))
11474 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11476 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11478 // With PIC, the address is actually $g + Offset.
11479 if (isGlobalRelativeToPICBase(OpFlags)) {
11480 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11481 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11488 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11489 int64_t Offset, SelectionDAG &DAG) const {
11490 // Create the TargetGlobalAddress node, folding in the constant
11491 // offset if it is legal.
11492 unsigned char OpFlags =
11493 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11494 CodeModel::Model M = DAG.getTarget().getCodeModel();
11495 auto PtrVT = getPointerTy(DAG.getDataLayout());
11497 if (OpFlags == X86II::MO_NO_FLAG &&
11498 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11499 // A direct static reference to a global.
11500 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11503 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11506 if (Subtarget->isPICStyleRIPRel() &&
11507 (M == CodeModel::Small || M == CodeModel::Kernel))
11508 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11510 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11512 // With PIC, the address is actually $g + Offset.
11513 if (isGlobalRelativeToPICBase(OpFlags)) {
11514 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11515 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11518 // For globals that require a load from a stub to get the address, emit the
11520 if (isGlobalStubReference(OpFlags))
11521 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11522 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11523 false, false, false, 0);
11525 // If there was a non-zero offset that we didn't fold, create an explicit
11526 // addition for it.
11528 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11529 DAG.getConstant(Offset, dl, PtrVT));
11535 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11536 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11537 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11538 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11542 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11543 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11544 unsigned char OperandFlags, bool LocalDynamic = false) {
11545 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11546 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11548 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11549 GA->getValueType(0),
11553 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11557 SDValue Ops[] = { Chain, TGA, *InFlag };
11558 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11560 SDValue Ops[] = { Chain, TGA };
11561 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11564 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11565 MFI->setAdjustsStack(true);
11566 MFI->setHasCalls(true);
11568 SDValue Flag = Chain.getValue(1);
11569 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11572 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11574 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11577 SDLoc dl(GA); // ? function entry point might be better
11578 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11579 DAG.getNode(X86ISD::GlobalBaseReg,
11580 SDLoc(), PtrVT), InFlag);
11581 InFlag = Chain.getValue(1);
11583 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11586 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11588 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11590 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11591 X86::RAX, X86II::MO_TLSGD);
11594 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11600 // Get the start address of the TLS block for this module.
11601 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11602 .getInfo<X86MachineFunctionInfo>();
11603 MFI->incNumLocalDynamicTLSAccesses();
11607 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11608 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11611 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11612 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11613 InFlag = Chain.getValue(1);
11614 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11615 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11618 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11622 unsigned char OperandFlags = X86II::MO_DTPOFF;
11623 unsigned WrapperKind = X86ISD::Wrapper;
11624 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11625 GA->getValueType(0),
11626 GA->getOffset(), OperandFlags);
11627 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11629 // Add x@dtpoff with the base.
11630 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11633 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11634 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11635 const EVT PtrVT, TLSModel::Model model,
11636 bool is64Bit, bool isPIC) {
11639 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11640 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11641 is64Bit ? 257 : 256));
11643 SDValue ThreadPointer =
11644 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11645 MachinePointerInfo(Ptr), false, false, false, 0);
11647 unsigned char OperandFlags = 0;
11648 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11650 unsigned WrapperKind = X86ISD::Wrapper;
11651 if (model == TLSModel::LocalExec) {
11652 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11653 } else if (model == TLSModel::InitialExec) {
11655 OperandFlags = X86II::MO_GOTTPOFF;
11656 WrapperKind = X86ISD::WrapperRIP;
11658 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11661 llvm_unreachable("Unexpected model");
11664 // emit "addl x@ntpoff,%eax" (local exec)
11665 // or "addl x@indntpoff,%eax" (initial exec)
11666 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11668 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11669 GA->getOffset(), OperandFlags);
11670 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11672 if (model == TLSModel::InitialExec) {
11673 if (isPIC && !is64Bit) {
11674 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11675 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11679 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11680 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11681 false, false, false, 0);
11684 // The address of the thread local variable is the add of the thread
11685 // pointer with the offset of the variable.
11686 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11690 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11692 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11693 const GlobalValue *GV = GA->getGlobal();
11694 auto PtrVT = getPointerTy(DAG.getDataLayout());
11696 if (Subtarget->isTargetELF()) {
11697 if (DAG.getTarget().Options.EmulatedTLS)
11698 return LowerToTLSEmulatedModel(GA, DAG);
11699 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11701 case TLSModel::GeneralDynamic:
11702 if (Subtarget->is64Bit())
11703 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11704 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11705 case TLSModel::LocalDynamic:
11706 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11707 Subtarget->is64Bit());
11708 case TLSModel::InitialExec:
11709 case TLSModel::LocalExec:
11710 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11711 DAG.getTarget().getRelocationModel() ==
11714 llvm_unreachable("Unknown TLS model.");
11717 if (Subtarget->isTargetDarwin()) {
11718 // Darwin only has one model of TLS. Lower to that.
11719 unsigned char OpFlag = 0;
11720 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11721 X86ISD::WrapperRIP : X86ISD::Wrapper;
11723 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11724 // global base reg.
11725 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11726 !Subtarget->is64Bit();
11728 OpFlag = X86II::MO_TLVP_PIC_BASE;
11730 OpFlag = X86II::MO_TLVP;
11732 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11733 GA->getValueType(0),
11734 GA->getOffset(), OpFlag);
11735 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11737 // With PIC32, the address is actually $g + Offset.
11739 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11740 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11743 // Lowering the machine isd will make sure everything is in the right
11745 SDValue Chain = DAG.getEntryNode();
11746 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11747 SDValue Args[] = { Chain, Offset };
11748 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11750 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11751 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11752 MFI->setAdjustsStack(true);
11754 // And our return value (tls address) is in the standard call return value
11756 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11757 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11760 if (Subtarget->isTargetKnownWindowsMSVC() ||
11761 Subtarget->isTargetWindowsGNU()) {
11762 // Just use the implicit TLS architecture
11763 // Need to generate someting similar to:
11764 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11766 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11767 // mov rcx, qword [rdx+rcx*8]
11768 // mov eax, .tls$:tlsvar
11769 // [rax+rcx] contains the address
11770 // Windows 64bit: gs:0x58
11771 // Windows 32bit: fs:__tls_array
11774 SDValue Chain = DAG.getEntryNode();
11776 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11777 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11778 // use its literal value of 0x2C.
11779 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11780 ? Type::getInt8PtrTy(*DAG.getContext(),
11782 : Type::getInt32PtrTy(*DAG.getContext(),
11785 SDValue TlsArray = Subtarget->is64Bit()
11786 ? DAG.getIntPtrConstant(0x58, dl)
11787 : (Subtarget->isTargetWindowsGNU()
11788 ? DAG.getIntPtrConstant(0x2C, dl)
11789 : DAG.getExternalSymbol("_tls_array", PtrVT));
11791 SDValue ThreadPointer =
11792 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11796 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11797 res = ThreadPointer;
11799 // Load the _tls_index variable
11800 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11801 if (Subtarget->is64Bit())
11802 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11803 MachinePointerInfo(), MVT::i32, false, false,
11806 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11809 auto &DL = DAG.getDataLayout();
11811 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11812 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11814 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11817 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11820 // Get the offset of start of .tls section
11821 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11822 GA->getValueType(0),
11823 GA->getOffset(), X86II::MO_SECREL);
11824 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11826 // The address of the thread local variable is the add of the thread
11827 // pointer with the offset of the variable.
11828 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11831 llvm_unreachable("TLS not implemented for this target.");
11834 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11835 /// and take a 2 x i32 value to shift plus a shift amount.
11836 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11837 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11838 MVT VT = Op.getSimpleValueType();
11839 unsigned VTBits = VT.getSizeInBits();
11841 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11842 SDValue ShOpLo = Op.getOperand(0);
11843 SDValue ShOpHi = Op.getOperand(1);
11844 SDValue ShAmt = Op.getOperand(2);
11845 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11846 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11848 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11849 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11850 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11851 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11852 : DAG.getConstant(0, dl, VT);
11854 SDValue Tmp2, Tmp3;
11855 if (Op.getOpcode() == ISD::SHL_PARTS) {
11856 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11857 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11859 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11860 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11863 // If the shift amount is larger or equal than the width of a part we can't
11864 // rely on the results of shld/shrd. Insert a test and select the appropriate
11865 // values for large shift amounts.
11866 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11867 DAG.getConstant(VTBits, dl, MVT::i8));
11868 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11869 AndNode, DAG.getConstant(0, dl, MVT::i8));
11872 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11873 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11874 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11876 if (Op.getOpcode() == ISD::SHL_PARTS) {
11877 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11878 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11880 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11881 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11884 SDValue Ops[2] = { Lo, Hi };
11885 return DAG.getMergeValues(Ops, dl);
11888 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11889 SelectionDAG &DAG) const {
11890 SDValue Src = Op.getOperand(0);
11891 MVT SrcVT = Src.getSimpleValueType();
11892 MVT VT = Op.getSimpleValueType();
11895 if (SrcVT.isVector()) {
11896 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11897 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11898 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11899 DAG.getUNDEF(SrcVT)));
11901 if (SrcVT.getVectorElementType() == MVT::i1) {
11902 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11903 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11904 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11909 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11910 "Unknown SINT_TO_FP to lower!");
11912 // These are really Legal; return the operand so the caller accepts it as
11914 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11916 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11917 Subtarget->is64Bit()) {
11921 unsigned Size = SrcVT.getSizeInBits()/8;
11922 MachineFunction &MF = DAG.getMachineFunction();
11923 auto PtrVT = getPointerTy(MF.getDataLayout());
11924 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11925 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11926 SDValue Chain = DAG.getStore(
11927 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11928 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11930 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11933 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11935 SelectionDAG &DAG) const {
11939 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11941 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11943 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11945 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11947 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11948 MachineMemOperand *MMO;
11950 int SSFI = FI->getIndex();
11951 MMO = DAG.getMachineFunction().getMachineMemOperand(
11952 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11953 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11955 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11956 StackSlot = StackSlot.getOperand(1);
11958 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11959 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11961 Tys, Ops, SrcVT, MMO);
11964 Chain = Result.getValue(1);
11965 SDValue InFlag = Result.getValue(2);
11967 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11968 // shouldn't be necessary except that RFP cannot be live across
11969 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11970 MachineFunction &MF = DAG.getMachineFunction();
11971 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11972 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11973 auto PtrVT = getPointerTy(MF.getDataLayout());
11974 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11975 Tys = DAG.getVTList(MVT::Other);
11977 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11979 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11980 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11981 MachineMemOperand::MOStore, SSFISize, SSFISize);
11983 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11984 Ops, Op.getValueType(), MMO);
11985 Result = DAG.getLoad(
11986 Op.getValueType(), DL, Chain, StackSlot,
11987 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11988 false, false, false, 0);
11994 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11995 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11996 SelectionDAG &DAG) const {
11997 // This algorithm is not obvious. Here it is what we're trying to output:
12000 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12001 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12003 haddpd %xmm0, %xmm0
12005 pshufd $0x4e, %xmm0, %xmm1
12011 LLVMContext *Context = DAG.getContext();
12013 // Build some magic constants.
12014 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12015 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12016 auto PtrVT = getPointerTy(DAG.getDataLayout());
12017 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12019 SmallVector<Constant*,2> CV1;
12021 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12022 APInt(64, 0x4330000000000000ULL))));
12024 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12025 APInt(64, 0x4530000000000000ULL))));
12026 Constant *C1 = ConstantVector::get(CV1);
12027 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12029 // Load the 64-bit value into an XMM register.
12030 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12033 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12034 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12035 false, false, false, 16);
12037 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12040 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12041 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12042 false, false, false, 16);
12043 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12044 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12047 if (Subtarget->hasSSE3()) {
12048 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12049 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12051 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12052 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12054 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12055 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12058 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12059 DAG.getIntPtrConstant(0, dl));
12062 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12063 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12064 SelectionDAG &DAG) const {
12066 // FP constant to bias correct the final result.
12067 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12070 // Load the 32-bit value into an XMM register.
12071 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12074 // Zero out the upper parts of the register.
12075 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12077 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12078 DAG.getBitcast(MVT::v2f64, Load),
12079 DAG.getIntPtrConstant(0, dl));
12081 // Or the load with the bias.
12082 SDValue Or = DAG.getNode(
12083 ISD::OR, dl, MVT::v2i64,
12084 DAG.getBitcast(MVT::v2i64,
12085 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12086 DAG.getBitcast(MVT::v2i64,
12087 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12089 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12090 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12092 // Subtract the bias.
12093 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12095 // Handle final rounding.
12096 EVT DestVT = Op.getValueType();
12098 if (DestVT.bitsLT(MVT::f64))
12099 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12100 DAG.getIntPtrConstant(0, dl));
12101 if (DestVT.bitsGT(MVT::f64))
12102 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12104 // Handle final rounding.
12108 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12109 const X86Subtarget &Subtarget) {
12110 // The algorithm is the following:
12111 // #ifdef __SSE4_1__
12112 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12113 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12114 // (uint4) 0x53000000, 0xaa);
12116 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12117 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12119 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12120 // return (float4) lo + fhi;
12123 SDValue V = Op->getOperand(0);
12124 EVT VecIntVT = V.getValueType();
12125 bool Is128 = VecIntVT == MVT::v4i32;
12126 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12127 // If we convert to something else than the supported type, e.g., to v4f64,
12129 if (VecFloatVT != Op->getValueType(0))
12132 unsigned NumElts = VecIntVT.getVectorNumElements();
12133 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12134 "Unsupported custom type");
12135 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12137 // In the #idef/#else code, we have in common:
12138 // - The vector of constants:
12144 // Create the splat vector for 0x4b000000.
12145 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12146 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12147 CstLow, CstLow, CstLow, CstLow};
12148 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12149 makeArrayRef(&CstLowArray[0], NumElts));
12150 // Create the splat vector for 0x53000000.
12151 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12152 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12153 CstHigh, CstHigh, CstHigh, CstHigh};
12154 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12155 makeArrayRef(&CstHighArray[0], NumElts));
12157 // Create the right shift.
12158 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12159 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12160 CstShift, CstShift, CstShift, CstShift};
12161 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12162 makeArrayRef(&CstShiftArray[0], NumElts));
12163 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12166 if (Subtarget.hasSSE41()) {
12167 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12168 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12169 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12170 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12171 // Low will be bitcasted right away, so do not bother bitcasting back to its
12173 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12174 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12175 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12176 // (uint4) 0x53000000, 0xaa);
12177 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12178 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12179 // High will be bitcasted right away, so do not bother bitcasting back to
12180 // its original type.
12181 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12182 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12184 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12185 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12186 CstMask, CstMask, CstMask);
12187 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12188 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12189 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12191 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12192 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12195 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12196 SDValue CstFAdd = DAG.getConstantFP(
12197 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12198 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12199 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12200 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12201 makeArrayRef(&CstFAddArray[0], NumElts));
12203 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12204 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12206 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12207 // return (float4) lo + fhi;
12208 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12209 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12212 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12213 SelectionDAG &DAG) const {
12214 SDValue N0 = Op.getOperand(0);
12215 MVT SVT = N0.getSimpleValueType();
12218 switch (SVT.SimpleTy) {
12220 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12225 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12226 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12227 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12231 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12234 if (Subtarget->hasAVX512())
12235 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12236 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12238 llvm_unreachable(nullptr);
12241 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12242 SelectionDAG &DAG) const {
12243 SDValue N0 = Op.getOperand(0);
12245 auto PtrVT = getPointerTy(DAG.getDataLayout());
12247 if (Op.getValueType().isVector())
12248 return lowerUINT_TO_FP_vec(Op, DAG);
12250 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12251 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12252 // the optimization here.
12253 if (DAG.SignBitIsZero(N0))
12254 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12256 MVT SrcVT = N0.getSimpleValueType();
12257 MVT DstVT = Op.getSimpleValueType();
12258 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12259 return LowerUINT_TO_FP_i64(Op, DAG);
12260 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12261 return LowerUINT_TO_FP_i32(Op, DAG);
12262 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12265 // Make a 64-bit buffer, and use it to build an FILD.
12266 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12267 if (SrcVT == MVT::i32) {
12268 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12269 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12270 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12271 StackSlot, MachinePointerInfo(),
12273 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12274 OffsetSlot, MachinePointerInfo(),
12276 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12280 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12281 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12282 StackSlot, MachinePointerInfo(),
12284 // For i64 source, we need to add the appropriate power of 2 if the input
12285 // was negative. This is the same as the optimization in
12286 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12287 // we must be careful to do the computation in x87 extended precision, not
12288 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12289 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12290 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12291 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12292 MachineMemOperand::MOLoad, 8, 8);
12294 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12295 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12296 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12299 APInt FF(32, 0x5F800000ULL);
12301 // Check whether the sign bit is set.
12302 SDValue SignSet = DAG.getSetCC(
12303 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12304 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12306 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12307 SDValue FudgePtr = DAG.getConstantPool(
12308 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12310 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12311 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12312 SDValue Four = DAG.getIntPtrConstant(4, dl);
12313 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12315 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12317 // Load the value out, extending it from f32 to f80.
12318 // FIXME: Avoid the extend by constructing the right constant pool?
12319 SDValue Fudge = DAG.getExtLoad(
12320 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12321 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12322 false, false, false, 4);
12323 // Extend everything to 80 bits to force it to be done on x87.
12324 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12325 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12326 DAG.getIntPtrConstant(0, dl));
12329 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12330 // is legal, or has an f16 source (which needs to be promoted to f32),
12331 // just return an <SDValue(), SDValue()> pair.
12332 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12333 // to i16, i32 or i64, and we lower it to a legal sequence.
12334 // If lowered to the final integer result we return a <result, SDValue()> pair.
12335 // Otherwise we lower it to a sequence ending with a FIST, return a
12336 // <FIST, StackSlot> pair, and the caller is responsible for loading
12337 // the final integer result from StackSlot.
12338 std::pair<SDValue,SDValue>
12339 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12340 bool IsSigned, bool IsReplace) const {
12343 EVT DstTy = Op.getValueType();
12344 EVT TheVT = Op.getOperand(0).getValueType();
12345 auto PtrVT = getPointerTy(DAG.getDataLayout());
12347 if (TheVT == MVT::f16)
12348 // We need to promote the f16 to f32 before using the lowering
12349 // in this routine.
12350 return std::make_pair(SDValue(), SDValue());
12352 assert((TheVT == MVT::f32 ||
12353 TheVT == MVT::f64 ||
12354 TheVT == MVT::f80) &&
12355 "Unexpected FP operand type in FP_TO_INTHelper");
12357 // If using FIST to compute an unsigned i64, we'll need some fixup
12358 // to handle values above the maximum signed i64. A FIST is always
12359 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12360 bool UnsignedFixup = !IsSigned &&
12361 DstTy == MVT::i64 &&
12362 (!Subtarget->is64Bit() ||
12363 !isScalarFPTypeInSSEReg(TheVT));
12365 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12366 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12367 // The low 32 bits of the fist result will have the correct uint32 result.
12368 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12372 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12373 DstTy.getSimpleVT() >= MVT::i16 &&
12374 "Unknown FP_TO_INT to lower!");
12376 // These are really Legal.
12377 if (DstTy == MVT::i32 &&
12378 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12379 return std::make_pair(SDValue(), SDValue());
12380 if (Subtarget->is64Bit() &&
12381 DstTy == MVT::i64 &&
12382 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12383 return std::make_pair(SDValue(), SDValue());
12385 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12387 MachineFunction &MF = DAG.getMachineFunction();
12388 unsigned MemSize = DstTy.getSizeInBits()/8;
12389 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12390 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12393 switch (DstTy.getSimpleVT().SimpleTy) {
12394 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12395 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12396 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12397 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12400 SDValue Chain = DAG.getEntryNode();
12401 SDValue Value = Op.getOperand(0);
12402 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12404 if (UnsignedFixup) {
12406 // Conversion to unsigned i64 is implemented with a select,
12407 // depending on whether the source value fits in the range
12408 // of a signed i64. Let Thresh be the FP equivalent of
12409 // 0x8000000000000000ULL.
12411 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12412 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12413 // Fist-to-mem64 FistSrc
12414 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12415 // to XOR'ing the high 32 bits with Adjust.
12417 // Being a power of 2, Thresh is exactly representable in all FP formats.
12418 // For X87 we'd like to use the smallest FP type for this constant, but
12419 // for DAG type consistency we have to match the FP operand type.
12421 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12422 APFloat::opStatus Status = APFloat::opOK;
12423 bool LosesInfo = false;
12424 if (TheVT == MVT::f64)
12425 // The rounding mode is irrelevant as the conversion should be exact.
12426 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12428 else if (TheVT == MVT::f80)
12429 Status = Thresh.convert(APFloat::x87DoubleExtended,
12430 APFloat::rmNearestTiesToEven, &LosesInfo);
12432 assert(Status == APFloat::opOK && !LosesInfo &&
12433 "FP conversion should have been exact");
12435 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12437 SDValue Cmp = DAG.getSetCC(DL,
12438 getSetCCResultType(DAG.getDataLayout(),
12439 *DAG.getContext(), TheVT),
12440 Value, ThreshVal, ISD::SETLT);
12441 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12442 DAG.getConstant(0, DL, MVT::i32),
12443 DAG.getConstant(0x80000000, DL, MVT::i32));
12444 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12445 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12446 *DAG.getContext(), TheVT),
12447 Value, ThreshVal, ISD::SETLT);
12448 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12451 // FIXME This causes a redundant load/store if the SSE-class value is already
12452 // in memory, such as if it is on the callstack.
12453 if (isScalarFPTypeInSSEReg(TheVT)) {
12454 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12455 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12456 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12458 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12460 Chain, StackSlot, DAG.getValueType(TheVT)
12463 MachineMemOperand *MMO =
12464 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12465 MachineMemOperand::MOLoad, MemSize, MemSize);
12466 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12467 Chain = Value.getValue(1);
12468 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12469 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12472 MachineMemOperand *MMO =
12473 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12474 MachineMemOperand::MOStore, MemSize, MemSize);
12476 if (UnsignedFixup) {
12478 // Insert the FIST, load its result as two i32's,
12479 // and XOR the high i32 with Adjust.
12481 SDValue FistOps[] = { Chain, Value, StackSlot };
12482 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12483 FistOps, DstTy, MMO);
12485 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12486 MachinePointerInfo(),
12487 false, false, false, 0);
12488 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12489 DAG.getConstant(4, DL, PtrVT));
12491 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12492 MachinePointerInfo(),
12493 false, false, false, 0);
12494 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12496 if (Subtarget->is64Bit()) {
12497 // Join High32 and Low32 into a 64-bit result.
12498 // (High32 << 32) | Low32
12499 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12500 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12501 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12502 DAG.getConstant(32, DL, MVT::i8));
12503 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12504 return std::make_pair(Result, SDValue());
12507 SDValue ResultOps[] = { Low32, High32 };
12509 SDValue pair = IsReplace
12510 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12511 : DAG.getMergeValues(ResultOps, DL);
12512 return std::make_pair(pair, SDValue());
12514 // Build the FP_TO_INT*_IN_MEM
12515 SDValue Ops[] = { Chain, Value, StackSlot };
12516 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12518 return std::make_pair(FIST, StackSlot);
12522 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12523 const X86Subtarget *Subtarget) {
12524 MVT VT = Op->getSimpleValueType(0);
12525 SDValue In = Op->getOperand(0);
12526 MVT InVT = In.getSimpleValueType();
12529 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12530 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12532 // Optimize vectors in AVX mode:
12535 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12536 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12537 // Concat upper and lower parts.
12540 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12541 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12542 // Concat upper and lower parts.
12545 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12546 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12547 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12550 if (Subtarget->hasInt256())
12551 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12553 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12554 SDValue Undef = DAG.getUNDEF(InVT);
12555 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12556 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12557 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12559 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12560 VT.getVectorNumElements()/2);
12562 OpLo = DAG.getBitcast(HVT, OpLo);
12563 OpHi = DAG.getBitcast(HVT, OpHi);
12565 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12568 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12569 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12570 MVT VT = Op->getSimpleValueType(0);
12571 SDValue In = Op->getOperand(0);
12572 MVT InVT = In.getSimpleValueType();
12574 unsigned int NumElts = VT.getVectorNumElements();
12575 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12578 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12579 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12581 assert(InVT.getVectorElementType() == MVT::i1);
12582 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12584 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12586 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12588 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12589 if (VT.is512BitVector())
12591 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12594 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12595 SelectionDAG &DAG) {
12596 if (Subtarget->hasFp256())
12597 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12603 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12604 SelectionDAG &DAG) {
12606 MVT VT = Op.getSimpleValueType();
12607 SDValue In = Op.getOperand(0);
12608 MVT SVT = In.getSimpleValueType();
12610 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12611 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12613 if (Subtarget->hasFp256())
12614 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12617 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12618 VT.getVectorNumElements() != SVT.getVectorNumElements());
12622 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12624 MVT VT = Op.getSimpleValueType();
12625 SDValue In = Op.getOperand(0);
12626 MVT InVT = In.getSimpleValueType();
12628 if (VT == MVT::i1) {
12629 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12630 "Invalid scalar TRUNCATE operation");
12631 if (InVT.getSizeInBits() >= 32)
12633 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12634 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12636 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12637 "Invalid TRUNCATE operation");
12639 // move vector to mask - truncate solution for SKX
12640 if (VT.getVectorElementType() == MVT::i1) {
12641 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12642 Subtarget->hasBWI())
12643 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12644 if ((InVT.is256BitVector() || InVT.is128BitVector())
12645 && InVT.getScalarSizeInBits() <= 16 &&
12646 Subtarget->hasBWI() && Subtarget->hasVLX())
12647 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12648 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12649 Subtarget->hasDQI())
12650 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12651 if ((InVT.is256BitVector() || InVT.is128BitVector())
12652 && InVT.getScalarSizeInBits() >= 32 &&
12653 Subtarget->hasDQI() && Subtarget->hasVLX())
12654 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12657 if (VT.getVectorElementType() == MVT::i1) {
12658 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12659 unsigned NumElts = InVT.getVectorNumElements();
12660 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12661 if (InVT.getSizeInBits() < 512) {
12662 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12663 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12668 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12669 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12670 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12673 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12674 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12675 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12676 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12678 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12679 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12680 if (Subtarget->hasInt256()) {
12681 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12682 In = DAG.getBitcast(MVT::v8i32, In);
12683 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12685 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12686 DAG.getIntPtrConstant(0, DL));
12689 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12690 DAG.getIntPtrConstant(0, DL));
12691 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12692 DAG.getIntPtrConstant(2, DL));
12693 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12694 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12695 static const int ShufMask[] = {0, 2, 4, 6};
12696 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12699 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12700 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12701 if (Subtarget->hasInt256()) {
12702 In = DAG.getBitcast(MVT::v32i8, In);
12704 SmallVector<SDValue,32> pshufbMask;
12705 for (unsigned i = 0; i < 2; ++i) {
12706 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12707 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12708 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12709 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12710 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12711 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12712 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12713 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12714 for (unsigned j = 0; j < 8; ++j)
12715 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12717 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12718 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12719 In = DAG.getBitcast(MVT::v4i64, In);
12721 static const int ShufMask[] = {0, 2, -1, -1};
12722 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12724 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12725 DAG.getIntPtrConstant(0, DL));
12726 return DAG.getBitcast(VT, In);
12729 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12730 DAG.getIntPtrConstant(0, DL));
12732 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12733 DAG.getIntPtrConstant(4, DL));
12735 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12736 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12738 // The PSHUFB mask:
12739 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12740 -1, -1, -1, -1, -1, -1, -1, -1};
12742 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12743 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12744 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12746 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12747 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12749 // The MOVLHPS Mask:
12750 static const int ShufMask2[] = {0, 1, 4, 5};
12751 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12752 return DAG.getBitcast(MVT::v8i16, res);
12755 // Handle truncation of V256 to V128 using shuffles.
12756 if (!VT.is128BitVector() || !InVT.is256BitVector())
12759 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12761 unsigned NumElems = VT.getVectorNumElements();
12762 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12764 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12765 // Prepare truncation shuffle mask
12766 for (unsigned i = 0; i != NumElems; ++i)
12767 MaskVec[i] = i * 2;
12768 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12769 DAG.getUNDEF(NVT), &MaskVec[0]);
12770 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12771 DAG.getIntPtrConstant(0, DL));
12774 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12775 SelectionDAG &DAG) const {
12776 assert(!Op.getSimpleValueType().isVector());
12778 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12779 /*IsSigned=*/ true, /*IsReplace=*/ false);
12780 SDValue FIST = Vals.first, StackSlot = Vals.second;
12781 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12782 if (!FIST.getNode())
12785 if (StackSlot.getNode())
12786 // Load the result.
12787 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12788 FIST, StackSlot, MachinePointerInfo(),
12789 false, false, false, 0);
12791 // The node is the result.
12795 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12796 SelectionDAG &DAG) const {
12797 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12798 /*IsSigned=*/ false, /*IsReplace=*/ false);
12799 SDValue FIST = Vals.first, StackSlot = Vals.second;
12800 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12801 if (!FIST.getNode())
12804 if (StackSlot.getNode())
12805 // Load the result.
12806 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12807 FIST, StackSlot, MachinePointerInfo(),
12808 false, false, false, 0);
12810 // The node is the result.
12814 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12816 MVT VT = Op.getSimpleValueType();
12817 SDValue In = Op.getOperand(0);
12818 MVT SVT = In.getSimpleValueType();
12820 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12822 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12823 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12824 In, DAG.getUNDEF(SVT)));
12827 /// The only differences between FABS and FNEG are the mask and the logic op.
12828 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12829 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12830 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12831 "Wrong opcode for lowering FABS or FNEG.");
12833 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12835 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12836 // into an FNABS. We'll lower the FABS after that if it is still in use.
12838 for (SDNode *User : Op->uses())
12839 if (User->getOpcode() == ISD::FNEG)
12843 MVT VT = Op.getSimpleValueType();
12845 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12846 // decide if we should generate a 16-byte constant mask when we only need 4 or
12847 // 8 bytes for the scalar case.
12853 if (VT.isVector()) {
12855 EltVT = VT.getVectorElementType();
12856 NumElts = VT.getVectorNumElements();
12858 // There are no scalar bitwise logical SSE/AVX instructions, so we
12859 // generate a 16-byte vector constant and logic op even for the scalar case.
12860 // Using a 16-byte mask allows folding the load of the mask with
12861 // the logic op, so it can save (~4 bytes) on code size.
12862 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12864 NumElts = (VT == MVT::f64) ? 2 : 4;
12867 unsigned EltBits = EltVT.getSizeInBits();
12868 LLVMContext *Context = DAG.getContext();
12869 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12871 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12872 Constant *C = ConstantInt::get(*Context, MaskElt);
12873 C = ConstantVector::getSplat(NumElts, C);
12874 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12875 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12876 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12878 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12879 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12880 false, false, false, Alignment);
12882 SDValue Op0 = Op.getOperand(0);
12883 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12885 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12886 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12889 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12891 // For the scalar case extend to a 128-bit vector, perform the logic op,
12892 // and extract the scalar result back out.
12893 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12894 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12895 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12896 DAG.getIntPtrConstant(0, dl));
12899 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12900 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12901 LLVMContext *Context = DAG.getContext();
12902 SDValue Op0 = Op.getOperand(0);
12903 SDValue Op1 = Op.getOperand(1);
12905 MVT VT = Op.getSimpleValueType();
12906 MVT SrcVT = Op1.getSimpleValueType();
12908 // If second operand is smaller, extend it first.
12909 if (SrcVT.bitsLT(VT)) {
12910 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12913 // And if it is bigger, shrink it first.
12914 if (SrcVT.bitsGT(VT)) {
12915 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12919 // At this point the operands and the result should have the same
12920 // type, and that won't be f80 since that is not custom lowered.
12922 const fltSemantics &Sem =
12923 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12924 const unsigned SizeInBits = VT.getSizeInBits();
12926 SmallVector<Constant *, 4> CV(
12927 VT == MVT::f64 ? 2 : 4,
12928 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12930 // First, clear all bits but the sign bit from the second operand (sign).
12931 CV[0] = ConstantFP::get(*Context,
12932 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12933 Constant *C = ConstantVector::get(CV);
12934 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12935 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12937 // Perform all logic operations as 16-byte vectors because there are no
12938 // scalar FP logic instructions in SSE. This allows load folding of the
12939 // constants into the logic instructions.
12940 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12942 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12943 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12944 false, false, false, 16);
12945 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12946 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12948 // Next, clear the sign bit from the first operand (magnitude).
12949 // If it's a constant, we can clear it here.
12950 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12951 APFloat APF = Op0CN->getValueAPF();
12952 // If the magnitude is a positive zero, the sign bit alone is enough.
12953 if (APF.isPosZero())
12954 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12955 DAG.getIntPtrConstant(0, dl));
12957 CV[0] = ConstantFP::get(*Context, APF);
12959 CV[0] = ConstantFP::get(
12961 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12963 C = ConstantVector::get(CV);
12964 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12966 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12967 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12968 false, false, false, 16);
12969 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12970 if (!isa<ConstantFPSDNode>(Op0)) {
12971 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12972 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12974 // OR the magnitude value with the sign bit.
12975 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12976 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12977 DAG.getIntPtrConstant(0, dl));
12980 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12981 SDValue N0 = Op.getOperand(0);
12983 MVT VT = Op.getSimpleValueType();
12985 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12986 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12987 DAG.getConstant(1, dl, VT));
12988 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12991 // Check whether an OR'd tree is PTEST-able.
12992 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12993 SelectionDAG &DAG) {
12994 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12996 if (!Subtarget->hasSSE41())
12999 if (!Op->hasOneUse())
13002 SDNode *N = Op.getNode();
13005 SmallVector<SDValue, 8> Opnds;
13006 DenseMap<SDValue, unsigned> VecInMap;
13007 SmallVector<SDValue, 8> VecIns;
13008 EVT VT = MVT::Other;
13010 // Recognize a special case where a vector is casted into wide integer to
13012 Opnds.push_back(N->getOperand(0));
13013 Opnds.push_back(N->getOperand(1));
13015 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13016 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13017 // BFS traverse all OR'd operands.
13018 if (I->getOpcode() == ISD::OR) {
13019 Opnds.push_back(I->getOperand(0));
13020 Opnds.push_back(I->getOperand(1));
13021 // Re-evaluate the number of nodes to be traversed.
13022 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13026 // Quit if a non-EXTRACT_VECTOR_ELT
13027 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13030 // Quit if without a constant index.
13031 SDValue Idx = I->getOperand(1);
13032 if (!isa<ConstantSDNode>(Idx))
13035 SDValue ExtractedFromVec = I->getOperand(0);
13036 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13037 if (M == VecInMap.end()) {
13038 VT = ExtractedFromVec.getValueType();
13039 // Quit if not 128/256-bit vector.
13040 if (!VT.is128BitVector() && !VT.is256BitVector())
13042 // Quit if not the same type.
13043 if (VecInMap.begin() != VecInMap.end() &&
13044 VT != VecInMap.begin()->first.getValueType())
13046 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13047 VecIns.push_back(ExtractedFromVec);
13049 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13052 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13053 "Not extracted from 128-/256-bit vector.");
13055 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13057 for (DenseMap<SDValue, unsigned>::const_iterator
13058 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13059 // Quit if not all elements are used.
13060 if (I->second != FullMask)
13064 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13066 // Cast all vectors into TestVT for PTEST.
13067 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13068 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13070 // If more than one full vectors are evaluated, OR them first before PTEST.
13071 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13072 // Each iteration will OR 2 nodes and append the result until there is only
13073 // 1 node left, i.e. the final OR'd value of all vectors.
13074 SDValue LHS = VecIns[Slot];
13075 SDValue RHS = VecIns[Slot + 1];
13076 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13079 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13080 VecIns.back(), VecIns.back());
13083 /// \brief return true if \c Op has a use that doesn't just read flags.
13084 static bool hasNonFlagsUse(SDValue Op) {
13085 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13087 SDNode *User = *UI;
13088 unsigned UOpNo = UI.getOperandNo();
13089 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13090 // Look pass truncate.
13091 UOpNo = User->use_begin().getOperandNo();
13092 User = *User->use_begin();
13095 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13096 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13102 /// Emit nodes that will be selected as "test Op0,Op0", or something
13104 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13105 SelectionDAG &DAG) const {
13106 if (Op.getValueType() == MVT::i1) {
13107 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13108 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13109 DAG.getConstant(0, dl, MVT::i8));
13111 // CF and OF aren't always set the way we want. Determine which
13112 // of these we need.
13113 bool NeedCF = false;
13114 bool NeedOF = false;
13117 case X86::COND_A: case X86::COND_AE:
13118 case X86::COND_B: case X86::COND_BE:
13121 case X86::COND_G: case X86::COND_GE:
13122 case X86::COND_L: case X86::COND_LE:
13123 case X86::COND_O: case X86::COND_NO: {
13124 // Check if we really need to set the
13125 // Overflow flag. If NoSignedWrap is present
13126 // that is not actually needed.
13127 switch (Op->getOpcode()) {
13132 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13133 if (BinNode->Flags.hasNoSignedWrap())
13143 // See if we can use the EFLAGS value from the operand instead of
13144 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13145 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13146 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13147 // Emit a CMP with 0, which is the TEST pattern.
13148 //if (Op.getValueType() == MVT::i1)
13149 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13150 // DAG.getConstant(0, MVT::i1));
13151 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13152 DAG.getConstant(0, dl, Op.getValueType()));
13154 unsigned Opcode = 0;
13155 unsigned NumOperands = 0;
13157 // Truncate operations may prevent the merge of the SETCC instruction
13158 // and the arithmetic instruction before it. Attempt to truncate the operands
13159 // of the arithmetic instruction and use a reduced bit-width instruction.
13160 bool NeedTruncation = false;
13161 SDValue ArithOp = Op;
13162 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13163 SDValue Arith = Op->getOperand(0);
13164 // Both the trunc and the arithmetic op need to have one user each.
13165 if (Arith->hasOneUse())
13166 switch (Arith.getOpcode()) {
13173 NeedTruncation = true;
13179 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13180 // which may be the result of a CAST. We use the variable 'Op', which is the
13181 // non-casted variable when we check for possible users.
13182 switch (ArithOp.getOpcode()) {
13184 // Due to an isel shortcoming, be conservative if this add is likely to be
13185 // selected as part of a load-modify-store instruction. When the root node
13186 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13187 // uses of other nodes in the match, such as the ADD in this case. This
13188 // leads to the ADD being left around and reselected, with the result being
13189 // two adds in the output. Alas, even if none our users are stores, that
13190 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13191 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13192 // climbing the DAG back to the root, and it doesn't seem to be worth the
13194 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13195 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13196 if (UI->getOpcode() != ISD::CopyToReg &&
13197 UI->getOpcode() != ISD::SETCC &&
13198 UI->getOpcode() != ISD::STORE)
13201 if (ConstantSDNode *C =
13202 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13203 // An add of one will be selected as an INC.
13204 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13205 Opcode = X86ISD::INC;
13210 // An add of negative one (subtract of one) will be selected as a DEC.
13211 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13212 Opcode = X86ISD::DEC;
13218 // Otherwise use a regular EFLAGS-setting add.
13219 Opcode = X86ISD::ADD;
13224 // If we have a constant logical shift that's only used in a comparison
13225 // against zero turn it into an equivalent AND. This allows turning it into
13226 // a TEST instruction later.
13227 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13228 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13229 EVT VT = Op.getValueType();
13230 unsigned BitWidth = VT.getSizeInBits();
13231 unsigned ShAmt = Op->getConstantOperandVal(1);
13232 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13234 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13235 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13236 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13237 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13239 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13240 DAG.getConstant(Mask, dl, VT));
13241 DAG.ReplaceAllUsesWith(Op, New);
13247 // If the primary and result isn't used, don't bother using X86ISD::AND,
13248 // because a TEST instruction will be better.
13249 if (!hasNonFlagsUse(Op))
13255 // Due to the ISEL shortcoming noted above, be conservative if this op is
13256 // likely to be selected as part of a load-modify-store instruction.
13257 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13258 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13259 if (UI->getOpcode() == ISD::STORE)
13262 // Otherwise use a regular EFLAGS-setting instruction.
13263 switch (ArithOp.getOpcode()) {
13264 default: llvm_unreachable("unexpected operator!");
13265 case ISD::SUB: Opcode = X86ISD::SUB; break;
13266 case ISD::XOR: Opcode = X86ISD::XOR; break;
13267 case ISD::AND: Opcode = X86ISD::AND; break;
13269 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13270 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13271 if (EFLAGS.getNode())
13274 Opcode = X86ISD::OR;
13288 return SDValue(Op.getNode(), 1);
13294 // If we found that truncation is beneficial, perform the truncation and
13296 if (NeedTruncation) {
13297 EVT VT = Op.getValueType();
13298 SDValue WideVal = Op->getOperand(0);
13299 EVT WideVT = WideVal.getValueType();
13300 unsigned ConvertedOp = 0;
13301 // Use a target machine opcode to prevent further DAGCombine
13302 // optimizations that may separate the arithmetic operations
13303 // from the setcc node.
13304 switch (WideVal.getOpcode()) {
13306 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13307 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13308 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13309 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13310 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13314 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13315 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13316 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13317 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13318 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13324 // Emit a CMP with 0, which is the TEST pattern.
13325 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13326 DAG.getConstant(0, dl, Op.getValueType()));
13328 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13329 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13331 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13332 DAG.ReplaceAllUsesWith(Op, New);
13333 return SDValue(New.getNode(), 1);
13336 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13338 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13339 SDLoc dl, SelectionDAG &DAG) const {
13340 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13341 if (C->getAPIntValue() == 0)
13342 return EmitTest(Op0, X86CC, dl, DAG);
13344 if (Op0.getValueType() == MVT::i1)
13345 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13348 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13349 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13350 // Do the comparison at i32 if it's smaller, besides the Atom case.
13351 // This avoids subregister aliasing issues. Keep the smaller reference
13352 // if we're optimizing for size, however, as that'll allow better folding
13353 // of memory operations.
13354 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13355 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13356 !Subtarget->isAtom()) {
13357 unsigned ExtendOp =
13358 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13359 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13360 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13362 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13363 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13364 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13366 return SDValue(Sub.getNode(), 1);
13368 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13371 /// Convert a comparison if required by the subtarget.
13372 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13373 SelectionDAG &DAG) const {
13374 // If the subtarget does not support the FUCOMI instruction, floating-point
13375 // comparisons have to be converted.
13376 if (Subtarget->hasCMov() ||
13377 Cmp.getOpcode() != X86ISD::CMP ||
13378 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13379 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13382 // The instruction selector will select an FUCOM instruction instead of
13383 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13384 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13385 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13387 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13388 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13389 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13390 DAG.getConstant(8, dl, MVT::i8));
13391 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13392 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13395 /// The minimum architected relative accuracy is 2^-12. We need one
13396 /// Newton-Raphson step to have a good float result (24 bits of precision).
13397 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13398 DAGCombinerInfo &DCI,
13399 unsigned &RefinementSteps,
13400 bool &UseOneConstNR) const {
13401 EVT VT = Op.getValueType();
13402 const char *RecipOp;
13404 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13405 // TODO: Add support for AVX512 (v16f32).
13406 // It is likely not profitable to do this for f64 because a double-precision
13407 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13408 // instructions: convert to single, rsqrtss, convert back to double, refine
13409 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13410 // along with FMA, this could be a throughput win.
13411 if (VT == MVT::f32 && Subtarget->hasSSE1())
13413 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13414 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13415 RecipOp = "vec-sqrtf";
13419 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13420 if (!Recips.isEnabled(RecipOp))
13423 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13424 UseOneConstNR = false;
13425 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13428 /// The minimum architected relative accuracy is 2^-12. We need one
13429 /// Newton-Raphson step to have a good float result (24 bits of precision).
13430 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13431 DAGCombinerInfo &DCI,
13432 unsigned &RefinementSteps) const {
13433 EVT VT = Op.getValueType();
13434 const char *RecipOp;
13436 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13437 // TODO: Add support for AVX512 (v16f32).
13438 // It is likely not profitable to do this for f64 because a double-precision
13439 // reciprocal estimate with refinement on x86 prior to FMA requires
13440 // 15 instructions: convert to single, rcpss, convert back to double, refine
13441 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13442 // along with FMA, this could be a throughput win.
13443 if (VT == MVT::f32 && Subtarget->hasSSE1())
13445 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13446 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13447 RecipOp = "vec-divf";
13451 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13452 if (!Recips.isEnabled(RecipOp))
13455 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13456 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13459 /// If we have at least two divisions that use the same divisor, convert to
13460 /// multplication by a reciprocal. This may need to be adjusted for a given
13461 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13462 /// This is because we still need one division to calculate the reciprocal and
13463 /// then we need two multiplies by that reciprocal as replacements for the
13464 /// original divisions.
13465 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13469 static bool isAllOnes(SDValue V) {
13470 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13471 return C && C->isAllOnesValue();
13474 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13475 /// if it's possible.
13476 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13477 SDLoc dl, SelectionDAG &DAG) const {
13478 SDValue Op0 = And.getOperand(0);
13479 SDValue Op1 = And.getOperand(1);
13480 if (Op0.getOpcode() == ISD::TRUNCATE)
13481 Op0 = Op0.getOperand(0);
13482 if (Op1.getOpcode() == ISD::TRUNCATE)
13483 Op1 = Op1.getOperand(0);
13486 if (Op1.getOpcode() == ISD::SHL)
13487 std::swap(Op0, Op1);
13488 if (Op0.getOpcode() == ISD::SHL) {
13489 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13490 if (And00C->getZExtValue() == 1) {
13491 // If we looked past a truncate, check that it's only truncating away
13493 unsigned BitWidth = Op0.getValueSizeInBits();
13494 unsigned AndBitWidth = And.getValueSizeInBits();
13495 if (BitWidth > AndBitWidth) {
13497 DAG.computeKnownBits(Op0, Zeros, Ones);
13498 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13502 RHS = Op0.getOperand(1);
13504 } else if (Op1.getOpcode() == ISD::Constant) {
13505 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13506 uint64_t AndRHSVal = AndRHS->getZExtValue();
13507 SDValue AndLHS = Op0;
13509 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13510 LHS = AndLHS.getOperand(0);
13511 RHS = AndLHS.getOperand(1);
13514 // Use BT if the immediate can't be encoded in a TEST instruction.
13515 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13517 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13521 if (LHS.getNode()) {
13522 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13523 // instruction. Since the shift amount is in-range-or-undefined, we know
13524 // that doing a bittest on the i32 value is ok. We extend to i32 because
13525 // the encoding for the i16 version is larger than the i32 version.
13526 // Also promote i16 to i32 for performance / code size reason.
13527 if (LHS.getValueType() == MVT::i8 ||
13528 LHS.getValueType() == MVT::i16)
13529 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13531 // If the operand types disagree, extend the shift amount to match. Since
13532 // BT ignores high bits (like shifts) we can use anyextend.
13533 if (LHS.getValueType() != RHS.getValueType())
13534 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13536 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13537 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13538 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13539 DAG.getConstant(Cond, dl, MVT::i8), BT);
13545 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13547 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13552 // SSE Condition code mapping:
13561 switch (SetCCOpcode) {
13562 default: llvm_unreachable("Unexpected SETCC condition");
13564 case ISD::SETEQ: SSECC = 0; break;
13566 case ISD::SETGT: Swap = true; // Fallthrough
13568 case ISD::SETOLT: SSECC = 1; break;
13570 case ISD::SETGE: Swap = true; // Fallthrough
13572 case ISD::SETOLE: SSECC = 2; break;
13573 case ISD::SETUO: SSECC = 3; break;
13575 case ISD::SETNE: SSECC = 4; break;
13576 case ISD::SETULE: Swap = true; // Fallthrough
13577 case ISD::SETUGE: SSECC = 5; break;
13578 case ISD::SETULT: Swap = true; // Fallthrough
13579 case ISD::SETUGT: SSECC = 6; break;
13580 case ISD::SETO: SSECC = 7; break;
13582 case ISD::SETONE: SSECC = 8; break;
13585 std::swap(Op0, Op1);
13590 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13591 // ones, and then concatenate the result back.
13592 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13593 MVT VT = Op.getSimpleValueType();
13595 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13596 "Unsupported value type for operation");
13598 unsigned NumElems = VT.getVectorNumElements();
13600 SDValue CC = Op.getOperand(2);
13602 // Extract the LHS vectors
13603 SDValue LHS = Op.getOperand(0);
13604 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13605 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13607 // Extract the RHS vectors
13608 SDValue RHS = Op.getOperand(1);
13609 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13610 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13612 // Issue the operation on the smaller types and concatenate the result back
13613 MVT EltVT = VT.getVectorElementType();
13614 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13615 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13616 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13617 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13620 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13621 SDValue Op0 = Op.getOperand(0);
13622 SDValue Op1 = Op.getOperand(1);
13623 SDValue CC = Op.getOperand(2);
13624 MVT VT = Op.getSimpleValueType();
13627 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13628 "Unexpected type for boolean compare operation");
13629 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13630 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13631 DAG.getConstant(-1, dl, VT));
13632 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13633 DAG.getConstant(-1, dl, VT));
13634 switch (SetCCOpcode) {
13635 default: llvm_unreachable("Unexpected SETCC condition");
13637 // (x == y) -> ~(x ^ y)
13638 return DAG.getNode(ISD::XOR, dl, VT,
13639 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13640 DAG.getConstant(-1, dl, VT));
13642 // (x != y) -> (x ^ y)
13643 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13646 // (x > y) -> (x & ~y)
13647 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13650 // (x < y) -> (~x & y)
13651 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13654 // (x <= y) -> (~x | y)
13655 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13658 // (x >=y) -> (x | ~y)
13659 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13663 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13664 const X86Subtarget *Subtarget) {
13665 SDValue Op0 = Op.getOperand(0);
13666 SDValue Op1 = Op.getOperand(1);
13667 SDValue CC = Op.getOperand(2);
13668 MVT VT = Op.getSimpleValueType();
13671 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13672 Op.getValueType().getScalarType() == MVT::i1 &&
13673 "Cannot set masked compare for this operation");
13675 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13677 bool Unsigned = false;
13680 switch (SetCCOpcode) {
13681 default: llvm_unreachable("Unexpected SETCC condition");
13682 case ISD::SETNE: SSECC = 4; break;
13683 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13684 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13685 case ISD::SETLT: Swap = true; //fall-through
13686 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13687 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13688 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13689 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13690 case ISD::SETULE: Unsigned = true; //fall-through
13691 case ISD::SETLE: SSECC = 2; break;
13695 std::swap(Op0, Op1);
13697 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13698 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13699 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13700 DAG.getConstant(SSECC, dl, MVT::i8));
13703 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13704 /// operand \p Op1. If non-trivial (for example because it's not constant)
13705 /// return an empty value.
13706 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13708 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13712 MVT VT = Op1.getSimpleValueType();
13713 MVT EVT = VT.getVectorElementType();
13714 unsigned n = VT.getVectorNumElements();
13715 SmallVector<SDValue, 8> ULTOp1;
13717 for (unsigned i = 0; i < n; ++i) {
13718 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13719 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13722 // Avoid underflow.
13723 APInt Val = Elt->getAPIntValue();
13727 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13730 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13733 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13734 SelectionDAG &DAG) {
13735 SDValue Op0 = Op.getOperand(0);
13736 SDValue Op1 = Op.getOperand(1);
13737 SDValue CC = Op.getOperand(2);
13738 MVT VT = Op.getSimpleValueType();
13739 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13740 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13745 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13746 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13749 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13750 unsigned Opc = X86ISD::CMPP;
13751 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13752 assert(VT.getVectorNumElements() <= 16);
13753 Opc = X86ISD::CMPM;
13755 // In the two special cases we can't handle, emit two comparisons.
13758 unsigned CombineOpc;
13759 if (SetCCOpcode == ISD::SETUEQ) {
13760 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13762 assert(SetCCOpcode == ISD::SETONE);
13763 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13766 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13767 DAG.getConstant(CC0, dl, MVT::i8));
13768 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13769 DAG.getConstant(CC1, dl, MVT::i8));
13770 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13772 // Handle all other FP comparisons here.
13773 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13774 DAG.getConstant(SSECC, dl, MVT::i8));
13777 // Break 256-bit integer vector compare into smaller ones.
13778 if (VT.is256BitVector() && !Subtarget->hasInt256())
13779 return Lower256IntVSETCC(Op, DAG);
13781 EVT OpVT = Op1.getValueType();
13782 if (OpVT.getVectorElementType() == MVT::i1)
13783 return LowerBoolVSETCC_AVX512(Op, DAG);
13785 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13786 if (Subtarget->hasAVX512()) {
13787 if (Op1.getValueType().is512BitVector() ||
13788 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13789 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13790 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13792 // In AVX-512 architecture setcc returns mask with i1 elements,
13793 // But there is no compare instruction for i8 and i16 elements in KNL.
13794 // We are not talking about 512-bit operands in this case, these
13795 // types are illegal.
13797 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13798 OpVT.getVectorElementType().getSizeInBits() >= 8))
13799 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13800 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13803 // We are handling one of the integer comparisons here. Since SSE only has
13804 // GT and EQ comparisons for integer, swapping operands and multiple
13805 // operations may be required for some comparisons.
13807 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13808 bool Subus = false;
13810 switch (SetCCOpcode) {
13811 default: llvm_unreachable("Unexpected SETCC condition");
13812 case ISD::SETNE: Invert = true;
13813 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13814 case ISD::SETLT: Swap = true;
13815 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13816 case ISD::SETGE: Swap = true;
13817 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13818 Invert = true; break;
13819 case ISD::SETULT: Swap = true;
13820 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13821 FlipSigns = true; break;
13822 case ISD::SETUGE: Swap = true;
13823 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13824 FlipSigns = true; Invert = true; break;
13827 // Special case: Use min/max operations for SETULE/SETUGE
13828 MVT VET = VT.getVectorElementType();
13830 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13831 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13834 switch (SetCCOpcode) {
13836 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13837 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13840 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13843 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13844 if (!MinMax && hasSubus) {
13845 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13847 // t = psubus Op0, Op1
13848 // pcmpeq t, <0..0>
13849 switch (SetCCOpcode) {
13851 case ISD::SETULT: {
13852 // If the comparison is against a constant we can turn this into a
13853 // setule. With psubus, setule does not require a swap. This is
13854 // beneficial because the constant in the register is no longer
13855 // destructed as the destination so it can be hoisted out of a loop.
13856 // Only do this pre-AVX since vpcmp* is no longer destructive.
13857 if (Subtarget->hasAVX())
13859 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13860 if (ULEOp1.getNode()) {
13862 Subus = true; Invert = false; Swap = false;
13866 // Psubus is better than flip-sign because it requires no inversion.
13867 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13868 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13872 Opc = X86ISD::SUBUS;
13878 std::swap(Op0, Op1);
13880 // Check that the operation in question is available (most are plain SSE2,
13881 // but PCMPGTQ and PCMPEQQ have different requirements).
13882 if (VT == MVT::v2i64) {
13883 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13884 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13886 // First cast everything to the right type.
13887 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13888 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13890 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13891 // bits of the inputs before performing those operations. The lower
13892 // compare is always unsigned.
13895 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13897 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13898 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13899 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13900 Sign, Zero, Sign, Zero);
13902 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13903 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13905 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13906 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13907 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13909 // Create masks for only the low parts/high parts of the 64 bit integers.
13910 static const int MaskHi[] = { 1, 1, 3, 3 };
13911 static const int MaskLo[] = { 0, 0, 2, 2 };
13912 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13913 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13914 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13916 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13917 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13920 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13922 return DAG.getBitcast(VT, Result);
13925 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13926 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13927 // pcmpeqd + pshufd + pand.
13928 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13930 // First cast everything to the right type.
13931 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13932 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13935 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13937 // Make sure the lower and upper halves are both all-ones.
13938 static const int Mask[] = { 1, 0, 3, 2 };
13939 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13940 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13943 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13945 return DAG.getBitcast(VT, Result);
13949 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13950 // bits of the inputs before performing those operations.
13952 EVT EltVT = VT.getVectorElementType();
13953 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13955 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13956 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13959 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13961 // If the logical-not of the result is required, perform that now.
13963 Result = DAG.getNOT(dl, Result, VT);
13966 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13969 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13970 getZeroVector(VT, Subtarget, DAG, dl));
13975 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13977 MVT VT = Op.getSimpleValueType();
13979 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13981 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13982 && "SetCC type must be 8-bit or 1-bit integer");
13983 SDValue Op0 = Op.getOperand(0);
13984 SDValue Op1 = Op.getOperand(1);
13986 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13988 // Optimize to BT if possible.
13989 // Lower (X & (1 << N)) == 0 to BT(X, N).
13990 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13991 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13992 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13993 Op1.getOpcode() == ISD::Constant &&
13994 cast<ConstantSDNode>(Op1)->isNullValue() &&
13995 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13996 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13997 if (NewSetCC.getNode()) {
13999 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14004 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14006 if (Op1.getOpcode() == ISD::Constant &&
14007 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14008 cast<ConstantSDNode>(Op1)->isNullValue()) &&
14009 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14011 // If the input is a setcc, then reuse the input setcc or use a new one with
14012 // the inverted condition.
14013 if (Op0.getOpcode() == X86ISD::SETCC) {
14014 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14015 bool Invert = (CC == ISD::SETNE) ^
14016 cast<ConstantSDNode>(Op1)->isNullValue();
14020 CCode = X86::GetOppositeBranchCondition(CCode);
14021 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14022 DAG.getConstant(CCode, dl, MVT::i8),
14023 Op0.getOperand(1));
14025 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14029 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14030 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14031 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14033 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14034 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14037 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14038 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14039 if (X86CC == X86::COND_INVALID)
14042 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14043 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14044 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14045 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14047 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14051 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14052 static bool isX86LogicalCmp(SDValue Op) {
14053 unsigned Opc = Op.getNode()->getOpcode();
14054 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14055 Opc == X86ISD::SAHF)
14057 if (Op.getResNo() == 1 &&
14058 (Opc == X86ISD::ADD ||
14059 Opc == X86ISD::SUB ||
14060 Opc == X86ISD::ADC ||
14061 Opc == X86ISD::SBB ||
14062 Opc == X86ISD::SMUL ||
14063 Opc == X86ISD::UMUL ||
14064 Opc == X86ISD::INC ||
14065 Opc == X86ISD::DEC ||
14066 Opc == X86ISD::OR ||
14067 Opc == X86ISD::XOR ||
14068 Opc == X86ISD::AND))
14071 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14077 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14078 if (V.getOpcode() != ISD::TRUNCATE)
14081 SDValue VOp0 = V.getOperand(0);
14082 unsigned InBits = VOp0.getValueSizeInBits();
14083 unsigned Bits = V.getValueSizeInBits();
14084 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14087 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14088 bool addTest = true;
14089 SDValue Cond = Op.getOperand(0);
14090 SDValue Op1 = Op.getOperand(1);
14091 SDValue Op2 = Op.getOperand(2);
14093 EVT VT = Op1.getValueType();
14096 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14097 // are available or VBLENDV if AVX is available.
14098 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14099 if (Cond.getOpcode() == ISD::SETCC &&
14100 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14101 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14102 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14103 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14104 int SSECC = translateX86FSETCC(
14105 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14108 if (Subtarget->hasAVX512()) {
14109 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14110 DAG.getConstant(SSECC, DL, MVT::i8));
14111 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14114 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14115 DAG.getConstant(SSECC, DL, MVT::i8));
14117 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14118 // of 3 logic instructions for size savings and potentially speed.
14119 // Unfortunately, there is no scalar form of VBLENDV.
14121 // If either operand is a constant, don't try this. We can expect to
14122 // optimize away at least one of the logic instructions later in that
14123 // case, so that sequence would be faster than a variable blend.
14125 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14126 // uses XMM0 as the selection register. That may need just as many
14127 // instructions as the AND/ANDN/OR sequence due to register moves, so
14130 if (Subtarget->hasAVX() &&
14131 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14133 // Convert to vectors, do a VSELECT, and convert back to scalar.
14134 // All of the conversions should be optimized away.
14136 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14137 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14138 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14139 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14141 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14142 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14144 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14146 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14147 VSel, DAG.getIntPtrConstant(0, DL));
14149 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14150 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14151 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14155 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14157 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14158 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14159 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14160 Op1Scalar = Op1.getOperand(0);
14162 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14163 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14164 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14165 Op2Scalar = Op2.getOperand(0);
14166 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14167 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14168 Op1Scalar.getValueType(),
14169 Cond, Op1Scalar, Op2Scalar);
14170 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14171 return DAG.getBitcast(VT, newSelect);
14172 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14173 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14174 DAG.getIntPtrConstant(0, DL));
14178 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14179 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14180 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14181 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14182 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14183 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14184 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14186 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14189 if (Cond.getOpcode() == ISD::SETCC) {
14190 SDValue NewCond = LowerSETCC(Cond, DAG);
14191 if (NewCond.getNode())
14195 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14196 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14197 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14198 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14199 if (Cond.getOpcode() == X86ISD::SETCC &&
14200 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14201 isZero(Cond.getOperand(1).getOperand(1))) {
14202 SDValue Cmp = Cond.getOperand(1);
14204 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14206 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14207 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14208 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14210 SDValue CmpOp0 = Cmp.getOperand(0);
14211 // Apply further optimizations for special cases
14212 // (select (x != 0), -1, 0) -> neg & sbb
14213 // (select (x == 0), 0, -1) -> neg & sbb
14214 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14215 if (YC->isNullValue() &&
14216 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14217 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14218 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14219 DAG.getConstant(0, DL,
14220 CmpOp0.getValueType()),
14222 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14223 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14224 SDValue(Neg.getNode(), 1));
14228 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14229 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14230 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14232 SDValue Res = // Res = 0 or -1.
14233 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14234 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14236 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14237 Res = DAG.getNOT(DL, Res, Res.getValueType());
14239 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14240 if (!N2C || !N2C->isNullValue())
14241 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14246 // Look past (and (setcc_carry (cmp ...)), 1).
14247 if (Cond.getOpcode() == ISD::AND &&
14248 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14249 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14250 if (C && C->getAPIntValue() == 1)
14251 Cond = Cond.getOperand(0);
14254 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14255 // setting operand in place of the X86ISD::SETCC.
14256 unsigned CondOpcode = Cond.getOpcode();
14257 if (CondOpcode == X86ISD::SETCC ||
14258 CondOpcode == X86ISD::SETCC_CARRY) {
14259 CC = Cond.getOperand(0);
14261 SDValue Cmp = Cond.getOperand(1);
14262 unsigned Opc = Cmp.getOpcode();
14263 MVT VT = Op.getSimpleValueType();
14265 bool IllegalFPCMov = false;
14266 if (VT.isFloatingPoint() && !VT.isVector() &&
14267 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14268 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14270 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14271 Opc == X86ISD::BT) { // FIXME
14275 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14276 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14277 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14278 Cond.getOperand(0).getValueType() != MVT::i8)) {
14279 SDValue LHS = Cond.getOperand(0);
14280 SDValue RHS = Cond.getOperand(1);
14281 unsigned X86Opcode;
14284 switch (CondOpcode) {
14285 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14286 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14287 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14288 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14289 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14290 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14291 default: llvm_unreachable("unexpected overflowing operator");
14293 if (CondOpcode == ISD::UMULO)
14294 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14297 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14299 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14301 if (CondOpcode == ISD::UMULO)
14302 Cond = X86Op.getValue(2);
14304 Cond = X86Op.getValue(1);
14306 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14311 // Look past the truncate if the high bits are known zero.
14312 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14313 Cond = Cond.getOperand(0);
14315 // We know the result of AND is compared against zero. Try to match
14317 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14318 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14319 if (NewSetCC.getNode()) {
14320 CC = NewSetCC.getOperand(0);
14321 Cond = NewSetCC.getOperand(1);
14328 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14329 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14332 // a < b ? -1 : 0 -> RES = ~setcc_carry
14333 // a < b ? 0 : -1 -> RES = setcc_carry
14334 // a >= b ? -1 : 0 -> RES = setcc_carry
14335 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14336 if (Cond.getOpcode() == X86ISD::SUB) {
14337 Cond = ConvertCmpIfNecessary(Cond, DAG);
14338 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14340 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14341 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14342 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14343 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14345 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14346 return DAG.getNOT(DL, Res, Res.getValueType());
14351 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14352 // widen the cmov and push the truncate through. This avoids introducing a new
14353 // branch during isel and doesn't add any extensions.
14354 if (Op.getValueType() == MVT::i8 &&
14355 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14356 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14357 if (T1.getValueType() == T2.getValueType() &&
14358 // Blacklist CopyFromReg to avoid partial register stalls.
14359 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14360 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14361 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14362 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14366 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14367 // condition is true.
14368 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14369 SDValue Ops[] = { Op2, Op1, CC, Cond };
14370 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14373 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14374 const X86Subtarget *Subtarget,
14375 SelectionDAG &DAG) {
14376 MVT VT = Op->getSimpleValueType(0);
14377 SDValue In = Op->getOperand(0);
14378 MVT InVT = In.getSimpleValueType();
14379 MVT VTElt = VT.getVectorElementType();
14380 MVT InVTElt = InVT.getVectorElementType();
14384 if ((InVTElt == MVT::i1) &&
14385 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14386 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14388 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14389 VTElt.getSizeInBits() <= 16)) ||
14391 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14392 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14394 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14395 VTElt.getSizeInBits() >= 32))))
14396 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14398 unsigned int NumElts = VT.getVectorNumElements();
14400 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14403 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14404 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14405 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14406 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14409 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14410 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14412 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14415 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14417 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14418 if (VT.is512BitVector())
14420 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14423 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14424 const X86Subtarget *Subtarget,
14425 SelectionDAG &DAG) {
14426 SDValue In = Op->getOperand(0);
14427 MVT VT = Op->getSimpleValueType(0);
14428 MVT InVT = In.getSimpleValueType();
14429 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14431 MVT InSVT = InVT.getScalarType();
14432 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14434 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14436 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14441 // SSE41 targets can use the pmovsx* instructions directly.
14442 if (Subtarget->hasSSE41())
14443 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14445 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14449 // As SRAI is only available on i16/i32 types, we expand only up to i32
14450 // and handle i64 separately.
14451 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14452 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14453 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14454 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14455 Curr = DAG.getBitcast(CurrVT, Curr);
14458 SDValue SignExt = Curr;
14459 if (CurrVT != InVT) {
14460 unsigned SignExtShift =
14461 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14462 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14463 DAG.getConstant(SignExtShift, dl, MVT::i8));
14469 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14470 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14471 DAG.getConstant(31, dl, MVT::i8));
14472 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14473 return DAG.getBitcast(VT, Ext);
14479 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14480 SelectionDAG &DAG) {
14481 MVT VT = Op->getSimpleValueType(0);
14482 SDValue In = Op->getOperand(0);
14483 MVT InVT = In.getSimpleValueType();
14486 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14487 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14489 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14490 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14491 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14494 if (Subtarget->hasInt256())
14495 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14497 // Optimize vectors in AVX mode
14498 // Sign extend v8i16 to v8i32 and
14501 // Divide input vector into two parts
14502 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14503 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14504 // concat the vectors to original VT
14506 unsigned NumElems = InVT.getVectorNumElements();
14507 SDValue Undef = DAG.getUNDEF(InVT);
14509 SmallVector<int,8> ShufMask1(NumElems, -1);
14510 for (unsigned i = 0; i != NumElems/2; ++i)
14513 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14515 SmallVector<int,8> ShufMask2(NumElems, -1);
14516 for (unsigned i = 0; i != NumElems/2; ++i)
14517 ShufMask2[i] = i + NumElems/2;
14519 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14521 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14522 VT.getVectorNumElements()/2);
14524 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14525 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14527 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14530 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14531 // may emit an illegal shuffle but the expansion is still better than scalar
14532 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14533 // we'll emit a shuffle and a arithmetic shift.
14534 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14535 // TODO: It is possible to support ZExt by zeroing the undef values during
14536 // the shuffle phase or after the shuffle.
14537 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14538 SelectionDAG &DAG) {
14539 MVT RegVT = Op.getSimpleValueType();
14540 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14541 assert(RegVT.isInteger() &&
14542 "We only custom lower integer vector sext loads.");
14544 // Nothing useful we can do without SSE2 shuffles.
14545 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14547 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14549 EVT MemVT = Ld->getMemoryVT();
14550 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14551 unsigned RegSz = RegVT.getSizeInBits();
14553 ISD::LoadExtType Ext = Ld->getExtensionType();
14555 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14556 && "Only anyext and sext are currently implemented.");
14557 assert(MemVT != RegVT && "Cannot extend to the same type");
14558 assert(MemVT.isVector() && "Must load a vector from memory");
14560 unsigned NumElems = RegVT.getVectorNumElements();
14561 unsigned MemSz = MemVT.getSizeInBits();
14562 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14564 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14565 // The only way in which we have a legal 256-bit vector result but not the
14566 // integer 256-bit operations needed to directly lower a sextload is if we
14567 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14568 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14569 // correctly legalized. We do this late to allow the canonical form of
14570 // sextload to persist throughout the rest of the DAG combiner -- it wants
14571 // to fold together any extensions it can, and so will fuse a sign_extend
14572 // of an sextload into a sextload targeting a wider value.
14574 if (MemSz == 128) {
14575 // Just switch this to a normal load.
14576 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14577 "it must be a legal 128-bit vector "
14579 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14580 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14581 Ld->isInvariant(), Ld->getAlignment());
14583 assert(MemSz < 128 &&
14584 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14585 // Do an sext load to a 128-bit vector type. We want to use the same
14586 // number of elements, but elements half as wide. This will end up being
14587 // recursively lowered by this routine, but will succeed as we definitely
14588 // have all the necessary features if we're using AVX1.
14590 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14591 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14593 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14594 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14595 Ld->isNonTemporal(), Ld->isInvariant(),
14596 Ld->getAlignment());
14599 // Replace chain users with the new chain.
14600 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14601 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14603 // Finally, do a normal sign-extend to the desired register.
14604 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14607 // All sizes must be a power of two.
14608 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14609 "Non-power-of-two elements are not custom lowered!");
14611 // Attempt to load the original value using scalar loads.
14612 // Find the largest scalar type that divides the total loaded size.
14613 MVT SclrLoadTy = MVT::i8;
14614 for (MVT Tp : MVT::integer_valuetypes()) {
14615 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14620 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14621 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14623 SclrLoadTy = MVT::f64;
14625 // Calculate the number of scalar loads that we need to perform
14626 // in order to load our vector from memory.
14627 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14629 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14630 "Can only lower sext loads with a single scalar load!");
14632 unsigned loadRegZize = RegSz;
14633 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14636 // Represent our vector as a sequence of elements which are the
14637 // largest scalar that we can load.
14638 EVT LoadUnitVecVT = EVT::getVectorVT(
14639 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14641 // Represent the data using the same element type that is stored in
14642 // memory. In practice, we ''widen'' MemVT.
14644 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14645 loadRegZize / MemVT.getScalarType().getSizeInBits());
14647 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14648 "Invalid vector type");
14650 // We can't shuffle using an illegal type.
14651 assert(TLI.isTypeLegal(WideVecVT) &&
14652 "We only lower types that form legal widened vector types");
14654 SmallVector<SDValue, 8> Chains;
14655 SDValue Ptr = Ld->getBasePtr();
14656 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14657 TLI.getPointerTy(DAG.getDataLayout()));
14658 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14660 for (unsigned i = 0; i < NumLoads; ++i) {
14661 // Perform a single load.
14662 SDValue ScalarLoad =
14663 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14664 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14665 Ld->getAlignment());
14666 Chains.push_back(ScalarLoad.getValue(1));
14667 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14668 // another round of DAGCombining.
14670 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14672 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14673 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14675 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14678 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14680 // Bitcast the loaded value to a vector of the original element type, in
14681 // the size of the target vector type.
14682 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14683 unsigned SizeRatio = RegSz / MemSz;
14685 if (Ext == ISD::SEXTLOAD) {
14686 // If we have SSE4.1, we can directly emit a VSEXT node.
14687 if (Subtarget->hasSSE41()) {
14688 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14689 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14693 // Otherwise we'll shuffle the small elements in the high bits of the
14694 // larger type and perform an arithmetic shift. If the shift is not legal
14695 // it's better to scalarize.
14696 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14697 "We can't implement a sext load without an arithmetic right shift!");
14699 // Redistribute the loaded elements into the different locations.
14700 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14701 for (unsigned i = 0; i != NumElems; ++i)
14702 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14704 SDValue Shuff = DAG.getVectorShuffle(
14705 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14707 Shuff = DAG.getBitcast(RegVT, Shuff);
14709 // Build the arithmetic shift.
14710 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14711 MemVT.getVectorElementType().getSizeInBits();
14713 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14714 DAG.getConstant(Amt, dl, RegVT));
14716 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14720 // Redistribute the loaded elements into the different locations.
14721 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14722 for (unsigned i = 0; i != NumElems; ++i)
14723 ShuffleVec[i * SizeRatio] = i;
14725 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14726 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14728 // Bitcast to the requested type.
14729 Shuff = DAG.getBitcast(RegVT, Shuff);
14730 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14734 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14735 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14736 // from the AND / OR.
14737 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14738 Opc = Op.getOpcode();
14739 if (Opc != ISD::OR && Opc != ISD::AND)
14741 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14742 Op.getOperand(0).hasOneUse() &&
14743 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14744 Op.getOperand(1).hasOneUse());
14747 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14748 // 1 and that the SETCC node has a single use.
14749 static bool isXor1OfSetCC(SDValue Op) {
14750 if (Op.getOpcode() != ISD::XOR)
14752 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14753 if (N1C && N1C->getAPIntValue() == 1) {
14754 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14755 Op.getOperand(0).hasOneUse();
14760 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14761 bool addTest = true;
14762 SDValue Chain = Op.getOperand(0);
14763 SDValue Cond = Op.getOperand(1);
14764 SDValue Dest = Op.getOperand(2);
14767 bool Inverted = false;
14769 if (Cond.getOpcode() == ISD::SETCC) {
14770 // Check for setcc([su]{add,sub,mul}o == 0).
14771 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14772 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14773 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14774 Cond.getOperand(0).getResNo() == 1 &&
14775 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14776 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14777 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14778 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14779 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14780 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14782 Cond = Cond.getOperand(0);
14784 SDValue NewCond = LowerSETCC(Cond, DAG);
14785 if (NewCond.getNode())
14790 // FIXME: LowerXALUO doesn't handle these!!
14791 else if (Cond.getOpcode() == X86ISD::ADD ||
14792 Cond.getOpcode() == X86ISD::SUB ||
14793 Cond.getOpcode() == X86ISD::SMUL ||
14794 Cond.getOpcode() == X86ISD::UMUL)
14795 Cond = LowerXALUO(Cond, DAG);
14798 // Look pass (and (setcc_carry (cmp ...)), 1).
14799 if (Cond.getOpcode() == ISD::AND &&
14800 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14801 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14802 if (C && C->getAPIntValue() == 1)
14803 Cond = Cond.getOperand(0);
14806 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14807 // setting operand in place of the X86ISD::SETCC.
14808 unsigned CondOpcode = Cond.getOpcode();
14809 if (CondOpcode == X86ISD::SETCC ||
14810 CondOpcode == X86ISD::SETCC_CARRY) {
14811 CC = Cond.getOperand(0);
14813 SDValue Cmp = Cond.getOperand(1);
14814 unsigned Opc = Cmp.getOpcode();
14815 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14816 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14820 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14824 // These can only come from an arithmetic instruction with overflow,
14825 // e.g. SADDO, UADDO.
14826 Cond = Cond.getNode()->getOperand(1);
14832 CondOpcode = Cond.getOpcode();
14833 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14834 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14835 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14836 Cond.getOperand(0).getValueType() != MVT::i8)) {
14837 SDValue LHS = Cond.getOperand(0);
14838 SDValue RHS = Cond.getOperand(1);
14839 unsigned X86Opcode;
14842 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14843 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14845 switch (CondOpcode) {
14846 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14848 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14850 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14853 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14854 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14856 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14858 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14861 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14862 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14863 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14864 default: llvm_unreachable("unexpected overflowing operator");
14867 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14868 if (CondOpcode == ISD::UMULO)
14869 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14872 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14874 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14876 if (CondOpcode == ISD::UMULO)
14877 Cond = X86Op.getValue(2);
14879 Cond = X86Op.getValue(1);
14881 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14885 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14886 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14887 if (CondOpc == ISD::OR) {
14888 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14889 // two branches instead of an explicit OR instruction with a
14891 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14892 isX86LogicalCmp(Cmp)) {
14893 CC = Cond.getOperand(0).getOperand(0);
14894 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14895 Chain, Dest, CC, Cmp);
14896 CC = Cond.getOperand(1).getOperand(0);
14900 } else { // ISD::AND
14901 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14902 // two branches instead of an explicit AND instruction with a
14903 // separate test. However, we only do this if this block doesn't
14904 // have a fall-through edge, because this requires an explicit
14905 // jmp when the condition is false.
14906 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14907 isX86LogicalCmp(Cmp) &&
14908 Op.getNode()->hasOneUse()) {
14909 X86::CondCode CCode =
14910 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14911 CCode = X86::GetOppositeBranchCondition(CCode);
14912 CC = DAG.getConstant(CCode, dl, MVT::i8);
14913 SDNode *User = *Op.getNode()->use_begin();
14914 // Look for an unconditional branch following this conditional branch.
14915 // We need this because we need to reverse the successors in order
14916 // to implement FCMP_OEQ.
14917 if (User->getOpcode() == ISD::BR) {
14918 SDValue FalseBB = User->getOperand(1);
14920 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14921 assert(NewBR == User);
14925 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14926 Chain, Dest, CC, Cmp);
14927 X86::CondCode CCode =
14928 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14929 CCode = X86::GetOppositeBranchCondition(CCode);
14930 CC = DAG.getConstant(CCode, dl, MVT::i8);
14936 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14937 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14938 // It should be transformed during dag combiner except when the condition
14939 // is set by a arithmetics with overflow node.
14940 X86::CondCode CCode =
14941 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14942 CCode = X86::GetOppositeBranchCondition(CCode);
14943 CC = DAG.getConstant(CCode, dl, MVT::i8);
14944 Cond = Cond.getOperand(0).getOperand(1);
14946 } else if (Cond.getOpcode() == ISD::SETCC &&
14947 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14948 // For FCMP_OEQ, we can emit
14949 // two branches instead of an explicit AND instruction with a
14950 // separate test. However, we only do this if this block doesn't
14951 // have a fall-through edge, because this requires an explicit
14952 // jmp when the condition is false.
14953 if (Op.getNode()->hasOneUse()) {
14954 SDNode *User = *Op.getNode()->use_begin();
14955 // Look for an unconditional branch following this conditional branch.
14956 // We need this because we need to reverse the successors in order
14957 // to implement FCMP_OEQ.
14958 if (User->getOpcode() == ISD::BR) {
14959 SDValue FalseBB = User->getOperand(1);
14961 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14962 assert(NewBR == User);
14966 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14967 Cond.getOperand(0), Cond.getOperand(1));
14968 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14969 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14970 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14971 Chain, Dest, CC, Cmp);
14972 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14977 } else if (Cond.getOpcode() == ISD::SETCC &&
14978 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14979 // For FCMP_UNE, we can emit
14980 // two branches instead of an explicit AND instruction with a
14981 // separate test. However, we only do this if this block doesn't
14982 // have a fall-through edge, because this requires an explicit
14983 // jmp when the condition is false.
14984 if (Op.getNode()->hasOneUse()) {
14985 SDNode *User = *Op.getNode()->use_begin();
14986 // Look for an unconditional branch following this conditional branch.
14987 // We need this because we need to reverse the successors in order
14988 // to implement FCMP_UNE.
14989 if (User->getOpcode() == ISD::BR) {
14990 SDValue FalseBB = User->getOperand(1);
14992 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14993 assert(NewBR == User);
14996 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14997 Cond.getOperand(0), Cond.getOperand(1));
14998 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14999 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15000 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15001 Chain, Dest, CC, Cmp);
15002 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15012 // Look pass the truncate if the high bits are known zero.
15013 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15014 Cond = Cond.getOperand(0);
15016 // We know the result of AND is compared against zero. Try to match
15018 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15019 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15020 if (NewSetCC.getNode()) {
15021 CC = NewSetCC.getOperand(0);
15022 Cond = NewSetCC.getOperand(1);
15029 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15030 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15031 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15033 Cond = ConvertCmpIfNecessary(Cond, DAG);
15034 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15035 Chain, Dest, CC, Cond);
15038 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15039 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15040 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15041 // that the guard pages used by the OS virtual memory manager are allocated in
15042 // correct sequence.
15044 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15045 SelectionDAG &DAG) const {
15046 MachineFunction &MF = DAG.getMachineFunction();
15047 bool SplitStack = MF.shouldSplitStack();
15048 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15054 SDNode* Node = Op.getNode();
15056 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15057 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15058 " not tell us which reg is the stack pointer!");
15059 EVT VT = Node->getValueType(0);
15060 SDValue Tmp1 = SDValue(Node, 0);
15061 SDValue Tmp2 = SDValue(Node, 1);
15062 SDValue Tmp3 = Node->getOperand(2);
15063 SDValue Chain = Tmp1.getOperand(0);
15065 // Chain the dynamic stack allocation so that it doesn't modify the stack
15066 // pointer when other instructions are using the stack.
15067 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15070 SDValue Size = Tmp2.getOperand(1);
15071 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15072 Chain = SP.getValue(1);
15073 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15074 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15075 unsigned StackAlign = TFI.getStackAlignment();
15076 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15077 if (Align > StackAlign)
15078 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15079 DAG.getConstant(-(uint64_t)Align, dl, VT));
15080 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15082 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15083 DAG.getIntPtrConstant(0, dl, true), SDValue(),
15086 SDValue Ops[2] = { Tmp1, Tmp2 };
15087 return DAG.getMergeValues(Ops, dl);
15091 SDValue Chain = Op.getOperand(0);
15092 SDValue Size = Op.getOperand(1);
15093 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15094 EVT VT = Op.getNode()->getValueType(0);
15096 bool Is64Bit = Subtarget->is64Bit();
15097 MVT SPTy = getPointerTy(DAG.getDataLayout());
15100 MachineRegisterInfo &MRI = MF.getRegInfo();
15103 // The 64 bit implementation of segmented stacks needs to clobber both r10
15104 // r11. This makes it impossible to use it along with nested parameters.
15105 const Function *F = MF.getFunction();
15107 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15109 if (I->hasNestAttr())
15110 report_fatal_error("Cannot use segmented stacks with functions that "
15111 "have nested arguments.");
15114 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15115 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15116 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15117 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15118 DAG.getRegister(Vreg, SPTy));
15119 SDValue Ops1[2] = { Value, Chain };
15120 return DAG.getMergeValues(Ops1, dl);
15123 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15125 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15126 Flag = Chain.getValue(1);
15127 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15129 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15131 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15132 unsigned SPReg = RegInfo->getStackRegister();
15133 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15134 Chain = SP.getValue(1);
15137 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15138 DAG.getConstant(-(uint64_t)Align, dl, VT));
15139 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15142 SDValue Ops1[2] = { SP, Chain };
15143 return DAG.getMergeValues(Ops1, dl);
15147 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15148 MachineFunction &MF = DAG.getMachineFunction();
15149 auto PtrVT = getPointerTy(MF.getDataLayout());
15150 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15152 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15155 if (!Subtarget->is64Bit() ||
15156 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15157 // vastart just stores the address of the VarArgsFrameIndex slot into the
15158 // memory location argument.
15159 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15160 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15161 MachinePointerInfo(SV), false, false, 0);
15165 // gp_offset (0 - 6 * 8)
15166 // fp_offset (48 - 48 + 8 * 16)
15167 // overflow_arg_area (point to parameters coming in memory).
15169 SmallVector<SDValue, 8> MemOps;
15170 SDValue FIN = Op.getOperand(1);
15172 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15173 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15175 FIN, MachinePointerInfo(SV), false, false, 0);
15176 MemOps.push_back(Store);
15179 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15180 Store = DAG.getStore(Op.getOperand(0), DL,
15181 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15183 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15184 MemOps.push_back(Store);
15186 // Store ptr to overflow_arg_area
15187 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15188 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15189 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15190 MachinePointerInfo(SV, 8),
15192 MemOps.push_back(Store);
15194 // Store ptr to reg_save_area.
15195 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15196 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15197 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15198 MachinePointerInfo(SV, 16), false, false, 0);
15199 MemOps.push_back(Store);
15200 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15203 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15204 assert(Subtarget->is64Bit() &&
15205 "LowerVAARG only handles 64-bit va_arg!");
15206 assert(Op.getNode()->getNumOperands() == 4);
15208 MachineFunction &MF = DAG.getMachineFunction();
15209 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15210 // The Win64 ABI uses char* instead of a structure.
15211 return DAG.expandVAArg(Op.getNode());
15213 SDValue Chain = Op.getOperand(0);
15214 SDValue SrcPtr = Op.getOperand(1);
15215 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15216 unsigned Align = Op.getConstantOperandVal(3);
15219 EVT ArgVT = Op.getNode()->getValueType(0);
15220 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15221 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15224 // Decide which area this value should be read from.
15225 // TODO: Implement the AMD64 ABI in its entirety. This simple
15226 // selection mechanism works only for the basic types.
15227 if (ArgVT == MVT::f80) {
15228 llvm_unreachable("va_arg for f80 not yet implemented");
15229 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15230 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15231 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15232 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15234 llvm_unreachable("Unhandled argument type in LowerVAARG");
15237 if (ArgMode == 2) {
15238 // Sanity Check: Make sure using fp_offset makes sense.
15239 assert(!Subtarget->useSoftFloat() &&
15240 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15241 Subtarget->hasSSE1());
15244 // Insert VAARG_64 node into the DAG
15245 // VAARG_64 returns two values: Variable Argument Address, Chain
15246 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15247 DAG.getConstant(ArgMode, dl, MVT::i8),
15248 DAG.getConstant(Align, dl, MVT::i32)};
15249 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15250 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15251 VTs, InstOps, MVT::i64,
15252 MachinePointerInfo(SV),
15254 /*Volatile=*/false,
15256 /*WriteMem=*/true);
15257 Chain = VAARG.getValue(1);
15259 // Load the next argument and return it
15260 return DAG.getLoad(ArgVT, dl,
15263 MachinePointerInfo(),
15264 false, false, false, 0);
15267 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15268 SelectionDAG &DAG) {
15269 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15270 // where a va_list is still an i8*.
15271 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15272 if (Subtarget->isCallingConvWin64(
15273 DAG.getMachineFunction().getFunction()->getCallingConv()))
15274 // Probably a Win64 va_copy.
15275 return DAG.expandVACopy(Op.getNode());
15277 SDValue Chain = Op.getOperand(0);
15278 SDValue DstPtr = Op.getOperand(1);
15279 SDValue SrcPtr = Op.getOperand(2);
15280 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15281 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15284 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15285 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15287 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15290 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15291 // amount is a constant. Takes immediate version of shift as input.
15292 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15293 SDValue SrcOp, uint64_t ShiftAmt,
15294 SelectionDAG &DAG) {
15295 MVT ElementType = VT.getVectorElementType();
15297 // Fold this packed shift into its first operand if ShiftAmt is 0.
15301 // Check for ShiftAmt >= element width
15302 if (ShiftAmt >= ElementType.getSizeInBits()) {
15303 if (Opc == X86ISD::VSRAI)
15304 ShiftAmt = ElementType.getSizeInBits() - 1;
15306 return DAG.getConstant(0, dl, VT);
15309 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15310 && "Unknown target vector shift-by-constant node");
15312 // Fold this packed vector shift into a build vector if SrcOp is a
15313 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15314 if (VT == SrcOp.getSimpleValueType() &&
15315 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15316 SmallVector<SDValue, 8> Elts;
15317 unsigned NumElts = SrcOp->getNumOperands();
15318 ConstantSDNode *ND;
15321 default: llvm_unreachable(nullptr);
15322 case X86ISD::VSHLI:
15323 for (unsigned i=0; i!=NumElts; ++i) {
15324 SDValue CurrentOp = SrcOp->getOperand(i);
15325 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15326 Elts.push_back(CurrentOp);
15329 ND = cast<ConstantSDNode>(CurrentOp);
15330 const APInt &C = ND->getAPIntValue();
15331 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15334 case X86ISD::VSRLI:
15335 for (unsigned i=0; i!=NumElts; ++i) {
15336 SDValue CurrentOp = SrcOp->getOperand(i);
15337 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15338 Elts.push_back(CurrentOp);
15341 ND = cast<ConstantSDNode>(CurrentOp);
15342 const APInt &C = ND->getAPIntValue();
15343 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15346 case X86ISD::VSRAI:
15347 for (unsigned i=0; i!=NumElts; ++i) {
15348 SDValue CurrentOp = SrcOp->getOperand(i);
15349 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15350 Elts.push_back(CurrentOp);
15353 ND = cast<ConstantSDNode>(CurrentOp);
15354 const APInt &C = ND->getAPIntValue();
15355 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15360 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15363 return DAG.getNode(Opc, dl, VT, SrcOp,
15364 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15367 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15368 // may or may not be a constant. Takes immediate version of shift as input.
15369 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15370 SDValue SrcOp, SDValue ShAmt,
15371 SelectionDAG &DAG) {
15372 MVT SVT = ShAmt.getSimpleValueType();
15373 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15375 // Catch shift-by-constant.
15376 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15377 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15378 CShAmt->getZExtValue(), DAG);
15380 // Change opcode to non-immediate version
15382 default: llvm_unreachable("Unknown target vector shift node");
15383 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15384 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15385 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15388 const X86Subtarget &Subtarget =
15389 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15390 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15391 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15392 // Let the shuffle legalizer expand this shift amount node.
15393 SDValue Op0 = ShAmt.getOperand(0);
15394 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15395 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15397 // Need to build a vector containing shift amount.
15398 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15399 SmallVector<SDValue, 4> ShOps;
15400 ShOps.push_back(ShAmt);
15401 if (SVT == MVT::i32) {
15402 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15403 ShOps.push_back(DAG.getUNDEF(SVT));
15405 ShOps.push_back(DAG.getUNDEF(SVT));
15407 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15408 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15411 // The return type has to be a 128-bit type with the same element
15412 // type as the input type.
15413 MVT EltVT = VT.getVectorElementType();
15414 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15416 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15417 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15420 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15421 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15422 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15423 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15424 SDValue PreservedSrc,
15425 const X86Subtarget *Subtarget,
15426 SelectionDAG &DAG) {
15427 EVT VT = Op.getValueType();
15428 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15429 MVT::i1, VT.getVectorNumElements());
15430 SDValue VMask = SDValue();
15431 unsigned OpcodeSelect = ISD::VSELECT;
15434 assert(MaskVT.isSimple() && "invalid mask type");
15436 if (isAllOnes(Mask))
15439 if (MaskVT.bitsGT(Mask.getValueType())) {
15440 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15441 MaskVT.getSizeInBits());
15442 VMask = DAG.getBitcast(MaskVT,
15443 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15445 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15446 Mask.getValueType().getSizeInBits());
15447 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15448 // are extracted by EXTRACT_SUBVECTOR.
15449 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15450 DAG.getBitcast(BitcastVT, Mask),
15451 DAG.getIntPtrConstant(0, dl));
15454 switch (Op.getOpcode()) {
15456 case X86ISD::PCMPEQM:
15457 case X86ISD::PCMPGTM:
15459 case X86ISD::CMPMU:
15460 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15461 case X86ISD::VTRUNC:
15462 case X86ISD::VTRUNCS:
15463 case X86ISD::VTRUNCUS:
15464 // We can't use ISD::VSELECT here because it is not always "Legal"
15465 // for the destination type. For example vpmovqb require only AVX512
15466 // and vselect that can operate on byte element type require BWI
15467 OpcodeSelect = X86ISD::SELECT;
15470 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15471 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15472 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15475 /// \brief Creates an SDNode for a predicated scalar operation.
15476 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15477 /// The mask is coming as MVT::i8 and it should be truncated
15478 /// to MVT::i1 while lowering masking intrinsics.
15479 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15480 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15481 /// for a scalar instruction.
15482 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15483 SDValue PreservedSrc,
15484 const X86Subtarget *Subtarget,
15485 SelectionDAG &DAG) {
15486 if (isAllOnes(Mask))
15489 EVT VT = Op.getValueType();
15491 // The mask should be of type MVT::i1
15492 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15494 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15495 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15496 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15499 static int getSEHRegistrationNodeSize(const Function *Fn) {
15500 if (!Fn->hasPersonalityFn())
15501 report_fatal_error(
15502 "querying registration node size for function without personality");
15503 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15504 // WinEHStatePass for the full struct definition.
15505 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15506 case EHPersonality::MSVC_X86SEH: return 24;
15507 case EHPersonality::MSVC_CXX: return 16;
15510 report_fatal_error("can only recover FP for MSVC EH personality functions");
15513 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15514 /// function or when returning to a parent frame after catching an exception, we
15515 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15516 /// Here's the math:
15517 /// RegNodeBase = EntryEBP - RegNodeSize
15518 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15519 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15520 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15521 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15522 SDValue EntryEBP) {
15523 MachineFunction &MF = DAG.getMachineFunction();
15526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15527 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15529 // It's possible that the parent function no longer has a personality function
15530 // if the exceptional code was optimized away, in which case we just return
15531 // the incoming EBP.
15532 if (!Fn->hasPersonalityFn())
15535 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15537 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15539 MCSymbol *OffsetSym =
15540 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15541 GlobalValue::getRealLinkageName(Fn->getName()));
15542 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15543 SDValue RegNodeFrameOffset =
15544 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15546 // RegNodeBase = EntryEBP - RegNodeSize
15547 // ParentFP = RegNodeBase - RegNodeFrameOffset
15548 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15549 DAG.getConstant(RegNodeSize, dl, PtrVT));
15550 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15553 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15554 SelectionDAG &DAG) {
15556 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15557 EVT VT = Op.getValueType();
15558 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15560 switch(IntrData->Type) {
15561 case INTR_TYPE_1OP:
15562 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15563 case INTR_TYPE_2OP:
15564 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15566 case INTR_TYPE_3OP:
15567 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15568 Op.getOperand(2), Op.getOperand(3));
15569 case INTR_TYPE_4OP:
15570 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15571 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15572 case INTR_TYPE_1OP_MASK_RM: {
15573 SDValue Src = Op.getOperand(1);
15574 SDValue PassThru = Op.getOperand(2);
15575 SDValue Mask = Op.getOperand(3);
15576 SDValue RoundingMode;
15577 // We allways add rounding mode to the Node.
15578 // If the rounding mode is not specified, we add the
15579 // "current direction" mode.
15580 if (Op.getNumOperands() == 4)
15582 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15584 RoundingMode = Op.getOperand(4);
15585 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15586 if (IntrWithRoundingModeOpcode != 0)
15587 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15588 X86::STATIC_ROUNDING::CUR_DIRECTION)
15589 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15590 dl, Op.getValueType(), Src, RoundingMode),
15591 Mask, PassThru, Subtarget, DAG);
15592 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15594 Mask, PassThru, Subtarget, DAG);
15596 case INTR_TYPE_1OP_MASK: {
15597 SDValue Src = Op.getOperand(1);
15598 SDValue PassThru = Op.getOperand(2);
15599 SDValue Mask = Op.getOperand(3);
15600 // We add rounding mode to the Node when
15601 // - RM Opcode is specified and
15602 // - RM is not "current direction".
15603 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15604 if (IntrWithRoundingModeOpcode != 0) {
15605 SDValue Rnd = Op.getOperand(4);
15606 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15607 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15608 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15609 dl, Op.getValueType(),
15611 Mask, PassThru, Subtarget, DAG);
15614 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15615 Mask, PassThru, Subtarget, DAG);
15617 case INTR_TYPE_SCALAR_MASK_RM: {
15618 SDValue Src1 = Op.getOperand(1);
15619 SDValue Src2 = Op.getOperand(2);
15620 SDValue Src0 = Op.getOperand(3);
15621 SDValue Mask = Op.getOperand(4);
15622 // There are 2 kinds of intrinsics in this group:
15623 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15624 // (2) With rounding mode and sae - 7 operands.
15625 if (Op.getNumOperands() == 6) {
15626 SDValue Sae = Op.getOperand(5);
15627 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15628 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15630 Mask, Src0, Subtarget, DAG);
15632 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15633 SDValue RoundingMode = Op.getOperand(5);
15634 SDValue Sae = Op.getOperand(6);
15635 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15636 RoundingMode, Sae),
15637 Mask, Src0, Subtarget, DAG);
15639 case INTR_TYPE_2OP_MASK: {
15640 SDValue Src1 = Op.getOperand(1);
15641 SDValue Src2 = Op.getOperand(2);
15642 SDValue PassThru = Op.getOperand(3);
15643 SDValue Mask = Op.getOperand(4);
15644 // We specify 2 possible opcodes for intrinsics with rounding modes.
15645 // First, we check if the intrinsic may have non-default rounding mode,
15646 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15647 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15648 if (IntrWithRoundingModeOpcode != 0) {
15649 SDValue Rnd = Op.getOperand(5);
15650 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15651 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15652 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15653 dl, Op.getValueType(),
15655 Mask, PassThru, Subtarget, DAG);
15658 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15660 Mask, PassThru, Subtarget, DAG);
15662 case INTR_TYPE_2OP_MASK_RM: {
15663 SDValue Src1 = Op.getOperand(1);
15664 SDValue Src2 = Op.getOperand(2);
15665 SDValue PassThru = Op.getOperand(3);
15666 SDValue Mask = Op.getOperand(4);
15667 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15668 // First, we check if the intrinsic have rounding mode (6 operands),
15669 // if not, we set rounding mode to "current".
15671 if (Op.getNumOperands() == 6)
15672 Rnd = Op.getOperand(5);
15674 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15675 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15677 Mask, PassThru, Subtarget, DAG);
15679 case INTR_TYPE_3OP_MASK_RM: {
15680 SDValue Src1 = Op.getOperand(1);
15681 SDValue Src2 = Op.getOperand(2);
15682 SDValue Imm = Op.getOperand(3);
15683 SDValue PassThru = Op.getOperand(4);
15684 SDValue Mask = Op.getOperand(5);
15685 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15686 // First, we check if the intrinsic have rounding mode (7 operands),
15687 // if not, we set rounding mode to "current".
15689 if (Op.getNumOperands() == 7)
15690 Rnd = Op.getOperand(6);
15692 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15693 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15694 Src1, Src2, Imm, Rnd),
15695 Mask, PassThru, Subtarget, DAG);
15697 case INTR_TYPE_3OP_MASK: {
15698 SDValue Src1 = Op.getOperand(1);
15699 SDValue Src2 = Op.getOperand(2);
15700 SDValue Src3 = Op.getOperand(3);
15701 SDValue PassThru = Op.getOperand(4);
15702 SDValue Mask = Op.getOperand(5);
15703 // We specify 2 possible opcodes for intrinsics with rounding modes.
15704 // First, we check if the intrinsic may have non-default rounding mode,
15705 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15706 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15707 if (IntrWithRoundingModeOpcode != 0) {
15708 SDValue Rnd = Op.getOperand(6);
15709 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15710 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15711 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15712 dl, Op.getValueType(),
15713 Src1, Src2, Src3, Rnd),
15714 Mask, PassThru, Subtarget, DAG);
15717 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15719 Mask, PassThru, Subtarget, DAG);
15721 case VPERM_3OP_MASKZ:
15722 case VPERM_3OP_MASK:
15725 case FMA_OP_MASK: {
15726 SDValue Src1 = Op.getOperand(1);
15727 SDValue Src2 = Op.getOperand(2);
15728 SDValue Src3 = Op.getOperand(3);
15729 SDValue Mask = Op.getOperand(4);
15730 EVT VT = Op.getValueType();
15731 SDValue PassThru = SDValue();
15733 // set PassThru element
15734 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15735 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15736 else if (IntrData->Type == FMA_OP_MASK3)
15741 // We specify 2 possible opcodes for intrinsics with rounding modes.
15742 // First, we check if the intrinsic may have non-default rounding mode,
15743 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15744 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15745 if (IntrWithRoundingModeOpcode != 0) {
15746 SDValue Rnd = Op.getOperand(5);
15747 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15748 X86::STATIC_ROUNDING::CUR_DIRECTION)
15749 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15750 dl, Op.getValueType(),
15751 Src1, Src2, Src3, Rnd),
15752 Mask, PassThru, Subtarget, DAG);
15754 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15755 dl, Op.getValueType(),
15757 Mask, PassThru, Subtarget, DAG);
15760 case CMP_MASK_CC: {
15761 // Comparison intrinsics with masks.
15762 // Example of transformation:
15763 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15764 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15766 // (v8i1 (insert_subvector undef,
15767 // (v2i1 (and (PCMPEQM %a, %b),
15768 // (extract_subvector
15769 // (v8i1 (bitcast %mask)), 0))), 0))))
15770 EVT VT = Op.getOperand(1).getValueType();
15771 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15772 VT.getVectorNumElements());
15773 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15774 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15775 Mask.getValueType().getSizeInBits());
15777 if (IntrData->Type == CMP_MASK_CC) {
15778 SDValue CC = Op.getOperand(3);
15779 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15780 // We specify 2 possible opcodes for intrinsics with rounding modes.
15781 // First, we check if the intrinsic may have non-default rounding mode,
15782 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15783 if (IntrData->Opc1 != 0) {
15784 SDValue Rnd = Op.getOperand(5);
15785 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15786 X86::STATIC_ROUNDING::CUR_DIRECTION)
15787 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15788 Op.getOperand(2), CC, Rnd);
15790 //default rounding mode
15792 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15793 Op.getOperand(2), CC);
15796 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15797 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15800 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15801 DAG.getTargetConstant(0, dl,
15804 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15805 DAG.getUNDEF(BitcastVT), CmpMask,
15806 DAG.getIntPtrConstant(0, dl));
15807 return DAG.getBitcast(Op.getValueType(), Res);
15809 case COMI: { // Comparison intrinsics
15810 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15811 SDValue LHS = Op.getOperand(1);
15812 SDValue RHS = Op.getOperand(2);
15813 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15814 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15815 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15816 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15817 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15818 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15821 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15822 Op.getOperand(1), Op.getOperand(2), DAG);
15824 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15825 Op.getSimpleValueType(),
15827 Op.getOperand(2), DAG),
15828 Op.getOperand(4), Op.getOperand(3), Subtarget,
15830 case COMPRESS_EXPAND_IN_REG: {
15831 SDValue Mask = Op.getOperand(3);
15832 SDValue DataToCompress = Op.getOperand(1);
15833 SDValue PassThru = Op.getOperand(2);
15834 if (isAllOnes(Mask)) // return data as is
15835 return Op.getOperand(1);
15837 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15839 Mask, PassThru, Subtarget, DAG);
15842 SDValue Mask = Op.getOperand(3);
15843 EVT VT = Op.getValueType();
15844 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15845 VT.getVectorNumElements());
15846 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15847 Mask.getValueType().getSizeInBits());
15849 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15850 DAG.getBitcast(BitcastVT, Mask),
15851 DAG.getIntPtrConstant(0, dl));
15852 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15861 default: return SDValue(); // Don't custom lower most intrinsics.
15863 case Intrinsic::x86_avx2_permd:
15864 case Intrinsic::x86_avx2_permps:
15865 // Operands intentionally swapped. Mask is last operand to intrinsic,
15866 // but second operand for node/instruction.
15867 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15868 Op.getOperand(2), Op.getOperand(1));
15870 // ptest and testp intrinsics. The intrinsic these come from are designed to
15871 // return an integer value, not just an instruction so lower it to the ptest
15872 // or testp pattern and a setcc for the result.
15873 case Intrinsic::x86_sse41_ptestz:
15874 case Intrinsic::x86_sse41_ptestc:
15875 case Intrinsic::x86_sse41_ptestnzc:
15876 case Intrinsic::x86_avx_ptestz_256:
15877 case Intrinsic::x86_avx_ptestc_256:
15878 case Intrinsic::x86_avx_ptestnzc_256:
15879 case Intrinsic::x86_avx_vtestz_ps:
15880 case Intrinsic::x86_avx_vtestc_ps:
15881 case Intrinsic::x86_avx_vtestnzc_ps:
15882 case Intrinsic::x86_avx_vtestz_pd:
15883 case Intrinsic::x86_avx_vtestc_pd:
15884 case Intrinsic::x86_avx_vtestnzc_pd:
15885 case Intrinsic::x86_avx_vtestz_ps_256:
15886 case Intrinsic::x86_avx_vtestc_ps_256:
15887 case Intrinsic::x86_avx_vtestnzc_ps_256:
15888 case Intrinsic::x86_avx_vtestz_pd_256:
15889 case Intrinsic::x86_avx_vtestc_pd_256:
15890 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15891 bool IsTestPacked = false;
15894 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15895 case Intrinsic::x86_avx_vtestz_ps:
15896 case Intrinsic::x86_avx_vtestz_pd:
15897 case Intrinsic::x86_avx_vtestz_ps_256:
15898 case Intrinsic::x86_avx_vtestz_pd_256:
15899 IsTestPacked = true; // Fallthrough
15900 case Intrinsic::x86_sse41_ptestz:
15901 case Intrinsic::x86_avx_ptestz_256:
15903 X86CC = X86::COND_E;
15905 case Intrinsic::x86_avx_vtestc_ps:
15906 case Intrinsic::x86_avx_vtestc_pd:
15907 case Intrinsic::x86_avx_vtestc_ps_256:
15908 case Intrinsic::x86_avx_vtestc_pd_256:
15909 IsTestPacked = true; // Fallthrough
15910 case Intrinsic::x86_sse41_ptestc:
15911 case Intrinsic::x86_avx_ptestc_256:
15913 X86CC = X86::COND_B;
15915 case Intrinsic::x86_avx_vtestnzc_ps:
15916 case Intrinsic::x86_avx_vtestnzc_pd:
15917 case Intrinsic::x86_avx_vtestnzc_ps_256:
15918 case Intrinsic::x86_avx_vtestnzc_pd_256:
15919 IsTestPacked = true; // Fallthrough
15920 case Intrinsic::x86_sse41_ptestnzc:
15921 case Intrinsic::x86_avx_ptestnzc_256:
15923 X86CC = X86::COND_A;
15927 SDValue LHS = Op.getOperand(1);
15928 SDValue RHS = Op.getOperand(2);
15929 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15930 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15931 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15932 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15933 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15935 case Intrinsic::x86_avx512_kortestz_w:
15936 case Intrinsic::x86_avx512_kortestc_w: {
15937 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15938 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15939 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15940 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15941 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15942 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15943 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15946 case Intrinsic::x86_sse42_pcmpistria128:
15947 case Intrinsic::x86_sse42_pcmpestria128:
15948 case Intrinsic::x86_sse42_pcmpistric128:
15949 case Intrinsic::x86_sse42_pcmpestric128:
15950 case Intrinsic::x86_sse42_pcmpistrio128:
15951 case Intrinsic::x86_sse42_pcmpestrio128:
15952 case Intrinsic::x86_sse42_pcmpistris128:
15953 case Intrinsic::x86_sse42_pcmpestris128:
15954 case Intrinsic::x86_sse42_pcmpistriz128:
15955 case Intrinsic::x86_sse42_pcmpestriz128: {
15959 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15960 case Intrinsic::x86_sse42_pcmpistria128:
15961 Opcode = X86ISD::PCMPISTRI;
15962 X86CC = X86::COND_A;
15964 case Intrinsic::x86_sse42_pcmpestria128:
15965 Opcode = X86ISD::PCMPESTRI;
15966 X86CC = X86::COND_A;
15968 case Intrinsic::x86_sse42_pcmpistric128:
15969 Opcode = X86ISD::PCMPISTRI;
15970 X86CC = X86::COND_B;
15972 case Intrinsic::x86_sse42_pcmpestric128:
15973 Opcode = X86ISD::PCMPESTRI;
15974 X86CC = X86::COND_B;
15976 case Intrinsic::x86_sse42_pcmpistrio128:
15977 Opcode = X86ISD::PCMPISTRI;
15978 X86CC = X86::COND_O;
15980 case Intrinsic::x86_sse42_pcmpestrio128:
15981 Opcode = X86ISD::PCMPESTRI;
15982 X86CC = X86::COND_O;
15984 case Intrinsic::x86_sse42_pcmpistris128:
15985 Opcode = X86ISD::PCMPISTRI;
15986 X86CC = X86::COND_S;
15988 case Intrinsic::x86_sse42_pcmpestris128:
15989 Opcode = X86ISD::PCMPESTRI;
15990 X86CC = X86::COND_S;
15992 case Intrinsic::x86_sse42_pcmpistriz128:
15993 Opcode = X86ISD::PCMPISTRI;
15994 X86CC = X86::COND_E;
15996 case Intrinsic::x86_sse42_pcmpestriz128:
15997 Opcode = X86ISD::PCMPESTRI;
15998 X86CC = X86::COND_E;
16001 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16002 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16003 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16004 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16005 DAG.getConstant(X86CC, dl, MVT::i8),
16006 SDValue(PCMP.getNode(), 1));
16007 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16010 case Intrinsic::x86_sse42_pcmpistri128:
16011 case Intrinsic::x86_sse42_pcmpestri128: {
16013 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16014 Opcode = X86ISD::PCMPISTRI;
16016 Opcode = X86ISD::PCMPESTRI;
16018 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16019 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16020 return DAG.getNode(Opcode, dl, VTs, NewOps);
16023 case Intrinsic::x86_seh_lsda: {
16024 // Compute the symbol for the LSDA. We know it'll get emitted later.
16025 MachineFunction &MF = DAG.getMachineFunction();
16026 SDValue Op1 = Op.getOperand(1);
16027 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16028 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16029 GlobalValue::getRealLinkageName(Fn->getName()));
16031 // Generate a simple absolute symbol reference. This intrinsic is only
16032 // supported on 32-bit Windows, which isn't PIC.
16033 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16034 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16037 case Intrinsic::x86_seh_recoverfp: {
16038 SDValue FnOp = Op.getOperand(1);
16039 SDValue IncomingFPOp = Op.getOperand(2);
16040 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16041 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16043 report_fatal_error(
16044 "llvm.x86.seh.recoverfp must take a function as the first argument");
16045 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16048 case Intrinsic::localaddress: {
16049 // Returns one of the stack, base, or frame pointer registers, depending on
16050 // which is used to reference local variables.
16051 MachineFunction &MF = DAG.getMachineFunction();
16052 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16054 if (RegInfo->hasBasePointer(MF))
16055 Reg = RegInfo->getBaseRegister();
16056 else // This function handles the SP or FP case.
16057 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16058 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16063 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16064 SDValue Src, SDValue Mask, SDValue Base,
16065 SDValue Index, SDValue ScaleOp, SDValue Chain,
16066 const X86Subtarget * Subtarget) {
16068 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16070 llvm_unreachable("Invalid scale type");
16071 unsigned ScaleVal = C->getZExtValue();
16072 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16073 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16075 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16076 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16077 Index.getSimpleValueType().getVectorNumElements());
16079 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16081 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16083 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16084 Mask.getValueType().getSizeInBits());
16086 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16087 // are extracted by EXTRACT_SUBVECTOR.
16088 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16089 DAG.getBitcast(BitcastVT, Mask),
16090 DAG.getIntPtrConstant(0, dl));
16092 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16093 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16094 SDValue Segment = DAG.getRegister(0, MVT::i32);
16095 if (Src.getOpcode() == ISD::UNDEF)
16096 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16097 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16098 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16099 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16100 return DAG.getMergeValues(RetOps, dl);
16103 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16104 SDValue Src, SDValue Mask, SDValue Base,
16105 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16107 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16109 llvm_unreachable("Invalid scale type");
16110 unsigned ScaleVal = C->getZExtValue();
16111 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16112 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16114 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16115 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16116 SDValue Segment = DAG.getRegister(0, MVT::i32);
16117 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16118 Index.getSimpleValueType().getVectorNumElements());
16120 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16122 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16124 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16125 Mask.getValueType().getSizeInBits());
16127 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16128 // are extracted by EXTRACT_SUBVECTOR.
16129 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16130 DAG.getBitcast(BitcastVT, Mask),
16131 DAG.getIntPtrConstant(0, dl));
16133 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16134 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16135 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16136 return SDValue(Res, 1);
16139 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16140 SDValue Mask, SDValue Base, SDValue Index,
16141 SDValue ScaleOp, SDValue Chain) {
16143 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16144 assert(C && "Invalid scale type");
16145 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16146 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16147 SDValue Segment = DAG.getRegister(0, MVT::i32);
16149 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16151 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16153 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16155 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16156 //SDVTList VTs = DAG.getVTList(MVT::Other);
16157 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16158 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16159 return SDValue(Res, 0);
16162 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16163 // read performance monitor counters (x86_rdpmc).
16164 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16165 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16166 SmallVectorImpl<SDValue> &Results) {
16167 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16168 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16171 // The ECX register is used to select the index of the performance counter
16173 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16175 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16177 // Reads the content of a 64-bit performance counter and returns it in the
16178 // registers EDX:EAX.
16179 if (Subtarget->is64Bit()) {
16180 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16181 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16184 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16185 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16188 Chain = HI.getValue(1);
16190 if (Subtarget->is64Bit()) {
16191 // The EAX register is loaded with the low-order 32 bits. The EDX register
16192 // is loaded with the supported high-order bits of the counter.
16193 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16194 DAG.getConstant(32, DL, MVT::i8));
16195 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16196 Results.push_back(Chain);
16200 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16201 SDValue Ops[] = { LO, HI };
16202 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16203 Results.push_back(Pair);
16204 Results.push_back(Chain);
16207 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16208 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16209 // also used to custom lower READCYCLECOUNTER nodes.
16210 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16211 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16212 SmallVectorImpl<SDValue> &Results) {
16213 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16214 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16217 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16218 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16219 // and the EAX register is loaded with the low-order 32 bits.
16220 if (Subtarget->is64Bit()) {
16221 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16222 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16225 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16226 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16229 SDValue Chain = HI.getValue(1);
16231 if (Opcode == X86ISD::RDTSCP_DAG) {
16232 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16234 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16235 // the ECX register. Add 'ecx' explicitly to the chain.
16236 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16238 // Explicitly store the content of ECX at the location passed in input
16239 // to the 'rdtscp' intrinsic.
16240 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16241 MachinePointerInfo(), false, false, 0);
16244 if (Subtarget->is64Bit()) {
16245 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16246 // the EAX register is loaded with the low-order 32 bits.
16247 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16248 DAG.getConstant(32, DL, MVT::i8));
16249 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16250 Results.push_back(Chain);
16254 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16255 SDValue Ops[] = { LO, HI };
16256 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16257 Results.push_back(Pair);
16258 Results.push_back(Chain);
16261 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16262 SelectionDAG &DAG) {
16263 SmallVector<SDValue, 2> Results;
16265 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16267 return DAG.getMergeValues(Results, DL);
16270 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16271 SelectionDAG &DAG) {
16272 MachineFunction &MF = DAG.getMachineFunction();
16273 const Function *Fn = MF.getFunction();
16275 SDValue Chain = Op.getOperand(0);
16277 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16278 "using llvm.x86.seh.restoreframe requires a frame pointer");
16280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16281 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16283 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16284 unsigned FrameReg =
16285 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16286 unsigned SPReg = RegInfo->getStackRegister();
16287 unsigned SlotSize = RegInfo->getSlotSize();
16289 // Get incoming EBP.
16290 SDValue IncomingEBP =
16291 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16293 // SP is saved in the first field of every registration node, so load
16294 // [EBP-RegNodeSize] into SP.
16295 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16296 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16297 DAG.getConstant(-RegNodeSize, dl, VT));
16299 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16300 false, VT.getScalarSizeInBits() / 8);
16301 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16303 if (!RegInfo->needsStackRealignment(MF)) {
16304 // Adjust EBP to point back to the original frame position.
16305 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16306 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16308 assert(RegInfo->hasBasePointer(MF) &&
16309 "functions with Win32 EH must use frame or base pointer register");
16311 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16312 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16313 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16315 // Reload the spilled EBP value, now that the stack and base pointers are
16317 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16318 X86FI->setHasSEHFramePtrSave(true);
16319 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16320 X86FI->setSEHFramePtrSaveIndex(FI);
16321 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16322 MachinePointerInfo(), false, false, false,
16323 VT.getScalarSizeInBits() / 8);
16324 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16330 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16331 /// return truncate Store/MaskedStore Node
16332 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16336 SDValue Mask = Op.getOperand(4);
16337 SDValue DataToTruncate = Op.getOperand(3);
16338 SDValue Addr = Op.getOperand(2);
16339 SDValue Chain = Op.getOperand(0);
16341 EVT VT = DataToTruncate.getValueType();
16342 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16343 ElementType, VT.getVectorNumElements());
16345 if (isAllOnes(Mask)) // return just a truncate store
16346 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16347 MachinePointerInfo(), SVT, false, false,
16348 SVT.getScalarSizeInBits()/8);
16350 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16351 MVT::i1, VT.getVectorNumElements());
16352 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16353 Mask.getValueType().getSizeInBits());
16354 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16355 // are extracted by EXTRACT_SUBVECTOR.
16356 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16357 DAG.getBitcast(BitcastVT, Mask),
16358 DAG.getIntPtrConstant(0, dl));
16360 MachineMemOperand *MMO = DAG.getMachineFunction().
16361 getMachineMemOperand(MachinePointerInfo(),
16362 MachineMemOperand::MOStore, SVT.getStoreSize(),
16363 SVT.getScalarSizeInBits()/8);
16365 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16366 VMask, SVT, MMO, true);
16369 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16370 SelectionDAG &DAG) {
16371 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16373 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16375 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16376 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16381 switch(IntrData->Type) {
16383 llvm_unreachable("Unknown Intrinsic Type");
16387 // Emit the node with the right value type.
16388 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16389 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16391 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16392 // Otherwise return the value from Rand, which is always 0, casted to i32.
16393 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16394 DAG.getConstant(1, dl, Op->getValueType(1)),
16395 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16396 SDValue(Result.getNode(), 1) };
16397 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16398 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16401 // Return { result, isValid, chain }.
16402 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16403 SDValue(Result.getNode(), 2));
16406 //gather(v1, mask, index, base, scale);
16407 SDValue Chain = Op.getOperand(0);
16408 SDValue Src = Op.getOperand(2);
16409 SDValue Base = Op.getOperand(3);
16410 SDValue Index = Op.getOperand(4);
16411 SDValue Mask = Op.getOperand(5);
16412 SDValue Scale = Op.getOperand(6);
16413 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16417 //scatter(base, mask, index, v1, scale);
16418 SDValue Chain = Op.getOperand(0);
16419 SDValue Base = Op.getOperand(2);
16420 SDValue Mask = Op.getOperand(3);
16421 SDValue Index = Op.getOperand(4);
16422 SDValue Src = Op.getOperand(5);
16423 SDValue Scale = Op.getOperand(6);
16424 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16428 SDValue Hint = Op.getOperand(6);
16429 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16430 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16431 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16432 SDValue Chain = Op.getOperand(0);
16433 SDValue Mask = Op.getOperand(2);
16434 SDValue Index = Op.getOperand(3);
16435 SDValue Base = Op.getOperand(4);
16436 SDValue Scale = Op.getOperand(5);
16437 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16439 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16441 SmallVector<SDValue, 2> Results;
16442 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16444 return DAG.getMergeValues(Results, dl);
16446 // Read Performance Monitoring Counters.
16448 SmallVector<SDValue, 2> Results;
16449 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16450 return DAG.getMergeValues(Results, dl);
16452 // XTEST intrinsics.
16454 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16455 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16456 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16457 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16459 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16460 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16461 Ret, SDValue(InTrans.getNode(), 1));
16465 SmallVector<SDValue, 2> Results;
16466 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16467 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16468 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16469 DAG.getConstant(-1, dl, MVT::i8));
16470 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16471 Op.getOperand(4), GenCF.getValue(1));
16472 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16473 Op.getOperand(5), MachinePointerInfo(),
16475 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16476 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16478 Results.push_back(SetCC);
16479 Results.push_back(Store);
16480 return DAG.getMergeValues(Results, dl);
16482 case COMPRESS_TO_MEM: {
16484 SDValue Mask = Op.getOperand(4);
16485 SDValue DataToCompress = Op.getOperand(3);
16486 SDValue Addr = Op.getOperand(2);
16487 SDValue Chain = Op.getOperand(0);
16489 EVT VT = DataToCompress.getValueType();
16490 if (isAllOnes(Mask)) // return just a store
16491 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16492 MachinePointerInfo(), false, false,
16493 VT.getScalarSizeInBits()/8);
16495 SDValue Compressed =
16496 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16497 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16498 return DAG.getStore(Chain, dl, Compressed, Addr,
16499 MachinePointerInfo(), false, false,
16500 VT.getScalarSizeInBits()/8);
16502 case TRUNCATE_TO_MEM_VI8:
16503 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16504 case TRUNCATE_TO_MEM_VI16:
16505 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16506 case TRUNCATE_TO_MEM_VI32:
16507 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16508 case EXPAND_FROM_MEM: {
16510 SDValue Mask = Op.getOperand(4);
16511 SDValue PassThru = Op.getOperand(3);
16512 SDValue Addr = Op.getOperand(2);
16513 SDValue Chain = Op.getOperand(0);
16514 EVT VT = Op.getValueType();
16516 if (isAllOnes(Mask)) // return just a load
16517 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16518 false, VT.getScalarSizeInBits()/8);
16520 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16521 false, false, false,
16522 VT.getScalarSizeInBits()/8);
16524 SDValue Results[] = {
16525 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16526 Mask, PassThru, Subtarget, DAG), Chain};
16527 return DAG.getMergeValues(Results, dl);
16532 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16533 SelectionDAG &DAG) const {
16534 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16535 MFI->setReturnAddressIsTaken(true);
16537 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16540 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16542 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16545 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16546 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16547 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16548 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16549 DAG.getNode(ISD::ADD, dl, PtrVT,
16550 FrameAddr, Offset),
16551 MachinePointerInfo(), false, false, false, 0);
16554 // Just load the return address.
16555 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16556 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16557 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16560 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16561 MachineFunction &MF = DAG.getMachineFunction();
16562 MachineFrameInfo *MFI = MF.getFrameInfo();
16563 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16564 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16565 EVT VT = Op.getValueType();
16567 MFI->setFrameAddressIsTaken(true);
16569 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16570 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16571 // is not possible to crawl up the stack without looking at the unwind codes
16573 int FrameAddrIndex = FuncInfo->getFAIndex();
16574 if (!FrameAddrIndex) {
16575 // Set up a frame object for the return address.
16576 unsigned SlotSize = RegInfo->getSlotSize();
16577 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16578 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16579 FuncInfo->setFAIndex(FrameAddrIndex);
16581 return DAG.getFrameIndex(FrameAddrIndex, VT);
16584 unsigned FrameReg =
16585 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16586 SDLoc dl(Op); // FIXME probably not meaningful
16587 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16588 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16589 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16590 "Invalid Frame Register!");
16591 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16593 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16594 MachinePointerInfo(),
16595 false, false, false, 0);
16599 // FIXME? Maybe this could be a TableGen attribute on some registers and
16600 // this table could be generated automatically from RegInfo.
16601 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16602 SelectionDAG &DAG) const {
16603 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16604 const MachineFunction &MF = DAG.getMachineFunction();
16606 unsigned Reg = StringSwitch<unsigned>(RegName)
16607 .Case("esp", X86::ESP)
16608 .Case("rsp", X86::RSP)
16609 .Case("ebp", X86::EBP)
16610 .Case("rbp", X86::RBP)
16613 if (Reg == X86::EBP || Reg == X86::RBP) {
16614 if (!TFI.hasFP(MF))
16615 report_fatal_error("register " + StringRef(RegName) +
16616 " is allocatable: function has no frame pointer");
16619 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16620 unsigned FrameReg =
16621 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16622 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16623 "Invalid Frame Register!");
16631 report_fatal_error("Invalid register name global variable");
16634 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16635 SelectionDAG &DAG) const {
16636 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16637 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16640 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16641 SDValue Chain = Op.getOperand(0);
16642 SDValue Offset = Op.getOperand(1);
16643 SDValue Handler = Op.getOperand(2);
16646 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16647 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16648 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16649 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16650 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16651 "Invalid Frame Register!");
16652 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16653 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16655 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16656 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16658 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16659 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16661 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16663 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16664 DAG.getRegister(StoreAddrReg, PtrVT));
16667 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16668 SelectionDAG &DAG) const {
16670 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16671 DAG.getVTList(MVT::i32, MVT::Other),
16672 Op.getOperand(0), Op.getOperand(1));
16675 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16676 SelectionDAG &DAG) const {
16678 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16679 Op.getOperand(0), Op.getOperand(1));
16682 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16683 return Op.getOperand(0);
16686 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16687 SelectionDAG &DAG) const {
16688 SDValue Root = Op.getOperand(0);
16689 SDValue Trmp = Op.getOperand(1); // trampoline
16690 SDValue FPtr = Op.getOperand(2); // nested function
16691 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16694 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16695 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16697 if (Subtarget->is64Bit()) {
16698 SDValue OutChains[6];
16700 // Large code-model.
16701 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16702 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16704 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16705 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16707 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16709 // Load the pointer to the nested function into R11.
16710 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16711 SDValue Addr = Trmp;
16712 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16713 Addr, MachinePointerInfo(TrmpAddr),
16716 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16717 DAG.getConstant(2, dl, MVT::i64));
16718 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16719 MachinePointerInfo(TrmpAddr, 2),
16722 // Load the 'nest' parameter value into R10.
16723 // R10 is specified in X86CallingConv.td
16724 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16725 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16726 DAG.getConstant(10, dl, MVT::i64));
16727 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16728 Addr, MachinePointerInfo(TrmpAddr, 10),
16731 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16732 DAG.getConstant(12, dl, MVT::i64));
16733 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16734 MachinePointerInfo(TrmpAddr, 12),
16737 // Jump to the nested function.
16738 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16739 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16740 DAG.getConstant(20, dl, MVT::i64));
16741 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16742 Addr, MachinePointerInfo(TrmpAddr, 20),
16745 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16746 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16747 DAG.getConstant(22, dl, MVT::i64));
16748 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16749 Addr, MachinePointerInfo(TrmpAddr, 22),
16752 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16754 const Function *Func =
16755 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16756 CallingConv::ID CC = Func->getCallingConv();
16761 llvm_unreachable("Unsupported calling convention");
16762 case CallingConv::C:
16763 case CallingConv::X86_StdCall: {
16764 // Pass 'nest' parameter in ECX.
16765 // Must be kept in sync with X86CallingConv.td
16766 NestReg = X86::ECX;
16768 // Check that ECX wasn't needed by an 'inreg' parameter.
16769 FunctionType *FTy = Func->getFunctionType();
16770 const AttributeSet &Attrs = Func->getAttributes();
16772 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16773 unsigned InRegCount = 0;
16776 for (FunctionType::param_iterator I = FTy->param_begin(),
16777 E = FTy->param_end(); I != E; ++I, ++Idx)
16778 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16779 auto &DL = DAG.getDataLayout();
16780 // FIXME: should only count parameters that are lowered to integers.
16781 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16784 if (InRegCount > 2) {
16785 report_fatal_error("Nest register in use - reduce number of inreg"
16791 case CallingConv::X86_FastCall:
16792 case CallingConv::X86_ThisCall:
16793 case CallingConv::Fast:
16794 // Pass 'nest' parameter in EAX.
16795 // Must be kept in sync with X86CallingConv.td
16796 NestReg = X86::EAX;
16800 SDValue OutChains[4];
16801 SDValue Addr, Disp;
16803 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16804 DAG.getConstant(10, dl, MVT::i32));
16805 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16807 // This is storing the opcode for MOV32ri.
16808 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16809 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16810 OutChains[0] = DAG.getStore(Root, dl,
16811 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16812 Trmp, MachinePointerInfo(TrmpAddr),
16815 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16816 DAG.getConstant(1, dl, MVT::i32));
16817 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16818 MachinePointerInfo(TrmpAddr, 1),
16821 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16822 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16823 DAG.getConstant(5, dl, MVT::i32));
16824 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16825 Addr, MachinePointerInfo(TrmpAddr, 5),
16828 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16829 DAG.getConstant(6, dl, MVT::i32));
16830 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16831 MachinePointerInfo(TrmpAddr, 6),
16834 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16838 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16839 SelectionDAG &DAG) const {
16841 The rounding mode is in bits 11:10 of FPSR, and has the following
16843 00 Round to nearest
16848 FLT_ROUNDS, on the other hand, expects the following:
16855 To perform the conversion, we do:
16856 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16859 MachineFunction &MF = DAG.getMachineFunction();
16860 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16861 unsigned StackAlignment = TFI.getStackAlignment();
16862 MVT VT = Op.getSimpleValueType();
16865 // Save FP Control Word to stack slot
16866 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16867 SDValue StackSlot =
16868 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16870 MachineMemOperand *MMO =
16871 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16872 MachineMemOperand::MOStore, 2, 2);
16874 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16875 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16876 DAG.getVTList(MVT::Other),
16877 Ops, MVT::i16, MMO);
16879 // Load FP Control Word from stack slot
16880 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16881 MachinePointerInfo(), false, false, false, 0);
16883 // Transform as necessary
16885 DAG.getNode(ISD::SRL, DL, MVT::i16,
16886 DAG.getNode(ISD::AND, DL, MVT::i16,
16887 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16888 DAG.getConstant(11, DL, MVT::i8));
16890 DAG.getNode(ISD::SRL, DL, MVT::i16,
16891 DAG.getNode(ISD::AND, DL, MVT::i16,
16892 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16893 DAG.getConstant(9, DL, MVT::i8));
16896 DAG.getNode(ISD::AND, DL, MVT::i16,
16897 DAG.getNode(ISD::ADD, DL, MVT::i16,
16898 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16899 DAG.getConstant(1, DL, MVT::i16)),
16900 DAG.getConstant(3, DL, MVT::i16));
16902 return DAG.getNode((VT.getSizeInBits() < 16 ?
16903 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16906 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16907 MVT VT = Op.getSimpleValueType();
16909 unsigned NumBits = VT.getSizeInBits();
16912 Op = Op.getOperand(0);
16913 if (VT == MVT::i8) {
16914 // Zero extend to i32 since there is not an i8 bsr.
16916 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16919 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16920 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16921 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16923 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16926 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16927 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16930 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16932 // Finally xor with NumBits-1.
16933 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16934 DAG.getConstant(NumBits - 1, dl, OpVT));
16937 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16941 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16942 MVT VT = Op.getSimpleValueType();
16944 unsigned NumBits = VT.getSizeInBits();
16947 Op = Op.getOperand(0);
16948 if (VT == MVT::i8) {
16949 // Zero extend to i32 since there is not an i8 bsr.
16951 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16954 // Issue a bsr (scan bits in reverse).
16955 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16956 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16958 // And xor with NumBits-1.
16959 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16960 DAG.getConstant(NumBits - 1, dl, OpVT));
16963 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16967 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16968 MVT VT = Op.getSimpleValueType();
16969 unsigned NumBits = VT.getSizeInBits();
16971 Op = Op.getOperand(0);
16973 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16974 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16975 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16977 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16980 DAG.getConstant(NumBits, dl, VT),
16981 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16984 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16987 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16988 // ones, and then concatenate the result back.
16989 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16990 MVT VT = Op.getSimpleValueType();
16992 assert(VT.is256BitVector() && VT.isInteger() &&
16993 "Unsupported value type for operation");
16995 unsigned NumElems = VT.getVectorNumElements();
16998 // Extract the LHS vectors
16999 SDValue LHS = Op.getOperand(0);
17000 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17001 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17003 // Extract the RHS vectors
17004 SDValue RHS = Op.getOperand(1);
17005 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17006 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17008 MVT EltVT = VT.getVectorElementType();
17009 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17011 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17012 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17013 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17016 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17017 if (Op.getValueType() == MVT::i1)
17018 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17019 Op.getOperand(0), Op.getOperand(1));
17020 assert(Op.getSimpleValueType().is256BitVector() &&
17021 Op.getSimpleValueType().isInteger() &&
17022 "Only handle AVX 256-bit vector integer operation");
17023 return Lower256IntArith(Op, DAG);
17026 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17027 if (Op.getValueType() == MVT::i1)
17028 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17029 Op.getOperand(0), Op.getOperand(1));
17030 assert(Op.getSimpleValueType().is256BitVector() &&
17031 Op.getSimpleValueType().isInteger() &&
17032 "Only handle AVX 256-bit vector integer operation");
17033 return Lower256IntArith(Op, DAG);
17036 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17037 assert(Op.getSimpleValueType().is256BitVector() &&
17038 Op.getSimpleValueType().isInteger() &&
17039 "Only handle AVX 256-bit vector integer operation");
17040 return Lower256IntArith(Op, DAG);
17043 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17044 SelectionDAG &DAG) {
17046 MVT VT = Op.getSimpleValueType();
17049 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17051 // Decompose 256-bit ops into smaller 128-bit ops.
17052 if (VT.is256BitVector() && !Subtarget->hasInt256())
17053 return Lower256IntArith(Op, DAG);
17055 SDValue A = Op.getOperand(0);
17056 SDValue B = Op.getOperand(1);
17058 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17059 // pairs, multiply and truncate.
17060 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17061 if (Subtarget->hasInt256()) {
17062 if (VT == MVT::v32i8) {
17063 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17064 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17065 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17066 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17067 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17068 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17069 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17070 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17071 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17072 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17075 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17076 return DAG.getNode(
17077 ISD::TRUNCATE, dl, VT,
17078 DAG.getNode(ISD::MUL, dl, ExVT,
17079 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17080 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17083 assert(VT == MVT::v16i8 &&
17084 "Pre-AVX2 support only supports v16i8 multiplication");
17085 MVT ExVT = MVT::v8i16;
17087 // Extract the lo parts and sign extend to i16
17089 if (Subtarget->hasSSE41()) {
17090 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17091 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17093 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17094 -1, 4, -1, 5, -1, 6, -1, 7};
17095 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17096 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17097 ALo = DAG.getBitcast(ExVT, ALo);
17098 BLo = DAG.getBitcast(ExVT, BLo);
17099 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17100 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17103 // Extract the hi parts and sign extend to i16
17105 if (Subtarget->hasSSE41()) {
17106 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
17107 -1, -1, -1, -1, -1, -1, -1, -1};
17108 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17109 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17110 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17111 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17113 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
17114 -1, 12, -1, 13, -1, 14, -1, 15};
17115 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17116 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17117 AHi = DAG.getBitcast(ExVT, AHi);
17118 BHi = DAG.getBitcast(ExVT, BHi);
17119 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17120 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17123 // Multiply, mask the lower 8bits of the lo/hi results and pack
17124 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17125 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17126 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17127 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17128 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17131 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17132 if (VT == MVT::v4i32) {
17133 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17134 "Should not custom lower when pmuldq is available!");
17136 // Extract the odd parts.
17137 static const int UnpackMask[] = { 1, -1, 3, -1 };
17138 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17139 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17141 // Multiply the even parts.
17142 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17143 // Now multiply odd parts.
17144 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17146 Evens = DAG.getBitcast(VT, Evens);
17147 Odds = DAG.getBitcast(VT, Odds);
17149 // Merge the two vectors back together with a shuffle. This expands into 2
17151 static const int ShufMask[] = { 0, 4, 2, 6 };
17152 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17155 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17156 "Only know how to lower V2I64/V4I64/V8I64 multiply");
17158 // Ahi = psrlqi(a, 32);
17159 // Bhi = psrlqi(b, 32);
17161 // AloBlo = pmuludq(a, b);
17162 // AloBhi = pmuludq(a, Bhi);
17163 // AhiBlo = pmuludq(Ahi, b);
17165 // AloBhi = psllqi(AloBhi, 32);
17166 // AhiBlo = psllqi(AhiBlo, 32);
17167 // return AloBlo + AloBhi + AhiBlo;
17169 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17170 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17172 SDValue AhiBlo = Ahi;
17173 SDValue AloBhi = Bhi;
17174 // Bit cast to 32-bit vectors for MULUDQ
17175 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17176 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17177 A = DAG.getBitcast(MulVT, A);
17178 B = DAG.getBitcast(MulVT, B);
17179 Ahi = DAG.getBitcast(MulVT, Ahi);
17180 Bhi = DAG.getBitcast(MulVT, Bhi);
17182 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17183 // After shifting right const values the result may be all-zero.
17184 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17185 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17186 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17188 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17189 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17190 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17193 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17194 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17197 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17198 assert(Subtarget->isTargetWin64() && "Unexpected target");
17199 EVT VT = Op.getValueType();
17200 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17201 "Unexpected return type for lowering");
17205 switch (Op->getOpcode()) {
17206 default: llvm_unreachable("Unexpected request for libcall!");
17207 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17208 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17209 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17210 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17211 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17212 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17216 SDValue InChain = DAG.getEntryNode();
17218 TargetLowering::ArgListTy Args;
17219 TargetLowering::ArgListEntry Entry;
17220 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17221 EVT ArgVT = Op->getOperand(i).getValueType();
17222 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17223 "Unexpected argument type for lowering");
17224 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17225 Entry.Node = StackPtr;
17226 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17228 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17229 Entry.Ty = PointerType::get(ArgTy,0);
17230 Entry.isSExt = false;
17231 Entry.isZExt = false;
17232 Args.push_back(Entry);
17235 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17236 getPointerTy(DAG.getDataLayout()));
17238 TargetLowering::CallLoweringInfo CLI(DAG);
17239 CLI.setDebugLoc(dl).setChain(InChain)
17240 .setCallee(getLibcallCallingConv(LC),
17241 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17242 Callee, std::move(Args), 0)
17243 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17245 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17246 return DAG.getBitcast(VT, CallInfo.first);
17249 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17250 SelectionDAG &DAG) {
17251 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17252 EVT VT = Op0.getValueType();
17255 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17256 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17258 // PMULxD operations multiply each even value (starting at 0) of LHS with
17259 // the related value of RHS and produce a widen result.
17260 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17261 // => <2 x i64> <ae|cg>
17263 // In other word, to have all the results, we need to perform two PMULxD:
17264 // 1. one with the even values.
17265 // 2. one with the odd values.
17266 // To achieve #2, with need to place the odd values at an even position.
17268 // Place the odd value at an even position (basically, shift all values 1
17269 // step to the left):
17270 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17271 // <a|b|c|d> => <b|undef|d|undef>
17272 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17273 // <e|f|g|h> => <f|undef|h|undef>
17274 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17276 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17278 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17279 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17281 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17282 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17283 // => <2 x i64> <ae|cg>
17284 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17285 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17286 // => <2 x i64> <bf|dh>
17287 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17289 // Shuffle it back into the right order.
17290 SDValue Highs, Lows;
17291 if (VT == MVT::v8i32) {
17292 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17293 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17294 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17295 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17297 const int HighMask[] = {1, 5, 3, 7};
17298 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17299 const int LowMask[] = {0, 4, 2, 6};
17300 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17303 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17304 // unsigned multiply.
17305 if (IsSigned && !Subtarget->hasSSE41()) {
17306 SDValue ShAmt = DAG.getConstant(
17308 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17309 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17310 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17311 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17312 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17314 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17315 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17318 // The first result of MUL_LOHI is actually the low value, followed by the
17320 SDValue Ops[] = {Lows, Highs};
17321 return DAG.getMergeValues(Ops, dl);
17324 // Return true if the required (according to Opcode) shift-imm form is natively
17325 // supported by the Subtarget
17326 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17328 if (VT.getScalarSizeInBits() < 16)
17331 if (VT.is512BitVector() &&
17332 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17335 bool LShift = VT.is128BitVector() ||
17336 (VT.is256BitVector() && Subtarget->hasInt256());
17338 bool AShift = LShift && (Subtarget->hasVLX() ||
17339 (VT != MVT::v2i64 && VT != MVT::v4i64));
17340 return (Opcode == ISD::SRA) ? AShift : LShift;
17343 // The shift amount is a variable, but it is the same for all vector lanes.
17344 // These instructions are defined together with shift-immediate.
17346 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17348 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17351 // Return true if the required (according to Opcode) variable-shift form is
17352 // natively supported by the Subtarget
17353 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17356 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17359 // vXi16 supported only on AVX-512, BWI
17360 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17363 if (VT.is512BitVector() || Subtarget->hasVLX())
17366 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17367 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17368 return (Opcode == ISD::SRA) ? AShift : LShift;
17371 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17372 const X86Subtarget *Subtarget) {
17373 MVT VT = Op.getSimpleValueType();
17375 SDValue R = Op.getOperand(0);
17376 SDValue Amt = Op.getOperand(1);
17378 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17379 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17381 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17382 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17383 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17384 SDValue Ex = DAG.getBitcast(ExVT, R);
17386 if (ShiftAmt >= 32) {
17387 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17389 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17390 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17391 ShiftAmt - 32, DAG);
17392 if (VT == MVT::v2i64)
17393 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17394 if (VT == MVT::v4i64)
17395 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17396 {9, 1, 11, 3, 13, 5, 15, 7});
17398 // SRA upper i32, SHL whole i64 and select lower i32.
17399 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17402 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17403 Lower = DAG.getBitcast(ExVT, Lower);
17404 if (VT == MVT::v2i64)
17405 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17406 if (VT == MVT::v4i64)
17407 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17408 {8, 1, 10, 3, 12, 5, 14, 7});
17410 return DAG.getBitcast(VT, Ex);
17413 // Optimize shl/srl/sra with constant shift amount.
17414 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17415 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17416 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17418 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17419 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17421 // i64 SRA needs to be performed as partial shifts.
17422 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17423 Op.getOpcode() == ISD::SRA)
17424 return ArithmeticShiftRight64(ShiftAmt);
17426 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17427 unsigned NumElts = VT.getVectorNumElements();
17428 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17430 if (Op.getOpcode() == ISD::SHL) {
17431 // Simple i8 add case
17433 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17435 // Make a large shift.
17436 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17438 SHL = DAG.getBitcast(VT, SHL);
17439 // Zero out the rightmost bits.
17440 SmallVector<SDValue, 32> V(
17441 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17442 return DAG.getNode(ISD::AND, dl, VT, SHL,
17443 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17445 if (Op.getOpcode() == ISD::SRL) {
17446 // Make a large shift.
17447 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17449 SRL = DAG.getBitcast(VT, SRL);
17450 // Zero out the leftmost bits.
17451 SmallVector<SDValue, 32> V(
17452 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17453 return DAG.getNode(ISD::AND, dl, VT, SRL,
17454 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17456 if (Op.getOpcode() == ISD::SRA) {
17457 if (ShiftAmt == 7) {
17458 // ashr(R, 7) === cmp_slt(R, 0)
17459 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17460 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17463 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17464 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17465 SmallVector<SDValue, 32> V(NumElts,
17466 DAG.getConstant(128 >> ShiftAmt, dl,
17468 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17469 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17470 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17473 llvm_unreachable("Unknown shift opcode.");
17478 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17479 if (!Subtarget->is64Bit() &&
17480 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17482 // Peek through any splat that was introduced for i64 shift vectorization.
17483 int SplatIndex = -1;
17484 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17485 if (SVN->isSplat()) {
17486 SplatIndex = SVN->getSplatIndex();
17487 Amt = Amt.getOperand(0);
17488 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17489 "Splat shuffle referencing second operand");
17492 if (Amt.getOpcode() != ISD::BITCAST ||
17493 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17496 Amt = Amt.getOperand(0);
17497 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17498 VT.getVectorNumElements();
17499 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17500 uint64_t ShiftAmt = 0;
17501 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17502 for (unsigned i = 0; i != Ratio; ++i) {
17503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17507 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17510 // Check remaining shift amounts (if not a splat).
17511 if (SplatIndex < 0) {
17512 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17513 uint64_t ShAmt = 0;
17514 for (unsigned j = 0; j != Ratio; ++j) {
17515 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17519 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17521 if (ShAmt != ShiftAmt)
17526 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17527 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17529 if (Op.getOpcode() == ISD::SRA)
17530 return ArithmeticShiftRight64(ShiftAmt);
17536 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17537 const X86Subtarget* Subtarget) {
17538 MVT VT = Op.getSimpleValueType();
17540 SDValue R = Op.getOperand(0);
17541 SDValue Amt = Op.getOperand(1);
17543 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17544 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17546 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17547 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17549 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17551 EVT EltVT = VT.getVectorElementType();
17553 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17554 // Check if this build_vector node is doing a splat.
17555 // If so, then set BaseShAmt equal to the splat value.
17556 BaseShAmt = BV->getSplatValue();
17557 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17558 BaseShAmt = SDValue();
17560 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17561 Amt = Amt.getOperand(0);
17563 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17564 if (SVN && SVN->isSplat()) {
17565 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17566 SDValue InVec = Amt.getOperand(0);
17567 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17568 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17569 "Unexpected shuffle index found!");
17570 BaseShAmt = InVec.getOperand(SplatIdx);
17571 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17572 if (ConstantSDNode *C =
17573 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17574 if (C->getZExtValue() == SplatIdx)
17575 BaseShAmt = InVec.getOperand(1);
17580 // Avoid introducing an extract element from a shuffle.
17581 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17582 DAG.getIntPtrConstant(SplatIdx, dl));
17586 if (BaseShAmt.getNode()) {
17587 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17588 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17589 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17590 else if (EltVT.bitsLT(MVT::i32))
17591 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17593 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17597 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17598 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17599 Amt.getOpcode() == ISD::BITCAST &&
17600 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17601 Amt = Amt.getOperand(0);
17602 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17603 VT.getVectorNumElements();
17604 std::vector<SDValue> Vals(Ratio);
17605 for (unsigned i = 0; i != Ratio; ++i)
17606 Vals[i] = Amt.getOperand(i);
17607 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17608 for (unsigned j = 0; j != Ratio; ++j)
17609 if (Vals[j] != Amt.getOperand(i + j))
17613 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17614 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17619 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17620 SelectionDAG &DAG) {
17621 MVT VT = Op.getSimpleValueType();
17623 SDValue R = Op.getOperand(0);
17624 SDValue Amt = Op.getOperand(1);
17626 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17627 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17629 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17632 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17635 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17638 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17639 // shifts per-lane and then shuffle the partial results back together.
17640 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17641 // Splat the shift amounts so the scalar shifts above will catch it.
17642 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17643 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17644 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17645 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17646 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17649 // i64 vector arithmetic shift can be emulated with the transform:
17650 // M = lshr(SIGN_BIT, Amt)
17651 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17652 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17653 Op.getOpcode() == ISD::SRA) {
17654 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17655 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17656 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17657 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17658 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17662 // If possible, lower this packed shift into a vector multiply instead of
17663 // expanding it into a sequence of scalar shifts.
17664 // Do this only if the vector shift count is a constant build_vector.
17665 if (Op.getOpcode() == ISD::SHL &&
17666 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17667 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17668 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17669 SmallVector<SDValue, 8> Elts;
17670 EVT SVT = VT.getScalarType();
17671 unsigned SVTBits = SVT.getSizeInBits();
17672 const APInt &One = APInt(SVTBits, 1);
17673 unsigned NumElems = VT.getVectorNumElements();
17675 for (unsigned i=0; i !=NumElems; ++i) {
17676 SDValue Op = Amt->getOperand(i);
17677 if (Op->getOpcode() == ISD::UNDEF) {
17678 Elts.push_back(Op);
17682 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17683 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17684 uint64_t ShAmt = C.getZExtValue();
17685 if (ShAmt >= SVTBits) {
17686 Elts.push_back(DAG.getUNDEF(SVT));
17689 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17691 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17692 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17695 // Lower SHL with variable shift amount.
17696 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17697 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17699 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17700 DAG.getConstant(0x3f800000U, dl, VT));
17701 Op = DAG.getBitcast(MVT::v4f32, Op);
17702 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17703 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17706 // If possible, lower this shift as a sequence of two shifts by
17707 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17709 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17711 // Could be rewritten as:
17712 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17714 // The advantage is that the two shifts from the example would be
17715 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17716 // the vector shift into four scalar shifts plus four pairs of vector
17718 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17719 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17720 unsigned TargetOpcode = X86ISD::MOVSS;
17721 bool CanBeSimplified;
17722 // The splat value for the first packed shift (the 'X' from the example).
17723 SDValue Amt1 = Amt->getOperand(0);
17724 // The splat value for the second packed shift (the 'Y' from the example).
17725 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17726 Amt->getOperand(2);
17728 // See if it is possible to replace this node with a sequence of
17729 // two shifts followed by a MOVSS/MOVSD
17730 if (VT == MVT::v4i32) {
17731 // Check if it is legal to use a MOVSS.
17732 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17733 Amt2 == Amt->getOperand(3);
17734 if (!CanBeSimplified) {
17735 // Otherwise, check if we can still simplify this node using a MOVSD.
17736 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17737 Amt->getOperand(2) == Amt->getOperand(3);
17738 TargetOpcode = X86ISD::MOVSD;
17739 Amt2 = Amt->getOperand(2);
17742 // Do similar checks for the case where the machine value type
17744 CanBeSimplified = Amt1 == Amt->getOperand(1);
17745 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17746 CanBeSimplified = Amt2 == Amt->getOperand(i);
17748 if (!CanBeSimplified) {
17749 TargetOpcode = X86ISD::MOVSD;
17750 CanBeSimplified = true;
17751 Amt2 = Amt->getOperand(4);
17752 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17753 CanBeSimplified = Amt1 == Amt->getOperand(i);
17754 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17755 CanBeSimplified = Amt2 == Amt->getOperand(j);
17759 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17760 isa<ConstantSDNode>(Amt2)) {
17761 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17762 EVT CastVT = MVT::v4i32;
17764 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17765 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17767 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17768 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17769 if (TargetOpcode == X86ISD::MOVSD)
17770 CastVT = MVT::v2i64;
17771 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17772 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17773 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17775 return DAG.getBitcast(VT, Result);
17779 // v4i32 Non Uniform Shifts.
17780 // If the shift amount is constant we can shift each lane using the SSE2
17781 // immediate shifts, else we need to zero-extend each lane to the lower i64
17782 // and shift using the SSE2 variable shifts.
17783 // The separate results can then be blended together.
17784 if (VT == MVT::v4i32) {
17785 unsigned Opc = Op.getOpcode();
17786 SDValue Amt0, Amt1, Amt2, Amt3;
17787 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17788 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17789 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17790 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17791 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17793 // ISD::SHL is handled above but we include it here for completeness.
17796 llvm_unreachable("Unknown target vector shift node");
17798 Opc = X86ISD::VSHL;
17801 Opc = X86ISD::VSRL;
17804 Opc = X86ISD::VSRA;
17807 // The SSE2 shifts use the lower i64 as the same shift amount for
17808 // all lanes and the upper i64 is ignored. These shuffle masks
17809 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17810 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17811 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17812 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17813 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17814 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17817 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17818 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17819 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17820 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17821 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17822 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17823 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17826 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17827 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17828 unsigned ShiftOpcode = Op->getOpcode();
17830 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17831 // On SSE41 targets we make use of the fact that VSELECT lowers
17832 // to PBLENDVB which selects bytes based just on the sign bit.
17833 if (Subtarget->hasSSE41()) {
17834 V0 = DAG.getBitcast(VT, V0);
17835 V1 = DAG.getBitcast(VT, V1);
17836 Sel = DAG.getBitcast(VT, Sel);
17837 return DAG.getBitcast(SelVT,
17838 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17840 // On pre-SSE41 targets we test for the sign bit by comparing to
17841 // zero - a negative value will set all bits of the lanes to true
17842 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17843 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17844 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17845 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17848 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17849 // We can safely do this using i16 shifts as we're only interested in
17850 // the 3 lower bits of each byte.
17851 Amt = DAG.getBitcast(ExtVT, Amt);
17852 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17853 Amt = DAG.getBitcast(VT, Amt);
17855 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17856 // r = VSELECT(r, shift(r, 4), a);
17858 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17859 R = SignBitSelect(VT, Amt, M, R);
17862 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17864 // r = VSELECT(r, shift(r, 2), a);
17865 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17866 R = SignBitSelect(VT, Amt, M, R);
17869 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17871 // return VSELECT(r, shift(r, 1), a);
17872 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17873 R = SignBitSelect(VT, Amt, M, R);
17877 if (Op->getOpcode() == ISD::SRA) {
17878 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17879 // so we can correctly sign extend. We don't care what happens to the
17881 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17882 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17883 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17884 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17885 ALo = DAG.getBitcast(ExtVT, ALo);
17886 AHi = DAG.getBitcast(ExtVT, AHi);
17887 RLo = DAG.getBitcast(ExtVT, RLo);
17888 RHi = DAG.getBitcast(ExtVT, RHi);
17890 // r = VSELECT(r, shift(r, 4), a);
17891 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17892 DAG.getConstant(4, dl, ExtVT));
17893 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17894 DAG.getConstant(4, dl, ExtVT));
17895 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17896 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17899 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17900 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17902 // r = VSELECT(r, shift(r, 2), a);
17903 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17904 DAG.getConstant(2, dl, ExtVT));
17905 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17906 DAG.getConstant(2, dl, ExtVT));
17907 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17908 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17911 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17912 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17914 // r = VSELECT(r, shift(r, 1), a);
17915 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17916 DAG.getConstant(1, dl, ExtVT));
17917 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17918 DAG.getConstant(1, dl, ExtVT));
17919 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17920 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17922 // Logical shift the result back to the lower byte, leaving a zero upper
17924 // meaning that we can safely pack with PACKUSWB.
17926 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17928 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17929 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17933 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17934 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17935 // solution better.
17936 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17937 MVT ExtVT = MVT::v8i32;
17939 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17940 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17941 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17942 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17943 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17946 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17947 MVT ExtVT = MVT::v8i32;
17948 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17949 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17950 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17951 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17952 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17953 ALo = DAG.getBitcast(ExtVT, ALo);
17954 AHi = DAG.getBitcast(ExtVT, AHi);
17955 RLo = DAG.getBitcast(ExtVT, RLo);
17956 RHi = DAG.getBitcast(ExtVT, RHi);
17957 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17958 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17959 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17960 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17961 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17964 if (VT == MVT::v8i16) {
17965 unsigned ShiftOpcode = Op->getOpcode();
17967 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17968 // On SSE41 targets we make use of the fact that VSELECT lowers
17969 // to PBLENDVB which selects bytes based just on the sign bit.
17970 if (Subtarget->hasSSE41()) {
17971 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17972 V0 = DAG.getBitcast(ExtVT, V0);
17973 V1 = DAG.getBitcast(ExtVT, V1);
17974 Sel = DAG.getBitcast(ExtVT, Sel);
17975 return DAG.getBitcast(
17976 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17978 // On pre-SSE41 targets we splat the sign bit - a negative value will
17979 // set all bits of the lanes to true and VSELECT uses that in
17980 // its OR(AND(V0,C),AND(V1,~C)) lowering.
17982 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17983 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17986 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17987 if (Subtarget->hasSSE41()) {
17988 // On SSE41 targets we need to replicate the shift mask in both
17989 // bytes for PBLENDVB.
17992 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17993 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17995 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17998 // r = VSELECT(r, shift(r, 8), a);
17999 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18000 R = SignBitSelect(Amt, M, R);
18003 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18005 // r = VSELECT(r, shift(r, 4), a);
18006 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18007 R = SignBitSelect(Amt, M, R);
18010 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18012 // r = VSELECT(r, shift(r, 2), a);
18013 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18014 R = SignBitSelect(Amt, M, R);
18017 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18019 // return VSELECT(r, shift(r, 1), a);
18020 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18021 R = SignBitSelect(Amt, M, R);
18025 // Decompose 256-bit shifts into smaller 128-bit shifts.
18026 if (VT.is256BitVector()) {
18027 unsigned NumElems = VT.getVectorNumElements();
18028 MVT EltVT = VT.getVectorElementType();
18029 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18031 // Extract the two vectors
18032 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18033 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18035 // Recreate the shift amount vectors
18036 SDValue Amt1, Amt2;
18037 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18038 // Constant shift amount
18039 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18040 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18041 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18043 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18044 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18046 // Variable shift amount
18047 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18048 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18051 // Issue new vector shifts for the smaller types
18052 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18053 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18055 // Concatenate the result back
18056 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18062 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18063 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18064 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18065 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18066 // has only one use.
18067 SDNode *N = Op.getNode();
18068 SDValue LHS = N->getOperand(0);
18069 SDValue RHS = N->getOperand(1);
18070 unsigned BaseOp = 0;
18073 switch (Op.getOpcode()) {
18074 default: llvm_unreachable("Unknown ovf instruction!");
18076 // A subtract of one will be selected as a INC. Note that INC doesn't
18077 // set CF, so we can't do this for UADDO.
18078 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18080 BaseOp = X86ISD::INC;
18081 Cond = X86::COND_O;
18084 BaseOp = X86ISD::ADD;
18085 Cond = X86::COND_O;
18088 BaseOp = X86ISD::ADD;
18089 Cond = X86::COND_B;
18092 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18093 // set CF, so we can't do this for USUBO.
18094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18096 BaseOp = X86ISD::DEC;
18097 Cond = X86::COND_O;
18100 BaseOp = X86ISD::SUB;
18101 Cond = X86::COND_O;
18104 BaseOp = X86ISD::SUB;
18105 Cond = X86::COND_B;
18108 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18109 Cond = X86::COND_O;
18111 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18112 if (N->getValueType(0) == MVT::i8) {
18113 BaseOp = X86ISD::UMUL8;
18114 Cond = X86::COND_O;
18117 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18119 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18122 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18123 DAG.getConstant(X86::COND_O, DL, MVT::i32),
18124 SDValue(Sum.getNode(), 2));
18126 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18130 // Also sets EFLAGS.
18131 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18132 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18135 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18136 DAG.getConstant(Cond, DL, MVT::i32),
18137 SDValue(Sum.getNode(), 1));
18139 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18142 /// Returns true if the operand type is exactly twice the native width, and
18143 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18144 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18145 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18146 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18147 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18150 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18151 else if (OpWidth == 128)
18152 return Subtarget->hasCmpxchg16b();
18157 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18158 return needsCmpXchgNb(SI->getValueOperand()->getType());
18161 // Note: this turns large loads into lock cmpxchg8b/16b.
18162 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18163 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18164 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18165 return needsCmpXchgNb(PTy->getElementType());
18168 TargetLoweringBase::AtomicRMWExpansionKind
18169 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18170 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18171 Type *MemType = AI->getType();
18173 // If the operand is too big, we must see if cmpxchg8/16b is available
18174 // and default to library calls otherwise.
18175 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18176 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18177 : AtomicRMWExpansionKind::None;
18180 AtomicRMWInst::BinOp Op = AI->getOperation();
18183 llvm_unreachable("Unknown atomic operation");
18184 case AtomicRMWInst::Xchg:
18185 case AtomicRMWInst::Add:
18186 case AtomicRMWInst::Sub:
18187 // It's better to use xadd, xsub or xchg for these in all cases.
18188 return AtomicRMWExpansionKind::None;
18189 case AtomicRMWInst::Or:
18190 case AtomicRMWInst::And:
18191 case AtomicRMWInst::Xor:
18192 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18193 // prefix to a normal instruction for these operations.
18194 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18195 : AtomicRMWExpansionKind::None;
18196 case AtomicRMWInst::Nand:
18197 case AtomicRMWInst::Max:
18198 case AtomicRMWInst::Min:
18199 case AtomicRMWInst::UMax:
18200 case AtomicRMWInst::UMin:
18201 // These always require a non-trivial set of data operations on x86. We must
18202 // use a cmpxchg loop.
18203 return AtomicRMWExpansionKind::CmpXChg;
18207 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18208 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18209 // no-sse2). There isn't any reason to disable it if the target processor
18211 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18215 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18216 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18217 Type *MemType = AI->getType();
18218 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18219 // there is no benefit in turning such RMWs into loads, and it is actually
18220 // harmful as it introduces a mfence.
18221 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18224 auto Builder = IRBuilder<>(AI);
18225 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18226 auto SynchScope = AI->getSynchScope();
18227 // We must restrict the ordering to avoid generating loads with Release or
18228 // ReleaseAcquire orderings.
18229 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18230 auto Ptr = AI->getPointerOperand();
18232 // Before the load we need a fence. Here is an example lifted from
18233 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18236 // x.store(1, relaxed);
18237 // r1 = y.fetch_add(0, release);
18239 // y.fetch_add(42, acquire);
18240 // r2 = x.load(relaxed);
18241 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18242 // lowered to just a load without a fence. A mfence flushes the store buffer,
18243 // making the optimization clearly correct.
18244 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18245 // otherwise, we might be able to be more aggressive on relaxed idempotent
18246 // rmw. In practice, they do not look useful, so we don't try to be
18247 // especially clever.
18248 if (SynchScope == SingleThread)
18249 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18250 // the IR level, so we must wrap it in an intrinsic.
18253 if (!hasMFENCE(*Subtarget))
18254 // FIXME: it might make sense to use a locked operation here but on a
18255 // different cache-line to prevent cache-line bouncing. In practice it
18256 // is probably a small win, and x86 processors without mfence are rare
18257 // enough that we do not bother.
18261 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18262 Builder.CreateCall(MFence, {});
18264 // Finally we can emit the atomic load.
18265 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18266 AI->getType()->getPrimitiveSizeInBits());
18267 Loaded->setAtomic(Order, SynchScope);
18268 AI->replaceAllUsesWith(Loaded);
18269 AI->eraseFromParent();
18273 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18274 SelectionDAG &DAG) {
18276 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18277 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18278 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18279 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18281 // The only fence that needs an instruction is a sequentially-consistent
18282 // cross-thread fence.
18283 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18284 if (hasMFENCE(*Subtarget))
18285 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18287 SDValue Chain = Op.getOperand(0);
18288 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18290 DAG.getRegister(X86::ESP, MVT::i32), // Base
18291 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18292 DAG.getRegister(0, MVT::i32), // Index
18293 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18294 DAG.getRegister(0, MVT::i32), // Segment.
18298 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18299 return SDValue(Res, 0);
18302 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18303 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18306 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18307 SelectionDAG &DAG) {
18308 MVT T = Op.getSimpleValueType();
18312 switch(T.SimpleTy) {
18313 default: llvm_unreachable("Invalid value type!");
18314 case MVT::i8: Reg = X86::AL; size = 1; break;
18315 case MVT::i16: Reg = X86::AX; size = 2; break;
18316 case MVT::i32: Reg = X86::EAX; size = 4; break;
18318 assert(Subtarget->is64Bit() && "Node not type legal!");
18319 Reg = X86::RAX; size = 8;
18322 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18323 Op.getOperand(2), SDValue());
18324 SDValue Ops[] = { cpIn.getValue(0),
18327 DAG.getTargetConstant(size, DL, MVT::i8),
18328 cpIn.getValue(1) };
18329 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18330 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18331 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18335 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18336 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18337 MVT::i32, cpOut.getValue(2));
18338 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18339 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18342 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18343 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18344 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18348 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18349 SelectionDAG &DAG) {
18350 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18351 MVT DstVT = Op.getSimpleValueType();
18353 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18354 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18355 if (DstVT != MVT::f64)
18356 // This conversion needs to be expanded.
18359 SDValue InVec = Op->getOperand(0);
18361 unsigned NumElts = SrcVT.getVectorNumElements();
18362 EVT SVT = SrcVT.getVectorElementType();
18364 // Widen the vector in input in the case of MVT::v2i32.
18365 // Example: from MVT::v2i32 to MVT::v4i32.
18366 SmallVector<SDValue, 16> Elts;
18367 for (unsigned i = 0, e = NumElts; i != e; ++i)
18368 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18369 DAG.getIntPtrConstant(i, dl)));
18371 // Explicitly mark the extra elements as Undef.
18372 Elts.append(NumElts, DAG.getUNDEF(SVT));
18374 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18375 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18376 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18377 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18378 DAG.getIntPtrConstant(0, dl));
18381 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18382 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18383 assert((DstVT == MVT::i64 ||
18384 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18385 "Unexpected custom BITCAST");
18386 // i64 <=> MMX conversions are Legal.
18387 if (SrcVT==MVT::i64 && DstVT.isVector())
18389 if (DstVT==MVT::i64 && SrcVT.isVector())
18391 // MMX <=> MMX conversions are Legal.
18392 if (SrcVT.isVector() && DstVT.isVector())
18394 // All other conversions need to be expanded.
18398 /// Compute the horizontal sum of bytes in V for the elements of VT.
18400 /// Requires V to be a byte vector and VT to be an integer vector type with
18401 /// wider elements than V's type. The width of the elements of VT determines
18402 /// how many bytes of V are summed horizontally to produce each element of the
18404 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18405 const X86Subtarget *Subtarget,
18406 SelectionDAG &DAG) {
18408 MVT ByteVecVT = V.getSimpleValueType();
18409 MVT EltVT = VT.getVectorElementType();
18410 int NumElts = VT.getVectorNumElements();
18411 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18412 "Expected value to have byte element type.");
18413 assert(EltVT != MVT::i8 &&
18414 "Horizontal byte sum only makes sense for wider elements!");
18415 unsigned VecSize = VT.getSizeInBits();
18416 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18418 // PSADBW instruction horizontally add all bytes and leave the result in i64
18419 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18420 if (EltVT == MVT::i64) {
18421 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18422 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18423 return DAG.getBitcast(VT, V);
18426 if (EltVT == MVT::i32) {
18427 // We unpack the low half and high half into i32s interleaved with zeros so
18428 // that we can use PSADBW to horizontally sum them. The most useful part of
18429 // this is that it lines up the results of two PSADBW instructions to be
18430 // two v2i64 vectors which concatenated are the 4 population counts. We can
18431 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18432 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18433 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18434 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18436 // Do the horizontal sums into two v2i64s.
18437 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18438 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18439 DAG.getBitcast(ByteVecVT, Low), Zeros);
18440 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18441 DAG.getBitcast(ByteVecVT, High), Zeros);
18443 // Merge them together.
18444 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18445 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18446 DAG.getBitcast(ShortVecVT, Low),
18447 DAG.getBitcast(ShortVecVT, High));
18449 return DAG.getBitcast(VT, V);
18452 // The only element type left is i16.
18453 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18455 // To obtain pop count for each i16 element starting from the pop count for
18456 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18457 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18458 // directly supported.
18459 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18460 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18461 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18462 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18463 DAG.getBitcast(ByteVecVT, V));
18464 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18467 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18468 const X86Subtarget *Subtarget,
18469 SelectionDAG &DAG) {
18470 MVT VT = Op.getSimpleValueType();
18471 MVT EltVT = VT.getVectorElementType();
18472 unsigned VecSize = VT.getSizeInBits();
18474 // Implement a lookup table in register by using an algorithm based on:
18475 // http://wm.ite.pl/articles/sse-popcount.html
18477 // The general idea is that every lower byte nibble in the input vector is an
18478 // index into a in-register pre-computed pop count table. We then split up the
18479 // input vector in two new ones: (1) a vector with only the shifted-right
18480 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18481 // masked out higher ones) for each byte. PSHUB is used separately with both
18482 // to index the in-register table. Next, both are added and the result is a
18483 // i8 vector where each element contains the pop count for input byte.
18485 // To obtain the pop count for elements != i8, we follow up with the same
18486 // approach and use additional tricks as described below.
18488 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18489 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18490 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18491 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18493 int NumByteElts = VecSize / 8;
18494 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18495 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18496 SmallVector<SDValue, 16> LUTVec;
18497 for (int i = 0; i < NumByteElts; ++i)
18498 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18499 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18500 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18501 DAG.getConstant(0x0F, DL, MVT::i8));
18502 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18505 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18506 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18507 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18510 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18512 // The input vector is used as the shuffle mask that index elements into the
18513 // LUT. After counting low and high nibbles, add the vector to obtain the
18514 // final pop count per i8 element.
18515 SDValue HighPopCnt =
18516 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18517 SDValue LowPopCnt =
18518 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18519 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18521 if (EltVT == MVT::i8)
18524 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18527 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18528 const X86Subtarget *Subtarget,
18529 SelectionDAG &DAG) {
18530 MVT VT = Op.getSimpleValueType();
18531 assert(VT.is128BitVector() &&
18532 "Only 128-bit vector bitmath lowering supported.");
18534 int VecSize = VT.getSizeInBits();
18535 MVT EltVT = VT.getVectorElementType();
18536 int Len = EltVT.getSizeInBits();
18538 // This is the vectorized version of the "best" algorithm from
18539 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18540 // with a minor tweak to use a series of adds + shifts instead of vector
18541 // multiplications. Implemented for all integer vector types. We only use
18542 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18543 // much faster, even faster than using native popcnt instructions.
18545 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18546 MVT VT = V.getSimpleValueType();
18547 SmallVector<SDValue, 32> Shifters(
18548 VT.getVectorNumElements(),
18549 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18550 return DAG.getNode(OpCode, DL, VT, V,
18551 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18553 auto GetMask = [&](SDValue V, APInt Mask) {
18554 MVT VT = V.getSimpleValueType();
18555 SmallVector<SDValue, 32> Masks(
18556 VT.getVectorNumElements(),
18557 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18558 return DAG.getNode(ISD::AND, DL, VT, V,
18559 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18562 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18563 // x86, so set the SRL type to have elements at least i16 wide. This is
18564 // correct because all of our SRLs are followed immediately by a mask anyways
18565 // that handles any bits that sneak into the high bits of the byte elements.
18566 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18570 // v = v - ((v >> 1) & 0x55555555...)
18572 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18573 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18574 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18576 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18577 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18578 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18579 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18580 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18582 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18583 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18584 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18585 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18587 // At this point, V contains the byte-wise population count, and we are
18588 // merely doing a horizontal sum if necessary to get the wider element
18590 if (EltVT == MVT::i8)
18593 return LowerHorizontalByteSum(
18594 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18598 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18599 SelectionDAG &DAG) {
18600 MVT VT = Op.getSimpleValueType();
18601 // FIXME: Need to add AVX-512 support here!
18602 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18603 "Unknown CTPOP type to handle");
18604 SDLoc DL(Op.getNode());
18605 SDValue Op0 = Op.getOperand(0);
18607 if (!Subtarget->hasSSSE3()) {
18608 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18609 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18610 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18613 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18614 unsigned NumElems = VT.getVectorNumElements();
18616 // Extract each 128-bit vector, compute pop count and concat the result.
18617 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18618 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18620 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18621 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18622 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18625 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18628 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18629 SelectionDAG &DAG) {
18630 assert(Op.getValueType().isVector() &&
18631 "We only do custom lowering for vector population count.");
18632 return LowerVectorCTPOP(Op, Subtarget, DAG);
18635 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18636 SDNode *Node = Op.getNode();
18638 EVT T = Node->getValueType(0);
18639 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18640 DAG.getConstant(0, dl, T), Node->getOperand(2));
18641 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18642 cast<AtomicSDNode>(Node)->getMemoryVT(),
18643 Node->getOperand(0),
18644 Node->getOperand(1), negOp,
18645 cast<AtomicSDNode>(Node)->getMemOperand(),
18646 cast<AtomicSDNode>(Node)->getOrdering(),
18647 cast<AtomicSDNode>(Node)->getSynchScope());
18650 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18651 SDNode *Node = Op.getNode();
18653 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18655 // Convert seq_cst store -> xchg
18656 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18657 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18658 // (The only way to get a 16-byte store is cmpxchg16b)
18659 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18660 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18661 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18662 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18663 cast<AtomicSDNode>(Node)->getMemoryVT(),
18664 Node->getOperand(0),
18665 Node->getOperand(1), Node->getOperand(2),
18666 cast<AtomicSDNode>(Node)->getMemOperand(),
18667 cast<AtomicSDNode>(Node)->getOrdering(),
18668 cast<AtomicSDNode>(Node)->getSynchScope());
18669 return Swap.getValue(1);
18671 // Other atomic stores have a simple pattern.
18675 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18676 EVT VT = Op.getNode()->getSimpleValueType(0);
18678 // Let legalize expand this if it isn't a legal type yet.
18679 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18682 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18685 bool ExtraOp = false;
18686 switch (Op.getOpcode()) {
18687 default: llvm_unreachable("Invalid code");
18688 case ISD::ADDC: Opc = X86ISD::ADD; break;
18689 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18690 case ISD::SUBC: Opc = X86ISD::SUB; break;
18691 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18695 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18697 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18698 Op.getOperand(1), Op.getOperand(2));
18701 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18702 SelectionDAG &DAG) {
18703 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18705 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18706 // which returns the values as { float, float } (in XMM0) or
18707 // { double, double } (which is returned in XMM0, XMM1).
18709 SDValue Arg = Op.getOperand(0);
18710 EVT ArgVT = Arg.getValueType();
18711 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18713 TargetLowering::ArgListTy Args;
18714 TargetLowering::ArgListEntry Entry;
18718 Entry.isSExt = false;
18719 Entry.isZExt = false;
18720 Args.push_back(Entry);
18722 bool isF64 = ArgVT == MVT::f64;
18723 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18724 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18725 // the results are returned via SRet in memory.
18726 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18727 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18729 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18731 Type *RetTy = isF64
18732 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18733 : (Type*)VectorType::get(ArgTy, 4);
18735 TargetLowering::CallLoweringInfo CLI(DAG);
18736 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18737 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18739 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18742 // Returned in xmm0 and xmm1.
18743 return CallResult.first;
18745 // Returned in bits 0:31 and 32:64 xmm0.
18746 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18747 CallResult.first, DAG.getIntPtrConstant(0, dl));
18748 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18749 CallResult.first, DAG.getIntPtrConstant(1, dl));
18750 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18751 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18754 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18755 SelectionDAG &DAG) {
18756 assert(Subtarget->hasAVX512() &&
18757 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18759 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18760 EVT VT = N->getValue().getValueType();
18761 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18764 // X86 scatter kills mask register, so its type should be added to
18765 // the list of return values
18766 if (N->getNumValues() == 1) {
18767 SDValue Index = N->getIndex();
18768 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18769 !Index.getValueType().is512BitVector())
18770 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18772 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18773 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18774 N->getOperand(3), Index };
18776 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18777 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18778 return SDValue(NewScatter.getNode(), 0);
18783 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18784 SelectionDAG &DAG) {
18785 assert(Subtarget->hasAVX512() &&
18786 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18788 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18789 EVT VT = Op.getValueType();
18790 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18793 SDValue Index = N->getIndex();
18794 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18795 !Index.getValueType().is512BitVector()) {
18796 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18797 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18798 N->getOperand(3), Index };
18799 DAG.UpdateNodeOperands(N, Ops);
18804 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18805 SelectionDAG &DAG) const {
18806 // TODO: Eventually, the lowering of these nodes should be informed by or
18807 // deferred to the GC strategy for the function in which they appear. For
18808 // now, however, they must be lowered to something. Since they are logically
18809 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18810 // require special handling for these nodes), lower them as literal NOOPs for
18812 SmallVector<SDValue, 2> Ops;
18814 Ops.push_back(Op.getOperand(0));
18815 if (Op->getGluedNode())
18816 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18819 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18820 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18825 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18826 SelectionDAG &DAG) const {
18827 // TODO: Eventually, the lowering of these nodes should be informed by or
18828 // deferred to the GC strategy for the function in which they appear. For
18829 // now, however, they must be lowered to something. Since they are logically
18830 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18831 // require special handling for these nodes), lower them as literal NOOPs for
18833 SmallVector<SDValue, 2> Ops;
18835 Ops.push_back(Op.getOperand(0));
18836 if (Op->getGluedNode())
18837 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18840 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18841 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18846 /// LowerOperation - Provide custom lowering hooks for some operations.
18848 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18849 switch (Op.getOpcode()) {
18850 default: llvm_unreachable("Should not custom lower this!");
18851 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18852 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18853 return LowerCMP_SWAP(Op, Subtarget, DAG);
18854 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18855 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18856 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18857 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18858 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18859 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18860 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18861 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18862 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18863 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18864 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18865 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18866 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18867 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18868 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18869 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18870 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18871 case ISD::SHL_PARTS:
18872 case ISD::SRA_PARTS:
18873 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18874 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18875 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18876 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18877 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18878 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18879 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18880 case ISD::SIGN_EXTEND_VECTOR_INREG:
18881 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18882 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18883 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18884 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18885 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18887 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18888 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18889 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18890 case ISD::SETCC: return LowerSETCC(Op, DAG);
18891 case ISD::SELECT: return LowerSELECT(Op, DAG);
18892 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18893 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18894 case ISD::VASTART: return LowerVASTART(Op, DAG);
18895 case ISD::VAARG: return LowerVAARG(Op, DAG);
18896 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18897 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18898 case ISD::INTRINSIC_VOID:
18899 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18900 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18901 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18902 case ISD::FRAME_TO_ARGS_OFFSET:
18903 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18904 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18905 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18906 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18907 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18908 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18909 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18910 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18911 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18912 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18913 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18914 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18915 case ISD::UMUL_LOHI:
18916 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18919 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18925 case ISD::UMULO: return LowerXALUO(Op, DAG);
18926 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18927 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18931 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18932 case ISD::ADD: return LowerADD(Op, DAG);
18933 case ISD::SUB: return LowerSUB(Op, DAG);
18937 case ISD::UMIN: return LowerMINMAX(Op, DAG);
18938 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18939 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18940 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18941 case ISD::GC_TRANSITION_START:
18942 return LowerGC_TRANSITION_START(Op, DAG);
18943 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18947 /// ReplaceNodeResults - Replace a node with an illegal result type
18948 /// with a new node built out of custom code.
18949 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18950 SmallVectorImpl<SDValue>&Results,
18951 SelectionDAG &DAG) const {
18953 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18954 switch (N->getOpcode()) {
18956 llvm_unreachable("Do not know how to custom type legalize this operation!");
18957 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18958 case X86ISD::FMINC:
18960 case X86ISD::FMAXC:
18961 case X86ISD::FMAX: {
18962 EVT VT = N->getValueType(0);
18963 if (VT != MVT::v2f32)
18964 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18965 SDValue UNDEF = DAG.getUNDEF(VT);
18966 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18967 N->getOperand(0), UNDEF);
18968 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18969 N->getOperand(1), UNDEF);
18970 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18973 case ISD::SIGN_EXTEND_INREG:
18978 // We don't want to expand or promote these.
18985 case ISD::UDIVREM: {
18986 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18987 Results.push_back(V);
18990 case ISD::FP_TO_SINT:
18991 case ISD::FP_TO_UINT: {
18992 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18994 std::pair<SDValue,SDValue> Vals =
18995 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18996 SDValue FIST = Vals.first, StackSlot = Vals.second;
18997 if (FIST.getNode()) {
18998 EVT VT = N->getValueType(0);
18999 // Return a load from the stack slot.
19000 if (StackSlot.getNode())
19001 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19002 MachinePointerInfo(),
19003 false, false, false, 0));
19005 Results.push_back(FIST);
19009 case ISD::UINT_TO_FP: {
19010 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19011 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19012 N->getValueType(0) != MVT::v2f32)
19014 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19016 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19018 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19019 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19020 DAG.getBitcast(MVT::v2i64, VBias));
19021 Or = DAG.getBitcast(MVT::v2f64, Or);
19022 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19023 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19026 case ISD::FP_ROUND: {
19027 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19029 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19030 Results.push_back(V);
19033 case ISD::FP_EXTEND: {
19034 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19035 // No other ValueType for FP_EXTEND should reach this point.
19036 assert(N->getValueType(0) == MVT::v2f32 &&
19037 "Do not know how to legalize this Node");
19040 case ISD::INTRINSIC_W_CHAIN: {
19041 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19043 default : llvm_unreachable("Do not know how to custom type "
19044 "legalize this intrinsic operation!");
19045 case Intrinsic::x86_rdtsc:
19046 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19048 case Intrinsic::x86_rdtscp:
19049 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19051 case Intrinsic::x86_rdpmc:
19052 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19055 case ISD::READCYCLECOUNTER: {
19056 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19059 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19060 EVT T = N->getValueType(0);
19061 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19062 bool Regs64bit = T == MVT::i128;
19063 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19064 SDValue cpInL, cpInH;
19065 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19066 DAG.getConstant(0, dl, HalfT));
19067 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19068 DAG.getConstant(1, dl, HalfT));
19069 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19070 Regs64bit ? X86::RAX : X86::EAX,
19072 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19073 Regs64bit ? X86::RDX : X86::EDX,
19074 cpInH, cpInL.getValue(1));
19075 SDValue swapInL, swapInH;
19076 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19077 DAG.getConstant(0, dl, HalfT));
19078 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19079 DAG.getConstant(1, dl, HalfT));
19080 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19081 Regs64bit ? X86::RBX : X86::EBX,
19082 swapInL, cpInH.getValue(1));
19083 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19084 Regs64bit ? X86::RCX : X86::ECX,
19085 swapInH, swapInL.getValue(1));
19086 SDValue Ops[] = { swapInH.getValue(0),
19088 swapInH.getValue(1) };
19089 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19090 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19091 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19092 X86ISD::LCMPXCHG8_DAG;
19093 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19094 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19095 Regs64bit ? X86::RAX : X86::EAX,
19096 HalfT, Result.getValue(1));
19097 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19098 Regs64bit ? X86::RDX : X86::EDX,
19099 HalfT, cpOutL.getValue(2));
19100 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19102 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19103 MVT::i32, cpOutH.getValue(2));
19105 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19106 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19107 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19109 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19110 Results.push_back(Success);
19111 Results.push_back(EFLAGS.getValue(1));
19114 case ISD::ATOMIC_SWAP:
19115 case ISD::ATOMIC_LOAD_ADD:
19116 case ISD::ATOMIC_LOAD_SUB:
19117 case ISD::ATOMIC_LOAD_AND:
19118 case ISD::ATOMIC_LOAD_OR:
19119 case ISD::ATOMIC_LOAD_XOR:
19120 case ISD::ATOMIC_LOAD_NAND:
19121 case ISD::ATOMIC_LOAD_MIN:
19122 case ISD::ATOMIC_LOAD_MAX:
19123 case ISD::ATOMIC_LOAD_UMIN:
19124 case ISD::ATOMIC_LOAD_UMAX:
19125 case ISD::ATOMIC_LOAD: {
19126 // Delegate to generic TypeLegalization. Situations we can really handle
19127 // should have already been dealt with by AtomicExpandPass.cpp.
19130 case ISD::BITCAST: {
19131 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19132 EVT DstVT = N->getValueType(0);
19133 EVT SrcVT = N->getOperand(0)->getValueType(0);
19135 if (SrcVT != MVT::f64 ||
19136 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19139 unsigned NumElts = DstVT.getVectorNumElements();
19140 EVT SVT = DstVT.getVectorElementType();
19141 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19142 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19143 MVT::v2f64, N->getOperand(0));
19144 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19146 if (ExperimentalVectorWideningLegalization) {
19147 // If we are legalizing vectors by widening, we already have the desired
19148 // legal vector type, just return it.
19149 Results.push_back(ToVecInt);
19153 SmallVector<SDValue, 8> Elts;
19154 for (unsigned i = 0, e = NumElts; i != e; ++i)
19155 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19156 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19158 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19163 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19164 switch ((X86ISD::NodeType)Opcode) {
19165 case X86ISD::FIRST_NUMBER: break;
19166 case X86ISD::BSF: return "X86ISD::BSF";
19167 case X86ISD::BSR: return "X86ISD::BSR";
19168 case X86ISD::SHLD: return "X86ISD::SHLD";
19169 case X86ISD::SHRD: return "X86ISD::SHRD";
19170 case X86ISD::FAND: return "X86ISD::FAND";
19171 case X86ISD::FANDN: return "X86ISD::FANDN";
19172 case X86ISD::FOR: return "X86ISD::FOR";
19173 case X86ISD::FXOR: return "X86ISD::FXOR";
19174 case X86ISD::FILD: return "X86ISD::FILD";
19175 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19176 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19177 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19178 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19179 case X86ISD::FLD: return "X86ISD::FLD";
19180 case X86ISD::FST: return "X86ISD::FST";
19181 case X86ISD::CALL: return "X86ISD::CALL";
19182 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19183 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19184 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19185 case X86ISD::BT: return "X86ISD::BT";
19186 case X86ISD::CMP: return "X86ISD::CMP";
19187 case X86ISD::COMI: return "X86ISD::COMI";
19188 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19189 case X86ISD::CMPM: return "X86ISD::CMPM";
19190 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19191 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19192 case X86ISD::SETCC: return "X86ISD::SETCC";
19193 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19194 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19195 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19196 case X86ISD::CMOV: return "X86ISD::CMOV";
19197 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19198 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19199 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19200 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19201 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19202 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19203 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19204 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19205 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19206 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19207 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19208 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19209 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19210 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19211 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19212 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19213 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19214 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19215 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19216 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19217 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19218 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19219 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19220 case X86ISD::HADD: return "X86ISD::HADD";
19221 case X86ISD::HSUB: return "X86ISD::HSUB";
19222 case X86ISD::FHADD: return "X86ISD::FHADD";
19223 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19224 case X86ISD::ABS: return "X86ISD::ABS";
19225 case X86ISD::FMAX: return "X86ISD::FMAX";
19226 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19227 case X86ISD::FMIN: return "X86ISD::FMIN";
19228 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19229 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19230 case X86ISD::FMINC: return "X86ISD::FMINC";
19231 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19232 case X86ISD::FRCP: return "X86ISD::FRCP";
19233 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19234 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19235 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19236 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19237 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19238 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19239 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19240 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19241 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19242 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19243 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19244 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19245 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19246 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19247 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19248 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19249 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19250 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19251 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19252 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19253 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19254 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19255 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19256 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19257 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19258 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19259 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19260 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19261 case X86ISD::VSHL: return "X86ISD::VSHL";
19262 case X86ISD::VSRL: return "X86ISD::VSRL";
19263 case X86ISD::VSRA: return "X86ISD::VSRA";
19264 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19265 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19266 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19267 case X86ISD::CMPP: return "X86ISD::CMPP";
19268 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19269 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19270 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19271 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19272 case X86ISD::ADD: return "X86ISD::ADD";
19273 case X86ISD::SUB: return "X86ISD::SUB";
19274 case X86ISD::ADC: return "X86ISD::ADC";
19275 case X86ISD::SBB: return "X86ISD::SBB";
19276 case X86ISD::SMUL: return "X86ISD::SMUL";
19277 case X86ISD::UMUL: return "X86ISD::UMUL";
19278 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19279 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19280 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19281 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19282 case X86ISD::INC: return "X86ISD::INC";
19283 case X86ISD::DEC: return "X86ISD::DEC";
19284 case X86ISD::OR: return "X86ISD::OR";
19285 case X86ISD::XOR: return "X86ISD::XOR";
19286 case X86ISD::AND: return "X86ISD::AND";
19287 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19288 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19289 case X86ISD::PTEST: return "X86ISD::PTEST";
19290 case X86ISD::TESTP: return "X86ISD::TESTP";
19291 case X86ISD::TESTM: return "X86ISD::TESTM";
19292 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19293 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19294 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19295 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19296 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19297 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19298 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19299 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19300 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19301 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19302 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19303 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19304 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19305 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19306 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19307 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19308 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19309 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19310 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19311 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19312 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19313 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19314 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19315 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19316 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19317 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19318 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19319 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19320 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19321 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19322 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19323 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19324 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19325 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19326 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19327 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19328 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19329 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19330 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19331 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19332 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19333 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19334 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19335 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19336 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19337 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19338 case X86ISD::SAHF: return "X86ISD::SAHF";
19339 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19340 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19341 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19342 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19343 case X86ISD::FMADD: return "X86ISD::FMADD";
19344 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19345 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19346 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19347 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19348 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19349 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19350 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19351 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19352 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19353 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19354 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19355 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19356 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19357 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19358 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19359 case X86ISD::XTEST: return "X86ISD::XTEST";
19360 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19361 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19362 case X86ISD::SELECT: return "X86ISD::SELECT";
19363 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19364 case X86ISD::RCP28: return "X86ISD::RCP28";
19365 case X86ISD::EXP2: return "X86ISD::EXP2";
19366 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19367 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19368 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19369 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19370 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19371 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19372 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19373 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19374 case X86ISD::ADDS: return "X86ISD::ADDS";
19375 case X86ISD::SUBS: return "X86ISD::SUBS";
19376 case X86ISD::AVG: return "X86ISD::AVG";
19377 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19378 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19379 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19380 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19381 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19386 // isLegalAddressingMode - Return true if the addressing mode represented
19387 // by AM is legal for this target, for a load/store of the specified type.
19388 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19389 const AddrMode &AM, Type *Ty,
19390 unsigned AS) const {
19391 // X86 supports extremely general addressing modes.
19392 CodeModel::Model M = getTargetMachine().getCodeModel();
19393 Reloc::Model R = getTargetMachine().getRelocationModel();
19395 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19396 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19401 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19403 // If a reference to this global requires an extra load, we can't fold it.
19404 if (isGlobalStubReference(GVFlags))
19407 // If BaseGV requires a register for the PIC base, we cannot also have a
19408 // BaseReg specified.
19409 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19412 // If lower 4G is not available, then we must use rip-relative addressing.
19413 if ((M != CodeModel::Small || R != Reloc::Static) &&
19414 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19418 switch (AM.Scale) {
19424 // These scales always work.
19429 // These scales are formed with basereg+scalereg. Only accept if there is
19434 default: // Other stuff never works.
19441 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19442 unsigned Bits = Ty->getScalarSizeInBits();
19444 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19445 // particularly cheaper than those without.
19449 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19450 // variable shifts just as cheap as scalar ones.
19451 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19454 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19455 // fully general vector.
19459 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19460 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19462 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19463 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19464 return NumBits1 > NumBits2;
19467 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19468 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19471 if (!isTypeLegal(EVT::getEVT(Ty1)))
19474 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19476 // Assuming the caller doesn't have a zeroext or signext return parameter,
19477 // truncation all the way down to i1 is valid.
19481 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19482 return isInt<32>(Imm);
19485 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19486 // Can also use sub to handle negated immediates.
19487 return isInt<32>(Imm);
19490 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19491 if (!VT1.isInteger() || !VT2.isInteger())
19493 unsigned NumBits1 = VT1.getSizeInBits();
19494 unsigned NumBits2 = VT2.getSizeInBits();
19495 return NumBits1 > NumBits2;
19498 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19499 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19500 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19503 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19504 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19505 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19508 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19509 EVT VT1 = Val.getValueType();
19510 if (isZExtFree(VT1, VT2))
19513 if (Val.getOpcode() != ISD::LOAD)
19516 if (!VT1.isSimple() || !VT1.isInteger() ||
19517 !VT2.isSimple() || !VT2.isInteger())
19520 switch (VT1.getSimpleVT().SimpleTy) {
19525 // X86 has 8, 16, and 32-bit zero-extending loads.
19532 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19535 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19536 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19539 VT = VT.getScalarType();
19541 if (!VT.isSimple())
19544 switch (VT.getSimpleVT().SimpleTy) {
19555 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19556 // i16 instructions are longer (0x66 prefix) and potentially slower.
19557 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19560 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19561 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19562 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19563 /// are assumed to be legal.
19565 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19567 if (!VT.isSimple())
19570 // Not for i1 vectors
19571 if (VT.getScalarType() == MVT::i1)
19574 // Very little shuffling can be done for 64-bit vectors right now.
19575 if (VT.getSizeInBits() == 64)
19578 // We only care that the types being shuffled are legal. The lowering can
19579 // handle any possible shuffle mask that results.
19580 return isTypeLegal(VT.getSimpleVT());
19584 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19586 // Just delegate to the generic legality, clear masks aren't special.
19587 return isShuffleMaskLegal(Mask, VT);
19590 //===----------------------------------------------------------------------===//
19591 // X86 Scheduler Hooks
19592 //===----------------------------------------------------------------------===//
19594 /// Utility function to emit xbegin specifying the start of an RTM region.
19595 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19596 const TargetInstrInfo *TII) {
19597 DebugLoc DL = MI->getDebugLoc();
19599 const BasicBlock *BB = MBB->getBasicBlock();
19600 MachineFunction::iterator I = MBB;
19603 // For the v = xbegin(), we generate
19614 MachineBasicBlock *thisMBB = MBB;
19615 MachineFunction *MF = MBB->getParent();
19616 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19617 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19618 MF->insert(I, mainMBB);
19619 MF->insert(I, sinkMBB);
19621 // Transfer the remainder of BB and its successor edges to sinkMBB.
19622 sinkMBB->splice(sinkMBB->begin(), MBB,
19623 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19624 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19628 // # fallthrough to mainMBB
19629 // # abortion to sinkMBB
19630 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19631 thisMBB->addSuccessor(mainMBB);
19632 thisMBB->addSuccessor(sinkMBB);
19636 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19637 mainMBB->addSuccessor(sinkMBB);
19640 // EAX is live into the sinkMBB
19641 sinkMBB->addLiveIn(X86::EAX);
19642 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19643 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19646 MI->eraseFromParent();
19650 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19651 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19652 // in the .td file.
19653 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19654 const TargetInstrInfo *TII) {
19656 switch (MI->getOpcode()) {
19657 default: llvm_unreachable("illegal opcode!");
19658 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19659 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19660 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19661 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19662 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19663 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19664 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19665 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19668 DebugLoc dl = MI->getDebugLoc();
19669 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19671 unsigned NumArgs = MI->getNumOperands();
19672 for (unsigned i = 1; i < NumArgs; ++i) {
19673 MachineOperand &Op = MI->getOperand(i);
19674 if (!(Op.isReg() && Op.isImplicit()))
19675 MIB.addOperand(Op);
19677 if (MI->hasOneMemOperand())
19678 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19680 BuildMI(*BB, MI, dl,
19681 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19682 .addReg(X86::XMM0);
19684 MI->eraseFromParent();
19688 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19689 // defs in an instruction pattern
19690 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19691 const TargetInstrInfo *TII) {
19693 switch (MI->getOpcode()) {
19694 default: llvm_unreachable("illegal opcode!");
19695 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19696 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19697 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19698 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19699 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19700 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19701 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19702 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19705 DebugLoc dl = MI->getDebugLoc();
19706 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19708 unsigned NumArgs = MI->getNumOperands(); // remove the results
19709 for (unsigned i = 1; i < NumArgs; ++i) {
19710 MachineOperand &Op = MI->getOperand(i);
19711 if (!(Op.isReg() && Op.isImplicit()))
19712 MIB.addOperand(Op);
19714 if (MI->hasOneMemOperand())
19715 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19717 BuildMI(*BB, MI, dl,
19718 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19721 MI->eraseFromParent();
19725 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19726 const X86Subtarget *Subtarget) {
19727 DebugLoc dl = MI->getDebugLoc();
19728 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19729 // Address into RAX/EAX, other two args into ECX, EDX.
19730 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19731 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19732 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19733 for (int i = 0; i < X86::AddrNumOperands; ++i)
19734 MIB.addOperand(MI->getOperand(i));
19736 unsigned ValOps = X86::AddrNumOperands;
19737 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19738 .addReg(MI->getOperand(ValOps).getReg());
19739 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19740 .addReg(MI->getOperand(ValOps+1).getReg());
19742 // The instruction doesn't actually take any operands though.
19743 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19745 MI->eraseFromParent(); // The pseudo is gone now.
19749 MachineBasicBlock *
19750 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19751 MachineBasicBlock *MBB) const {
19752 // Emit va_arg instruction on X86-64.
19754 // Operands to this pseudo-instruction:
19755 // 0 ) Output : destination address (reg)
19756 // 1-5) Input : va_list address (addr, i64mem)
19757 // 6 ) ArgSize : Size (in bytes) of vararg type
19758 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19759 // 8 ) Align : Alignment of type
19760 // 9 ) EFLAGS (implicit-def)
19762 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19763 static_assert(X86::AddrNumOperands == 5,
19764 "VAARG_64 assumes 5 address operands");
19766 unsigned DestReg = MI->getOperand(0).getReg();
19767 MachineOperand &Base = MI->getOperand(1);
19768 MachineOperand &Scale = MI->getOperand(2);
19769 MachineOperand &Index = MI->getOperand(3);
19770 MachineOperand &Disp = MI->getOperand(4);
19771 MachineOperand &Segment = MI->getOperand(5);
19772 unsigned ArgSize = MI->getOperand(6).getImm();
19773 unsigned ArgMode = MI->getOperand(7).getImm();
19774 unsigned Align = MI->getOperand(8).getImm();
19776 // Memory Reference
19777 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19778 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19779 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19781 // Machine Information
19782 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19783 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19784 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19785 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19786 DebugLoc DL = MI->getDebugLoc();
19788 // struct va_list {
19791 // i64 overflow_area (address)
19792 // i64 reg_save_area (address)
19794 // sizeof(va_list) = 24
19795 // alignment(va_list) = 8
19797 unsigned TotalNumIntRegs = 6;
19798 unsigned TotalNumXMMRegs = 8;
19799 bool UseGPOffset = (ArgMode == 1);
19800 bool UseFPOffset = (ArgMode == 2);
19801 unsigned MaxOffset = TotalNumIntRegs * 8 +
19802 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19804 /* Align ArgSize to a multiple of 8 */
19805 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19806 bool NeedsAlign = (Align > 8);
19808 MachineBasicBlock *thisMBB = MBB;
19809 MachineBasicBlock *overflowMBB;
19810 MachineBasicBlock *offsetMBB;
19811 MachineBasicBlock *endMBB;
19813 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19814 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19815 unsigned OffsetReg = 0;
19817 if (!UseGPOffset && !UseFPOffset) {
19818 // If we only pull from the overflow region, we don't create a branch.
19819 // We don't need to alter control flow.
19820 OffsetDestReg = 0; // unused
19821 OverflowDestReg = DestReg;
19823 offsetMBB = nullptr;
19824 overflowMBB = thisMBB;
19827 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19828 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19829 // If not, pull from overflow_area. (branch to overflowMBB)
19834 // offsetMBB overflowMBB
19839 // Registers for the PHI in endMBB
19840 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19841 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19843 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19844 MachineFunction *MF = MBB->getParent();
19845 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19846 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19847 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19849 MachineFunction::iterator MBBIter = MBB;
19852 // Insert the new basic blocks
19853 MF->insert(MBBIter, offsetMBB);
19854 MF->insert(MBBIter, overflowMBB);
19855 MF->insert(MBBIter, endMBB);
19857 // Transfer the remainder of MBB and its successor edges to endMBB.
19858 endMBB->splice(endMBB->begin(), thisMBB,
19859 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19860 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19862 // Make offsetMBB and overflowMBB successors of thisMBB
19863 thisMBB->addSuccessor(offsetMBB);
19864 thisMBB->addSuccessor(overflowMBB);
19866 // endMBB is a successor of both offsetMBB and overflowMBB
19867 offsetMBB->addSuccessor(endMBB);
19868 overflowMBB->addSuccessor(endMBB);
19870 // Load the offset value into a register
19871 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19872 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19876 .addDisp(Disp, UseFPOffset ? 4 : 0)
19877 .addOperand(Segment)
19878 .setMemRefs(MMOBegin, MMOEnd);
19880 // Check if there is enough room left to pull this argument.
19881 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19883 .addImm(MaxOffset + 8 - ArgSizeA8);
19885 // Branch to "overflowMBB" if offset >= max
19886 // Fall through to "offsetMBB" otherwise
19887 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19888 .addMBB(overflowMBB);
19891 // In offsetMBB, emit code to use the reg_save_area.
19893 assert(OffsetReg != 0);
19895 // Read the reg_save_area address.
19896 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19897 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19902 .addOperand(Segment)
19903 .setMemRefs(MMOBegin, MMOEnd);
19905 // Zero-extend the offset
19906 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19907 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19910 .addImm(X86::sub_32bit);
19912 // Add the offset to the reg_save_area to get the final address.
19913 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19914 .addReg(OffsetReg64)
19915 .addReg(RegSaveReg);
19917 // Compute the offset for the next argument
19918 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19919 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19921 .addImm(UseFPOffset ? 16 : 8);
19923 // Store it back into the va_list.
19924 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19928 .addDisp(Disp, UseFPOffset ? 4 : 0)
19929 .addOperand(Segment)
19930 .addReg(NextOffsetReg)
19931 .setMemRefs(MMOBegin, MMOEnd);
19934 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19939 // Emit code to use overflow area
19942 // Load the overflow_area address into a register.
19943 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19944 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19949 .addOperand(Segment)
19950 .setMemRefs(MMOBegin, MMOEnd);
19952 // If we need to align it, do so. Otherwise, just copy the address
19953 // to OverflowDestReg.
19955 // Align the overflow address
19956 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19957 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19959 // aligned_addr = (addr + (align-1)) & ~(align-1)
19960 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19961 .addReg(OverflowAddrReg)
19964 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19966 .addImm(~(uint64_t)(Align-1));
19968 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19969 .addReg(OverflowAddrReg);
19972 // Compute the next overflow address after this argument.
19973 // (the overflow address should be kept 8-byte aligned)
19974 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19975 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19976 .addReg(OverflowDestReg)
19977 .addImm(ArgSizeA8);
19979 // Store the new overflow address.
19980 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19985 .addOperand(Segment)
19986 .addReg(NextAddrReg)
19987 .setMemRefs(MMOBegin, MMOEnd);
19989 // If we branched, emit the PHI to the front of endMBB.
19991 BuildMI(*endMBB, endMBB->begin(), DL,
19992 TII->get(X86::PHI), DestReg)
19993 .addReg(OffsetDestReg).addMBB(offsetMBB)
19994 .addReg(OverflowDestReg).addMBB(overflowMBB);
19997 // Erase the pseudo instruction
19998 MI->eraseFromParent();
20003 MachineBasicBlock *
20004 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20006 MachineBasicBlock *MBB) const {
20007 // Emit code to save XMM registers to the stack. The ABI says that the
20008 // number of registers to save is given in %al, so it's theoretically
20009 // possible to do an indirect jump trick to avoid saving all of them,
20010 // however this code takes a simpler approach and just executes all
20011 // of the stores if %al is non-zero. It's less code, and it's probably
20012 // easier on the hardware branch predictor, and stores aren't all that
20013 // expensive anyway.
20015 // Create the new basic blocks. One block contains all the XMM stores,
20016 // and one block is the final destination regardless of whether any
20017 // stores were performed.
20018 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20019 MachineFunction *F = MBB->getParent();
20020 MachineFunction::iterator MBBIter = MBB;
20022 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20023 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20024 F->insert(MBBIter, XMMSaveMBB);
20025 F->insert(MBBIter, EndMBB);
20027 // Transfer the remainder of MBB and its successor edges to EndMBB.
20028 EndMBB->splice(EndMBB->begin(), MBB,
20029 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20030 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20032 // The original block will now fall through to the XMM save block.
20033 MBB->addSuccessor(XMMSaveMBB);
20034 // The XMMSaveMBB will fall through to the end block.
20035 XMMSaveMBB->addSuccessor(EndMBB);
20037 // Now add the instructions.
20038 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20039 DebugLoc DL = MI->getDebugLoc();
20041 unsigned CountReg = MI->getOperand(0).getReg();
20042 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20043 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20045 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20046 // If %al is 0, branch around the XMM save block.
20047 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20048 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20049 MBB->addSuccessor(EndMBB);
20052 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20053 // that was just emitted, but clearly shouldn't be "saved".
20054 assert((MI->getNumOperands() <= 3 ||
20055 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20056 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20057 && "Expected last argument to be EFLAGS");
20058 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20059 // In the XMM save block, save all the XMM argument registers.
20060 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20061 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20062 MachineMemOperand *MMO = F->getMachineMemOperand(
20063 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20064 MachineMemOperand::MOStore,
20065 /*Size=*/16, /*Align=*/16);
20066 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20067 .addFrameIndex(RegSaveFrameIndex)
20068 .addImm(/*Scale=*/1)
20069 .addReg(/*IndexReg=*/0)
20070 .addImm(/*Disp=*/Offset)
20071 .addReg(/*Segment=*/0)
20072 .addReg(MI->getOperand(i).getReg())
20073 .addMemOperand(MMO);
20076 MI->eraseFromParent(); // The pseudo instruction is gone now.
20081 // The EFLAGS operand of SelectItr might be missing a kill marker
20082 // because there were multiple uses of EFLAGS, and ISel didn't know
20083 // which to mark. Figure out whether SelectItr should have had a
20084 // kill marker, and set it if it should. Returns the correct kill
20086 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20087 MachineBasicBlock* BB,
20088 const TargetRegisterInfo* TRI) {
20089 // Scan forward through BB for a use/def of EFLAGS.
20090 MachineBasicBlock::iterator miI(std::next(SelectItr));
20091 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20092 const MachineInstr& mi = *miI;
20093 if (mi.readsRegister(X86::EFLAGS))
20095 if (mi.definesRegister(X86::EFLAGS))
20096 break; // Should have kill-flag - update below.
20099 // If we hit the end of the block, check whether EFLAGS is live into a
20101 if (miI == BB->end()) {
20102 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20103 sEnd = BB->succ_end();
20104 sItr != sEnd; ++sItr) {
20105 MachineBasicBlock* succ = *sItr;
20106 if (succ->isLiveIn(X86::EFLAGS))
20111 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20112 // out. SelectMI should have a kill flag on EFLAGS.
20113 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20117 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20118 // together with other CMOV pseudo-opcodes into a single basic-block with
20119 // conditional jump around it.
20120 static bool isCMOVPseudo(MachineInstr *MI) {
20121 switch (MI->getOpcode()) {
20122 case X86::CMOV_FR32:
20123 case X86::CMOV_FR64:
20124 case X86::CMOV_GR8:
20125 case X86::CMOV_GR16:
20126 case X86::CMOV_GR32:
20127 case X86::CMOV_RFP32:
20128 case X86::CMOV_RFP64:
20129 case X86::CMOV_RFP80:
20130 case X86::CMOV_V2F64:
20131 case X86::CMOV_V2I64:
20132 case X86::CMOV_V4F32:
20133 case X86::CMOV_V4F64:
20134 case X86::CMOV_V4I64:
20135 case X86::CMOV_V16F32:
20136 case X86::CMOV_V8F32:
20137 case X86::CMOV_V8F64:
20138 case X86::CMOV_V8I64:
20139 case X86::CMOV_V8I1:
20140 case X86::CMOV_V16I1:
20141 case X86::CMOV_V32I1:
20142 case X86::CMOV_V64I1:
20150 MachineBasicBlock *
20151 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20152 MachineBasicBlock *BB) const {
20153 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20154 DebugLoc DL = MI->getDebugLoc();
20156 // To "insert" a SELECT_CC instruction, we actually have to insert the
20157 // diamond control-flow pattern. The incoming instruction knows the
20158 // destination vreg to set, the condition code register to branch on, the
20159 // true/false values to select between, and a branch opcode to use.
20160 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20161 MachineFunction::iterator It = BB;
20167 // cmpTY ccX, r1, r2
20169 // fallthrough --> copy0MBB
20170 MachineBasicBlock *thisMBB = BB;
20171 MachineFunction *F = BB->getParent();
20173 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20174 // as described above, by inserting a BB, and then making a PHI at the join
20175 // point to select the true and false operands of the CMOV in the PHI.
20177 // The code also handles two different cases of multiple CMOV opcodes
20181 // In this case, there are multiple CMOVs in a row, all which are based on
20182 // the same condition setting (or the exact opposite condition setting).
20183 // In this case we can lower all the CMOVs using a single inserted BB, and
20184 // then make a number of PHIs at the join point to model the CMOVs. The only
20185 // trickiness here, is that in a case like:
20187 // t2 = CMOV cond1 t1, f1
20188 // t3 = CMOV cond1 t2, f2
20190 // when rewriting this into PHIs, we have to perform some renaming on the
20191 // temps since you cannot have a PHI operand refer to a PHI result earlier
20192 // in the same block. The "simple" but wrong lowering would be:
20194 // t2 = PHI t1(BB1), f1(BB2)
20195 // t3 = PHI t2(BB1), f2(BB2)
20197 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20198 // renaming is to note that on the path through BB1, t2 is really just a
20199 // copy of t1, and do that renaming, properly generating:
20201 // t2 = PHI t1(BB1), f1(BB2)
20202 // t3 = PHI t1(BB1), f2(BB2)
20204 // Case 2, we lower cascaded CMOVs such as
20206 // (CMOV (CMOV F, T, cc1), T, cc2)
20208 // to two successives branches. For that, we look for another CMOV as the
20209 // following instruction.
20211 // Without this, we would add a PHI between the two jumps, which ends up
20212 // creating a few copies all around. For instance, for
20214 // (sitofp (zext (fcmp une)))
20216 // we would generate:
20218 // ucomiss %xmm1, %xmm0
20219 // movss <1.0f>, %xmm0
20220 // movaps %xmm0, %xmm1
20222 // xorps %xmm1, %xmm1
20225 // movaps %xmm1, %xmm0
20229 // because this custom-inserter would have generated:
20241 // A: X = ...; Y = ...
20243 // C: Z = PHI [X, A], [Y, B]
20245 // E: PHI [X, C], [Z, D]
20247 // If we lower both CMOVs in a single step, we can instead generate:
20259 // A: X = ...; Y = ...
20261 // E: PHI [X, A], [X, C], [Y, D]
20263 // Which, in our sitofp/fcmp example, gives us something like:
20265 // ucomiss %xmm1, %xmm0
20266 // movss <1.0f>, %xmm0
20269 // xorps %xmm0, %xmm0
20273 MachineInstr *CascadedCMOV = nullptr;
20274 MachineInstr *LastCMOV = MI;
20275 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20276 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20277 MachineBasicBlock::iterator NextMIIt =
20278 std::next(MachineBasicBlock::iterator(MI));
20280 // Check for case 1, where there are multiple CMOVs with the same condition
20281 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20282 // number of jumps the most.
20284 if (isCMOVPseudo(MI)) {
20285 // See if we have a string of CMOVS with the same condition.
20286 while (NextMIIt != BB->end() &&
20287 isCMOVPseudo(NextMIIt) &&
20288 (NextMIIt->getOperand(3).getImm() == CC ||
20289 NextMIIt->getOperand(3).getImm() == OppCC)) {
20290 LastCMOV = &*NextMIIt;
20295 // This checks for case 2, but only do this if we didn't already find
20296 // case 1, as indicated by LastCMOV == MI.
20297 if (LastCMOV == MI &&
20298 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20299 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20300 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20301 CascadedCMOV = &*NextMIIt;
20304 MachineBasicBlock *jcc1MBB = nullptr;
20306 // If we have a cascaded CMOV, we lower it to two successive branches to
20307 // the same block. EFLAGS is used by both, so mark it as live in the second.
20308 if (CascadedCMOV) {
20309 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20310 F->insert(It, jcc1MBB);
20311 jcc1MBB->addLiveIn(X86::EFLAGS);
20314 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20315 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20316 F->insert(It, copy0MBB);
20317 F->insert(It, sinkMBB);
20319 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20320 // live into the sink and copy blocks.
20321 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20323 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20324 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20325 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20326 copy0MBB->addLiveIn(X86::EFLAGS);
20327 sinkMBB->addLiveIn(X86::EFLAGS);
20330 // Transfer the remainder of BB and its successor edges to sinkMBB.
20331 sinkMBB->splice(sinkMBB->begin(), BB,
20332 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20333 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20335 // Add the true and fallthrough blocks as its successors.
20336 if (CascadedCMOV) {
20337 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20338 BB->addSuccessor(jcc1MBB);
20340 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20341 // jump to the sinkMBB.
20342 jcc1MBB->addSuccessor(copy0MBB);
20343 jcc1MBB->addSuccessor(sinkMBB);
20345 BB->addSuccessor(copy0MBB);
20348 // The true block target of the first (or only) branch is always sinkMBB.
20349 BB->addSuccessor(sinkMBB);
20351 // Create the conditional branch instruction.
20352 unsigned Opc = X86::GetCondBranchFromCond(CC);
20353 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20355 if (CascadedCMOV) {
20356 unsigned Opc2 = X86::GetCondBranchFromCond(
20357 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20358 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20362 // %FalseValue = ...
20363 // # fallthrough to sinkMBB
20364 copy0MBB->addSuccessor(sinkMBB);
20367 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20369 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20370 MachineBasicBlock::iterator MIItEnd =
20371 std::next(MachineBasicBlock::iterator(LastCMOV));
20372 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20373 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20374 MachineInstrBuilder MIB;
20376 // As we are creating the PHIs, we have to be careful if there is more than
20377 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20378 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20379 // That also means that PHI construction must work forward from earlier to
20380 // later, and that the code must maintain a mapping from earlier PHI's
20381 // destination registers, and the registers that went into the PHI.
20383 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20384 unsigned DestReg = MIIt->getOperand(0).getReg();
20385 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20386 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20388 // If this CMOV we are generating is the opposite condition from
20389 // the jump we generated, then we have to swap the operands for the
20390 // PHI that is going to be generated.
20391 if (MIIt->getOperand(3).getImm() == OppCC)
20392 std::swap(Op1Reg, Op2Reg);
20394 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20395 Op1Reg = RegRewriteTable[Op1Reg].first;
20397 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20398 Op2Reg = RegRewriteTable[Op2Reg].second;
20400 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20401 TII->get(X86::PHI), DestReg)
20402 .addReg(Op1Reg).addMBB(copy0MBB)
20403 .addReg(Op2Reg).addMBB(thisMBB);
20405 // Add this PHI to the rewrite table.
20406 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20409 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20410 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20411 if (CascadedCMOV) {
20412 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20413 // Copy the PHI result to the register defined by the second CMOV.
20414 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20415 DL, TII->get(TargetOpcode::COPY),
20416 CascadedCMOV->getOperand(0).getReg())
20417 .addReg(MI->getOperand(0).getReg());
20418 CascadedCMOV->eraseFromParent();
20421 // Now remove the CMOV(s).
20422 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20423 (MIIt++)->eraseFromParent();
20428 MachineBasicBlock *
20429 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20430 MachineBasicBlock *BB) const {
20431 // Combine the following atomic floating-point modification pattern:
20432 // a.store(reg OP a.load(acquire), release)
20433 // Transform them into:
20434 // OPss (%gpr), %xmm
20435 // movss %xmm, (%gpr)
20436 // Or sd equivalent for 64-bit operations.
20438 switch (MI->getOpcode()) {
20439 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20440 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20441 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20443 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20444 DebugLoc DL = MI->getDebugLoc();
20445 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20446 unsigned MSrc = MI->getOperand(0).getReg();
20447 unsigned VSrc = MI->getOperand(5).getReg();
20448 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20449 .addReg(/*Base=*/MSrc)
20450 .addImm(/*Scale=*/1)
20451 .addReg(/*Index=*/0)
20454 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20455 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20457 .addReg(/*Base=*/MSrc)
20458 .addImm(/*Scale=*/1)
20459 .addReg(/*Index=*/0)
20460 .addImm(/*Disp=*/0)
20461 .addReg(/*Segment=*/0);
20462 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20463 MI->eraseFromParent(); // The pseudo instruction is gone now.
20467 MachineBasicBlock *
20468 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20469 MachineBasicBlock *BB) const {
20470 MachineFunction *MF = BB->getParent();
20471 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20472 DebugLoc DL = MI->getDebugLoc();
20473 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20475 assert(MF->shouldSplitStack());
20477 const bool Is64Bit = Subtarget->is64Bit();
20478 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20480 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20481 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20484 // ... [Till the alloca]
20485 // If stacklet is not large enough, jump to mallocMBB
20488 // Allocate by subtracting from RSP
20489 // Jump to continueMBB
20492 // Allocate by call to runtime
20496 // [rest of original BB]
20499 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20500 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20501 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20503 MachineRegisterInfo &MRI = MF->getRegInfo();
20504 const TargetRegisterClass *AddrRegClass =
20505 getRegClassFor(getPointerTy(MF->getDataLayout()));
20507 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20508 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20509 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20510 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20511 sizeVReg = MI->getOperand(1).getReg(),
20512 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20514 MachineFunction::iterator MBBIter = BB;
20517 MF->insert(MBBIter, bumpMBB);
20518 MF->insert(MBBIter, mallocMBB);
20519 MF->insert(MBBIter, continueMBB);
20521 continueMBB->splice(continueMBB->begin(), BB,
20522 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20523 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20525 // Add code to the main basic block to check if the stack limit has been hit,
20526 // and if so, jump to mallocMBB otherwise to bumpMBB.
20527 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20528 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20529 .addReg(tmpSPVReg).addReg(sizeVReg);
20530 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20531 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20532 .addReg(SPLimitVReg);
20533 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20535 // bumpMBB simply decreases the stack pointer, since we know the current
20536 // stacklet has enough space.
20537 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20538 .addReg(SPLimitVReg);
20539 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20540 .addReg(SPLimitVReg);
20541 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20543 // Calls into a routine in libgcc to allocate more space from the heap.
20544 const uint32_t *RegMask =
20545 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20547 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20549 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20550 .addExternalSymbol("__morestack_allocate_stack_space")
20551 .addRegMask(RegMask)
20552 .addReg(X86::RDI, RegState::Implicit)
20553 .addReg(X86::RAX, RegState::ImplicitDefine);
20554 } else if (Is64Bit) {
20555 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20557 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20558 .addExternalSymbol("__morestack_allocate_stack_space")
20559 .addRegMask(RegMask)
20560 .addReg(X86::EDI, RegState::Implicit)
20561 .addReg(X86::EAX, RegState::ImplicitDefine);
20563 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20565 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20566 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20567 .addExternalSymbol("__morestack_allocate_stack_space")
20568 .addRegMask(RegMask)
20569 .addReg(X86::EAX, RegState::ImplicitDefine);
20573 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20576 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20577 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20578 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20580 // Set up the CFG correctly.
20581 BB->addSuccessor(bumpMBB);
20582 BB->addSuccessor(mallocMBB);
20583 mallocMBB->addSuccessor(continueMBB);
20584 bumpMBB->addSuccessor(continueMBB);
20586 // Take care of the PHI nodes.
20587 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20588 MI->getOperand(0).getReg())
20589 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20590 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20592 // Delete the original pseudo instruction.
20593 MI->eraseFromParent();
20596 return continueMBB;
20599 MachineBasicBlock *
20600 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20601 MachineBasicBlock *BB) const {
20602 DebugLoc DL = MI->getDebugLoc();
20604 assert(!Subtarget->isTargetMachO());
20606 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20609 MI->eraseFromParent(); // The pseudo instruction is gone now.
20613 MachineBasicBlock *
20614 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20615 MachineBasicBlock *BB) const {
20616 // This is pretty easy. We're taking the value that we received from
20617 // our load from the relocation, sticking it in either RDI (x86-64)
20618 // or EAX and doing an indirect call. The return value will then
20619 // be in the normal return register.
20620 MachineFunction *F = BB->getParent();
20621 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20622 DebugLoc DL = MI->getDebugLoc();
20624 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20625 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20627 // Get a register mask for the lowered call.
20628 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20629 // proper register mask.
20630 const uint32_t *RegMask =
20631 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20632 if (Subtarget->is64Bit()) {
20633 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20634 TII->get(X86::MOV64rm), X86::RDI)
20636 .addImm(0).addReg(0)
20637 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20638 MI->getOperand(3).getTargetFlags())
20640 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20641 addDirectMem(MIB, X86::RDI);
20642 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20643 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20644 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20645 TII->get(X86::MOV32rm), X86::EAX)
20647 .addImm(0).addReg(0)
20648 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20649 MI->getOperand(3).getTargetFlags())
20651 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20652 addDirectMem(MIB, X86::EAX);
20653 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20655 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20656 TII->get(X86::MOV32rm), X86::EAX)
20657 .addReg(TII->getGlobalBaseReg(F))
20658 .addImm(0).addReg(0)
20659 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20660 MI->getOperand(3).getTargetFlags())
20662 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20663 addDirectMem(MIB, X86::EAX);
20664 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20667 MI->eraseFromParent(); // The pseudo instruction is gone now.
20671 MachineBasicBlock *
20672 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20673 MachineBasicBlock *MBB) const {
20674 DebugLoc DL = MI->getDebugLoc();
20675 MachineFunction *MF = MBB->getParent();
20676 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20677 MachineRegisterInfo &MRI = MF->getRegInfo();
20679 const BasicBlock *BB = MBB->getBasicBlock();
20680 MachineFunction::iterator I = MBB;
20683 // Memory Reference
20684 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20685 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20688 unsigned MemOpndSlot = 0;
20690 unsigned CurOp = 0;
20692 DstReg = MI->getOperand(CurOp++).getReg();
20693 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20694 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20695 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20696 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20698 MemOpndSlot = CurOp;
20700 MVT PVT = getPointerTy(MF->getDataLayout());
20701 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20702 "Invalid Pointer Size!");
20704 // For v = setjmp(buf), we generate
20707 // buf[LabelOffset] = restoreMBB
20708 // SjLjSetup restoreMBB
20714 // v = phi(main, restore)
20717 // if base pointer being used, load it from frame
20720 MachineBasicBlock *thisMBB = MBB;
20721 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20722 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20723 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20724 MF->insert(I, mainMBB);
20725 MF->insert(I, sinkMBB);
20726 MF->push_back(restoreMBB);
20728 MachineInstrBuilder MIB;
20730 // Transfer the remainder of BB and its successor edges to sinkMBB.
20731 sinkMBB->splice(sinkMBB->begin(), MBB,
20732 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20733 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20736 unsigned PtrStoreOpc = 0;
20737 unsigned LabelReg = 0;
20738 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20739 Reloc::Model RM = MF->getTarget().getRelocationModel();
20740 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20741 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20743 // Prepare IP either in reg or imm.
20744 if (!UseImmLabel) {
20745 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20746 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20747 LabelReg = MRI.createVirtualRegister(PtrRC);
20748 if (Subtarget->is64Bit()) {
20749 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20753 .addMBB(restoreMBB)
20756 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20757 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20758 .addReg(XII->getGlobalBaseReg(MF))
20761 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20765 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20767 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20768 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20769 if (i == X86::AddrDisp)
20770 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20772 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20775 MIB.addReg(LabelReg);
20777 MIB.addMBB(restoreMBB);
20778 MIB.setMemRefs(MMOBegin, MMOEnd);
20780 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20781 .addMBB(restoreMBB);
20783 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20784 MIB.addRegMask(RegInfo->getNoPreservedMask());
20785 thisMBB->addSuccessor(mainMBB);
20786 thisMBB->addSuccessor(restoreMBB);
20790 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20791 mainMBB->addSuccessor(sinkMBB);
20794 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20795 TII->get(X86::PHI), DstReg)
20796 .addReg(mainDstReg).addMBB(mainMBB)
20797 .addReg(restoreDstReg).addMBB(restoreMBB);
20800 if (RegInfo->hasBasePointer(*MF)) {
20801 const bool Uses64BitFramePtr =
20802 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20803 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20804 X86FI->setRestoreBasePointer(MF);
20805 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20806 unsigned BasePtr = RegInfo->getBaseRegister();
20807 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20808 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20809 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20810 .setMIFlag(MachineInstr::FrameSetup);
20812 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20813 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20814 restoreMBB->addSuccessor(sinkMBB);
20816 MI->eraseFromParent();
20820 MachineBasicBlock *
20821 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20822 MachineBasicBlock *MBB) const {
20823 DebugLoc DL = MI->getDebugLoc();
20824 MachineFunction *MF = MBB->getParent();
20825 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20826 MachineRegisterInfo &MRI = MF->getRegInfo();
20828 // Memory Reference
20829 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20830 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20832 MVT PVT = getPointerTy(MF->getDataLayout());
20833 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20834 "Invalid Pointer Size!");
20836 const TargetRegisterClass *RC =
20837 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20838 unsigned Tmp = MRI.createVirtualRegister(RC);
20839 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20840 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20841 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20842 unsigned SP = RegInfo->getStackRegister();
20844 MachineInstrBuilder MIB;
20846 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20847 const int64_t SPOffset = 2 * PVT.getStoreSize();
20849 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20850 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20853 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20854 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20855 MIB.addOperand(MI->getOperand(i));
20856 MIB.setMemRefs(MMOBegin, MMOEnd);
20858 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20859 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20860 if (i == X86::AddrDisp)
20861 MIB.addDisp(MI->getOperand(i), LabelOffset);
20863 MIB.addOperand(MI->getOperand(i));
20865 MIB.setMemRefs(MMOBegin, MMOEnd);
20867 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20868 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20869 if (i == X86::AddrDisp)
20870 MIB.addDisp(MI->getOperand(i), SPOffset);
20872 MIB.addOperand(MI->getOperand(i));
20874 MIB.setMemRefs(MMOBegin, MMOEnd);
20876 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20878 MI->eraseFromParent();
20882 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20883 // accumulator loops. Writing back to the accumulator allows the coalescer
20884 // to remove extra copies in the loop.
20885 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20886 MachineBasicBlock *
20887 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20888 MachineBasicBlock *MBB) const {
20889 MachineOperand &AddendOp = MI->getOperand(3);
20891 // Bail out early if the addend isn't a register - we can't switch these.
20892 if (!AddendOp.isReg())
20895 MachineFunction &MF = *MBB->getParent();
20896 MachineRegisterInfo &MRI = MF.getRegInfo();
20898 // Check whether the addend is defined by a PHI:
20899 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20900 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20901 if (!AddendDef.isPHI())
20904 // Look for the following pattern:
20906 // %addend = phi [%entry, 0], [%loop, %result]
20908 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20912 // %addend = phi [%entry, 0], [%loop, %result]
20914 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20916 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20917 assert(AddendDef.getOperand(i).isReg());
20918 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20919 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20920 if (&PHISrcInst == MI) {
20921 // Found a matching instruction.
20922 unsigned NewFMAOpc = 0;
20923 switch (MI->getOpcode()) {
20924 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20925 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20926 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20927 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20928 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20929 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20930 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20931 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20932 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20933 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20934 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20935 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20936 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20937 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20938 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20939 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20940 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20941 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20942 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20943 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20945 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20946 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20947 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20948 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20949 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20950 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20951 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20952 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20953 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20954 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20955 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20956 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20957 default: llvm_unreachable("Unrecognized FMA variant.");
20960 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20961 MachineInstrBuilder MIB =
20962 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20963 .addOperand(MI->getOperand(0))
20964 .addOperand(MI->getOperand(3))
20965 .addOperand(MI->getOperand(2))
20966 .addOperand(MI->getOperand(1));
20967 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20968 MI->eraseFromParent();
20975 MachineBasicBlock *
20976 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20977 MachineBasicBlock *BB) const {
20978 switch (MI->getOpcode()) {
20979 default: llvm_unreachable("Unexpected instr type to insert");
20980 case X86::TAILJMPd64:
20981 case X86::TAILJMPr64:
20982 case X86::TAILJMPm64:
20983 case X86::TAILJMPd64_REX:
20984 case X86::TAILJMPr64_REX:
20985 case X86::TAILJMPm64_REX:
20986 llvm_unreachable("TAILJMP64 would not be touched here.");
20987 case X86::TCRETURNdi64:
20988 case X86::TCRETURNri64:
20989 case X86::TCRETURNmi64:
20991 case X86::WIN_ALLOCA:
20992 return EmitLoweredWinAlloca(MI, BB);
20993 case X86::SEG_ALLOCA_32:
20994 case X86::SEG_ALLOCA_64:
20995 return EmitLoweredSegAlloca(MI, BB);
20996 case X86::TLSCall_32:
20997 case X86::TLSCall_64:
20998 return EmitLoweredTLSCall(MI, BB);
20999 case X86::CMOV_FR32:
21000 case X86::CMOV_FR64:
21001 case X86::CMOV_GR8:
21002 case X86::CMOV_GR16:
21003 case X86::CMOV_GR32:
21004 case X86::CMOV_RFP32:
21005 case X86::CMOV_RFP64:
21006 case X86::CMOV_RFP80:
21007 case X86::CMOV_V2F64:
21008 case X86::CMOV_V2I64:
21009 case X86::CMOV_V4F32:
21010 case X86::CMOV_V4F64:
21011 case X86::CMOV_V4I64:
21012 case X86::CMOV_V16F32:
21013 case X86::CMOV_V8F32:
21014 case X86::CMOV_V8F64:
21015 case X86::CMOV_V8I64:
21016 case X86::CMOV_V8I1:
21017 case X86::CMOV_V16I1:
21018 case X86::CMOV_V32I1:
21019 case X86::CMOV_V64I1:
21020 return EmitLoweredSelect(MI, BB);
21022 case X86::RELEASE_FADD32mr:
21023 case X86::RELEASE_FADD64mr:
21024 return EmitLoweredAtomicFP(MI, BB);
21026 case X86::FP32_TO_INT16_IN_MEM:
21027 case X86::FP32_TO_INT32_IN_MEM:
21028 case X86::FP32_TO_INT64_IN_MEM:
21029 case X86::FP64_TO_INT16_IN_MEM:
21030 case X86::FP64_TO_INT32_IN_MEM:
21031 case X86::FP64_TO_INT64_IN_MEM:
21032 case X86::FP80_TO_INT16_IN_MEM:
21033 case X86::FP80_TO_INT32_IN_MEM:
21034 case X86::FP80_TO_INT64_IN_MEM: {
21035 MachineFunction *F = BB->getParent();
21036 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21037 DebugLoc DL = MI->getDebugLoc();
21039 // Change the floating point control register to use "round towards zero"
21040 // mode when truncating to an integer value.
21041 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21042 addFrameReference(BuildMI(*BB, MI, DL,
21043 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21045 // Load the old value of the high byte of the control word...
21047 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21048 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21051 // Set the high part to be round to zero...
21052 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21055 // Reload the modified control word now...
21056 addFrameReference(BuildMI(*BB, MI, DL,
21057 TII->get(X86::FLDCW16m)), CWFrameIdx);
21059 // Restore the memory image of control word to original value
21060 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21063 // Get the X86 opcode to use.
21065 switch (MI->getOpcode()) {
21066 default: llvm_unreachable("illegal opcode!");
21067 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21068 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21069 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21070 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21071 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21072 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21073 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21074 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21075 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21079 MachineOperand &Op = MI->getOperand(0);
21081 AM.BaseType = X86AddressMode::RegBase;
21082 AM.Base.Reg = Op.getReg();
21084 AM.BaseType = X86AddressMode::FrameIndexBase;
21085 AM.Base.FrameIndex = Op.getIndex();
21087 Op = MI->getOperand(1);
21089 AM.Scale = Op.getImm();
21090 Op = MI->getOperand(2);
21092 AM.IndexReg = Op.getImm();
21093 Op = MI->getOperand(3);
21094 if (Op.isGlobal()) {
21095 AM.GV = Op.getGlobal();
21097 AM.Disp = Op.getImm();
21099 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21100 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21102 // Reload the original control word now.
21103 addFrameReference(BuildMI(*BB, MI, DL,
21104 TII->get(X86::FLDCW16m)), CWFrameIdx);
21106 MI->eraseFromParent(); // The pseudo instruction is gone now.
21109 // String/text processing lowering.
21110 case X86::PCMPISTRM128REG:
21111 case X86::VPCMPISTRM128REG:
21112 case X86::PCMPISTRM128MEM:
21113 case X86::VPCMPISTRM128MEM:
21114 case X86::PCMPESTRM128REG:
21115 case X86::VPCMPESTRM128REG:
21116 case X86::PCMPESTRM128MEM:
21117 case X86::VPCMPESTRM128MEM:
21118 assert(Subtarget->hasSSE42() &&
21119 "Target must have SSE4.2 or AVX features enabled");
21120 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21122 // String/text processing lowering.
21123 case X86::PCMPISTRIREG:
21124 case X86::VPCMPISTRIREG:
21125 case X86::PCMPISTRIMEM:
21126 case X86::VPCMPISTRIMEM:
21127 case X86::PCMPESTRIREG:
21128 case X86::VPCMPESTRIREG:
21129 case X86::PCMPESTRIMEM:
21130 case X86::VPCMPESTRIMEM:
21131 assert(Subtarget->hasSSE42() &&
21132 "Target must have SSE4.2 or AVX features enabled");
21133 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21135 // Thread synchronization.
21137 return EmitMonitor(MI, BB, Subtarget);
21141 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21143 case X86::VASTART_SAVE_XMM_REGS:
21144 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21146 case X86::VAARG_64:
21147 return EmitVAARG64WithCustomInserter(MI, BB);
21149 case X86::EH_SjLj_SetJmp32:
21150 case X86::EH_SjLj_SetJmp64:
21151 return emitEHSjLjSetJmp(MI, BB);
21153 case X86::EH_SjLj_LongJmp32:
21154 case X86::EH_SjLj_LongJmp64:
21155 return emitEHSjLjLongJmp(MI, BB);
21157 case TargetOpcode::STATEPOINT:
21158 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21159 // this point in the process. We diverge later.
21160 return emitPatchPoint(MI, BB);
21162 case TargetOpcode::STACKMAP:
21163 case TargetOpcode::PATCHPOINT:
21164 return emitPatchPoint(MI, BB);
21166 case X86::VFMADDPDr213r:
21167 case X86::VFMADDPSr213r:
21168 case X86::VFMADDSDr213r:
21169 case X86::VFMADDSSr213r:
21170 case X86::VFMSUBPDr213r:
21171 case X86::VFMSUBPSr213r:
21172 case X86::VFMSUBSDr213r:
21173 case X86::VFMSUBSSr213r:
21174 case X86::VFNMADDPDr213r:
21175 case X86::VFNMADDPSr213r:
21176 case X86::VFNMADDSDr213r:
21177 case X86::VFNMADDSSr213r:
21178 case X86::VFNMSUBPDr213r:
21179 case X86::VFNMSUBPSr213r:
21180 case X86::VFNMSUBSDr213r:
21181 case X86::VFNMSUBSSr213r:
21182 case X86::VFMADDSUBPDr213r:
21183 case X86::VFMADDSUBPSr213r:
21184 case X86::VFMSUBADDPDr213r:
21185 case X86::VFMSUBADDPSr213r:
21186 case X86::VFMADDPDr213rY:
21187 case X86::VFMADDPSr213rY:
21188 case X86::VFMSUBPDr213rY:
21189 case X86::VFMSUBPSr213rY:
21190 case X86::VFNMADDPDr213rY:
21191 case X86::VFNMADDPSr213rY:
21192 case X86::VFNMSUBPDr213rY:
21193 case X86::VFNMSUBPSr213rY:
21194 case X86::VFMADDSUBPDr213rY:
21195 case X86::VFMADDSUBPSr213rY:
21196 case X86::VFMSUBADDPDr213rY:
21197 case X86::VFMSUBADDPSr213rY:
21198 return emitFMA3Instr(MI, BB);
21202 //===----------------------------------------------------------------------===//
21203 // X86 Optimization Hooks
21204 //===----------------------------------------------------------------------===//
21206 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21209 const SelectionDAG &DAG,
21210 unsigned Depth) const {
21211 unsigned BitWidth = KnownZero.getBitWidth();
21212 unsigned Opc = Op.getOpcode();
21213 assert((Opc >= ISD::BUILTIN_OP_END ||
21214 Opc == ISD::INTRINSIC_WO_CHAIN ||
21215 Opc == ISD::INTRINSIC_W_CHAIN ||
21216 Opc == ISD::INTRINSIC_VOID) &&
21217 "Should use MaskedValueIsZero if you don't know whether Op"
21218 " is a target node!");
21220 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21234 // These nodes' second result is a boolean.
21235 if (Op.getResNo() == 0)
21238 case X86ISD::SETCC:
21239 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21241 case ISD::INTRINSIC_WO_CHAIN: {
21242 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21243 unsigned NumLoBits = 0;
21246 case Intrinsic::x86_sse_movmsk_ps:
21247 case Intrinsic::x86_avx_movmsk_ps_256:
21248 case Intrinsic::x86_sse2_movmsk_pd:
21249 case Intrinsic::x86_avx_movmsk_pd_256:
21250 case Intrinsic::x86_mmx_pmovmskb:
21251 case Intrinsic::x86_sse2_pmovmskb_128:
21252 case Intrinsic::x86_avx2_pmovmskb: {
21253 // High bits of movmskp{s|d}, pmovmskb are known zero.
21255 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21256 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21257 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21258 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21259 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21260 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21261 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21262 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21264 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21273 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21275 const SelectionDAG &,
21276 unsigned Depth) const {
21277 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21278 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21279 return Op.getValueType().getScalarType().getSizeInBits();
21285 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21286 /// node is a GlobalAddress + offset.
21287 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21288 const GlobalValue* &GA,
21289 int64_t &Offset) const {
21290 if (N->getOpcode() == X86ISD::Wrapper) {
21291 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21292 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21293 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21297 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21300 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21301 /// same as extracting the high 128-bit part of 256-bit vector and then
21302 /// inserting the result into the low part of a new 256-bit vector
21303 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21304 EVT VT = SVOp->getValueType(0);
21305 unsigned NumElems = VT.getVectorNumElements();
21307 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21308 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21309 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21310 SVOp->getMaskElt(j) >= 0)
21316 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21317 /// same as extracting the low 128-bit part of 256-bit vector and then
21318 /// inserting the result into the high part of a new 256-bit vector
21319 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21320 EVT VT = SVOp->getValueType(0);
21321 unsigned NumElems = VT.getVectorNumElements();
21323 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21324 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21325 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21326 SVOp->getMaskElt(j) >= 0)
21332 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21333 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21334 TargetLowering::DAGCombinerInfo &DCI,
21335 const X86Subtarget* Subtarget) {
21337 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21338 SDValue V1 = SVOp->getOperand(0);
21339 SDValue V2 = SVOp->getOperand(1);
21340 EVT VT = SVOp->getValueType(0);
21341 unsigned NumElems = VT.getVectorNumElements();
21343 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21344 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21348 // V UNDEF BUILD_VECTOR UNDEF
21350 // CONCAT_VECTOR CONCAT_VECTOR
21353 // RESULT: V + zero extended
21355 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21356 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21357 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21360 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21363 // To match the shuffle mask, the first half of the mask should
21364 // be exactly the first vector, and all the rest a splat with the
21365 // first element of the second one.
21366 for (unsigned i = 0; i != NumElems/2; ++i)
21367 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21368 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21371 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21372 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21373 if (Ld->hasNUsesOfValue(1, 0)) {
21374 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21375 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21377 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21379 Ld->getPointerInfo(),
21380 Ld->getAlignment(),
21381 false/*isVolatile*/, true/*ReadMem*/,
21382 false/*WriteMem*/);
21384 // Make sure the newly-created LOAD is in the same position as Ld in
21385 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21386 // and update uses of Ld's output chain to use the TokenFactor.
21387 if (Ld->hasAnyUseOfValue(1)) {
21388 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21389 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21390 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21391 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21392 SDValue(ResNode.getNode(), 1));
21395 return DAG.getBitcast(VT, ResNode);
21399 // Emit a zeroed vector and insert the desired subvector on its
21401 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21402 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21403 return DCI.CombineTo(N, InsV);
21406 //===--------------------------------------------------------------------===//
21407 // Combine some shuffles into subvector extracts and inserts:
21410 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21411 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21412 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21413 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21414 return DCI.CombineTo(N, InsV);
21417 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21418 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21419 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21420 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21421 return DCI.CombineTo(N, InsV);
21427 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21430 /// This is the leaf of the recursive combinine below. When we have found some
21431 /// chain of single-use x86 shuffle instructions and accumulated the combined
21432 /// shuffle mask represented by them, this will try to pattern match that mask
21433 /// into either a single instruction if there is a special purpose instruction
21434 /// for this operation, or into a PSHUFB instruction which is a fully general
21435 /// instruction but should only be used to replace chains over a certain depth.
21436 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21437 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21438 TargetLowering::DAGCombinerInfo &DCI,
21439 const X86Subtarget *Subtarget) {
21440 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21442 // Find the operand that enters the chain. Note that multiple uses are OK
21443 // here, we're not going to remove the operand we find.
21444 SDValue Input = Op.getOperand(0);
21445 while (Input.getOpcode() == ISD::BITCAST)
21446 Input = Input.getOperand(0);
21448 MVT VT = Input.getSimpleValueType();
21449 MVT RootVT = Root.getSimpleValueType();
21452 // Just remove no-op shuffle masks.
21453 if (Mask.size() == 1) {
21454 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21459 // Use the float domain if the operand type is a floating point type.
21460 bool FloatDomain = VT.isFloatingPoint();
21462 // For floating point shuffles, we don't have free copies in the shuffle
21463 // instructions or the ability to load as part of the instruction, so
21464 // canonicalize their shuffles to UNPCK or MOV variants.
21466 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21467 // vectors because it can have a load folded into it that UNPCK cannot. This
21468 // doesn't preclude something switching to the shorter encoding post-RA.
21470 // FIXME: Should teach these routines about AVX vector widths.
21471 if (FloatDomain && VT.getSizeInBits() == 128) {
21472 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21473 bool Lo = Mask.equals({0, 0});
21476 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21477 // is no slower than UNPCKLPD but has the option to fold the input operand
21478 // into even an unaligned memory load.
21479 if (Lo && Subtarget->hasSSE3()) {
21480 Shuffle = X86ISD::MOVDDUP;
21481 ShuffleVT = MVT::v2f64;
21483 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21484 // than the UNPCK variants.
21485 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21486 ShuffleVT = MVT::v4f32;
21488 if (Depth == 1 && Root->getOpcode() == Shuffle)
21489 return false; // Nothing to do!
21490 Op = DAG.getBitcast(ShuffleVT, Input);
21491 DCI.AddToWorklist(Op.getNode());
21492 if (Shuffle == X86ISD::MOVDDUP)
21493 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21495 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21496 DCI.AddToWorklist(Op.getNode());
21497 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21501 if (Subtarget->hasSSE3() &&
21502 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21503 bool Lo = Mask.equals({0, 0, 2, 2});
21504 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21505 MVT ShuffleVT = MVT::v4f32;
21506 if (Depth == 1 && Root->getOpcode() == Shuffle)
21507 return false; // Nothing to do!
21508 Op = DAG.getBitcast(ShuffleVT, Input);
21509 DCI.AddToWorklist(Op.getNode());
21510 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21511 DCI.AddToWorklist(Op.getNode());
21512 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21516 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21517 bool Lo = Mask.equals({0, 0, 1, 1});
21518 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21519 MVT ShuffleVT = MVT::v4f32;
21520 if (Depth == 1 && Root->getOpcode() == Shuffle)
21521 return false; // Nothing to do!
21522 Op = DAG.getBitcast(ShuffleVT, Input);
21523 DCI.AddToWorklist(Op.getNode());
21524 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21525 DCI.AddToWorklist(Op.getNode());
21526 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21532 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21533 // variants as none of these have single-instruction variants that are
21534 // superior to the UNPCK formulation.
21535 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21536 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21537 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21538 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21540 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21541 bool Lo = Mask[0] == 0;
21542 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21543 if (Depth == 1 && Root->getOpcode() == Shuffle)
21544 return false; // Nothing to do!
21546 switch (Mask.size()) {
21548 ShuffleVT = MVT::v8i16;
21551 ShuffleVT = MVT::v16i8;
21554 llvm_unreachable("Impossible mask size!");
21556 Op = DAG.getBitcast(ShuffleVT, Input);
21557 DCI.AddToWorklist(Op.getNode());
21558 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21559 DCI.AddToWorklist(Op.getNode());
21560 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21565 // Don't try to re-form single instruction chains under any circumstances now
21566 // that we've done encoding canonicalization for them.
21570 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21571 // can replace them with a single PSHUFB instruction profitably. Intel's
21572 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21573 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21574 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21575 SmallVector<SDValue, 16> PSHUFBMask;
21576 int NumBytes = VT.getSizeInBits() / 8;
21577 int Ratio = NumBytes / Mask.size();
21578 for (int i = 0; i < NumBytes; ++i) {
21579 if (Mask[i / Ratio] == SM_SentinelUndef) {
21580 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21583 int M = Mask[i / Ratio] != SM_SentinelZero
21584 ? Ratio * Mask[i / Ratio] + i % Ratio
21586 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21588 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21589 Op = DAG.getBitcast(ByteVT, Input);
21590 DCI.AddToWorklist(Op.getNode());
21591 SDValue PSHUFBMaskOp =
21592 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21593 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21594 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21595 DCI.AddToWorklist(Op.getNode());
21596 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21601 // Failed to find any combines.
21605 /// \brief Fully generic combining of x86 shuffle instructions.
21607 /// This should be the last combine run over the x86 shuffle instructions. Once
21608 /// they have been fully optimized, this will recursively consider all chains
21609 /// of single-use shuffle instructions, build a generic model of the cumulative
21610 /// shuffle operation, and check for simpler instructions which implement this
21611 /// operation. We use this primarily for two purposes:
21613 /// 1) Collapse generic shuffles to specialized single instructions when
21614 /// equivalent. In most cases, this is just an encoding size win, but
21615 /// sometimes we will collapse multiple generic shuffles into a single
21616 /// special-purpose shuffle.
21617 /// 2) Look for sequences of shuffle instructions with 3 or more total
21618 /// instructions, and replace them with the slightly more expensive SSSE3
21619 /// PSHUFB instruction if available. We do this as the last combining step
21620 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21621 /// a suitable short sequence of other instructions. The PHUFB will either
21622 /// use a register or have to read from memory and so is slightly (but only
21623 /// slightly) more expensive than the other shuffle instructions.
21625 /// Because this is inherently a quadratic operation (for each shuffle in
21626 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21627 /// This should never be an issue in practice as the shuffle lowering doesn't
21628 /// produce sequences of more than 8 instructions.
21630 /// FIXME: We will currently miss some cases where the redundant shuffling
21631 /// would simplify under the threshold for PSHUFB formation because of
21632 /// combine-ordering. To fix this, we should do the redundant instruction
21633 /// combining in this recursive walk.
21634 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21635 ArrayRef<int> RootMask,
21636 int Depth, bool HasPSHUFB,
21638 TargetLowering::DAGCombinerInfo &DCI,
21639 const X86Subtarget *Subtarget) {
21640 // Bound the depth of our recursive combine because this is ultimately
21641 // quadratic in nature.
21645 // Directly rip through bitcasts to find the underlying operand.
21646 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21647 Op = Op.getOperand(0);
21649 MVT VT = Op.getSimpleValueType();
21650 if (!VT.isVector())
21651 return false; // Bail if we hit a non-vector.
21653 assert(Root.getSimpleValueType().isVector() &&
21654 "Shuffles operate on vector types!");
21655 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21656 "Can only combine shuffles of the same vector register size.");
21658 if (!isTargetShuffle(Op.getOpcode()))
21660 SmallVector<int, 16> OpMask;
21662 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21663 // We only can combine unary shuffles which we can decode the mask for.
21664 if (!HaveMask || !IsUnary)
21667 assert(VT.getVectorNumElements() == OpMask.size() &&
21668 "Different mask size from vector size!");
21669 assert(((RootMask.size() > OpMask.size() &&
21670 RootMask.size() % OpMask.size() == 0) ||
21671 (OpMask.size() > RootMask.size() &&
21672 OpMask.size() % RootMask.size() == 0) ||
21673 OpMask.size() == RootMask.size()) &&
21674 "The smaller number of elements must divide the larger.");
21675 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21676 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21677 assert(((RootRatio == 1 && OpRatio == 1) ||
21678 (RootRatio == 1) != (OpRatio == 1)) &&
21679 "Must not have a ratio for both incoming and op masks!");
21681 SmallVector<int, 16> Mask;
21682 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21684 // Merge this shuffle operation's mask into our accumulated mask. Note that
21685 // this shuffle's mask will be the first applied to the input, followed by the
21686 // root mask to get us all the way to the root value arrangement. The reason
21687 // for this order is that we are recursing up the operation chain.
21688 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21689 int RootIdx = i / RootRatio;
21690 if (RootMask[RootIdx] < 0) {
21691 // This is a zero or undef lane, we're done.
21692 Mask.push_back(RootMask[RootIdx]);
21696 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21697 int OpIdx = RootMaskedIdx / OpRatio;
21698 if (OpMask[OpIdx] < 0) {
21699 // The incoming lanes are zero or undef, it doesn't matter which ones we
21701 Mask.push_back(OpMask[OpIdx]);
21705 // Ok, we have non-zero lanes, map them through.
21706 Mask.push_back(OpMask[OpIdx] * OpRatio +
21707 RootMaskedIdx % OpRatio);
21710 // See if we can recurse into the operand to combine more things.
21711 switch (Op.getOpcode()) {
21712 case X86ISD::PSHUFB:
21714 case X86ISD::PSHUFD:
21715 case X86ISD::PSHUFHW:
21716 case X86ISD::PSHUFLW:
21717 if (Op.getOperand(0).hasOneUse() &&
21718 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21719 HasPSHUFB, DAG, DCI, Subtarget))
21723 case X86ISD::UNPCKL:
21724 case X86ISD::UNPCKH:
21725 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21726 // We can't check for single use, we have to check that this shuffle is the only user.
21727 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21728 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21729 HasPSHUFB, DAG, DCI, Subtarget))
21734 // Minor canonicalization of the accumulated shuffle mask to make it easier
21735 // to match below. All this does is detect masks with squential pairs of
21736 // elements, and shrink them to the half-width mask. It does this in a loop
21737 // so it will reduce the size of the mask to the minimal width mask which
21738 // performs an equivalent shuffle.
21739 SmallVector<int, 16> WidenedMask;
21740 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21741 Mask = std::move(WidenedMask);
21742 WidenedMask.clear();
21745 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21749 /// \brief Get the PSHUF-style mask from PSHUF node.
21751 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21752 /// PSHUF-style masks that can be reused with such instructions.
21753 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21754 MVT VT = N.getSimpleValueType();
21755 SmallVector<int, 4> Mask;
21757 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21761 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21762 // matter. Check that the upper masks are repeats and remove them.
21763 if (VT.getSizeInBits() > 128) {
21764 int LaneElts = 128 / VT.getScalarSizeInBits();
21766 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21767 for (int j = 0; j < LaneElts; ++j)
21768 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21769 "Mask doesn't repeat in high 128-bit lanes!");
21771 Mask.resize(LaneElts);
21774 switch (N.getOpcode()) {
21775 case X86ISD::PSHUFD:
21777 case X86ISD::PSHUFLW:
21780 case X86ISD::PSHUFHW:
21781 Mask.erase(Mask.begin(), Mask.begin() + 4);
21782 for (int &M : Mask)
21786 llvm_unreachable("No valid shuffle instruction found!");
21790 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21792 /// We walk up the chain and look for a combinable shuffle, skipping over
21793 /// shuffles that we could hoist this shuffle's transformation past without
21794 /// altering anything.
21796 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21798 TargetLowering::DAGCombinerInfo &DCI) {
21799 assert(N.getOpcode() == X86ISD::PSHUFD &&
21800 "Called with something other than an x86 128-bit half shuffle!");
21803 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21804 // of the shuffles in the chain so that we can form a fresh chain to replace
21806 SmallVector<SDValue, 8> Chain;
21807 SDValue V = N.getOperand(0);
21808 for (; V.hasOneUse(); V = V.getOperand(0)) {
21809 switch (V.getOpcode()) {
21811 return SDValue(); // Nothing combined!
21814 // Skip bitcasts as we always know the type for the target specific
21818 case X86ISD::PSHUFD:
21819 // Found another dword shuffle.
21822 case X86ISD::PSHUFLW:
21823 // Check that the low words (being shuffled) are the identity in the
21824 // dword shuffle, and the high words are self-contained.
21825 if (Mask[0] != 0 || Mask[1] != 1 ||
21826 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21829 Chain.push_back(V);
21832 case X86ISD::PSHUFHW:
21833 // Check that the high words (being shuffled) are the identity in the
21834 // dword shuffle, and the low words are self-contained.
21835 if (Mask[2] != 2 || Mask[3] != 3 ||
21836 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21839 Chain.push_back(V);
21842 case X86ISD::UNPCKL:
21843 case X86ISD::UNPCKH:
21844 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21845 // shuffle into a preceding word shuffle.
21846 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21847 V.getSimpleValueType().getScalarType() != MVT::i16)
21850 // Search for a half-shuffle which we can combine with.
21851 unsigned CombineOp =
21852 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21853 if (V.getOperand(0) != V.getOperand(1) ||
21854 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21856 Chain.push_back(V);
21857 V = V.getOperand(0);
21859 switch (V.getOpcode()) {
21861 return SDValue(); // Nothing to combine.
21863 case X86ISD::PSHUFLW:
21864 case X86ISD::PSHUFHW:
21865 if (V.getOpcode() == CombineOp)
21868 Chain.push_back(V);
21872 V = V.getOperand(0);
21876 } while (V.hasOneUse());
21879 // Break out of the loop if we break out of the switch.
21883 if (!V.hasOneUse())
21884 // We fell out of the loop without finding a viable combining instruction.
21887 // Merge this node's mask and our incoming mask.
21888 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21889 for (int &M : Mask)
21891 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21892 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21894 // Rebuild the chain around this new shuffle.
21895 while (!Chain.empty()) {
21896 SDValue W = Chain.pop_back_val();
21898 if (V.getValueType() != W.getOperand(0).getValueType())
21899 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21901 switch (W.getOpcode()) {
21903 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21905 case X86ISD::UNPCKL:
21906 case X86ISD::UNPCKH:
21907 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21910 case X86ISD::PSHUFD:
21911 case X86ISD::PSHUFLW:
21912 case X86ISD::PSHUFHW:
21913 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21917 if (V.getValueType() != N.getValueType())
21918 V = DAG.getBitcast(N.getValueType(), V);
21920 // Return the new chain to replace N.
21924 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21926 /// We walk up the chain, skipping shuffles of the other half and looking
21927 /// through shuffles which switch halves trying to find a shuffle of the same
21928 /// pair of dwords.
21929 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21931 TargetLowering::DAGCombinerInfo &DCI) {
21933 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21934 "Called with something other than an x86 128-bit half shuffle!");
21936 unsigned CombineOpcode = N.getOpcode();
21938 // Walk up a single-use chain looking for a combinable shuffle.
21939 SDValue V = N.getOperand(0);
21940 for (; V.hasOneUse(); V = V.getOperand(0)) {
21941 switch (V.getOpcode()) {
21943 return false; // Nothing combined!
21946 // Skip bitcasts as we always know the type for the target specific
21950 case X86ISD::PSHUFLW:
21951 case X86ISD::PSHUFHW:
21952 if (V.getOpcode() == CombineOpcode)
21955 // Other-half shuffles are no-ops.
21958 // Break out of the loop if we break out of the switch.
21962 if (!V.hasOneUse())
21963 // We fell out of the loop without finding a viable combining instruction.
21966 // Combine away the bottom node as its shuffle will be accumulated into
21967 // a preceding shuffle.
21968 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21970 // Record the old value.
21973 // Merge this node's mask and our incoming mask (adjusted to account for all
21974 // the pshufd instructions encountered).
21975 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21976 for (int &M : Mask)
21978 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21979 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21981 // Check that the shuffles didn't cancel each other out. If not, we need to
21982 // combine to the new one.
21984 // Replace the combinable shuffle with the combined one, updating all users
21985 // so that we re-evaluate the chain here.
21986 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21991 /// \brief Try to combine x86 target specific shuffles.
21992 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21993 TargetLowering::DAGCombinerInfo &DCI,
21994 const X86Subtarget *Subtarget) {
21996 MVT VT = N.getSimpleValueType();
21997 SmallVector<int, 4> Mask;
21999 switch (N.getOpcode()) {
22000 case X86ISD::PSHUFD:
22001 case X86ISD::PSHUFLW:
22002 case X86ISD::PSHUFHW:
22003 Mask = getPSHUFShuffleMask(N);
22004 assert(Mask.size() == 4);
22010 // Nuke no-op shuffles that show up after combining.
22011 if (isNoopShuffleMask(Mask))
22012 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22014 // Look for simplifications involving one or two shuffle instructions.
22015 SDValue V = N.getOperand(0);
22016 switch (N.getOpcode()) {
22019 case X86ISD::PSHUFLW:
22020 case X86ISD::PSHUFHW:
22021 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22023 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22024 return SDValue(); // We combined away this shuffle, so we're done.
22026 // See if this reduces to a PSHUFD which is no more expensive and can
22027 // combine with more operations. Note that it has to at least flip the
22028 // dwords as otherwise it would have been removed as a no-op.
22029 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22030 int DMask[] = {0, 1, 2, 3};
22031 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22032 DMask[DOffset + 0] = DOffset + 1;
22033 DMask[DOffset + 1] = DOffset + 0;
22034 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22035 V = DAG.getBitcast(DVT, V);
22036 DCI.AddToWorklist(V.getNode());
22037 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22038 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22039 DCI.AddToWorklist(V.getNode());
22040 return DAG.getBitcast(VT, V);
22043 // Look for shuffle patterns which can be implemented as a single unpack.
22044 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22045 // only works when we have a PSHUFD followed by two half-shuffles.
22046 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22047 (V.getOpcode() == X86ISD::PSHUFLW ||
22048 V.getOpcode() == X86ISD::PSHUFHW) &&
22049 V.getOpcode() != N.getOpcode() &&
22051 SDValue D = V.getOperand(0);
22052 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22053 D = D.getOperand(0);
22054 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22055 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22056 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22057 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22058 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22060 for (int i = 0; i < 4; ++i) {
22061 WordMask[i + NOffset] = Mask[i] + NOffset;
22062 WordMask[i + VOffset] = VMask[i] + VOffset;
22064 // Map the word mask through the DWord mask.
22066 for (int i = 0; i < 8; ++i)
22067 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22068 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22069 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22070 // We can replace all three shuffles with an unpack.
22071 V = DAG.getBitcast(VT, D.getOperand(0));
22072 DCI.AddToWorklist(V.getNode());
22073 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22082 case X86ISD::PSHUFD:
22083 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22092 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22094 /// We combine this directly on the abstract vector shuffle nodes so it is
22095 /// easier to generically match. We also insert dummy vector shuffle nodes for
22096 /// the operands which explicitly discard the lanes which are unused by this
22097 /// operation to try to flow through the rest of the combiner the fact that
22098 /// they're unused.
22099 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22101 EVT VT = N->getValueType(0);
22103 // We only handle target-independent shuffles.
22104 // FIXME: It would be easy and harmless to use the target shuffle mask
22105 // extraction tool to support more.
22106 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22109 auto *SVN = cast<ShuffleVectorSDNode>(N);
22110 ArrayRef<int> Mask = SVN->getMask();
22111 SDValue V1 = N->getOperand(0);
22112 SDValue V2 = N->getOperand(1);
22114 // We require the first shuffle operand to be the SUB node, and the second to
22115 // be the ADD node.
22116 // FIXME: We should support the commuted patterns.
22117 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22120 // If there are other uses of these operations we can't fold them.
22121 if (!V1->hasOneUse() || !V2->hasOneUse())
22124 // Ensure that both operations have the same operands. Note that we can
22125 // commute the FADD operands.
22126 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22127 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22128 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22131 // We're looking for blends between FADD and FSUB nodes. We insist on these
22132 // nodes being lined up in a specific expected pattern.
22133 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22134 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22135 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22138 // Only specific types are legal at this point, assert so we notice if and
22139 // when these change.
22140 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22141 VT == MVT::v4f64) &&
22142 "Unknown vector type encountered!");
22144 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22147 /// PerformShuffleCombine - Performs several different shuffle combines.
22148 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22149 TargetLowering::DAGCombinerInfo &DCI,
22150 const X86Subtarget *Subtarget) {
22152 SDValue N0 = N->getOperand(0);
22153 SDValue N1 = N->getOperand(1);
22154 EVT VT = N->getValueType(0);
22156 // Don't create instructions with illegal types after legalize types has run.
22157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22158 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22161 // If we have legalized the vector types, look for blends of FADD and FSUB
22162 // nodes that we can fuse into an ADDSUB node.
22163 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22164 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22167 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22168 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22169 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22170 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22172 // During Type Legalization, when promoting illegal vector types,
22173 // the backend might introduce new shuffle dag nodes and bitcasts.
22175 // This code performs the following transformation:
22176 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22177 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22179 // We do this only if both the bitcast and the BINOP dag nodes have
22180 // one use. Also, perform this transformation only if the new binary
22181 // operation is legal. This is to avoid introducing dag nodes that
22182 // potentially need to be further expanded (or custom lowered) into a
22183 // less optimal sequence of dag nodes.
22184 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22185 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22186 N0.getOpcode() == ISD::BITCAST) {
22187 SDValue BC0 = N0.getOperand(0);
22188 EVT SVT = BC0.getValueType();
22189 unsigned Opcode = BC0.getOpcode();
22190 unsigned NumElts = VT.getVectorNumElements();
22192 if (BC0.hasOneUse() && SVT.isVector() &&
22193 SVT.getVectorNumElements() * 2 == NumElts &&
22194 TLI.isOperationLegal(Opcode, VT)) {
22195 bool CanFold = false;
22207 unsigned SVTNumElts = SVT.getVectorNumElements();
22208 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22209 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22210 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22211 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22212 CanFold = SVOp->getMaskElt(i) < 0;
22215 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22216 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22217 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22218 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22223 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22224 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22225 // consecutive, non-overlapping, and in the right order.
22226 SmallVector<SDValue, 16> Elts;
22227 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22228 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22230 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22233 if (isTargetShuffle(N->getOpcode())) {
22235 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22236 if (Shuffle.getNode())
22239 // Try recursively combining arbitrary sequences of x86 shuffle
22240 // instructions into higher-order shuffles. We do this after combining
22241 // specific PSHUF instruction sequences into their minimal form so that we
22242 // can evaluate how many specialized shuffle instructions are involved in
22243 // a particular chain.
22244 SmallVector<int, 1> NonceMask; // Just a placeholder.
22245 NonceMask.push_back(0);
22246 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22247 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22249 return SDValue(); // This routine will use CombineTo to replace N.
22255 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22256 /// specific shuffle of a load can be folded into a single element load.
22257 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22258 /// shuffles have been custom lowered so we need to handle those here.
22259 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22260 TargetLowering::DAGCombinerInfo &DCI) {
22261 if (DCI.isBeforeLegalizeOps())
22264 SDValue InVec = N->getOperand(0);
22265 SDValue EltNo = N->getOperand(1);
22267 if (!isa<ConstantSDNode>(EltNo))
22270 EVT OriginalVT = InVec.getValueType();
22272 if (InVec.getOpcode() == ISD::BITCAST) {
22273 // Don't duplicate a load with other uses.
22274 if (!InVec.hasOneUse())
22276 EVT BCVT = InVec.getOperand(0).getValueType();
22277 if (!BCVT.isVector() ||
22278 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22280 InVec = InVec.getOperand(0);
22283 EVT CurrentVT = InVec.getValueType();
22285 if (!isTargetShuffle(InVec.getOpcode()))
22288 // Don't duplicate a load with other uses.
22289 if (!InVec.hasOneUse())
22292 SmallVector<int, 16> ShuffleMask;
22294 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22295 ShuffleMask, UnaryShuffle))
22298 // Select the input vector, guarding against out of range extract vector.
22299 unsigned NumElems = CurrentVT.getVectorNumElements();
22300 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22301 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22302 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22303 : InVec.getOperand(1);
22305 // If inputs to shuffle are the same for both ops, then allow 2 uses
22306 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22307 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22309 if (LdNode.getOpcode() == ISD::BITCAST) {
22310 // Don't duplicate a load with other uses.
22311 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22314 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22315 LdNode = LdNode.getOperand(0);
22318 if (!ISD::isNormalLoad(LdNode.getNode()))
22321 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22323 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22326 EVT EltVT = N->getValueType(0);
22327 // If there's a bitcast before the shuffle, check if the load type and
22328 // alignment is valid.
22329 unsigned Align = LN0->getAlignment();
22330 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22331 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22332 EltVT.getTypeForEVT(*DAG.getContext()));
22334 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22337 // All checks match so transform back to vector_shuffle so that DAG combiner
22338 // can finish the job
22341 // Create shuffle node taking into account the case that its a unary shuffle
22342 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22343 : InVec.getOperand(1);
22344 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22345 InVec.getOperand(0), Shuffle,
22347 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22348 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22352 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22353 /// special and don't usually play with other vector types, it's better to
22354 /// handle them early to be sure we emit efficient code by avoiding
22355 /// store-load conversions.
22356 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22357 if (N->getValueType(0) != MVT::x86mmx ||
22358 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22359 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22362 SDValue V = N->getOperand(0);
22363 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22364 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22365 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22366 N->getValueType(0), V.getOperand(0));
22371 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22372 /// generation and convert it from being a bunch of shuffles and extracts
22373 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22374 /// storing the value and loading scalars back, while for x64 we should
22375 /// use 64-bit extracts and shifts.
22376 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22377 TargetLowering::DAGCombinerInfo &DCI) {
22378 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22381 SDValue InputVector = N->getOperand(0);
22382 SDLoc dl(InputVector);
22383 // Detect mmx to i32 conversion through a v2i32 elt extract.
22384 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22385 N->getValueType(0) == MVT::i32 &&
22386 InputVector.getValueType() == MVT::v2i32) {
22388 // The bitcast source is a direct mmx result.
22389 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22390 if (MMXSrc.getValueType() == MVT::x86mmx)
22391 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22392 N->getValueType(0),
22393 InputVector.getNode()->getOperand(0));
22395 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22396 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22397 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22398 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22399 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22400 MMXSrcOp.getValueType() == MVT::v1i64 &&
22401 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22402 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22403 N->getValueType(0),
22404 MMXSrcOp.getOperand(0));
22407 EVT VT = N->getValueType(0);
22409 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22410 InputVector.getOpcode() == ISD::BITCAST &&
22411 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22412 uint64_t ExtractedElt =
22413 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22414 uint64_t InputValue =
22415 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22416 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22417 return DAG.getConstant(Res, dl, MVT::i1);
22419 // Only operate on vectors of 4 elements, where the alternative shuffling
22420 // gets to be more expensive.
22421 if (InputVector.getValueType() != MVT::v4i32)
22424 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22425 // single use which is a sign-extend or zero-extend, and all elements are
22427 SmallVector<SDNode *, 4> Uses;
22428 unsigned ExtractedElements = 0;
22429 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22430 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22431 if (UI.getUse().getResNo() != InputVector.getResNo())
22434 SDNode *Extract = *UI;
22435 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22438 if (Extract->getValueType(0) != MVT::i32)
22440 if (!Extract->hasOneUse())
22442 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22443 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22445 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22448 // Record which element was extracted.
22449 ExtractedElements |=
22450 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22452 Uses.push_back(Extract);
22455 // If not all the elements were used, this may not be worthwhile.
22456 if (ExtractedElements != 15)
22459 // Ok, we've now decided to do the transformation.
22460 // If 64-bit shifts are legal, use the extract-shift sequence,
22461 // otherwise bounce the vector off the cache.
22462 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22465 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22466 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22467 auto &DL = DAG.getDataLayout();
22468 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22469 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22470 DAG.getConstant(0, dl, VecIdxTy));
22471 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22472 DAG.getConstant(1, dl, VecIdxTy));
22474 SDValue ShAmt = DAG.getConstant(
22475 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22476 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22477 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22478 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22479 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22480 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22481 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22483 // Store the value to a temporary stack slot.
22484 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22485 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22486 MachinePointerInfo(), false, false, 0);
22488 EVT ElementType = InputVector.getValueType().getVectorElementType();
22489 unsigned EltSize = ElementType.getSizeInBits() / 8;
22491 // Replace each use (extract) with a load of the appropriate element.
22492 for (unsigned i = 0; i < 4; ++i) {
22493 uint64_t Offset = EltSize * i;
22494 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22495 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22497 SDValue ScalarAddr =
22498 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22500 // Load the scalar.
22501 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22502 ScalarAddr, MachinePointerInfo(),
22503 false, false, false, 0);
22508 // Replace the extracts
22509 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22510 UE = Uses.end(); UI != UE; ++UI) {
22511 SDNode *Extract = *UI;
22513 SDValue Idx = Extract->getOperand(1);
22514 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22515 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22518 // The replacement was made in place; don't return anything.
22523 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22524 const X86Subtarget *Subtarget) {
22526 SDValue Cond = N->getOperand(0);
22527 SDValue LHS = N->getOperand(1);
22528 SDValue RHS = N->getOperand(2);
22530 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22531 SDValue CondSrc = Cond->getOperand(0);
22532 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22533 Cond = CondSrc->getOperand(0);
22536 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22539 // A vselect where all conditions and data are constants can be optimized into
22540 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22541 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22542 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22545 unsigned MaskValue = 0;
22546 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22549 MVT VT = N->getSimpleValueType(0);
22550 unsigned NumElems = VT.getVectorNumElements();
22551 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22552 for (unsigned i = 0; i < NumElems; ++i) {
22553 // Be sure we emit undef where we can.
22554 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22555 ShuffleMask[i] = -1;
22557 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22560 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22561 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22563 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22566 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22568 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22569 TargetLowering::DAGCombinerInfo &DCI,
22570 const X86Subtarget *Subtarget) {
22572 SDValue Cond = N->getOperand(0);
22573 // Get the LHS/RHS of the select.
22574 SDValue LHS = N->getOperand(1);
22575 SDValue RHS = N->getOperand(2);
22576 EVT VT = LHS.getValueType();
22577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22579 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22580 // instructions match the semantics of the common C idiom x<y?x:y but not
22581 // x<=y?x:y, because of how they handle negative zero (which can be
22582 // ignored in unsafe-math mode).
22583 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22584 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22585 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22586 (Subtarget->hasSSE2() ||
22587 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22588 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22590 unsigned Opcode = 0;
22591 // Check for x CC y ? x : y.
22592 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22593 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22597 // Converting this to a min would handle NaNs incorrectly, and swapping
22598 // the operands would cause it to handle comparisons between positive
22599 // and negative zero incorrectly.
22600 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22601 if (!DAG.getTarget().Options.UnsafeFPMath &&
22602 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22604 std::swap(LHS, RHS);
22606 Opcode = X86ISD::FMIN;
22609 // Converting this to a min would handle comparisons between positive
22610 // and negative zero incorrectly.
22611 if (!DAG.getTarget().Options.UnsafeFPMath &&
22612 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22614 Opcode = X86ISD::FMIN;
22617 // Converting this to a min would handle both negative zeros and NaNs
22618 // incorrectly, but we can swap the operands to fix both.
22619 std::swap(LHS, RHS);
22623 Opcode = X86ISD::FMIN;
22627 // Converting this to a max would handle comparisons between positive
22628 // and negative zero incorrectly.
22629 if (!DAG.getTarget().Options.UnsafeFPMath &&
22630 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22632 Opcode = X86ISD::FMAX;
22635 // Converting this to a max would handle NaNs incorrectly, and swapping
22636 // the operands would cause it to handle comparisons between positive
22637 // and negative zero incorrectly.
22638 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22639 if (!DAG.getTarget().Options.UnsafeFPMath &&
22640 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22642 std::swap(LHS, RHS);
22644 Opcode = X86ISD::FMAX;
22647 // Converting this to a max would handle both negative zeros and NaNs
22648 // incorrectly, but we can swap the operands to fix both.
22649 std::swap(LHS, RHS);
22653 Opcode = X86ISD::FMAX;
22656 // Check for x CC y ? y : x -- a min/max with reversed arms.
22657 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22658 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22662 // Converting this to a min would handle comparisons between positive
22663 // and negative zero incorrectly, and swapping the operands would
22664 // cause it to handle NaNs incorrectly.
22665 if (!DAG.getTarget().Options.UnsafeFPMath &&
22666 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22667 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22669 std::swap(LHS, RHS);
22671 Opcode = X86ISD::FMIN;
22674 // Converting this to a min would handle NaNs incorrectly.
22675 if (!DAG.getTarget().Options.UnsafeFPMath &&
22676 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22678 Opcode = X86ISD::FMIN;
22681 // Converting this to a min would handle both negative zeros and NaNs
22682 // incorrectly, but we can swap the operands to fix both.
22683 std::swap(LHS, RHS);
22687 Opcode = X86ISD::FMIN;
22691 // Converting this to a max would handle NaNs incorrectly.
22692 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22694 Opcode = X86ISD::FMAX;
22697 // Converting this to a max would handle comparisons between positive
22698 // and negative zero incorrectly, and swapping the operands would
22699 // cause it to handle NaNs incorrectly.
22700 if (!DAG.getTarget().Options.UnsafeFPMath &&
22701 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22702 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22704 std::swap(LHS, RHS);
22706 Opcode = X86ISD::FMAX;
22709 // Converting this to a max would handle both negative zeros and NaNs
22710 // incorrectly, but we can swap the operands to fix both.
22711 std::swap(LHS, RHS);
22715 Opcode = X86ISD::FMAX;
22721 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22724 EVT CondVT = Cond.getValueType();
22725 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22726 CondVT.getVectorElementType() == MVT::i1) {
22727 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22728 // lowering on KNL. In this case we convert it to
22729 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22730 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22731 // Since SKX these selects have a proper lowering.
22732 EVT OpVT = LHS.getValueType();
22733 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22734 (OpVT.getVectorElementType() == MVT::i8 ||
22735 OpVT.getVectorElementType() == MVT::i16) &&
22736 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22737 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22738 DCI.AddToWorklist(Cond.getNode());
22739 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22742 // If this is a select between two integer constants, try to do some
22744 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22745 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22746 // Don't do this for crazy integer types.
22747 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22748 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22749 // so that TrueC (the true value) is larger than FalseC.
22750 bool NeedsCondInvert = false;
22752 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22753 // Efficiently invertible.
22754 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22755 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22756 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22757 NeedsCondInvert = true;
22758 std::swap(TrueC, FalseC);
22761 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22762 if (FalseC->getAPIntValue() == 0 &&
22763 TrueC->getAPIntValue().isPowerOf2()) {
22764 if (NeedsCondInvert) // Invert the condition if needed.
22765 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22766 DAG.getConstant(1, DL, Cond.getValueType()));
22768 // Zero extend the condition if needed.
22769 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22771 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22772 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22773 DAG.getConstant(ShAmt, DL, MVT::i8));
22776 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22777 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22778 if (NeedsCondInvert) // Invert the condition if needed.
22779 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22780 DAG.getConstant(1, DL, Cond.getValueType()));
22782 // Zero extend the condition if needed.
22783 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22784 FalseC->getValueType(0), Cond);
22785 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22786 SDValue(FalseC, 0));
22789 // Optimize cases that will turn into an LEA instruction. This requires
22790 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22791 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22792 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22793 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22795 bool isFastMultiplier = false;
22797 switch ((unsigned char)Diff) {
22799 case 1: // result = add base, cond
22800 case 2: // result = lea base( , cond*2)
22801 case 3: // result = lea base(cond, cond*2)
22802 case 4: // result = lea base( , cond*4)
22803 case 5: // result = lea base(cond, cond*4)
22804 case 8: // result = lea base( , cond*8)
22805 case 9: // result = lea base(cond, cond*8)
22806 isFastMultiplier = true;
22811 if (isFastMultiplier) {
22812 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22813 if (NeedsCondInvert) // Invert the condition if needed.
22814 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22815 DAG.getConstant(1, DL, Cond.getValueType()));
22817 // Zero extend the condition if needed.
22818 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22820 // Scale the condition by the difference.
22822 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22823 DAG.getConstant(Diff, DL,
22824 Cond.getValueType()));
22826 // Add the base if non-zero.
22827 if (FalseC->getAPIntValue() != 0)
22828 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22829 SDValue(FalseC, 0));
22836 // Canonicalize max and min:
22837 // (x > y) ? x : y -> (x >= y) ? x : y
22838 // (x < y) ? x : y -> (x <= y) ? x : y
22839 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22840 // the need for an extra compare
22841 // against zero. e.g.
22842 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22844 // testl %edi, %edi
22846 // cmovgl %edi, %eax
22850 // cmovsl %eax, %edi
22851 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22852 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22853 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22854 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22859 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22860 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22861 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22862 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22867 // Early exit check
22868 if (!TLI.isTypeLegal(VT))
22871 // Match VSELECTs into subs with unsigned saturation.
22872 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22873 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22874 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22875 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22876 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22878 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22879 // left side invert the predicate to simplify logic below.
22881 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22883 CC = ISD::getSetCCInverse(CC, true);
22884 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22888 if (Other.getNode() && Other->getNumOperands() == 2 &&
22889 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22890 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22891 SDValue CondRHS = Cond->getOperand(1);
22893 // Look for a general sub with unsigned saturation first.
22894 // x >= y ? x-y : 0 --> subus x, y
22895 // x > y ? x-y : 0 --> subus x, y
22896 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22897 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22898 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22900 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22901 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22902 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22903 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22904 // If the RHS is a constant we have to reverse the const
22905 // canonicalization.
22906 // x > C-1 ? x+-C : 0 --> subus x, C
22907 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22908 CondRHSConst->getAPIntValue() ==
22909 (-OpRHSConst->getAPIntValue() - 1))
22910 return DAG.getNode(
22911 X86ISD::SUBUS, DL, VT, OpLHS,
22912 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22914 // Another special case: If C was a sign bit, the sub has been
22915 // canonicalized into a xor.
22916 // FIXME: Would it be better to use computeKnownBits to determine
22917 // whether it's safe to decanonicalize the xor?
22918 // x s< 0 ? x^C : 0 --> subus x, C
22919 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22920 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22921 OpRHSConst->getAPIntValue().isSignBit())
22922 // Note that we have to rebuild the RHS constant here to ensure we
22923 // don't rely on particular values of undef lanes.
22924 return DAG.getNode(
22925 X86ISD::SUBUS, DL, VT, OpLHS,
22926 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22931 // Simplify vector selection if condition value type matches vselect
22933 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22934 assert(Cond.getValueType().isVector() &&
22935 "vector select expects a vector selector!");
22937 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22938 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22940 // Try invert the condition if true value is not all 1s and false value
22942 if (!TValIsAllOnes && !FValIsAllZeros &&
22943 // Check if the selector will be produced by CMPP*/PCMP*
22944 Cond.getOpcode() == ISD::SETCC &&
22945 // Check if SETCC has already been promoted
22946 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22948 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22949 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22951 if (TValIsAllZeros || FValIsAllOnes) {
22952 SDValue CC = Cond.getOperand(2);
22953 ISD::CondCode NewCC =
22954 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22955 Cond.getOperand(0).getValueType().isInteger());
22956 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22957 std::swap(LHS, RHS);
22958 TValIsAllOnes = FValIsAllOnes;
22959 FValIsAllZeros = TValIsAllZeros;
22963 if (TValIsAllOnes || FValIsAllZeros) {
22966 if (TValIsAllOnes && FValIsAllZeros)
22968 else if (TValIsAllOnes)
22970 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22971 else if (FValIsAllZeros)
22972 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22973 DAG.getBitcast(CondVT, LHS));
22975 return DAG.getBitcast(VT, Ret);
22979 // We should generate an X86ISD::BLENDI from a vselect if its argument
22980 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22981 // constants. This specific pattern gets generated when we split a
22982 // selector for a 512 bit vector in a machine without AVX512 (but with
22983 // 256-bit vectors), during legalization:
22985 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22987 // Iff we find this pattern and the build_vectors are built from
22988 // constants, we translate the vselect into a shuffle_vector that we
22989 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22990 if ((N->getOpcode() == ISD::VSELECT ||
22991 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22992 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22993 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22994 if (Shuffle.getNode())
22998 // If this is a *dynamic* select (non-constant condition) and we can match
22999 // this node with one of the variable blend instructions, restructure the
23000 // condition so that the blends can use the high bit of each element and use
23001 // SimplifyDemandedBits to simplify the condition operand.
23002 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23003 !DCI.isBeforeLegalize() &&
23004 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23005 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23007 // Don't optimize vector selects that map to mask-registers.
23011 // We can only handle the cases where VSELECT is directly legal on the
23012 // subtarget. We custom lower VSELECT nodes with constant conditions and
23013 // this makes it hard to see whether a dynamic VSELECT will correctly
23014 // lower, so we both check the operation's status and explicitly handle the
23015 // cases where a *dynamic* blend will fail even though a constant-condition
23016 // blend could be custom lowered.
23017 // FIXME: We should find a better way to handle this class of problems.
23018 // Potentially, we should combine constant-condition vselect nodes
23019 // pre-legalization into shuffles and not mark as many types as custom
23021 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23023 // FIXME: We don't support i16-element blends currently. We could and
23024 // should support them by making *all* the bits in the condition be set
23025 // rather than just the high bit and using an i8-element blend.
23026 if (VT.getScalarType() == MVT::i16)
23028 // Dynamic blending was only available from SSE4.1 onward.
23029 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23031 // Byte blends are only available in AVX2
23032 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23033 !Subtarget->hasAVX2())
23036 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23037 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23039 APInt KnownZero, KnownOne;
23040 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23041 DCI.isBeforeLegalizeOps());
23042 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23043 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23045 // If we changed the computation somewhere in the DAG, this change
23046 // will affect all users of Cond.
23047 // Make sure it is fine and update all the nodes so that we do not
23048 // use the generic VSELECT anymore. Otherwise, we may perform
23049 // wrong optimizations as we messed up with the actual expectation
23050 // for the vector boolean values.
23051 if (Cond != TLO.Old) {
23052 // Check all uses of that condition operand to check whether it will be
23053 // consumed by non-BLEND instructions, which may depend on all bits are
23055 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23057 if (I->getOpcode() != ISD::VSELECT)
23058 // TODO: Add other opcodes eventually lowered into BLEND.
23061 // Update all the users of the condition, before committing the change,
23062 // so that the VSELECT optimizations that expect the correct vector
23063 // boolean value will not be triggered.
23064 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23066 DAG.ReplaceAllUsesOfValueWith(
23068 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23069 Cond, I->getOperand(1), I->getOperand(2)));
23070 DCI.CommitTargetLoweringOpt(TLO);
23073 // At this point, only Cond is changed. Change the condition
23074 // just for N to keep the opportunity to optimize all other
23075 // users their own way.
23076 DAG.ReplaceAllUsesOfValueWith(
23078 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23079 TLO.New, N->getOperand(1), N->getOperand(2)));
23087 // Check whether a boolean test is testing a boolean value generated by
23088 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23091 // Simplify the following patterns:
23092 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23093 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23094 // to (Op EFLAGS Cond)
23096 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23097 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23098 // to (Op EFLAGS !Cond)
23100 // where Op could be BRCOND or CMOV.
23102 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23103 // Quit if not CMP and SUB with its value result used.
23104 if (Cmp.getOpcode() != X86ISD::CMP &&
23105 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23108 // Quit if not used as a boolean value.
23109 if (CC != X86::COND_E && CC != X86::COND_NE)
23112 // Check CMP operands. One of them should be 0 or 1 and the other should be
23113 // an SetCC or extended from it.
23114 SDValue Op1 = Cmp.getOperand(0);
23115 SDValue Op2 = Cmp.getOperand(1);
23118 const ConstantSDNode* C = nullptr;
23119 bool needOppositeCond = (CC == X86::COND_E);
23120 bool checkAgainstTrue = false; // Is it a comparison against 1?
23122 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23124 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23126 else // Quit if all operands are not constants.
23129 if (C->getZExtValue() == 1) {
23130 needOppositeCond = !needOppositeCond;
23131 checkAgainstTrue = true;
23132 } else if (C->getZExtValue() != 0)
23133 // Quit if the constant is neither 0 or 1.
23136 bool truncatedToBoolWithAnd = false;
23137 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23138 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23139 SetCC.getOpcode() == ISD::TRUNCATE ||
23140 SetCC.getOpcode() == ISD::AND) {
23141 if (SetCC.getOpcode() == ISD::AND) {
23143 ConstantSDNode *CS;
23144 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23145 CS->getZExtValue() == 1)
23147 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23148 CS->getZExtValue() == 1)
23152 SetCC = SetCC.getOperand(OpIdx);
23153 truncatedToBoolWithAnd = true;
23155 SetCC = SetCC.getOperand(0);
23158 switch (SetCC.getOpcode()) {
23159 case X86ISD::SETCC_CARRY:
23160 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23161 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23162 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23163 // truncated to i1 using 'and'.
23164 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23166 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23167 "Invalid use of SETCC_CARRY!");
23169 case X86ISD::SETCC:
23170 // Set the condition code or opposite one if necessary.
23171 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23172 if (needOppositeCond)
23173 CC = X86::GetOppositeBranchCondition(CC);
23174 return SetCC.getOperand(1);
23175 case X86ISD::CMOV: {
23176 // Check whether false/true value has canonical one, i.e. 0 or 1.
23177 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23178 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23179 // Quit if true value is not a constant.
23182 // Quit if false value is not a constant.
23184 SDValue Op = SetCC.getOperand(0);
23185 // Skip 'zext' or 'trunc' node.
23186 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23187 Op.getOpcode() == ISD::TRUNCATE)
23188 Op = Op.getOperand(0);
23189 // A special case for rdrand/rdseed, where 0 is set if false cond is
23191 if ((Op.getOpcode() != X86ISD::RDRAND &&
23192 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23195 // Quit if false value is not the constant 0 or 1.
23196 bool FValIsFalse = true;
23197 if (FVal && FVal->getZExtValue() != 0) {
23198 if (FVal->getZExtValue() != 1)
23200 // If FVal is 1, opposite cond is needed.
23201 needOppositeCond = !needOppositeCond;
23202 FValIsFalse = false;
23204 // Quit if TVal is not the constant opposite of FVal.
23205 if (FValIsFalse && TVal->getZExtValue() != 1)
23207 if (!FValIsFalse && TVal->getZExtValue() != 0)
23209 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23210 if (needOppositeCond)
23211 CC = X86::GetOppositeBranchCondition(CC);
23212 return SetCC.getOperand(3);
23219 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23221 /// (X86or (X86setcc) (X86setcc))
23222 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23223 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23224 X86::CondCode &CC1, SDValue &Flags,
23226 if (Cond->getOpcode() == X86ISD::CMP) {
23227 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23228 if (!CondOp1C || !CondOp1C->isNullValue())
23231 Cond = Cond->getOperand(0);
23236 SDValue SetCC0, SetCC1;
23237 switch (Cond->getOpcode()) {
23238 default: return false;
23245 SetCC0 = Cond->getOperand(0);
23246 SetCC1 = Cond->getOperand(1);
23250 // Make sure we have SETCC nodes, using the same flags value.
23251 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23252 SetCC1.getOpcode() != X86ISD::SETCC ||
23253 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23256 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23257 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23258 Flags = SetCC0->getOperand(1);
23262 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23263 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23264 TargetLowering::DAGCombinerInfo &DCI,
23265 const X86Subtarget *Subtarget) {
23268 // If the flag operand isn't dead, don't touch this CMOV.
23269 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23272 SDValue FalseOp = N->getOperand(0);
23273 SDValue TrueOp = N->getOperand(1);
23274 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23275 SDValue Cond = N->getOperand(3);
23277 if (CC == X86::COND_E || CC == X86::COND_NE) {
23278 switch (Cond.getOpcode()) {
23282 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23283 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23284 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23290 Flags = checkBoolTestSetCCCombine(Cond, CC);
23291 if (Flags.getNode() &&
23292 // Extra check as FCMOV only supports a subset of X86 cond.
23293 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23294 SDValue Ops[] = { FalseOp, TrueOp,
23295 DAG.getConstant(CC, DL, MVT::i8), Flags };
23296 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23299 // If this is a select between two integer constants, try to do some
23300 // optimizations. Note that the operands are ordered the opposite of SELECT
23302 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23303 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23304 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23305 // larger than FalseC (the false value).
23306 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23307 CC = X86::GetOppositeBranchCondition(CC);
23308 std::swap(TrueC, FalseC);
23309 std::swap(TrueOp, FalseOp);
23312 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23313 // This is efficient for any integer data type (including i8/i16) and
23315 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23316 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23317 DAG.getConstant(CC, DL, MVT::i8), Cond);
23319 // Zero extend the condition if needed.
23320 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23322 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23323 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23324 DAG.getConstant(ShAmt, DL, MVT::i8));
23325 if (N->getNumValues() == 2) // Dead flag value?
23326 return DCI.CombineTo(N, Cond, SDValue());
23330 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23331 // for any integer data type, including i8/i16.
23332 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23333 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23334 DAG.getConstant(CC, DL, MVT::i8), Cond);
23336 // Zero extend the condition if needed.
23337 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23338 FalseC->getValueType(0), Cond);
23339 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23340 SDValue(FalseC, 0));
23342 if (N->getNumValues() == 2) // Dead flag value?
23343 return DCI.CombineTo(N, Cond, SDValue());
23347 // Optimize cases that will turn into an LEA instruction. This requires
23348 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23349 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23350 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23351 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23353 bool isFastMultiplier = false;
23355 switch ((unsigned char)Diff) {
23357 case 1: // result = add base, cond
23358 case 2: // result = lea base( , cond*2)
23359 case 3: // result = lea base(cond, cond*2)
23360 case 4: // result = lea base( , cond*4)
23361 case 5: // result = lea base(cond, cond*4)
23362 case 8: // result = lea base( , cond*8)
23363 case 9: // result = lea base(cond, cond*8)
23364 isFastMultiplier = true;
23369 if (isFastMultiplier) {
23370 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23371 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23372 DAG.getConstant(CC, DL, MVT::i8), Cond);
23373 // Zero extend the condition if needed.
23374 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23376 // Scale the condition by the difference.
23378 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23379 DAG.getConstant(Diff, DL, Cond.getValueType()));
23381 // Add the base if non-zero.
23382 if (FalseC->getAPIntValue() != 0)
23383 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23384 SDValue(FalseC, 0));
23385 if (N->getNumValues() == 2) // Dead flag value?
23386 return DCI.CombineTo(N, Cond, SDValue());
23393 // Handle these cases:
23394 // (select (x != c), e, c) -> select (x != c), e, x),
23395 // (select (x == c), c, e) -> select (x == c), x, e)
23396 // where the c is an integer constant, and the "select" is the combination
23397 // of CMOV and CMP.
23399 // The rationale for this change is that the conditional-move from a constant
23400 // needs two instructions, however, conditional-move from a register needs
23401 // only one instruction.
23403 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23404 // some instruction-combining opportunities. This opt needs to be
23405 // postponed as late as possible.
23407 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23408 // the DCI.xxxx conditions are provided to postpone the optimization as
23409 // late as possible.
23411 ConstantSDNode *CmpAgainst = nullptr;
23412 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23413 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23414 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23416 if (CC == X86::COND_NE &&
23417 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23418 CC = X86::GetOppositeBranchCondition(CC);
23419 std::swap(TrueOp, FalseOp);
23422 if (CC == X86::COND_E &&
23423 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23424 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23425 DAG.getConstant(CC, DL, MVT::i8), Cond };
23426 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23431 // Fold and/or of setcc's to double CMOV:
23432 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23433 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23435 // This combine lets us generate:
23436 // cmovcc1 (jcc1 if we don't have CMOV)
23442 // cmovne (jne if we don't have CMOV)
23443 // When we can't use the CMOV instruction, it might increase branch
23445 // When we can use CMOV, or when there is no mispredict, this improves
23446 // throughput and reduces register pressure.
23448 if (CC == X86::COND_NE) {
23450 X86::CondCode CC0, CC1;
23452 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23454 std::swap(FalseOp, TrueOp);
23455 CC0 = X86::GetOppositeBranchCondition(CC0);
23456 CC1 = X86::GetOppositeBranchCondition(CC1);
23459 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23461 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23462 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23463 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23464 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23472 /// PerformMulCombine - Optimize a single multiply with constant into two
23473 /// in order to implement it with two cheaper instructions, e.g.
23474 /// LEA + SHL, LEA + LEA.
23475 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23476 TargetLowering::DAGCombinerInfo &DCI) {
23477 // An imul is usually smaller than the alternative sequence.
23478 if (DAG.getMachineFunction().getFunction()->optForMinSize())
23481 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23484 EVT VT = N->getValueType(0);
23485 if (VT != MVT::i64 && VT != MVT::i32)
23488 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23491 uint64_t MulAmt = C->getZExtValue();
23492 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23495 uint64_t MulAmt1 = 0;
23496 uint64_t MulAmt2 = 0;
23497 if ((MulAmt % 9) == 0) {
23499 MulAmt2 = MulAmt / 9;
23500 } else if ((MulAmt % 5) == 0) {
23502 MulAmt2 = MulAmt / 5;
23503 } else if ((MulAmt % 3) == 0) {
23505 MulAmt2 = MulAmt / 3;
23508 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23511 if (isPowerOf2_64(MulAmt2) &&
23512 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23513 // If second multiplifer is pow2, issue it first. We want the multiply by
23514 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23516 std::swap(MulAmt1, MulAmt2);
23519 if (isPowerOf2_64(MulAmt1))
23520 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23521 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23523 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23524 DAG.getConstant(MulAmt1, DL, VT));
23526 if (isPowerOf2_64(MulAmt2))
23527 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23528 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23530 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23531 DAG.getConstant(MulAmt2, DL, VT));
23533 // Do not add new nodes to DAG combiner worklist.
23534 DCI.CombineTo(N, NewMul, false);
23539 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23540 SDValue N0 = N->getOperand(0);
23541 SDValue N1 = N->getOperand(1);
23542 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23543 EVT VT = N0.getValueType();
23545 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23546 // since the result of setcc_c is all zero's or all ones.
23547 if (VT.isInteger() && !VT.isVector() &&
23548 N1C && N0.getOpcode() == ISD::AND &&
23549 N0.getOperand(1).getOpcode() == ISD::Constant) {
23550 SDValue N00 = N0.getOperand(0);
23551 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23552 APInt ShAmt = N1C->getAPIntValue();
23553 Mask = Mask.shl(ShAmt);
23554 bool MaskOK = false;
23555 // We can handle cases concerning bit-widening nodes containing setcc_c if
23556 // we carefully interrogate the mask to make sure we are semantics
23558 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23559 // of the underlying setcc_c operation if the setcc_c was zero extended.
23560 // Consider the following example:
23561 // zext(setcc_c) -> i32 0x0000FFFF
23562 // c1 -> i32 0x0000FFFF
23563 // c2 -> i32 0x00000001
23564 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23565 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
23566 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23568 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23569 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23571 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23572 N00.getOpcode() == ISD::ANY_EXTEND) &&
23573 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23574 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23576 if (MaskOK && Mask != 0) {
23578 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23582 // Hardware support for vector shifts is sparse which makes us scalarize the
23583 // vector operations in many cases. Also, on sandybridge ADD is faster than
23585 // (shl V, 1) -> add V,V
23586 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23587 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23588 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23589 // We shift all of the values by one. In many cases we do not have
23590 // hardware support for this operation. This is better expressed as an ADD
23592 if (N1SplatC->getAPIntValue() == 1)
23593 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23599 /// \brief Returns a vector of 0s if the node in input is a vector logical
23600 /// shift by a constant amount which is known to be bigger than or equal
23601 /// to the vector element size in bits.
23602 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23603 const X86Subtarget *Subtarget) {
23604 EVT VT = N->getValueType(0);
23606 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23607 (!Subtarget->hasInt256() ||
23608 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23611 SDValue Amt = N->getOperand(1);
23613 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23614 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23615 APInt ShiftAmt = AmtSplat->getAPIntValue();
23616 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23618 // SSE2/AVX2 logical shifts always return a vector of 0s
23619 // if the shift amount is bigger than or equal to
23620 // the element size. The constant shift amount will be
23621 // encoded as a 8-bit immediate.
23622 if (ShiftAmt.trunc(8).uge(MaxAmount))
23623 return getZeroVector(VT, Subtarget, DAG, DL);
23629 /// PerformShiftCombine - Combine shifts.
23630 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23631 TargetLowering::DAGCombinerInfo &DCI,
23632 const X86Subtarget *Subtarget) {
23633 if (N->getOpcode() == ISD::SHL)
23634 if (SDValue V = PerformSHLCombine(N, DAG))
23637 // Try to fold this logical shift into a zero vector.
23638 if (N->getOpcode() != ISD::SRA)
23639 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23645 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23646 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23647 // and friends. Likewise for OR -> CMPNEQSS.
23648 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23649 TargetLowering::DAGCombinerInfo &DCI,
23650 const X86Subtarget *Subtarget) {
23653 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23654 // we're requiring SSE2 for both.
23655 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23656 SDValue N0 = N->getOperand(0);
23657 SDValue N1 = N->getOperand(1);
23658 SDValue CMP0 = N0->getOperand(1);
23659 SDValue CMP1 = N1->getOperand(1);
23662 // The SETCCs should both refer to the same CMP.
23663 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23666 SDValue CMP00 = CMP0->getOperand(0);
23667 SDValue CMP01 = CMP0->getOperand(1);
23668 EVT VT = CMP00.getValueType();
23670 if (VT == MVT::f32 || VT == MVT::f64) {
23671 bool ExpectingFlags = false;
23672 // Check for any users that want flags:
23673 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23674 !ExpectingFlags && UI != UE; ++UI)
23675 switch (UI->getOpcode()) {
23680 ExpectingFlags = true;
23682 case ISD::CopyToReg:
23683 case ISD::SIGN_EXTEND:
23684 case ISD::ZERO_EXTEND:
23685 case ISD::ANY_EXTEND:
23689 if (!ExpectingFlags) {
23690 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23691 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23693 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23694 X86::CondCode tmp = cc0;
23699 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23700 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23701 // FIXME: need symbolic constants for these magic numbers.
23702 // See X86ATTInstPrinter.cpp:printSSECC().
23703 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23704 if (Subtarget->hasAVX512()) {
23705 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23707 DAG.getConstant(x86cc, DL, MVT::i8));
23708 if (N->getValueType(0) != MVT::i1)
23709 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23713 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23714 CMP00.getValueType(), CMP00, CMP01,
23715 DAG.getConstant(x86cc, DL,
23718 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23719 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23721 if (is64BitFP && !Subtarget->is64Bit()) {
23722 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23723 // 64-bit integer, since that's not a legal type. Since
23724 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23725 // bits, but can do this little dance to extract the lowest 32 bits
23726 // and work with those going forward.
23727 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23729 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23730 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23731 Vector32, DAG.getIntPtrConstant(0, DL));
23735 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23736 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23737 DAG.getConstant(1, DL, IntVT));
23738 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23740 return OneBitOfTruth;
23748 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23749 /// so it can be folded inside ANDNP.
23750 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23751 EVT VT = N->getValueType(0);
23753 // Match direct AllOnes for 128 and 256-bit vectors
23754 if (ISD::isBuildVectorAllOnes(N))
23757 // Look through a bit convert.
23758 if (N->getOpcode() == ISD::BITCAST)
23759 N = N->getOperand(0).getNode();
23761 // Sometimes the operand may come from a insert_subvector building a 256-bit
23763 if (VT.is256BitVector() &&
23764 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23765 SDValue V1 = N->getOperand(0);
23766 SDValue V2 = N->getOperand(1);
23768 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23769 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23770 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23771 ISD::isBuildVectorAllOnes(V2.getNode()))
23778 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23779 // register. In most cases we actually compare or select YMM-sized registers
23780 // and mixing the two types creates horrible code. This method optimizes
23781 // some of the transition sequences.
23782 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23783 TargetLowering::DAGCombinerInfo &DCI,
23784 const X86Subtarget *Subtarget) {
23785 EVT VT = N->getValueType(0);
23786 if (!VT.is256BitVector())
23789 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23790 N->getOpcode() == ISD::ZERO_EXTEND ||
23791 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23793 SDValue Narrow = N->getOperand(0);
23794 EVT NarrowVT = Narrow->getValueType(0);
23795 if (!NarrowVT.is128BitVector())
23798 if (Narrow->getOpcode() != ISD::XOR &&
23799 Narrow->getOpcode() != ISD::AND &&
23800 Narrow->getOpcode() != ISD::OR)
23803 SDValue N0 = Narrow->getOperand(0);
23804 SDValue N1 = Narrow->getOperand(1);
23807 // The Left side has to be a trunc.
23808 if (N0.getOpcode() != ISD::TRUNCATE)
23811 // The type of the truncated inputs.
23812 EVT WideVT = N0->getOperand(0)->getValueType(0);
23816 // The right side has to be a 'trunc' or a constant vector.
23817 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23818 ConstantSDNode *RHSConstSplat = nullptr;
23819 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23820 RHSConstSplat = RHSBV->getConstantSplatNode();
23821 if (!RHSTrunc && !RHSConstSplat)
23824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23826 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23829 // Set N0 and N1 to hold the inputs to the new wide operation.
23830 N0 = N0->getOperand(0);
23831 if (RHSConstSplat) {
23832 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23833 SDValue(RHSConstSplat, 0));
23834 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23835 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23836 } else if (RHSTrunc) {
23837 N1 = N1->getOperand(0);
23840 // Generate the wide operation.
23841 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23842 unsigned Opcode = N->getOpcode();
23844 case ISD::ANY_EXTEND:
23846 case ISD::ZERO_EXTEND: {
23847 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23848 APInt Mask = APInt::getAllOnesValue(InBits);
23849 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23850 return DAG.getNode(ISD::AND, DL, VT,
23851 Op, DAG.getConstant(Mask, DL, VT));
23853 case ISD::SIGN_EXTEND:
23854 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23855 Op, DAG.getValueType(NarrowVT));
23857 llvm_unreachable("Unexpected opcode");
23861 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23862 TargetLowering::DAGCombinerInfo &DCI,
23863 const X86Subtarget *Subtarget) {
23864 SDValue N0 = N->getOperand(0);
23865 SDValue N1 = N->getOperand(1);
23868 // A vector zext_in_reg may be represented as a shuffle,
23869 // feeding into a bitcast (this represents anyext) feeding into
23870 // an and with a mask.
23871 // We'd like to try to combine that into a shuffle with zero
23872 // plus a bitcast, removing the and.
23873 if (N0.getOpcode() != ISD::BITCAST ||
23874 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23877 // The other side of the AND should be a splat of 2^C, where C
23878 // is the number of bits in the source type.
23879 if (N1.getOpcode() == ISD::BITCAST)
23880 N1 = N1.getOperand(0);
23881 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23883 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23885 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23886 EVT SrcType = Shuffle->getValueType(0);
23888 // We expect a single-source shuffle
23889 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23892 unsigned SrcSize = SrcType.getScalarSizeInBits();
23894 APInt SplatValue, SplatUndef;
23895 unsigned SplatBitSize;
23897 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23898 SplatBitSize, HasAnyUndefs))
23901 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23902 // Make sure the splat matches the mask we expect
23903 if (SplatBitSize > ResSize ||
23904 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23907 // Make sure the input and output size make sense
23908 if (SrcSize >= ResSize || ResSize % SrcSize)
23911 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23912 // The number of u's between each two values depends on the ratio between
23913 // the source and dest type.
23914 unsigned ZextRatio = ResSize / SrcSize;
23915 bool IsZext = true;
23916 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23917 if (i % ZextRatio) {
23918 if (Shuffle->getMaskElt(i) > 0) {
23924 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23925 // Expected element number
23935 // Ok, perform the transformation - replace the shuffle with
23936 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23937 // (instead of undef) where the k elements come from the zero vector.
23938 SmallVector<int, 8> Mask;
23939 unsigned NumElems = SrcType.getVectorNumElements();
23940 for (unsigned i = 0; i < NumElems; ++i)
23942 Mask.push_back(NumElems);
23944 Mask.push_back(i / ZextRatio);
23946 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23947 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23948 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23951 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23952 TargetLowering::DAGCombinerInfo &DCI,
23953 const X86Subtarget *Subtarget) {
23954 if (DCI.isBeforeLegalizeOps())
23957 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23960 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23963 EVT VT = N->getValueType(0);
23964 SDValue N0 = N->getOperand(0);
23965 SDValue N1 = N->getOperand(1);
23968 // Create BEXTR instructions
23969 // BEXTR is ((X >> imm) & (2**size-1))
23970 if (VT == MVT::i32 || VT == MVT::i64) {
23971 // Check for BEXTR.
23972 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23973 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23974 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23975 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23976 if (MaskNode && ShiftNode) {
23977 uint64_t Mask = MaskNode->getZExtValue();
23978 uint64_t Shift = ShiftNode->getZExtValue();
23979 if (isMask_64(Mask)) {
23980 uint64_t MaskSize = countPopulation(Mask);
23981 if (Shift + MaskSize <= VT.getSizeInBits())
23982 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23983 DAG.getConstant(Shift | (MaskSize << 8), DL,
23992 // Want to form ANDNP nodes:
23993 // 1) In the hopes of then easily combining them with OR and AND nodes
23994 // to form PBLEND/PSIGN.
23995 // 2) To match ANDN packed intrinsics
23996 if (VT != MVT::v2i64 && VT != MVT::v4i64)
23999 // Check LHS for vnot
24000 if (N0.getOpcode() == ISD::XOR &&
24001 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24002 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24003 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24005 // Check RHS for vnot
24006 if (N1.getOpcode() == ISD::XOR &&
24007 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24008 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24009 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24014 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24015 TargetLowering::DAGCombinerInfo &DCI,
24016 const X86Subtarget *Subtarget) {
24017 if (DCI.isBeforeLegalizeOps())
24020 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24023 SDValue N0 = N->getOperand(0);
24024 SDValue N1 = N->getOperand(1);
24025 EVT VT = N->getValueType(0);
24027 // look for psign/blend
24028 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24029 if (!Subtarget->hasSSSE3() ||
24030 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24033 // Canonicalize pandn to RHS
24034 if (N0.getOpcode() == X86ISD::ANDNP)
24036 // or (and (m, y), (pandn m, x))
24037 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24038 SDValue Mask = N1.getOperand(0);
24039 SDValue X = N1.getOperand(1);
24041 if (N0.getOperand(0) == Mask)
24042 Y = N0.getOperand(1);
24043 if (N0.getOperand(1) == Mask)
24044 Y = N0.getOperand(0);
24046 // Check to see if the mask appeared in both the AND and ANDNP and
24050 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24051 // Look through mask bitcast.
24052 if (Mask.getOpcode() == ISD::BITCAST)
24053 Mask = Mask.getOperand(0);
24054 if (X.getOpcode() == ISD::BITCAST)
24055 X = X.getOperand(0);
24056 if (Y.getOpcode() == ISD::BITCAST)
24057 Y = Y.getOperand(0);
24059 EVT MaskVT = Mask.getValueType();
24061 // Validate that the Mask operand is a vector sra node.
24062 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24063 // there is no psrai.b
24064 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24065 unsigned SraAmt = ~0;
24066 if (Mask.getOpcode() == ISD::SRA) {
24067 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24068 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24069 SraAmt = AmtConst->getZExtValue();
24070 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24071 SDValue SraC = Mask.getOperand(1);
24072 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24074 if ((SraAmt + 1) != EltBits)
24079 // Now we know we at least have a plendvb with the mask val. See if
24080 // we can form a psignb/w/d.
24081 // psign = x.type == y.type == mask.type && y = sub(0, x);
24082 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24083 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24084 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24085 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24086 "Unsupported VT for PSIGN");
24087 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24088 return DAG.getBitcast(VT, Mask);
24090 // PBLENDVB only available on SSE 4.1
24091 if (!Subtarget->hasSSE41())
24094 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24096 X = DAG.getBitcast(BlendVT, X);
24097 Y = DAG.getBitcast(BlendVT, Y);
24098 Mask = DAG.getBitcast(BlendVT, Mask);
24099 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24100 return DAG.getBitcast(VT, Mask);
24104 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24107 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24108 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24110 // SHLD/SHRD instructions have lower register pressure, but on some
24111 // platforms they have higher latency than the equivalent
24112 // series of shifts/or that would otherwise be generated.
24113 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24114 // have higher latencies and we are not optimizing for size.
24115 if (!OptForSize && Subtarget->isSHLDSlow())
24118 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24120 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24122 if (!N0.hasOneUse() || !N1.hasOneUse())
24125 SDValue ShAmt0 = N0.getOperand(1);
24126 if (ShAmt0.getValueType() != MVT::i8)
24128 SDValue ShAmt1 = N1.getOperand(1);
24129 if (ShAmt1.getValueType() != MVT::i8)
24131 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24132 ShAmt0 = ShAmt0.getOperand(0);
24133 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24134 ShAmt1 = ShAmt1.getOperand(0);
24137 unsigned Opc = X86ISD::SHLD;
24138 SDValue Op0 = N0.getOperand(0);
24139 SDValue Op1 = N1.getOperand(0);
24140 if (ShAmt0.getOpcode() == ISD::SUB) {
24141 Opc = X86ISD::SHRD;
24142 std::swap(Op0, Op1);
24143 std::swap(ShAmt0, ShAmt1);
24146 unsigned Bits = VT.getSizeInBits();
24147 if (ShAmt1.getOpcode() == ISD::SUB) {
24148 SDValue Sum = ShAmt1.getOperand(0);
24149 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24150 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24151 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24152 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24153 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24154 return DAG.getNode(Opc, DL, VT,
24156 DAG.getNode(ISD::TRUNCATE, DL,
24159 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24160 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24162 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24163 return DAG.getNode(Opc, DL, VT,
24164 N0.getOperand(0), N1.getOperand(0),
24165 DAG.getNode(ISD::TRUNCATE, DL,
24172 // Generate NEG and CMOV for integer abs.
24173 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24174 EVT VT = N->getValueType(0);
24176 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24177 // 8-bit integer abs to NEG and CMOV.
24178 if (VT.isInteger() && VT.getSizeInBits() == 8)
24181 SDValue N0 = N->getOperand(0);
24182 SDValue N1 = N->getOperand(1);
24185 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24186 // and change it to SUB and CMOV.
24187 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24188 N0.getOpcode() == ISD::ADD &&
24189 N0.getOperand(1) == N1 &&
24190 N1.getOpcode() == ISD::SRA &&
24191 N1.getOperand(0) == N0.getOperand(0))
24192 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24193 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24194 // Generate SUB & CMOV.
24195 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24196 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24198 SDValue Ops[] = { N0.getOperand(0), Neg,
24199 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24200 SDValue(Neg.getNode(), 1) };
24201 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24206 // Try to turn tests against the signbit in the form of:
24207 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24210 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24211 // This is only worth doing if the output type is i8.
24212 if (N->getValueType(0) != MVT::i8)
24215 SDValue N0 = N->getOperand(0);
24216 SDValue N1 = N->getOperand(1);
24218 // We should be performing an xor against a truncated shift.
24219 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24222 // Make sure we are performing an xor against one.
24223 if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24226 // SetCC on x86 zero extends so only act on this if it's a logical shift.
24227 SDValue Shift = N0.getOperand(0);
24228 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24231 // Make sure we are truncating from one of i16, i32 or i64.
24232 EVT ShiftTy = Shift.getValueType();
24233 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24236 // Make sure the shift amount extracts the sign bit.
24237 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24238 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24241 // Create a greater-than comparison against -1.
24242 // N.B. Using SETGE against 0 works but we want a canonical looking
24243 // comparison, using SETGT matches up with what TranslateX86CC.
24245 SDValue ShiftOp = Shift.getOperand(0);
24246 EVT ShiftOpTy = ShiftOp.getValueType();
24247 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24248 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24252 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24253 TargetLowering::DAGCombinerInfo &DCI,
24254 const X86Subtarget *Subtarget) {
24255 if (DCI.isBeforeLegalizeOps())
24258 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24261 if (Subtarget->hasCMov())
24262 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24268 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24269 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24270 TargetLowering::DAGCombinerInfo &DCI,
24271 const X86Subtarget *Subtarget) {
24272 LoadSDNode *Ld = cast<LoadSDNode>(N);
24273 EVT RegVT = Ld->getValueType(0);
24274 EVT MemVT = Ld->getMemoryVT();
24276 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24278 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24279 // into two 16-byte operations.
24280 ISD::LoadExtType Ext = Ld->getExtensionType();
24282 unsigned AddressSpace = Ld->getAddressSpace();
24283 unsigned Alignment = Ld->getAlignment();
24284 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24285 Ext == ISD::NON_EXTLOAD &&
24286 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24287 AddressSpace, Alignment, &Fast) && !Fast) {
24288 unsigned NumElems = RegVT.getVectorNumElements();
24292 SDValue Ptr = Ld->getBasePtr();
24293 SDValue Increment =
24294 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24296 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24298 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24299 Ld->getPointerInfo(), Ld->isVolatile(),
24300 Ld->isNonTemporal(), Ld->isInvariant(),
24302 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24303 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24304 Ld->getPointerInfo(), Ld->isVolatile(),
24305 Ld->isNonTemporal(), Ld->isInvariant(),
24306 std::min(16U, Alignment));
24307 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24309 Load2.getValue(1));
24311 SDValue NewVec = DAG.getUNDEF(RegVT);
24312 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24313 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24314 return DCI.CombineTo(N, NewVec, TF, true);
24320 /// PerformMLOADCombine - Resolve extending loads
24321 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24322 TargetLowering::DAGCombinerInfo &DCI,
24323 const X86Subtarget *Subtarget) {
24324 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24325 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24328 EVT VT = Mld->getValueType(0);
24329 unsigned NumElems = VT.getVectorNumElements();
24330 EVT LdVT = Mld->getMemoryVT();
24333 assert(LdVT != VT && "Cannot extend to the same type");
24334 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24335 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24336 // From, To sizes and ElemCount must be pow of two
24337 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24338 "Unexpected size for extending masked load");
24340 unsigned SizeRatio = ToSz / FromSz;
24341 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24343 // Create a type on which we perform the shuffle
24344 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24345 LdVT.getScalarType(), NumElems*SizeRatio);
24346 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24348 // Convert Src0 value
24349 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24350 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24351 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24352 for (unsigned i = 0; i != NumElems; ++i)
24353 ShuffleVec[i] = i * SizeRatio;
24355 // Can't shuffle using an illegal type.
24356 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24357 && "WideVecVT should be legal");
24358 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24359 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24361 // Prepare the new mask
24363 SDValue Mask = Mld->getMask();
24364 if (Mask.getValueType() == VT) {
24365 // Mask and original value have the same type
24366 NewMask = DAG.getBitcast(WideVecVT, Mask);
24367 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24368 for (unsigned i = 0; i != NumElems; ++i)
24369 ShuffleVec[i] = i * SizeRatio;
24370 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24371 ShuffleVec[i] = NumElems*SizeRatio;
24372 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24373 DAG.getConstant(0, dl, WideVecVT),
24377 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24378 unsigned WidenNumElts = NumElems*SizeRatio;
24379 unsigned MaskNumElts = VT.getVectorNumElements();
24380 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24383 unsigned NumConcat = WidenNumElts / MaskNumElts;
24384 SmallVector<SDValue, 16> Ops(NumConcat);
24385 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24387 for (unsigned i = 1; i != NumConcat; ++i)
24390 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24393 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24394 Mld->getBasePtr(), NewMask, WideSrc0,
24395 Mld->getMemoryVT(), Mld->getMemOperand(),
24397 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24398 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24401 /// PerformMSTORECombine - Resolve truncating stores
24402 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24403 const X86Subtarget *Subtarget) {
24404 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24405 if (!Mst->isTruncatingStore())
24408 EVT VT = Mst->getValue().getValueType();
24409 unsigned NumElems = VT.getVectorNumElements();
24410 EVT StVT = Mst->getMemoryVT();
24413 assert(StVT != VT && "Cannot truncate to the same type");
24414 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24415 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24417 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24419 // The truncating store is legal in some cases. For example
24420 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24421 // are designated for truncate store.
24422 // In this case we don't need any further transformations.
24423 if (TLI.isTruncStoreLegal(VT, StVT))
24426 // From, To sizes and ElemCount must be pow of two
24427 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24428 "Unexpected size for truncating masked store");
24429 // We are going to use the original vector elt for storing.
24430 // Accumulated smaller vector elements must be a multiple of the store size.
24431 assert (((NumElems * FromSz) % ToSz) == 0 &&
24432 "Unexpected ratio for truncating masked store");
24434 unsigned SizeRatio = FromSz / ToSz;
24435 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24437 // Create a type on which we perform the shuffle
24438 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24439 StVT.getScalarType(), NumElems*SizeRatio);
24441 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24443 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24444 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24445 for (unsigned i = 0; i != NumElems; ++i)
24446 ShuffleVec[i] = i * SizeRatio;
24448 // Can't shuffle using an illegal type.
24449 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24450 && "WideVecVT should be legal");
24452 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24453 DAG.getUNDEF(WideVecVT),
24457 SDValue Mask = Mst->getMask();
24458 if (Mask.getValueType() == VT) {
24459 // Mask and original value have the same type
24460 NewMask = DAG.getBitcast(WideVecVT, Mask);
24461 for (unsigned i = 0; i != NumElems; ++i)
24462 ShuffleVec[i] = i * SizeRatio;
24463 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24464 ShuffleVec[i] = NumElems*SizeRatio;
24465 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24466 DAG.getConstant(0, dl, WideVecVT),
24470 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24471 unsigned WidenNumElts = NumElems*SizeRatio;
24472 unsigned MaskNumElts = VT.getVectorNumElements();
24473 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24476 unsigned NumConcat = WidenNumElts / MaskNumElts;
24477 SmallVector<SDValue, 16> Ops(NumConcat);
24478 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24480 for (unsigned i = 1; i != NumConcat; ++i)
24483 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24486 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24487 NewMask, StVT, Mst->getMemOperand(), false);
24489 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24490 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24491 const X86Subtarget *Subtarget) {
24492 StoreSDNode *St = cast<StoreSDNode>(N);
24493 EVT VT = St->getValue().getValueType();
24494 EVT StVT = St->getMemoryVT();
24496 SDValue StoredVal = St->getOperand(1);
24497 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24499 // If we are saving a concatenation of two XMM registers and 32-byte stores
24500 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24502 unsigned AddressSpace = St->getAddressSpace();
24503 unsigned Alignment = St->getAlignment();
24504 if (VT.is256BitVector() && StVT == VT &&
24505 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24506 AddressSpace, Alignment, &Fast) && !Fast) {
24507 unsigned NumElems = VT.getVectorNumElements();
24511 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24512 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24515 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24516 SDValue Ptr0 = St->getBasePtr();
24517 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24519 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24520 St->getPointerInfo(), St->isVolatile(),
24521 St->isNonTemporal(), Alignment);
24522 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24523 St->getPointerInfo(), St->isVolatile(),
24524 St->isNonTemporal(),
24525 std::min(16U, Alignment));
24526 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24529 // Optimize trunc store (of multiple scalars) to shuffle and store.
24530 // First, pack all of the elements in one place. Next, store to memory
24531 // in fewer chunks.
24532 if (St->isTruncatingStore() && VT.isVector()) {
24533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24534 unsigned NumElems = VT.getVectorNumElements();
24535 assert(StVT != VT && "Cannot truncate to the same type");
24536 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24537 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24539 // The truncating store is legal in some cases. For example
24540 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24541 // are designated for truncate store.
24542 // In this case we don't need any further transformations.
24543 if (TLI.isTruncStoreLegal(VT, StVT))
24546 // From, To sizes and ElemCount must be pow of two
24547 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24548 // We are going to use the original vector elt for storing.
24549 // Accumulated smaller vector elements must be a multiple of the store size.
24550 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24552 unsigned SizeRatio = FromSz / ToSz;
24554 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24556 // Create a type on which we perform the shuffle
24557 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24558 StVT.getScalarType(), NumElems*SizeRatio);
24560 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24562 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24563 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24564 for (unsigned i = 0; i != NumElems; ++i)
24565 ShuffleVec[i] = i * SizeRatio;
24567 // Can't shuffle using an illegal type.
24568 if (!TLI.isTypeLegal(WideVecVT))
24571 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24572 DAG.getUNDEF(WideVecVT),
24574 // At this point all of the data is stored at the bottom of the
24575 // register. We now need to save it to mem.
24577 // Find the largest store unit
24578 MVT StoreType = MVT::i8;
24579 for (MVT Tp : MVT::integer_valuetypes()) {
24580 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24584 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24585 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24586 (64 <= NumElems * ToSz))
24587 StoreType = MVT::f64;
24589 // Bitcast the original vector into a vector of store-size units
24590 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24591 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24592 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24593 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24594 SmallVector<SDValue, 8> Chains;
24595 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24596 TLI.getPointerTy(DAG.getDataLayout()));
24597 SDValue Ptr = St->getBasePtr();
24599 // Perform one or more big stores into memory.
24600 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24601 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24602 StoreType, ShuffWide,
24603 DAG.getIntPtrConstant(i, dl));
24604 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24605 St->getPointerInfo(), St->isVolatile(),
24606 St->isNonTemporal(), St->getAlignment());
24607 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24608 Chains.push_back(Ch);
24611 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24614 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24615 // the FP state in cases where an emms may be missing.
24616 // A preferable solution to the general problem is to figure out the right
24617 // places to insert EMMS. This qualifies as a quick hack.
24619 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24620 if (VT.getSizeInBits() != 64)
24623 const Function *F = DAG.getMachineFunction().getFunction();
24624 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24626 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24627 if ((VT.isVector() ||
24628 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24629 isa<LoadSDNode>(St->getValue()) &&
24630 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24631 St->getChain().hasOneUse() && !St->isVolatile()) {
24632 SDNode* LdVal = St->getValue().getNode();
24633 LoadSDNode *Ld = nullptr;
24634 int TokenFactorIndex = -1;
24635 SmallVector<SDValue, 8> Ops;
24636 SDNode* ChainVal = St->getChain().getNode();
24637 // Must be a store of a load. We currently handle two cases: the load
24638 // is a direct child, and it's under an intervening TokenFactor. It is
24639 // possible to dig deeper under nested TokenFactors.
24640 if (ChainVal == LdVal)
24641 Ld = cast<LoadSDNode>(St->getChain());
24642 else if (St->getValue().hasOneUse() &&
24643 ChainVal->getOpcode() == ISD::TokenFactor) {
24644 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24645 if (ChainVal->getOperand(i).getNode() == LdVal) {
24646 TokenFactorIndex = i;
24647 Ld = cast<LoadSDNode>(St->getValue());
24649 Ops.push_back(ChainVal->getOperand(i));
24653 if (!Ld || !ISD::isNormalLoad(Ld))
24656 // If this is not the MMX case, i.e. we are just turning i64 load/store
24657 // into f64 load/store, avoid the transformation if there are multiple
24658 // uses of the loaded value.
24659 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24664 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24665 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24667 if (Subtarget->is64Bit() || F64IsLegal) {
24668 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24669 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24670 Ld->getPointerInfo(), Ld->isVolatile(),
24671 Ld->isNonTemporal(), Ld->isInvariant(),
24672 Ld->getAlignment());
24673 SDValue NewChain = NewLd.getValue(1);
24674 if (TokenFactorIndex != -1) {
24675 Ops.push_back(NewChain);
24676 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24678 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24679 St->getPointerInfo(),
24680 St->isVolatile(), St->isNonTemporal(),
24681 St->getAlignment());
24684 // Otherwise, lower to two pairs of 32-bit loads / stores.
24685 SDValue LoAddr = Ld->getBasePtr();
24686 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24687 DAG.getConstant(4, LdDL, MVT::i32));
24689 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24690 Ld->getPointerInfo(),
24691 Ld->isVolatile(), Ld->isNonTemporal(),
24692 Ld->isInvariant(), Ld->getAlignment());
24693 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24694 Ld->getPointerInfo().getWithOffset(4),
24695 Ld->isVolatile(), Ld->isNonTemporal(),
24697 MinAlign(Ld->getAlignment(), 4));
24699 SDValue NewChain = LoLd.getValue(1);
24700 if (TokenFactorIndex != -1) {
24701 Ops.push_back(LoLd);
24702 Ops.push_back(HiLd);
24703 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24706 LoAddr = St->getBasePtr();
24707 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24708 DAG.getConstant(4, StDL, MVT::i32));
24710 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24711 St->getPointerInfo(),
24712 St->isVolatile(), St->isNonTemporal(),
24713 St->getAlignment());
24714 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24715 St->getPointerInfo().getWithOffset(4),
24717 St->isNonTemporal(),
24718 MinAlign(St->getAlignment(), 4));
24719 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24722 // This is similar to the above case, but here we handle a scalar 64-bit
24723 // integer store that is extracted from a vector on a 32-bit target.
24724 // If we have SSE2, then we can treat it like a floating-point double
24725 // to get past legalization. The execution dependencies fixup pass will
24726 // choose the optimal machine instruction for the store if this really is
24727 // an integer or v2f32 rather than an f64.
24728 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24729 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24730 SDValue OldExtract = St->getOperand(1);
24731 SDValue ExtOp0 = OldExtract.getOperand(0);
24732 unsigned VecSize = ExtOp0.getValueSizeInBits();
24733 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24734 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24735 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24736 BitCast, OldExtract.getOperand(1));
24737 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24738 St->getPointerInfo(), St->isVolatile(),
24739 St->isNonTemporal(), St->getAlignment());
24745 /// Return 'true' if this vector operation is "horizontal"
24746 /// and return the operands for the horizontal operation in LHS and RHS. A
24747 /// horizontal operation performs the binary operation on successive elements
24748 /// of its first operand, then on successive elements of its second operand,
24749 /// returning the resulting values in a vector. For example, if
24750 /// A = < float a0, float a1, float a2, float a3 >
24752 /// B = < float b0, float b1, float b2, float b3 >
24753 /// then the result of doing a horizontal operation on A and B is
24754 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24755 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24756 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24757 /// set to A, RHS to B, and the routine returns 'true'.
24758 /// Note that the binary operation should have the property that if one of the
24759 /// operands is UNDEF then the result is UNDEF.
24760 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24761 // Look for the following pattern: if
24762 // A = < float a0, float a1, float a2, float a3 >
24763 // B = < float b0, float b1, float b2, float b3 >
24765 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24766 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24767 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24768 // which is A horizontal-op B.
24770 // At least one of the operands should be a vector shuffle.
24771 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24772 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24775 MVT VT = LHS.getSimpleValueType();
24777 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24778 "Unsupported vector type for horizontal add/sub");
24780 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24781 // operate independently on 128-bit lanes.
24782 unsigned NumElts = VT.getVectorNumElements();
24783 unsigned NumLanes = VT.getSizeInBits()/128;
24784 unsigned NumLaneElts = NumElts / NumLanes;
24785 assert((NumLaneElts % 2 == 0) &&
24786 "Vector type should have an even number of elements in each lane");
24787 unsigned HalfLaneElts = NumLaneElts/2;
24789 // View LHS in the form
24790 // LHS = VECTOR_SHUFFLE A, B, LMask
24791 // If LHS is not a shuffle then pretend it is the shuffle
24792 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24793 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24796 SmallVector<int, 16> LMask(NumElts);
24797 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24798 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24799 A = LHS.getOperand(0);
24800 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24801 B = LHS.getOperand(1);
24802 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24803 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24805 if (LHS.getOpcode() != ISD::UNDEF)
24807 for (unsigned i = 0; i != NumElts; ++i)
24811 // Likewise, view RHS in the form
24812 // RHS = VECTOR_SHUFFLE C, D, RMask
24814 SmallVector<int, 16> RMask(NumElts);
24815 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24816 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24817 C = RHS.getOperand(0);
24818 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24819 D = RHS.getOperand(1);
24820 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24821 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24823 if (RHS.getOpcode() != ISD::UNDEF)
24825 for (unsigned i = 0; i != NumElts; ++i)
24829 // Check that the shuffles are both shuffling the same vectors.
24830 if (!(A == C && B == D) && !(A == D && B == C))
24833 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24834 if (!A.getNode() && !B.getNode())
24837 // If A and B occur in reverse order in RHS, then "swap" them (which means
24838 // rewriting the mask).
24840 ShuffleVectorSDNode::commuteMask(RMask);
24842 // At this point LHS and RHS are equivalent to
24843 // LHS = VECTOR_SHUFFLE A, B, LMask
24844 // RHS = VECTOR_SHUFFLE A, B, RMask
24845 // Check that the masks correspond to performing a horizontal operation.
24846 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24847 for (unsigned i = 0; i != NumLaneElts; ++i) {
24848 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24850 // Ignore any UNDEF components.
24851 if (LIdx < 0 || RIdx < 0 ||
24852 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24853 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24856 // Check that successive elements are being operated on. If not, this is
24857 // not a horizontal operation.
24858 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24859 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24860 if (!(LIdx == Index && RIdx == Index + 1) &&
24861 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24866 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24867 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24871 /// Do target-specific dag combines on floating point adds.
24872 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24873 const X86Subtarget *Subtarget) {
24874 EVT VT = N->getValueType(0);
24875 SDValue LHS = N->getOperand(0);
24876 SDValue RHS = N->getOperand(1);
24878 // Try to synthesize horizontal adds from adds of shuffles.
24879 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24880 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24881 isHorizontalBinOp(LHS, RHS, true))
24882 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24886 /// Do target-specific dag combines on floating point subs.
24887 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24888 const X86Subtarget *Subtarget) {
24889 EVT VT = N->getValueType(0);
24890 SDValue LHS = N->getOperand(0);
24891 SDValue RHS = N->getOperand(1);
24893 // Try to synthesize horizontal subs from subs of shuffles.
24894 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24895 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24896 isHorizontalBinOp(LHS, RHS, false))
24897 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24901 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24902 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24903 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24905 // F[X]OR(0.0, x) -> x
24906 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24907 if (C->getValueAPF().isPosZero())
24908 return N->getOperand(1);
24910 // F[X]OR(x, 0.0) -> x
24911 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24912 if (C->getValueAPF().isPosZero())
24913 return N->getOperand(0);
24917 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24918 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24919 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24921 // Only perform optimizations if UnsafeMath is used.
24922 if (!DAG.getTarget().Options.UnsafeFPMath)
24925 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24926 // into FMINC and FMAXC, which are Commutative operations.
24927 unsigned NewOp = 0;
24928 switch (N->getOpcode()) {
24929 default: llvm_unreachable("unknown opcode");
24930 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24931 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24934 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24935 N->getOperand(0), N->getOperand(1));
24938 /// Do target-specific dag combines on X86ISD::FAND nodes.
24939 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24940 // FAND(0.0, x) -> 0.0
24941 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24942 if (C->getValueAPF().isPosZero())
24943 return N->getOperand(0);
24945 // FAND(x, 0.0) -> 0.0
24946 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24947 if (C->getValueAPF().isPosZero())
24948 return N->getOperand(1);
24953 /// Do target-specific dag combines on X86ISD::FANDN nodes
24954 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24955 // FANDN(0.0, x) -> x
24956 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24957 if (C->getValueAPF().isPosZero())
24958 return N->getOperand(1);
24960 // FANDN(x, 0.0) -> 0.0
24961 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24962 if (C->getValueAPF().isPosZero())
24963 return N->getOperand(1);
24968 static SDValue PerformBTCombine(SDNode *N,
24970 TargetLowering::DAGCombinerInfo &DCI) {
24971 // BT ignores high bits in the bit index operand.
24972 SDValue Op1 = N->getOperand(1);
24973 if (Op1.hasOneUse()) {
24974 unsigned BitWidth = Op1.getValueSizeInBits();
24975 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24976 APInt KnownZero, KnownOne;
24977 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24978 !DCI.isBeforeLegalizeOps());
24979 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24980 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24981 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24982 DCI.CommitTargetLoweringOpt(TLO);
24987 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24988 SDValue Op = N->getOperand(0);
24989 if (Op.getOpcode() == ISD::BITCAST)
24990 Op = Op.getOperand(0);
24991 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24992 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24993 VT.getVectorElementType().getSizeInBits() ==
24994 OpVT.getVectorElementType().getSizeInBits()) {
24995 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25000 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25001 const X86Subtarget *Subtarget) {
25002 EVT VT = N->getValueType(0);
25003 if (!VT.isVector())
25006 SDValue N0 = N->getOperand(0);
25007 SDValue N1 = N->getOperand(1);
25008 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25011 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25012 // both SSE and AVX2 since there is no sign-extended shift right
25013 // operation on a vector with 64-bit elements.
25014 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25015 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25016 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25017 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25018 SDValue N00 = N0.getOperand(0);
25020 // EXTLOAD has a better solution on AVX2,
25021 // it may be replaced with X86ISD::VSEXT node.
25022 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25023 if (!ISD::isNormalLoad(N00.getNode()))
25026 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25027 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25029 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25035 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25036 TargetLowering::DAGCombinerInfo &DCI,
25037 const X86Subtarget *Subtarget) {
25038 SDValue N0 = N->getOperand(0);
25039 EVT VT = N->getValueType(0);
25040 EVT SVT = VT.getScalarType();
25041 EVT InVT = N0.getValueType();
25042 EVT InSVT = InVT.getScalarType();
25045 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25046 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25047 // This exposes the sext to the sdivrem lowering, so that it directly extends
25048 // from AH (which we otherwise need to do contortions to access).
25049 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25050 InVT == MVT::i8 && VT == MVT::i32) {
25051 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25052 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25053 N0.getOperand(0), N0.getOperand(1));
25054 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25055 return R.getValue(1);
25058 if (!DCI.isBeforeLegalizeOps()) {
25059 if (InVT == MVT::i1) {
25060 SDValue Zero = DAG.getConstant(0, DL, VT);
25062 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25063 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25068 if (VT.isVector() && Subtarget->hasSSE2()) {
25069 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25070 EVT InVT = N.getValueType();
25071 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25072 Size / InVT.getScalarSizeInBits());
25073 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25074 DAG.getUNDEF(InVT));
25076 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25079 // If target-size is less than 128-bits, extend to a type that would extend
25080 // to 128 bits, extend that and extract the original target vector.
25081 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25082 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25083 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25084 unsigned Scale = 128 / VT.getSizeInBits();
25086 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25087 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25088 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25089 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25090 DAG.getIntPtrConstant(0, DL));
25093 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25094 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25095 if (VT.getSizeInBits() == 128 &&
25096 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25097 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25098 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25099 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25102 // On pre-AVX2 targets, split into 128-bit nodes of
25103 // ISD::SIGN_EXTEND_VECTOR_INREG.
25104 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25105 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25106 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25107 unsigned NumVecs = VT.getSizeInBits() / 128;
25108 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25109 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25110 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25112 SmallVector<SDValue, 8> Opnds;
25113 for (unsigned i = 0, Offset = 0; i != NumVecs;
25114 ++i, Offset += NumSubElts) {
25115 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25116 DAG.getIntPtrConstant(Offset, DL));
25117 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25118 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25119 Opnds.push_back(SrcVec);
25121 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25125 if (!Subtarget->hasFp256())
25128 if (VT.isVector() && VT.getSizeInBits() == 256)
25129 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25135 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25136 const X86Subtarget* Subtarget) {
25138 EVT VT = N->getValueType(0);
25140 // Let legalize expand this if it isn't a legal type yet.
25141 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25144 EVT ScalarVT = VT.getScalarType();
25145 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25146 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25147 !Subtarget->hasAVX512()))
25150 SDValue A = N->getOperand(0);
25151 SDValue B = N->getOperand(1);
25152 SDValue C = N->getOperand(2);
25154 bool NegA = (A.getOpcode() == ISD::FNEG);
25155 bool NegB = (B.getOpcode() == ISD::FNEG);
25156 bool NegC = (C.getOpcode() == ISD::FNEG);
25158 // Negative multiplication when NegA xor NegB
25159 bool NegMul = (NegA != NegB);
25161 A = A.getOperand(0);
25163 B = B.getOperand(0);
25165 C = C.getOperand(0);
25169 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25171 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25173 return DAG.getNode(Opcode, dl, VT, A, B, C);
25176 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25177 TargetLowering::DAGCombinerInfo &DCI,
25178 const X86Subtarget *Subtarget) {
25179 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25180 // (and (i32 x86isd::setcc_carry), 1)
25181 // This eliminates the zext. This transformation is necessary because
25182 // ISD::SETCC is always legalized to i8.
25184 SDValue N0 = N->getOperand(0);
25185 EVT VT = N->getValueType(0);
25187 if (N0.getOpcode() == ISD::AND &&
25189 N0.getOperand(0).hasOneUse()) {
25190 SDValue N00 = N0.getOperand(0);
25191 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25192 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25193 if (!C || C->getZExtValue() != 1)
25195 return DAG.getNode(ISD::AND, dl, VT,
25196 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25197 N00.getOperand(0), N00.getOperand(1)),
25198 DAG.getConstant(1, dl, VT));
25202 if (N0.getOpcode() == ISD::TRUNCATE &&
25204 N0.getOperand(0).hasOneUse()) {
25205 SDValue N00 = N0.getOperand(0);
25206 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25207 return DAG.getNode(ISD::AND, dl, VT,
25208 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25209 N00.getOperand(0), N00.getOperand(1)),
25210 DAG.getConstant(1, dl, VT));
25214 if (VT.is256BitVector())
25215 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25218 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25219 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25220 // This exposes the zext to the udivrem lowering, so that it directly extends
25221 // from AH (which we otherwise need to do contortions to access).
25222 if (N0.getOpcode() == ISD::UDIVREM &&
25223 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25224 (VT == MVT::i32 || VT == MVT::i64)) {
25225 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25226 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25227 N0.getOperand(0), N0.getOperand(1));
25228 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25229 return R.getValue(1);
25235 // Optimize x == -y --> x+y == 0
25236 // x != -y --> x+y != 0
25237 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25238 const X86Subtarget* Subtarget) {
25239 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25240 SDValue LHS = N->getOperand(0);
25241 SDValue RHS = N->getOperand(1);
25242 EVT VT = N->getValueType(0);
25245 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25246 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25247 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25248 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25249 LHS.getOperand(1));
25250 return DAG.getSetCC(DL, N->getValueType(0), addV,
25251 DAG.getConstant(0, DL, addV.getValueType()), CC);
25253 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25254 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25255 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25256 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25257 RHS.getOperand(1));
25258 return DAG.getSetCC(DL, N->getValueType(0), addV,
25259 DAG.getConstant(0, DL, addV.getValueType()), CC);
25262 if (VT.getScalarType() == MVT::i1 &&
25263 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25265 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25266 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25267 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25269 if (!IsSEXT0 || !IsVZero1) {
25270 // Swap the operands and update the condition code.
25271 std::swap(LHS, RHS);
25272 CC = ISD::getSetCCSwappedOperands(CC);
25274 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25275 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25276 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25279 if (IsSEXT0 && IsVZero1) {
25280 assert(VT == LHS.getOperand(0).getValueType() &&
25281 "Uexpected operand type");
25282 if (CC == ISD::SETGT)
25283 return DAG.getConstant(0, DL, VT);
25284 if (CC == ISD::SETLE)
25285 return DAG.getConstant(1, DL, VT);
25286 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25287 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25289 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25290 "Unexpected condition code!");
25291 return LHS.getOperand(0);
25298 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25299 SelectionDAG &DAG) {
25301 MVT VT = Load->getSimpleValueType(0);
25302 MVT EVT = VT.getVectorElementType();
25303 SDValue Addr = Load->getOperand(1);
25304 SDValue NewAddr = DAG.getNode(
25305 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25306 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25307 Addr.getSimpleValueType()));
25310 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25311 DAG.getMachineFunction().getMachineMemOperand(
25312 Load->getMemOperand(), 0, EVT.getStoreSize()));
25316 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25317 const X86Subtarget *Subtarget) {
25319 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25320 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25321 "X86insertps is only defined for v4x32");
25323 SDValue Ld = N->getOperand(1);
25324 if (MayFoldLoad(Ld)) {
25325 // Extract the countS bits from the immediate so we can get the proper
25326 // address when narrowing the vector load to a specific element.
25327 // When the second source op is a memory address, insertps doesn't use
25328 // countS and just gets an f32 from that address.
25329 unsigned DestIndex =
25330 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25332 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25334 // Create this as a scalar to vector to match the instruction pattern.
25335 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25336 // countS bits are ignored when loading from memory on insertps, which
25337 // means we don't need to explicitly set them to 0.
25338 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25339 LoadScalarToVector, N->getOperand(2));
25344 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25345 SDValue V0 = N->getOperand(0);
25346 SDValue V1 = N->getOperand(1);
25348 EVT VT = N->getValueType(0);
25350 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25351 // operands and changing the mask to 1. This saves us a bunch of
25352 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25353 // x86InstrInfo knows how to commute this back after instruction selection
25354 // if it would help register allocation.
25356 // TODO: If optimizing for size or a processor that doesn't suffer from
25357 // partial register update stalls, this should be transformed into a MOVSD
25358 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25360 if (VT == MVT::v2f64)
25361 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25362 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25363 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25364 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25370 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25371 // as "sbb reg,reg", since it can be extended without zext and produces
25372 // an all-ones bit which is more useful than 0/1 in some cases.
25373 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25376 return DAG.getNode(ISD::AND, DL, VT,
25377 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25378 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25380 DAG.getConstant(1, DL, VT));
25381 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25382 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25383 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25384 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25388 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25389 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25390 TargetLowering::DAGCombinerInfo &DCI,
25391 const X86Subtarget *Subtarget) {
25393 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25394 SDValue EFLAGS = N->getOperand(1);
25396 if (CC == X86::COND_A) {
25397 // Try to convert COND_A into COND_B in an attempt to facilitate
25398 // materializing "setb reg".
25400 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25401 // cannot take an immediate as its first operand.
25403 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25404 EFLAGS.getValueType().isInteger() &&
25405 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25406 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25407 EFLAGS.getNode()->getVTList(),
25408 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25409 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25410 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25414 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25415 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25417 if (CC == X86::COND_B)
25418 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25420 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25421 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25422 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25428 // Optimize branch condition evaluation.
25430 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25431 TargetLowering::DAGCombinerInfo &DCI,
25432 const X86Subtarget *Subtarget) {
25434 SDValue Chain = N->getOperand(0);
25435 SDValue Dest = N->getOperand(1);
25436 SDValue EFLAGS = N->getOperand(3);
25437 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25439 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25440 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25441 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25448 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25449 SelectionDAG &DAG) {
25450 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25451 // optimize away operation when it's from a constant.
25453 // The general transformation is:
25454 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25455 // AND(VECTOR_CMP(x,y), constant2)
25456 // constant2 = UNARYOP(constant)
25458 // Early exit if this isn't a vector operation, the operand of the
25459 // unary operation isn't a bitwise AND, or if the sizes of the operations
25460 // aren't the same.
25461 EVT VT = N->getValueType(0);
25462 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25463 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25464 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25467 // Now check that the other operand of the AND is a constant. We could
25468 // make the transformation for non-constant splats as well, but it's unclear
25469 // that would be a benefit as it would not eliminate any operations, just
25470 // perform one more step in scalar code before moving to the vector unit.
25471 if (BuildVectorSDNode *BV =
25472 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25473 // Bail out if the vector isn't a constant.
25474 if (!BV->isConstant())
25477 // Everything checks out. Build up the new and improved node.
25479 EVT IntVT = BV->getValueType(0);
25480 // Create a new constant of the appropriate type for the transformed
25482 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25483 // The AND node needs bitcasts to/from an integer vector type around it.
25484 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25485 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25486 N->getOperand(0)->getOperand(0), MaskConst);
25487 SDValue Res = DAG.getBitcast(VT, NewAnd);
25494 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25495 const X86Subtarget *Subtarget) {
25496 SDValue Op0 = N->getOperand(0);
25497 EVT VT = N->getValueType(0);
25498 EVT InVT = Op0.getValueType();
25499 EVT InSVT = InVT.getScalarType();
25500 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25502 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25503 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25504 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25506 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25507 InVT.getVectorNumElements());
25508 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25510 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25511 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25513 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25519 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25520 const X86Subtarget *Subtarget) {
25521 // First try to optimize away the conversion entirely when it's
25522 // conditionally from a constant. Vectors only.
25523 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25526 // Now move on to more general possibilities.
25527 SDValue Op0 = N->getOperand(0);
25528 EVT VT = N->getValueType(0);
25529 EVT InVT = Op0.getValueType();
25530 EVT InSVT = InVT.getScalarType();
25532 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25533 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25534 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25536 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25537 InVT.getVectorNumElements());
25538 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25539 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25542 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25543 // a 32-bit target where SSE doesn't support i64->FP operations.
25544 if (Op0.getOpcode() == ISD::LOAD) {
25545 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25546 EVT LdVT = Ld->getValueType(0);
25548 // This transformation is not supported if the result type is f16
25549 if (VT == MVT::f16)
25552 if (!Ld->isVolatile() && !VT.isVector() &&
25553 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25554 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25555 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25556 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25557 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25564 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25565 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25566 X86TargetLowering::DAGCombinerInfo &DCI) {
25567 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25568 // the result is either zero or one (depending on the input carry bit).
25569 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25570 if (X86::isZeroNode(N->getOperand(0)) &&
25571 X86::isZeroNode(N->getOperand(1)) &&
25572 // We don't have a good way to replace an EFLAGS use, so only do this when
25574 SDValue(N, 1).use_empty()) {
25576 EVT VT = N->getValueType(0);
25577 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25578 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25579 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25580 DAG.getConstant(X86::COND_B, DL,
25583 DAG.getConstant(1, DL, VT));
25584 return DCI.CombineTo(N, Res1, CarryOut);
25590 // fold (add Y, (sete X, 0)) -> adc 0, Y
25591 // (add Y, (setne X, 0)) -> sbb -1, Y
25592 // (sub (sete X, 0), Y) -> sbb 0, Y
25593 // (sub (setne X, 0), Y) -> adc -1, Y
25594 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25597 // Look through ZExts.
25598 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25599 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25602 SDValue SetCC = Ext.getOperand(0);
25603 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25606 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25607 if (CC != X86::COND_E && CC != X86::COND_NE)
25610 SDValue Cmp = SetCC.getOperand(1);
25611 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25612 !X86::isZeroNode(Cmp.getOperand(1)) ||
25613 !Cmp.getOperand(0).getValueType().isInteger())
25616 SDValue CmpOp0 = Cmp.getOperand(0);
25617 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25618 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25620 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25621 if (CC == X86::COND_NE)
25622 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25623 DL, OtherVal.getValueType(), OtherVal,
25624 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25626 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25627 DL, OtherVal.getValueType(), OtherVal,
25628 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25631 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25632 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25633 const X86Subtarget *Subtarget) {
25634 EVT VT = N->getValueType(0);
25635 SDValue Op0 = N->getOperand(0);
25636 SDValue Op1 = N->getOperand(1);
25638 // Try to synthesize horizontal adds from adds of shuffles.
25639 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25640 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25641 isHorizontalBinOp(Op0, Op1, true))
25642 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25644 return OptimizeConditionalInDecrement(N, DAG);
25647 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25648 const X86Subtarget *Subtarget) {
25649 SDValue Op0 = N->getOperand(0);
25650 SDValue Op1 = N->getOperand(1);
25652 // X86 can't encode an immediate LHS of a sub. See if we can push the
25653 // negation into a preceding instruction.
25654 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25655 // If the RHS of the sub is a XOR with one use and a constant, invert the
25656 // immediate. Then add one to the LHS of the sub so we can turn
25657 // X-Y -> X+~Y+1, saving one register.
25658 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25659 isa<ConstantSDNode>(Op1.getOperand(1))) {
25660 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25661 EVT VT = Op0.getValueType();
25662 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25664 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25665 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25666 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25670 // Try to synthesize horizontal adds from adds of shuffles.
25671 EVT VT = N->getValueType(0);
25672 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25673 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25674 isHorizontalBinOp(Op0, Op1, true))
25675 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25677 return OptimizeConditionalInDecrement(N, DAG);
25680 /// performVZEXTCombine - Performs build vector combines
25681 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25682 TargetLowering::DAGCombinerInfo &DCI,
25683 const X86Subtarget *Subtarget) {
25685 MVT VT = N->getSimpleValueType(0);
25686 SDValue Op = N->getOperand(0);
25687 MVT OpVT = Op.getSimpleValueType();
25688 MVT OpEltVT = OpVT.getVectorElementType();
25689 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25691 // (vzext (bitcast (vzext (x)) -> (vzext x)
25693 while (V.getOpcode() == ISD::BITCAST)
25694 V = V.getOperand(0);
25696 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25697 MVT InnerVT = V.getSimpleValueType();
25698 MVT InnerEltVT = InnerVT.getVectorElementType();
25700 // If the element sizes match exactly, we can just do one larger vzext. This
25701 // is always an exact type match as vzext operates on integer types.
25702 if (OpEltVT == InnerEltVT) {
25703 assert(OpVT == InnerVT && "Types must match for vzext!");
25704 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25707 // The only other way we can combine them is if only a single element of the
25708 // inner vzext is used in the input to the outer vzext.
25709 if (InnerEltVT.getSizeInBits() < InputBits)
25712 // In this case, the inner vzext is completely dead because we're going to
25713 // only look at bits inside of the low element. Just do the outer vzext on
25714 // a bitcast of the input to the inner.
25715 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25718 // Check if we can bypass extracting and re-inserting an element of an input
25719 // vector. Essentially:
25720 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25721 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25722 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25723 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25724 SDValue ExtractedV = V.getOperand(0);
25725 SDValue OrigV = ExtractedV.getOperand(0);
25726 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25727 if (ExtractIdx->getZExtValue() == 0) {
25728 MVT OrigVT = OrigV.getSimpleValueType();
25729 // Extract a subvector if necessary...
25730 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25731 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25732 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25733 OrigVT.getVectorNumElements() / Ratio);
25734 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25735 DAG.getIntPtrConstant(0, DL));
25737 Op = DAG.getBitcast(OpVT, OrigV);
25738 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25745 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25746 DAGCombinerInfo &DCI) const {
25747 SelectionDAG &DAG = DCI.DAG;
25748 switch (N->getOpcode()) {
25750 case ISD::EXTRACT_VECTOR_ELT:
25751 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25754 case X86ISD::SHRUNKBLEND:
25755 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25756 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25757 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25758 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25759 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25760 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25761 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25764 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25765 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25766 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25767 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25768 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25769 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25770 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25771 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25772 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25773 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25774 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25775 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25777 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25779 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25780 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25781 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25782 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25783 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25784 case ISD::ANY_EXTEND:
25785 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25786 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25787 case ISD::SIGN_EXTEND_INREG:
25788 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25789 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25790 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25791 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25792 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25793 case X86ISD::SHUFP: // Handle all target specific shuffles
25794 case X86ISD::PALIGNR:
25795 case X86ISD::UNPCKH:
25796 case X86ISD::UNPCKL:
25797 case X86ISD::MOVHLPS:
25798 case X86ISD::MOVLHPS:
25799 case X86ISD::PSHUFB:
25800 case X86ISD::PSHUFD:
25801 case X86ISD::PSHUFHW:
25802 case X86ISD::PSHUFLW:
25803 case X86ISD::MOVSS:
25804 case X86ISD::MOVSD:
25805 case X86ISD::VPERMILPI:
25806 case X86ISD::VPERM2X128:
25807 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25808 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25809 case X86ISD::INSERTPS: {
25810 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25811 return PerformINSERTPSCombine(N, DAG, Subtarget);
25814 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25820 /// isTypeDesirableForOp - Return true if the target has native support for
25821 /// the specified value type and it is 'desirable' to use the type for the
25822 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25823 /// instruction encodings are longer and some i16 instructions are slow.
25824 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25825 if (!isTypeLegal(VT))
25827 if (VT != MVT::i16)
25834 case ISD::SIGN_EXTEND:
25835 case ISD::ZERO_EXTEND:
25836 case ISD::ANY_EXTEND:
25849 /// IsDesirableToPromoteOp - This method query the target whether it is
25850 /// beneficial for dag combiner to promote the specified node. If true, it
25851 /// should return the desired promotion type by reference.
25852 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25853 EVT VT = Op.getValueType();
25854 if (VT != MVT::i16)
25857 bool Promote = false;
25858 bool Commute = false;
25859 switch (Op.getOpcode()) {
25862 LoadSDNode *LD = cast<LoadSDNode>(Op);
25863 // If the non-extending load has a single use and it's not live out, then it
25864 // might be folded.
25865 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25866 Op.hasOneUse()*/) {
25867 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25868 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25869 // The only case where we'd want to promote LOAD (rather then it being
25870 // promoted as an operand is when it's only use is liveout.
25871 if (UI->getOpcode() != ISD::CopyToReg)
25878 case ISD::SIGN_EXTEND:
25879 case ISD::ZERO_EXTEND:
25880 case ISD::ANY_EXTEND:
25885 SDValue N0 = Op.getOperand(0);
25886 // Look out for (store (shl (load), x)).
25887 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25900 SDValue N0 = Op.getOperand(0);
25901 SDValue N1 = Op.getOperand(1);
25902 if (!Commute && MayFoldLoad(N1))
25904 // Avoid disabling potential load folding opportunities.
25905 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25907 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25917 //===----------------------------------------------------------------------===//
25918 // X86 Inline Assembly Support
25919 //===----------------------------------------------------------------------===//
25921 // Helper to match a string separated by whitespace.
25922 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25923 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25925 for (StringRef Piece : Pieces) {
25926 if (!S.startswith(Piece)) // Check if the piece matches.
25929 S = S.substr(Piece.size());
25930 StringRef::size_type Pos = S.find_first_not_of(" \t");
25931 if (Pos == 0) // We matched a prefix.
25940 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25942 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25943 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25944 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25945 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25947 if (AsmPieces.size() == 3)
25949 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25956 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25957 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25959 std::string AsmStr = IA->getAsmString();
25961 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25962 if (!Ty || Ty->getBitWidth() % 16 != 0)
25965 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25966 SmallVector<StringRef, 4> AsmPieces;
25967 SplitString(AsmStr, AsmPieces, ";\n");
25969 switch (AsmPieces.size()) {
25970 default: return false;
25972 // FIXME: this should verify that we are targeting a 486 or better. If not,
25973 // we will turn this bswap into something that will be lowered to logical
25974 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25975 // lower so don't worry about this.
25977 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25978 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25979 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25980 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25981 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25982 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25983 // No need to check constraints, nothing other than the equivalent of
25984 // "=r,0" would be valid here.
25985 return IntrinsicLowering::LowerToByteSwap(CI);
25988 // rorw $$8, ${0:w} --> llvm.bswap.i16
25989 if (CI->getType()->isIntegerTy(16) &&
25990 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25991 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25992 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25994 StringRef ConstraintsStr = IA->getConstraintString();
25995 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25996 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25997 if (clobbersFlagRegisters(AsmPieces))
25998 return IntrinsicLowering::LowerToByteSwap(CI);
26002 if (CI->getType()->isIntegerTy(32) &&
26003 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26004 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26005 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26006 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26008 StringRef ConstraintsStr = IA->getConstraintString();
26009 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26010 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26011 if (clobbersFlagRegisters(AsmPieces))
26012 return IntrinsicLowering::LowerToByteSwap(CI);
26015 if (CI->getType()->isIntegerTy(64)) {
26016 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26017 if (Constraints.size() >= 2 &&
26018 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26019 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26020 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
26021 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26022 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26023 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26024 return IntrinsicLowering::LowerToByteSwap(CI);
26032 /// getConstraintType - Given a constraint letter, return the type of
26033 /// constraint it is for this target.
26034 X86TargetLowering::ConstraintType
26035 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26036 if (Constraint.size() == 1) {
26037 switch (Constraint[0]) {
26048 return C_RegisterClass;
26072 return TargetLowering::getConstraintType(Constraint);
26075 /// Examine constraint type and operand type and determine a weight value.
26076 /// This object must already have been set up with the operand type
26077 /// and the current alternative constraint selected.
26078 TargetLowering::ConstraintWeight
26079 X86TargetLowering::getSingleConstraintMatchWeight(
26080 AsmOperandInfo &info, const char *constraint) const {
26081 ConstraintWeight weight = CW_Invalid;
26082 Value *CallOperandVal = info.CallOperandVal;
26083 // If we don't have a value, we can't do a match,
26084 // but allow it at the lowest weight.
26085 if (!CallOperandVal)
26087 Type *type = CallOperandVal->getType();
26088 // Look at the constraint type.
26089 switch (*constraint) {
26091 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26102 if (CallOperandVal->getType()->isIntegerTy())
26103 weight = CW_SpecificReg;
26108 if (type->isFloatingPointTy())
26109 weight = CW_SpecificReg;
26112 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26113 weight = CW_SpecificReg;
26117 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26118 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26119 weight = CW_Register;
26122 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26123 if (C->getZExtValue() <= 31)
26124 weight = CW_Constant;
26128 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26129 if (C->getZExtValue() <= 63)
26130 weight = CW_Constant;
26134 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26135 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26136 weight = CW_Constant;
26140 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26141 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26142 weight = CW_Constant;
26146 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26147 if (C->getZExtValue() <= 3)
26148 weight = CW_Constant;
26152 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26153 if (C->getZExtValue() <= 0xff)
26154 weight = CW_Constant;
26159 if (isa<ConstantFP>(CallOperandVal)) {
26160 weight = CW_Constant;
26164 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26165 if ((C->getSExtValue() >= -0x80000000LL) &&
26166 (C->getSExtValue() <= 0x7fffffffLL))
26167 weight = CW_Constant;
26171 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26172 if (C->getZExtValue() <= 0xffffffff)
26173 weight = CW_Constant;
26180 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26181 /// with another that has more specific requirements based on the type of the
26182 /// corresponding operand.
26183 const char *X86TargetLowering::
26184 LowerXConstraint(EVT ConstraintVT) const {
26185 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26186 // 'f' like normal targets.
26187 if (ConstraintVT.isFloatingPoint()) {
26188 if (Subtarget->hasSSE2())
26190 if (Subtarget->hasSSE1())
26194 return TargetLowering::LowerXConstraint(ConstraintVT);
26197 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26198 /// vector. If it is invalid, don't add anything to Ops.
26199 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26200 std::string &Constraint,
26201 std::vector<SDValue>&Ops,
26202 SelectionDAG &DAG) const {
26205 // Only support length 1 constraints for now.
26206 if (Constraint.length() > 1) return;
26208 char ConstraintLetter = Constraint[0];
26209 switch (ConstraintLetter) {
26212 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26213 if (C->getZExtValue() <= 31) {
26214 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26215 Op.getValueType());
26221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26222 if (C->getZExtValue() <= 63) {
26223 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26224 Op.getValueType());
26230 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26231 if (isInt<8>(C->getSExtValue())) {
26232 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26233 Op.getValueType());
26239 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26240 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26241 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26242 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26243 Op.getValueType());
26249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26250 if (C->getZExtValue() <= 3) {
26251 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26252 Op.getValueType());
26258 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26259 if (C->getZExtValue() <= 255) {
26260 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26261 Op.getValueType());
26267 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26268 if (C->getZExtValue() <= 127) {
26269 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26270 Op.getValueType());
26276 // 32-bit signed value
26277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26278 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26279 C->getSExtValue())) {
26280 // Widen to 64 bits here to get it sign extended.
26281 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26284 // FIXME gcc accepts some relocatable values here too, but only in certain
26285 // memory models; it's complicated.
26290 // 32-bit unsigned value
26291 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26292 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26293 C->getZExtValue())) {
26294 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26295 Op.getValueType());
26299 // FIXME gcc accepts some relocatable values here too, but only in certain
26300 // memory models; it's complicated.
26304 // Literal immediates are always ok.
26305 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26306 // Widen to 64 bits here to get it sign extended.
26307 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26311 // In any sort of PIC mode addresses need to be computed at runtime by
26312 // adding in a register or some sort of table lookup. These can't
26313 // be used as immediates.
26314 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26317 // If we are in non-pic codegen mode, we allow the address of a global (with
26318 // an optional displacement) to be used with 'i'.
26319 GlobalAddressSDNode *GA = nullptr;
26320 int64_t Offset = 0;
26322 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26324 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26325 Offset += GA->getOffset();
26327 } else if (Op.getOpcode() == ISD::ADD) {
26328 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26329 Offset += C->getZExtValue();
26330 Op = Op.getOperand(0);
26333 } else if (Op.getOpcode() == ISD::SUB) {
26334 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26335 Offset += -C->getZExtValue();
26336 Op = Op.getOperand(0);
26341 // Otherwise, this isn't something we can handle, reject it.
26345 const GlobalValue *GV = GA->getGlobal();
26346 // If we require an extra load to get this address, as in PIC mode, we
26347 // can't accept it.
26348 if (isGlobalStubReference(
26349 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26352 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26353 GA->getValueType(0), Offset);
26358 if (Result.getNode()) {
26359 Ops.push_back(Result);
26362 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26365 std::pair<unsigned, const TargetRegisterClass *>
26366 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26367 StringRef Constraint,
26369 // First, see if this is a constraint that directly corresponds to an LLVM
26371 if (Constraint.size() == 1) {
26372 // GCC Constraint Letters
26373 switch (Constraint[0]) {
26375 // TODO: Slight differences here in allocation order and leaving
26376 // RIP in the class. Do they matter any more here than they do
26377 // in the normal allocation?
26378 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26379 if (Subtarget->is64Bit()) {
26380 if (VT == MVT::i32 || VT == MVT::f32)
26381 return std::make_pair(0U, &X86::GR32RegClass);
26382 if (VT == MVT::i16)
26383 return std::make_pair(0U, &X86::GR16RegClass);
26384 if (VT == MVT::i8 || VT == MVT::i1)
26385 return std::make_pair(0U, &X86::GR8RegClass);
26386 if (VT == MVT::i64 || VT == MVT::f64)
26387 return std::make_pair(0U, &X86::GR64RegClass);
26390 // 32-bit fallthrough
26391 case 'Q': // Q_REGS
26392 if (VT == MVT::i32 || VT == MVT::f32)
26393 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26394 if (VT == MVT::i16)
26395 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26396 if (VT == MVT::i8 || VT == MVT::i1)
26397 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26398 if (VT == MVT::i64)
26399 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26401 case 'r': // GENERAL_REGS
26402 case 'l': // INDEX_REGS
26403 if (VT == MVT::i8 || VT == MVT::i1)
26404 return std::make_pair(0U, &X86::GR8RegClass);
26405 if (VT == MVT::i16)
26406 return std::make_pair(0U, &X86::GR16RegClass);
26407 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26408 return std::make_pair(0U, &X86::GR32RegClass);
26409 return std::make_pair(0U, &X86::GR64RegClass);
26410 case 'R': // LEGACY_REGS
26411 if (VT == MVT::i8 || VT == MVT::i1)
26412 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26413 if (VT == MVT::i16)
26414 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26415 if (VT == MVT::i32 || !Subtarget->is64Bit())
26416 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26417 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26418 case 'f': // FP Stack registers.
26419 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26420 // value to the correct fpstack register class.
26421 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26422 return std::make_pair(0U, &X86::RFP32RegClass);
26423 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26424 return std::make_pair(0U, &X86::RFP64RegClass);
26425 return std::make_pair(0U, &X86::RFP80RegClass);
26426 case 'y': // MMX_REGS if MMX allowed.
26427 if (!Subtarget->hasMMX()) break;
26428 return std::make_pair(0U, &X86::VR64RegClass);
26429 case 'Y': // SSE_REGS if SSE2 allowed
26430 if (!Subtarget->hasSSE2()) break;
26432 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26433 if (!Subtarget->hasSSE1()) break;
26435 switch (VT.SimpleTy) {
26437 // Scalar SSE types.
26440 return std::make_pair(0U, &X86::FR32RegClass);
26443 return std::make_pair(0U, &X86::FR64RegClass);
26451 return std::make_pair(0U, &X86::VR128RegClass);
26459 return std::make_pair(0U, &X86::VR256RegClass);
26464 return std::make_pair(0U, &X86::VR512RegClass);
26470 // Use the default implementation in TargetLowering to convert the register
26471 // constraint into a member of a register class.
26472 std::pair<unsigned, const TargetRegisterClass*> Res;
26473 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26475 // Not found as a standard register?
26477 // Map st(0) -> st(7) -> ST0
26478 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26479 tolower(Constraint[1]) == 's' &&
26480 tolower(Constraint[2]) == 't' &&
26481 Constraint[3] == '(' &&
26482 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26483 Constraint[5] == ')' &&
26484 Constraint[6] == '}') {
26486 Res.first = X86::FP0+Constraint[4]-'0';
26487 Res.second = &X86::RFP80RegClass;
26491 // GCC allows "st(0)" to be called just plain "st".
26492 if (StringRef("{st}").equals_lower(Constraint)) {
26493 Res.first = X86::FP0;
26494 Res.second = &X86::RFP80RegClass;
26499 if (StringRef("{flags}").equals_lower(Constraint)) {
26500 Res.first = X86::EFLAGS;
26501 Res.second = &X86::CCRRegClass;
26505 // 'A' means EAX + EDX.
26506 if (Constraint == "A") {
26507 Res.first = X86::EAX;
26508 Res.second = &X86::GR32_ADRegClass;
26514 // Otherwise, check to see if this is a register class of the wrong value
26515 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26516 // turn into {ax},{dx}.
26517 // MVT::Other is used to specify clobber names.
26518 if (Res.second->hasType(VT) || VT == MVT::Other)
26519 return Res; // Correct type already, nothing to do.
26521 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26522 // return "eax". This should even work for things like getting 64bit integer
26523 // registers when given an f64 type.
26524 const TargetRegisterClass *Class = Res.second;
26525 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26526 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26527 unsigned Size = VT.getSizeInBits();
26528 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26529 : Size == 16 ? MVT::i16
26530 : Size == 32 ? MVT::i32
26531 : Size == 64 ? MVT::i64
26533 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26535 Res.first = DestReg;
26536 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26537 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26538 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26539 : &X86::GR64RegClass;
26540 assert(Res.second->contains(Res.first) && "Register in register class");
26542 // No register found/type mismatch.
26544 Res.second = nullptr;
26546 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26547 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26548 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26549 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26550 Class == &X86::VR512RegClass) {
26551 // Handle references to XMM physical registers that got mapped into the
26552 // wrong class. This can happen with constraints like {xmm0} where the
26553 // target independent register mapper will just pick the first match it can
26554 // find, ignoring the required type.
26556 if (VT == MVT::f32 || VT == MVT::i32)
26557 Res.second = &X86::FR32RegClass;
26558 else if (VT == MVT::f64 || VT == MVT::i64)
26559 Res.second = &X86::FR64RegClass;
26560 else if (X86::VR128RegClass.hasType(VT))
26561 Res.second = &X86::VR128RegClass;
26562 else if (X86::VR256RegClass.hasType(VT))
26563 Res.second = &X86::VR256RegClass;
26564 else if (X86::VR512RegClass.hasType(VT))
26565 Res.second = &X86::VR512RegClass;
26567 // Type mismatch and not a clobber: Return an error;
26569 Res.second = nullptr;
26576 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26577 const AddrMode &AM, Type *Ty,
26578 unsigned AS) const {
26579 // Scaling factors are not free at all.
26580 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26581 // will take 2 allocations in the out of order engine instead of 1
26582 // for plain addressing mode, i.e. inst (reg1).
26584 // vaddps (%rsi,%drx), %ymm0, %ymm1
26585 // Requires two allocations (one for the load, one for the computation)
26587 // vaddps (%rsi), %ymm0, %ymm1
26588 // Requires just 1 allocation, i.e., freeing allocations for other operations
26589 // and having less micro operations to execute.
26591 // For some X86 architectures, this is even worse because for instance for
26592 // stores, the complex addressing mode forces the instruction to use the
26593 // "load" ports instead of the dedicated "store" port.
26594 // E.g., on Haswell:
26595 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26596 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26597 if (isLegalAddressingMode(DL, AM, Ty, AS))
26598 // Scale represents reg2 * scale, thus account for 1
26599 // as soon as we use a second register.
26600 return AM.Scale != 0;
26604 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26605 // Integer division on x86 is expensive. However, when aggressively optimizing
26606 // for code size, we prefer to use a div instruction, as it is usually smaller
26607 // than the alternative sequence.
26608 // The exception to this is vector division. Since x86 doesn't have vector
26609 // integer division, leaving the division as-is is a loss even in terms of
26610 // size, because it will have to be scalarized, while the alternative code
26611 // sequence can be performed in vector form.
26612 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26613 Attribute::MinSize);
26614 return OptSize && !VT.isVector();