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);
118 // The _ftol2 runtime function has an unusual calling conv, which
119 // is modeled by a special pseudo-instruction.
120 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
121 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
122 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
123 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
126 if (Subtarget->isTargetDarwin()) {
127 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
128 setUseUnderscoreSetJmp(false);
129 setUseUnderscoreLongJmp(false);
130 } else if (Subtarget->isTargetWindowsGNU()) {
131 // MS runtime is weird: it exports _setjmp, but longjmp!
132 setUseUnderscoreSetJmp(true);
133 setUseUnderscoreLongJmp(false);
135 setUseUnderscoreSetJmp(true);
136 setUseUnderscoreLongJmp(true);
139 // Set up the register classes.
140 addRegisterClass(MVT::i8, &X86::GR8RegClass);
141 addRegisterClass(MVT::i16, &X86::GR16RegClass);
142 addRegisterClass(MVT::i32, &X86::GR32RegClass);
143 if (Subtarget->is64Bit())
144 addRegisterClass(MVT::i64, &X86::GR64RegClass);
146 for (MVT VT : MVT::integer_valuetypes())
147 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
149 // We don't accept any truncstore of integer registers.
150 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
151 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
152 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
153 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
154 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
155 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
157 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
159 // SETOEQ and SETUNE require checking two conditions.
160 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
161 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
162 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
163 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
164 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
165 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
167 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
169 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
170 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
171 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
173 if (Subtarget->is64Bit()) {
174 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
175 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
176 } else if (!Subtarget->useSoftFloat()) {
177 // We have an algorithm for SSE2->double, and we turn this into a
178 // 64-bit FILD followed by conditional FADD for other targets.
179 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
180 // We have an algorithm for SSE2, and we turn this into a 64-bit
181 // FILD for other targets.
182 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
185 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
187 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
188 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
190 if (!Subtarget->useSoftFloat()) {
191 // SSE has no i16 to fp conversion, only i32
192 if (X86ScalarSSEf32) {
193 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
194 // f32 and f64 cases are Legal, f80 case is not
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
197 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
202 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
205 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
206 // are Legal, f80 is custom lowered.
207 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
208 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
210 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
212 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
213 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
215 if (X86ScalarSSEf32) {
216 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
217 // f32 and f64 cases are Legal, f80 case is not
218 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
220 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
221 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
224 // Handle FP_TO_UINT by promoting the destination to a larger signed
226 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
227 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
228 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
230 if (Subtarget->is64Bit()) {
231 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
233 } else if (!Subtarget->useSoftFloat()) {
234 // Since AVX is a superset of SSE3, only check for SSE here.
235 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
236 // Expand FP_TO_UINT into a select.
237 // FIXME: We would like to use a Custom expander here eventually to do
238 // the optimal thing for SSE vs. the default expansion in the legalizer.
239 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
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);
246 if (isTargetFTOL()) {
247 // Use the _ftol2 runtime function, which has a pseudo-instruction
248 // to handle its weird calling convention.
249 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
252 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253 if (!X86ScalarSSEf64) {
254 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
255 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
258 // Without SSE, i64->f64 goes through memory.
259 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
263 // Scalar integer divide and remainder are lowered to use operations that
264 // produce two results, to match the available instructions. This exposes
265 // the two-result form to trivial CSE, which is able to combine x/y and x%y
266 // into a single instruction.
268 // Scalar integer multiply-high is also lowered to use two-result
269 // operations, to match the available instructions. However, plain multiply
270 // (low) operations are left as Legal, as there are single-result
271 // instructions for this in x86. Using the two-result multiply instructions
272 // when both high and low results are needed must be arranged by dagcombine.
273 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
275 setOperationAction(ISD::MULHS, VT, Expand);
276 setOperationAction(ISD::MULHU, VT, Expand);
277 setOperationAction(ISD::SDIV, VT, Expand);
278 setOperationAction(ISD::UDIV, VT, Expand);
279 setOperationAction(ISD::SREM, VT, Expand);
280 setOperationAction(ISD::UREM, VT, Expand);
282 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283 setOperationAction(ISD::ADDC, VT, Custom);
284 setOperationAction(ISD::ADDE, VT, Custom);
285 setOperationAction(ISD::SUBC, VT, Custom);
286 setOperationAction(ISD::SUBE, VT, Custom);
289 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
290 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
291 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
292 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
293 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
294 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
295 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
296 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
297 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
301 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
302 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
303 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
305 if (Subtarget->is64Bit())
306 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
308 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
309 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
310 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
311 setOperationAction(ISD::FREM , MVT::f32 , Expand);
312 setOperationAction(ISD::FREM , MVT::f64 , Expand);
313 setOperationAction(ISD::FREM , MVT::f80 , Expand);
314 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
316 // Promote the i8 variants and force them on up to i32 which has a shorter
318 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
319 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
320 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
321 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
322 if (Subtarget->hasBMI()) {
323 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
324 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
325 if (Subtarget->is64Bit())
326 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
328 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
329 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
330 if (Subtarget->is64Bit())
331 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
334 if (Subtarget->hasLZCNT()) {
335 // When promoting the i8 variants, force them to i32 for a shorter
337 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
338 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
339 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
340 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
341 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
342 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
343 if (Subtarget->is64Bit())
344 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
346 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
347 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
348 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
350 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
352 if (Subtarget->is64Bit()) {
353 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
358 // Special handling for half-precision floating point conversions.
359 // If we don't have F16C support, then lower half float conversions
360 // into library calls.
361 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
362 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
363 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
366 // There's never any support for operations beyond MVT::f32.
367 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
368 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
369 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
370 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
372 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
373 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
374 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
375 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
376 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
379 if (Subtarget->hasPOPCNT()) {
380 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
382 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
383 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
384 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
385 if (Subtarget->is64Bit())
386 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
389 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
391 if (!Subtarget->hasMOVBE())
392 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
394 // These should be promoted to a larger select which is supported.
395 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
396 // X86 wants to expand cmov itself.
397 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
398 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
399 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
400 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
401 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
402 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
403 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
404 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
405 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
406 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
407 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
408 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
409 if (Subtarget->is64Bit()) {
410 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
411 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
413 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
414 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
415 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
416 // support continuation, user-level threading, and etc.. As a result, no
417 // other SjLj exception interfaces are implemented and please don't build
418 // your own exception handling based on them.
419 // LLVM/Clang supports zero-cost DWARF exception handling.
420 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
421 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
424 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
425 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
426 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
427 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
428 if (Subtarget->is64Bit())
429 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
431 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
432 if (Subtarget->is64Bit()) {
433 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
434 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
435 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
436 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
437 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
439 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
441 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
442 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
443 if (Subtarget->is64Bit()) {
444 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
445 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
446 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
449 if (Subtarget->hasSSE1())
450 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
452 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
454 // Expand certain atomics
455 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
457 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
458 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
459 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
462 if (Subtarget->hasCmpxchg16b()) {
463 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
466 // FIXME - use subtarget debug flags
467 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
468 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
469 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
472 if (Subtarget->is64Bit()) {
473 setExceptionPointerRegister(X86::RAX);
474 setExceptionSelectorRegister(X86::RDX);
476 setExceptionPointerRegister(X86::EAX);
477 setExceptionSelectorRegister(X86::EDX);
479 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
480 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
482 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
483 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
485 setOperationAction(ISD::TRAP, MVT::Other, Legal);
486 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
488 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
489 setOperationAction(ISD::VASTART , MVT::Other, Custom);
490 setOperationAction(ISD::VAEND , MVT::Other, Expand);
491 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
492 // TargetInfo::X86_64ABIBuiltinVaList
493 setOperationAction(ISD::VAARG , MVT::Other, Custom);
494 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
496 // TargetInfo::CharPtrBuiltinVaList
497 setOperationAction(ISD::VAARG , MVT::Other, Expand);
498 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
501 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
502 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
504 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
506 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
507 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
508 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
510 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
511 // f32 and f64 use SSE.
512 // Set up the FP register classes.
513 addRegisterClass(MVT::f32, &X86::FR32RegClass);
514 addRegisterClass(MVT::f64, &X86::FR64RegClass);
516 // Use ANDPD to simulate FABS.
517 setOperationAction(ISD::FABS , MVT::f64, Custom);
518 setOperationAction(ISD::FABS , MVT::f32, Custom);
520 // Use XORP to simulate FNEG.
521 setOperationAction(ISD::FNEG , MVT::f64, Custom);
522 setOperationAction(ISD::FNEG , MVT::f32, Custom);
524 // Use ANDPD and ORPD to simulate FCOPYSIGN.
525 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
526 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
528 // Lower this to FGETSIGNx86 plus an AND.
529 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
530 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
532 // We don't support sin/cos/fmod
533 setOperationAction(ISD::FSIN , MVT::f64, Expand);
534 setOperationAction(ISD::FCOS , MVT::f64, Expand);
535 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
536 setOperationAction(ISD::FSIN , MVT::f32, Expand);
537 setOperationAction(ISD::FCOS , MVT::f32, Expand);
538 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
540 // Expand FP immediates into loads from the stack, except for the special
542 addLegalFPImmediate(APFloat(+0.0)); // xorpd
543 addLegalFPImmediate(APFloat(+0.0f)); // xorps
544 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
545 // Use SSE for f32, x87 for f64.
546 // Set up the FP register classes.
547 addRegisterClass(MVT::f32, &X86::FR32RegClass);
548 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
550 // Use ANDPS to simulate FABS.
551 setOperationAction(ISD::FABS , MVT::f32, Custom);
553 // Use XORP to simulate FNEG.
554 setOperationAction(ISD::FNEG , MVT::f32, Custom);
556 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
558 // Use ANDPS and ORPS to simulate FCOPYSIGN.
559 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
560 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
562 // We don't support sin/cos/fmod
563 setOperationAction(ISD::FSIN , MVT::f32, Expand);
564 setOperationAction(ISD::FCOS , MVT::f32, Expand);
565 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
567 // Special cases we handle for FP constants.
568 addLegalFPImmediate(APFloat(+0.0f)); // xorps
569 addLegalFPImmediate(APFloat(+0.0)); // FLD0
570 addLegalFPImmediate(APFloat(+1.0)); // FLD1
571 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
572 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
574 if (!TM.Options.UnsafeFPMath) {
575 setOperationAction(ISD::FSIN , MVT::f64, Expand);
576 setOperationAction(ISD::FCOS , MVT::f64, Expand);
577 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
579 } else if (!Subtarget->useSoftFloat()) {
580 // f32 and f64 in x87.
581 // Set up the FP register classes.
582 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
583 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
585 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
586 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
587 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
588 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
590 if (!TM.Options.UnsafeFPMath) {
591 setOperationAction(ISD::FSIN , MVT::f64, Expand);
592 setOperationAction(ISD::FSIN , MVT::f32, Expand);
593 setOperationAction(ISD::FCOS , MVT::f64, Expand);
594 setOperationAction(ISD::FCOS , MVT::f32, Expand);
595 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
596 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
598 addLegalFPImmediate(APFloat(+0.0)); // FLD0
599 addLegalFPImmediate(APFloat(+1.0)); // FLD1
600 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
608 // We don't support FMA.
609 setOperationAction(ISD::FMA, MVT::f64, Expand);
610 setOperationAction(ISD::FMA, MVT::f32, Expand);
612 // Long double always uses X87.
613 if (!Subtarget->useSoftFloat()) {
614 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
615 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
616 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
618 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
619 addLegalFPImmediate(TmpFlt); // FLD0
621 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
624 APFloat TmpFlt2(+1.0);
625 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
627 addLegalFPImmediate(TmpFlt2); // FLD1
628 TmpFlt2.changeSign();
629 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
632 if (!TM.Options.UnsafeFPMath) {
633 setOperationAction(ISD::FSIN , MVT::f80, Expand);
634 setOperationAction(ISD::FCOS , MVT::f80, Expand);
635 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
638 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
639 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
640 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
641 setOperationAction(ISD::FRINT, MVT::f80, Expand);
642 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
643 setOperationAction(ISD::FMA, MVT::f80, Expand);
646 // Always use a library call for pow.
647 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
648 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
649 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
651 setOperationAction(ISD::FLOG, MVT::f80, Expand);
652 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
653 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
654 setOperationAction(ISD::FEXP, MVT::f80, Expand);
655 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
657 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
659 // First set operation action for all vector types to either promote
660 // (for widening) or expand (for scalarization). Then we will selectively
661 // turn on ones that can be effectively codegen'd.
662 for (MVT VT : MVT::vector_valuetypes()) {
663 setOperationAction(ISD::ADD , VT, Expand);
664 setOperationAction(ISD::SUB , VT, Expand);
665 setOperationAction(ISD::FADD, VT, Expand);
666 setOperationAction(ISD::FNEG, VT, Expand);
667 setOperationAction(ISD::FSUB, VT, Expand);
668 setOperationAction(ISD::MUL , VT, Expand);
669 setOperationAction(ISD::FMUL, VT, Expand);
670 setOperationAction(ISD::SDIV, VT, Expand);
671 setOperationAction(ISD::UDIV, VT, Expand);
672 setOperationAction(ISD::FDIV, VT, Expand);
673 setOperationAction(ISD::SREM, VT, Expand);
674 setOperationAction(ISD::UREM, VT, Expand);
675 setOperationAction(ISD::LOAD, VT, Expand);
676 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
677 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
678 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
679 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
680 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
681 setOperationAction(ISD::FABS, VT, Expand);
682 setOperationAction(ISD::FSIN, VT, Expand);
683 setOperationAction(ISD::FSINCOS, VT, Expand);
684 setOperationAction(ISD::FCOS, VT, Expand);
685 setOperationAction(ISD::FSINCOS, VT, Expand);
686 setOperationAction(ISD::FREM, VT, Expand);
687 setOperationAction(ISD::FMA, VT, Expand);
688 setOperationAction(ISD::FPOWI, VT, Expand);
689 setOperationAction(ISD::FSQRT, VT, Expand);
690 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
691 setOperationAction(ISD::FFLOOR, VT, Expand);
692 setOperationAction(ISD::FCEIL, VT, Expand);
693 setOperationAction(ISD::FTRUNC, VT, Expand);
694 setOperationAction(ISD::FRINT, VT, Expand);
695 setOperationAction(ISD::FNEARBYINT, VT, Expand);
696 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
697 setOperationAction(ISD::MULHS, VT, Expand);
698 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699 setOperationAction(ISD::MULHU, VT, Expand);
700 setOperationAction(ISD::SDIVREM, VT, Expand);
701 setOperationAction(ISD::UDIVREM, VT, Expand);
702 setOperationAction(ISD::FPOW, VT, Expand);
703 setOperationAction(ISD::CTPOP, VT, Expand);
704 setOperationAction(ISD::CTTZ, VT, Expand);
705 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
706 setOperationAction(ISD::CTLZ, VT, Expand);
707 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
708 setOperationAction(ISD::SHL, VT, Expand);
709 setOperationAction(ISD::SRA, VT, Expand);
710 setOperationAction(ISD::SRL, VT, Expand);
711 setOperationAction(ISD::ROTL, VT, Expand);
712 setOperationAction(ISD::ROTR, VT, Expand);
713 setOperationAction(ISD::BSWAP, VT, Expand);
714 setOperationAction(ISD::SETCC, VT, Expand);
715 setOperationAction(ISD::FLOG, VT, Expand);
716 setOperationAction(ISD::FLOG2, VT, Expand);
717 setOperationAction(ISD::FLOG10, VT, Expand);
718 setOperationAction(ISD::FEXP, VT, Expand);
719 setOperationAction(ISD::FEXP2, VT, Expand);
720 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
721 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
722 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
723 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
724 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
725 setOperationAction(ISD::TRUNCATE, VT, Expand);
726 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
727 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
728 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
729 setOperationAction(ISD::VSELECT, VT, Expand);
730 setOperationAction(ISD::SELECT_CC, VT, Expand);
731 for (MVT InnerVT : MVT::vector_valuetypes()) {
732 setTruncStoreAction(InnerVT, VT, Expand);
734 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
737 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738 // types, we have to deal with them whether we ask for Expansion or not.
739 // Setting Expand causes its own optimisation problems though, so leave
741 if (VT.getVectorElementType() == MVT::i1)
742 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
744 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745 // split/scalarized right now.
746 if (VT.getVectorElementType() == MVT::f16)
747 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
751 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752 // with -msoft-float, disable use of MMX as well.
753 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
754 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755 // No operations on x86mmx supported, everything uses intrinsics.
758 // MMX-sized vectors (other than x86mmx) are expected to be expanded
759 // into smaller operations.
760 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761 setOperationAction(ISD::MULHS, MMXTy, Expand);
762 setOperationAction(ISD::AND, MMXTy, Expand);
763 setOperationAction(ISD::OR, MMXTy, Expand);
764 setOperationAction(ISD::XOR, MMXTy, Expand);
765 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
766 setOperationAction(ISD::SELECT, MMXTy, Expand);
767 setOperationAction(ISD::BITCAST, MMXTy, Expand);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
771 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
772 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
774 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
775 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
776 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
777 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
778 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
779 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
780 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
781 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
782 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
783 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
784 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
785 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
787 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
790 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
791 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
793 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794 // registers cannot be used even for integer operations.
795 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
800 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
801 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
802 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
803 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
804 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
805 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
806 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
807 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
808 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
809 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
810 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
811 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
812 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
813 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
814 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
815 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
816 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
817 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
818 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
819 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
820 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
821 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
822 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
824 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
825 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
826 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
827 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
829 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
830 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
831 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
832 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
838 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
840 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
841 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
842 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
843 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
845 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
846 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
847 MVT VT = (MVT::SimpleValueType)i;
848 // Do not attempt to custom lower non-power-of-2 vectors
849 if (!isPowerOf2_32(VT.getVectorNumElements()))
851 // Do not attempt to custom lower non-128-bit vectors
852 if (!VT.is128BitVector())
854 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
855 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
856 setOperationAction(ISD::VSELECT, VT, Custom);
857 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
860 // We support custom legalizing of sext and anyext loads for specific
861 // memory vector types which we can load as a scalar (or sequence of
862 // scalars) and extend in-register to a legal 128-bit vector type. For sext
863 // loads these must work with a single scalar load.
864 for (MVT VT : MVT::integer_vector_valuetypes()) {
865 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
866 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
867 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
868 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
869 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
870 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
871 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
872 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
873 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
876 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
877 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
878 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
879 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
880 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
881 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
885 if (Subtarget->is64Bit()) {
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
890 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
891 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
892 MVT VT = (MVT::SimpleValueType)i;
894 // Do not attempt to promote non-128-bit vectors
895 if (!VT.is128BitVector())
898 setOperationAction(ISD::AND, VT, Promote);
899 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
900 setOperationAction(ISD::OR, VT, Promote);
901 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
902 setOperationAction(ISD::XOR, VT, Promote);
903 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
904 setOperationAction(ISD::LOAD, VT, Promote);
905 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
906 setOperationAction(ISD::SELECT, VT, Promote);
907 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
910 // Custom lower v2i64 and v2f64 selects.
911 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
912 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
913 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
914 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
916 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
917 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
919 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
921 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
922 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
923 // As there is no 64-bit GPR available, we need build a special custom
924 // sequence to convert from v2i32 to v2f32.
925 if (!Subtarget->is64Bit())
926 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
928 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
929 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
931 for (MVT VT : MVT::fp_vector_valuetypes())
932 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
934 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
935 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
936 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
939 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
940 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
941 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
942 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
943 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
944 setOperationAction(ISD::FRINT, RoundedTy, Legal);
945 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
948 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
949 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
950 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
951 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
952 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
953 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
954 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
955 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
957 // FIXME: Do we need to handle scalar-to-vector here?
958 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
960 // We directly match byte blends in the backend as they match the VSELECT
962 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
964 // SSE41 brings specific instructions for doing vector sign extend even in
965 // cases where we don't have SRA.
966 for (MVT VT : MVT::integer_vector_valuetypes()) {
967 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
968 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
969 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
972 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
973 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
974 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
975 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
976 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
977 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
978 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
980 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
981 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
982 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
983 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
987 // i8 and i16 vectors are custom because the source register and source
988 // source memory operand types are not the same width. f32 vectors are
989 // custom since the immediate controlling the insert encodes additional
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
994 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
999 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1001 // FIXME: these should be Legal, but that's only for the case where
1002 // the index is constant. For now custom expand to deal with that.
1003 if (Subtarget->is64Bit()) {
1004 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1005 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1009 if (Subtarget->hasSSE2()) {
1010 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1011 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1012 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1014 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1015 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1017 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1018 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1020 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1021 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1023 // In the customized shift lowering, the legal cases in AVX2 will be
1025 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1026 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1028 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1031 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1032 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1035 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1036 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1039 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1040 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1041 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1043 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1044 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1045 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1047 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1051 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1058 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1060 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1063 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1064 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1067 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1068 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1069 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1070 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1071 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1073 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1074 // even though v8i16 is a legal type.
1075 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1076 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1077 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1079 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1080 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1081 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1083 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1084 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1086 for (MVT VT : MVT::fp_vector_valuetypes())
1087 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1089 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1090 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1092 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1093 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1095 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1096 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1098 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1099 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1100 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1101 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1103 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1104 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1105 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1107 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1108 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1109 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1110 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1111 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1112 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1113 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1114 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1115 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1116 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1117 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1118 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1120 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1121 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1122 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1123 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1125 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1126 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1127 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1128 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1129 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1130 setOperationAction(ISD::FMA, MVT::f32, Legal);
1131 setOperationAction(ISD::FMA, MVT::f64, Legal);
1134 if (Subtarget->hasInt256()) {
1135 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1136 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1137 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1138 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1140 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1141 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1142 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1143 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1145 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1146 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1147 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1148 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1150 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1151 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1152 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1153 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1155 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1156 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1157 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1158 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1159 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1160 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1161 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1162 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1163 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1164 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1165 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1166 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1168 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1169 // when we have a 256bit-wide blend with immediate.
1170 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1172 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1173 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1174 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1175 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1176 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1177 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1178 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1180 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1182 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1183 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1184 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1185 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1187 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1188 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1189 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1190 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1193 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1195 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1197 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1198 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1199 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1200 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1203 // In the customized shift lowering, the legal cases in AVX2 will be
1205 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1206 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1208 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1209 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1211 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1212 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1214 // Custom lower several nodes for 256-bit types.
1215 for (MVT VT : MVT::vector_valuetypes()) {
1216 if (VT.getScalarSizeInBits() >= 32) {
1217 setOperationAction(ISD::MLOAD, VT, Legal);
1218 setOperationAction(ISD::MSTORE, VT, Legal);
1220 // Extract subvector is special because the value type
1221 // (result) is 128-bit but the source is 256-bit wide.
1222 if (VT.is128BitVector()) {
1223 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1225 // Do not attempt to custom lower other non-256-bit vectors
1226 if (!VT.is256BitVector())
1229 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1230 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1231 setOperationAction(ISD::VSELECT, VT, Custom);
1232 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1233 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1234 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1235 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1236 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1239 if (Subtarget->hasInt256())
1240 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1243 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1244 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1245 MVT VT = (MVT::SimpleValueType)i;
1247 // Do not attempt to promote non-256-bit vectors
1248 if (!VT.is256BitVector())
1251 setOperationAction(ISD::AND, VT, Promote);
1252 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1253 setOperationAction(ISD::OR, VT, Promote);
1254 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1255 setOperationAction(ISD::XOR, VT, Promote);
1256 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1257 setOperationAction(ISD::LOAD, VT, Promote);
1258 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1259 setOperationAction(ISD::SELECT, VT, Promote);
1260 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1264 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1265 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1266 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1267 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1268 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1270 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1271 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1272 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1274 for (MVT VT : MVT::fp_vector_valuetypes())
1275 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1277 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1278 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1279 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1280 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1281 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1282 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1283 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1284 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1285 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1286 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1287 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1288 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1290 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1291 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1292 setOperationAction(ISD::XOR, MVT::i1, Legal);
1293 setOperationAction(ISD::OR, MVT::i1, Legal);
1294 setOperationAction(ISD::AND, MVT::i1, Legal);
1295 setOperationAction(ISD::SUB, MVT::i1, Custom);
1296 setOperationAction(ISD::ADD, MVT::i1, Custom);
1297 setOperationAction(ISD::MUL, MVT::i1, Custom);
1298 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1299 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1300 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1301 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1302 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1304 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1305 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1306 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1307 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1308 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1309 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1311 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1312 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1313 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1314 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1315 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1316 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1317 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1318 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1320 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1321 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1322 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1323 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1324 if (Subtarget->is64Bit()) {
1325 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1326 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1327 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1328 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1330 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1331 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1332 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1333 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1334 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1335 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1336 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1337 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1338 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1339 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1340 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1341 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1342 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1343 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1344 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1345 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1347 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1348 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1349 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1350 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1351 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1352 if (Subtarget->hasVLX()){
1353 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1354 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1355 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1356 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1357 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1359 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1360 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1361 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1362 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1363 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1365 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1368 if (Subtarget->hasDQI()) {
1369 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1372 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1373 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1374 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1375 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1376 if (Subtarget->hasVLX()) {
1377 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1378 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1381 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1382 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1383 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1384 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1387 if (Subtarget->hasVLX()) {
1388 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1389 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1390 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1391 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1392 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1393 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1394 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1395 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1397 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1398 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1399 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1400 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1401 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1402 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1403 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1404 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1405 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1406 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1407 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1408 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1409 if (Subtarget->hasDQI()) {
1410 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1411 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1413 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1414 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1415 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1416 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1417 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1418 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1419 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1420 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1421 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1422 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1424 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1425 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1426 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1427 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1428 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1430 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1431 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1433 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1435 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1436 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1437 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1438 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1439 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1440 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1441 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1442 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1443 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1444 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1445 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1447 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1448 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1449 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1450 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1451 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1452 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1453 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1454 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1456 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1457 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1459 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1460 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1462 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1465 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1467 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1468 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1470 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1471 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1473 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1474 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1475 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1476 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1477 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1478 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1480 if (Subtarget->hasCDI()) {
1481 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1482 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1484 if (Subtarget->hasDQI()) {
1485 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1486 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1487 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1489 // Custom lower several nodes.
1490 for (MVT VT : MVT::vector_valuetypes()) {
1491 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1493 setOperationAction(ISD::AND, VT, Legal);
1494 setOperationAction(ISD::OR, VT, Legal);
1495 setOperationAction(ISD::XOR, VT, Legal);
1497 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1498 setOperationAction(ISD::MGATHER, VT, Custom);
1499 setOperationAction(ISD::MSCATTER, VT, Custom);
1501 // Extract subvector is special because the value type
1502 // (result) is 256/128-bit but the source is 512-bit wide.
1503 if (VT.is128BitVector() || VT.is256BitVector()) {
1504 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1506 if (VT.getVectorElementType() == MVT::i1)
1507 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1509 // Do not attempt to custom lower other non-512-bit vectors
1510 if (!VT.is512BitVector())
1513 if (EltSize >= 32) {
1514 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1515 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1516 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1517 setOperationAction(ISD::VSELECT, VT, Legal);
1518 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1519 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1520 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1521 setOperationAction(ISD::MLOAD, VT, Legal);
1522 setOperationAction(ISD::MSTORE, VT, Legal);
1525 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1526 MVT VT = (MVT::SimpleValueType)i;
1528 // Do not attempt to promote non-512-bit vectors.
1529 if (!VT.is512BitVector())
1532 setOperationAction(ISD::SELECT, VT, Promote);
1533 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1537 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1538 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1539 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1541 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1542 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1544 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1545 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1546 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1547 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1548 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1549 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1550 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1551 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1552 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1553 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1554 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1555 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1556 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1557 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1558 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1559 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1560 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1561 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1562 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1563 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1564 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1565 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1566 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1567 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1568 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1569 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1570 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1571 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1572 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1573 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1575 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1576 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1577 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1578 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1579 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1580 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1581 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1582 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1584 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1585 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1586 if (Subtarget->hasVLX())
1587 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1589 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1590 const MVT VT = (MVT::SimpleValueType)i;
1592 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1594 // Do not attempt to promote non-512-bit vectors.
1595 if (!VT.is512BitVector())
1599 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1600 setOperationAction(ISD::VSELECT, VT, Legal);
1605 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1606 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1607 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1609 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1610 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1611 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1612 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1613 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1614 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1615 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1616 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1617 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1618 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1620 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1621 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1622 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1623 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1624 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1625 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1626 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1627 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1629 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1630 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1631 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1632 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1633 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1634 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1635 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1636 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1639 // We want to custom lower some of our intrinsics.
1640 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1641 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1642 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1643 if (!Subtarget->is64Bit())
1644 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1646 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1647 // handle type legalization for these operations here.
1649 // FIXME: We really should do custom legalization for addition and
1650 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1651 // than generic legalization for 64-bit multiplication-with-overflow, though.
1652 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1653 // Add/Sub/Mul with overflow operations are custom lowered.
1655 setOperationAction(ISD::SADDO, VT, Custom);
1656 setOperationAction(ISD::UADDO, VT, Custom);
1657 setOperationAction(ISD::SSUBO, VT, Custom);
1658 setOperationAction(ISD::USUBO, VT, Custom);
1659 setOperationAction(ISD::SMULO, VT, Custom);
1660 setOperationAction(ISD::UMULO, VT, Custom);
1664 if (!Subtarget->is64Bit()) {
1665 // These libcalls are not available in 32-bit.
1666 setLibcallName(RTLIB::SHL_I128, nullptr);
1667 setLibcallName(RTLIB::SRL_I128, nullptr);
1668 setLibcallName(RTLIB::SRA_I128, nullptr);
1671 // Combine sin / cos into one node or libcall if possible.
1672 if (Subtarget->hasSinCos()) {
1673 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1674 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1675 if (Subtarget->isTargetDarwin()) {
1676 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1677 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1678 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1679 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1683 if (Subtarget->isTargetWin64()) {
1684 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1685 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1686 setOperationAction(ISD::SREM, MVT::i128, Custom);
1687 setOperationAction(ISD::UREM, MVT::i128, Custom);
1688 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1689 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1692 // We have target-specific dag combine patterns for the following nodes:
1693 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1694 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1695 setTargetDAGCombine(ISD::BITCAST);
1696 setTargetDAGCombine(ISD::VSELECT);
1697 setTargetDAGCombine(ISD::SELECT);
1698 setTargetDAGCombine(ISD::SHL);
1699 setTargetDAGCombine(ISD::SRA);
1700 setTargetDAGCombine(ISD::SRL);
1701 setTargetDAGCombine(ISD::OR);
1702 setTargetDAGCombine(ISD::AND);
1703 setTargetDAGCombine(ISD::ADD);
1704 setTargetDAGCombine(ISD::FADD);
1705 setTargetDAGCombine(ISD::FSUB);
1706 setTargetDAGCombine(ISD::FMA);
1707 setTargetDAGCombine(ISD::SUB);
1708 setTargetDAGCombine(ISD::LOAD);
1709 setTargetDAGCombine(ISD::MLOAD);
1710 setTargetDAGCombine(ISD::STORE);
1711 setTargetDAGCombine(ISD::MSTORE);
1712 setTargetDAGCombine(ISD::ZERO_EXTEND);
1713 setTargetDAGCombine(ISD::ANY_EXTEND);
1714 setTargetDAGCombine(ISD::SIGN_EXTEND);
1715 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1716 setTargetDAGCombine(ISD::SINT_TO_FP);
1717 setTargetDAGCombine(ISD::UINT_TO_FP);
1718 setTargetDAGCombine(ISD::SETCC);
1719 setTargetDAGCombine(ISD::BUILD_VECTOR);
1720 setTargetDAGCombine(ISD::MUL);
1721 setTargetDAGCombine(ISD::XOR);
1723 computeRegisterProperties(Subtarget->getRegisterInfo());
1725 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1726 MaxStoresPerMemsetOptSize = 8;
1727 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1728 MaxStoresPerMemcpyOptSize = 4;
1729 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1730 MaxStoresPerMemmoveOptSize = 4;
1731 setPrefLoopAlignment(4); // 2^4 bytes.
1733 // Predictable cmov don't hurt on atom because it's in-order.
1734 PredictableSelectIsExpensive = !Subtarget->isAtom();
1735 EnableExtLdPromotion = true;
1736 setPrefFunctionAlignment(4); // 2^4 bytes.
1738 verifyIntrinsicTables();
1741 // This has so far only been implemented for 64-bit MachO.
1742 bool X86TargetLowering::useLoadStackGuardNode() const {
1743 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1746 TargetLoweringBase::LegalizeTypeAction
1747 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1748 if (ExperimentalVectorWideningLegalization &&
1749 VT.getVectorNumElements() != 1 &&
1750 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1751 return TypeWidenVector;
1753 return TargetLoweringBase::getPreferredVectorAction(VT);
1756 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1759 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1761 const unsigned NumElts = VT.getVectorNumElements();
1762 const EVT EltVT = VT.getVectorElementType();
1763 if (VT.is512BitVector()) {
1764 if (Subtarget->hasAVX512())
1765 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1766 EltVT == MVT::f32 || EltVT == MVT::f64)
1768 case 8: return MVT::v8i1;
1769 case 16: return MVT::v16i1;
1771 if (Subtarget->hasBWI())
1772 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1774 case 32: return MVT::v32i1;
1775 case 64: return MVT::v64i1;
1779 if (VT.is256BitVector() || VT.is128BitVector()) {
1780 if (Subtarget->hasVLX())
1781 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1782 EltVT == MVT::f32 || EltVT == MVT::f64)
1784 case 2: return MVT::v2i1;
1785 case 4: return MVT::v4i1;
1786 case 8: return MVT::v8i1;
1788 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1789 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1791 case 8: return MVT::v8i1;
1792 case 16: return MVT::v16i1;
1793 case 32: return MVT::v32i1;
1797 return VT.changeVectorElementTypeToInteger();
1800 /// Helper for getByValTypeAlignment to determine
1801 /// the desired ByVal argument alignment.
1802 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1805 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1806 if (VTy->getBitWidth() == 128)
1808 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1809 unsigned EltAlign = 0;
1810 getMaxByValAlign(ATy->getElementType(), EltAlign);
1811 if (EltAlign > MaxAlign)
1812 MaxAlign = EltAlign;
1813 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1814 for (auto *EltTy : STy->elements()) {
1815 unsigned EltAlign = 0;
1816 getMaxByValAlign(EltTy, EltAlign);
1817 if (EltAlign > MaxAlign)
1818 MaxAlign = EltAlign;
1825 /// Return the desired alignment for ByVal aggregate
1826 /// function arguments in the caller parameter area. For X86, aggregates
1827 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1828 /// are at 4-byte boundaries.
1829 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1830 const DataLayout &DL) const {
1831 if (Subtarget->is64Bit()) {
1832 // Max of 8 and alignment of type.
1833 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1840 if (Subtarget->hasSSE1())
1841 getMaxByValAlign(Ty, Align);
1845 /// Returns the target specific optimal type for load
1846 /// and store operations as a result of memset, memcpy, and memmove
1847 /// lowering. If DstAlign is zero that means it's safe to destination
1848 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1849 /// means there isn't a need to check it against alignment requirement,
1850 /// probably because the source does not need to be loaded. If 'IsMemset' is
1851 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1852 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1853 /// source is constant so it does not need to be loaded.
1854 /// It returns EVT::Other if the type should be determined using generic
1855 /// target-independent logic.
1857 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1858 unsigned DstAlign, unsigned SrcAlign,
1859 bool IsMemset, bool ZeroMemset,
1861 MachineFunction &MF) const {
1862 const Function *F = MF.getFunction();
1863 if ((!IsMemset || ZeroMemset) &&
1864 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1866 (Subtarget->isUnalignedMemAccessFast() ||
1867 ((DstAlign == 0 || DstAlign >= 16) &&
1868 (SrcAlign == 0 || SrcAlign >= 16)))) {
1870 if (Subtarget->hasInt256())
1872 if (Subtarget->hasFp256())
1875 if (Subtarget->hasSSE2())
1877 if (Subtarget->hasSSE1())
1879 } else if (!MemcpyStrSrc && Size >= 8 &&
1880 !Subtarget->is64Bit() &&
1881 Subtarget->hasSSE2()) {
1882 // Do not use f64 to lower memcpy if source is string constant. It's
1883 // better to use i32 to avoid the loads.
1887 if (Subtarget->is64Bit() && Size >= 8)
1892 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1894 return X86ScalarSSEf32;
1895 else if (VT == MVT::f64)
1896 return X86ScalarSSEf64;
1901 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1906 *Fast = Subtarget->isUnalignedMemAccessFast();
1910 /// Return the entry encoding for a jump table in the
1911 /// current function. The returned value is a member of the
1912 /// MachineJumpTableInfo::JTEntryKind enum.
1913 unsigned X86TargetLowering::getJumpTableEncoding() const {
1914 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1916 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1917 Subtarget->isPICStyleGOT())
1918 return MachineJumpTableInfo::EK_Custom32;
1920 // Otherwise, use the normal jump table encoding heuristics.
1921 return TargetLowering::getJumpTableEncoding();
1924 bool X86TargetLowering::useSoftFloat() const {
1925 return Subtarget->useSoftFloat();
1929 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1930 const MachineBasicBlock *MBB,
1931 unsigned uid,MCContext &Ctx) const{
1932 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1933 Subtarget->isPICStyleGOT());
1934 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1936 return MCSymbolRefExpr::create(MBB->getSymbol(),
1937 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1940 /// Returns relocation base for the given PIC jumptable.
1941 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1942 SelectionDAG &DAG) const {
1943 if (!Subtarget->is64Bit())
1944 // This doesn't have SDLoc associated with it, but is not really the
1945 // same as a Register.
1946 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1947 getPointerTy(DAG.getDataLayout()));
1951 /// This returns the relocation base for the given PIC jumptable,
1952 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1953 const MCExpr *X86TargetLowering::
1954 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1955 MCContext &Ctx) const {
1956 // X86-64 uses RIP relative addressing based on the jump table label.
1957 if (Subtarget->isPICStyleRIPRel())
1958 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1960 // Otherwise, the reference is relative to the PIC base.
1961 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1964 std::pair<const TargetRegisterClass *, uint8_t>
1965 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1967 const TargetRegisterClass *RRC = nullptr;
1969 switch (VT.SimpleTy) {
1971 return TargetLowering::findRepresentativeClass(TRI, VT);
1972 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1973 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1976 RRC = &X86::VR64RegClass;
1978 case MVT::f32: case MVT::f64:
1979 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1980 case MVT::v4f32: case MVT::v2f64:
1981 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1983 RRC = &X86::VR128RegClass;
1986 return std::make_pair(RRC, Cost);
1989 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1990 unsigned &Offset) const {
1991 if (!Subtarget->isTargetLinux())
1994 if (Subtarget->is64Bit()) {
1995 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1997 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2009 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2010 unsigned DestAS) const {
2011 assert(SrcAS != DestAS && "Expected different address spaces!");
2013 return SrcAS < 256 && DestAS < 256;
2016 //===----------------------------------------------------------------------===//
2017 // Return Value Calling Convention Implementation
2018 //===----------------------------------------------------------------------===//
2020 #include "X86GenCallingConv.inc"
2023 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2024 MachineFunction &MF, bool isVarArg,
2025 const SmallVectorImpl<ISD::OutputArg> &Outs,
2026 LLVMContext &Context) const {
2027 SmallVector<CCValAssign, 16> RVLocs;
2028 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2029 return CCInfo.CheckReturn(Outs, RetCC_X86);
2032 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2033 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2038 X86TargetLowering::LowerReturn(SDValue Chain,
2039 CallingConv::ID CallConv, bool isVarArg,
2040 const SmallVectorImpl<ISD::OutputArg> &Outs,
2041 const SmallVectorImpl<SDValue> &OutVals,
2042 SDLoc dl, SelectionDAG &DAG) const {
2043 MachineFunction &MF = DAG.getMachineFunction();
2044 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2046 SmallVector<CCValAssign, 16> RVLocs;
2047 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2048 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2051 SmallVector<SDValue, 6> RetOps;
2052 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2053 // Operand #1 = Bytes To Pop
2054 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2057 // Copy the result values into the output registers.
2058 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2059 CCValAssign &VA = RVLocs[i];
2060 assert(VA.isRegLoc() && "Can only return in registers!");
2061 SDValue ValToCopy = OutVals[i];
2062 EVT ValVT = ValToCopy.getValueType();
2064 // Promote values to the appropriate types.
2065 if (VA.getLocInfo() == CCValAssign::SExt)
2066 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2067 else if (VA.getLocInfo() == CCValAssign::ZExt)
2068 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2069 else if (VA.getLocInfo() == CCValAssign::AExt) {
2070 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2071 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2073 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2075 else if (VA.getLocInfo() == CCValAssign::BCvt)
2076 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2078 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2079 "Unexpected FP-extend for return value.");
2081 // If this is x86-64, and we disabled SSE, we can't return FP values,
2082 // or SSE or MMX vectors.
2083 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2084 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2085 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2086 report_fatal_error("SSE register return with SSE disabled");
2088 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2089 // llvm-gcc has never done it right and no one has noticed, so this
2090 // should be OK for now.
2091 if (ValVT == MVT::f64 &&
2092 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2093 report_fatal_error("SSE2 register return with SSE2 disabled");
2095 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2096 // the RET instruction and handled by the FP Stackifier.
2097 if (VA.getLocReg() == X86::FP0 ||
2098 VA.getLocReg() == X86::FP1) {
2099 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2100 // change the value to the FP stack register class.
2101 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2102 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2103 RetOps.push_back(ValToCopy);
2104 // Don't emit a copytoreg.
2108 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2109 // which is returned in RAX / RDX.
2110 if (Subtarget->is64Bit()) {
2111 if (ValVT == MVT::x86mmx) {
2112 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2113 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2114 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2116 // If we don't have SSE2 available, convert to v4f32 so the generated
2117 // register is legal.
2118 if (!Subtarget->hasSSE2())
2119 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2124 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2125 Flag = Chain.getValue(1);
2126 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2129 // All x86 ABIs require that for returning structs by value we copy
2130 // the sret argument into %rax/%eax (depending on ABI) for the return.
2131 // We saved the argument into a virtual register in the entry block,
2132 // so now we copy the value out and into %rax/%eax.
2134 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2135 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2136 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2137 // either case FuncInfo->setSRetReturnReg() will have been called.
2138 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2139 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2140 getPointerTy(MF.getDataLayout()));
2143 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2144 X86::RAX : X86::EAX;
2145 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2146 Flag = Chain.getValue(1);
2148 // RAX/EAX now acts like a return value.
2150 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2153 RetOps[0] = Chain; // Update chain.
2155 // Add the flag if we have it.
2157 RetOps.push_back(Flag);
2159 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2162 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2163 if (N->getNumValues() != 1)
2165 if (!N->hasNUsesOfValue(1, 0))
2168 SDValue TCChain = Chain;
2169 SDNode *Copy = *N->use_begin();
2170 if (Copy->getOpcode() == ISD::CopyToReg) {
2171 // If the copy has a glue operand, we conservatively assume it isn't safe to
2172 // perform a tail call.
2173 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2175 TCChain = Copy->getOperand(0);
2176 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2179 bool HasRet = false;
2180 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2182 if (UI->getOpcode() != X86ISD::RET_FLAG)
2184 // If we are returning more than one value, we can definitely
2185 // not make a tail call see PR19530
2186 if (UI->getNumOperands() > 4)
2188 if (UI->getNumOperands() == 4 &&
2189 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2202 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2203 ISD::NodeType ExtendKind) const {
2205 // TODO: Is this also valid on 32-bit?
2206 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2207 ReturnMVT = MVT::i8;
2209 ReturnMVT = MVT::i32;
2211 EVT MinVT = getRegisterType(Context, ReturnMVT);
2212 return VT.bitsLT(MinVT) ? MinVT : VT;
2215 /// Lower the result values of a call into the
2216 /// appropriate copies out of appropriate physical registers.
2219 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2220 CallingConv::ID CallConv, bool isVarArg,
2221 const SmallVectorImpl<ISD::InputArg> &Ins,
2222 SDLoc dl, SelectionDAG &DAG,
2223 SmallVectorImpl<SDValue> &InVals) const {
2225 // Assign locations to each value returned by this call.
2226 SmallVector<CCValAssign, 16> RVLocs;
2227 bool Is64Bit = Subtarget->is64Bit();
2228 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2230 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2232 // Copy all of the result registers out of their specified physreg.
2233 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2234 CCValAssign &VA = RVLocs[i];
2235 EVT CopyVT = VA.getLocVT();
2237 // If this is x86-64, and we disabled SSE, we can't return FP values
2238 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2239 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2240 report_fatal_error("SSE register return with SSE disabled");
2243 // If we prefer to use the value in xmm registers, copy it out as f80 and
2244 // use a truncate to move it from fp stack reg to xmm reg.
2245 bool RoundAfterCopy = false;
2246 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2247 isScalarFPTypeInSSEReg(VA.getValVT())) {
2249 RoundAfterCopy = (CopyVT != VA.getLocVT());
2252 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2253 CopyVT, InFlag).getValue(1);
2254 SDValue Val = Chain.getValue(0);
2257 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2258 // This truncation won't change the value.
2259 DAG.getIntPtrConstant(1, dl));
2261 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2262 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2264 InFlag = Chain.getValue(2);
2265 InVals.push_back(Val);
2271 //===----------------------------------------------------------------------===//
2272 // C & StdCall & Fast Calling Convention implementation
2273 //===----------------------------------------------------------------------===//
2274 // StdCall calling convention seems to be standard for many Windows' API
2275 // routines and around. It differs from C calling convention just a little:
2276 // callee should clean up the stack, not caller. Symbols should be also
2277 // decorated in some fancy way :) It doesn't support any vector arguments.
2278 // For info on fast calling convention see Fast Calling Convention (tail call)
2279 // implementation LowerX86_32FastCCCallTo.
2281 /// CallIsStructReturn - Determines whether a call uses struct return
2283 enum StructReturnType {
2288 static StructReturnType
2289 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2291 return NotStructReturn;
2293 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2294 if (!Flags.isSRet())
2295 return NotStructReturn;
2296 if (Flags.isInReg())
2297 return RegStructReturn;
2298 return StackStructReturn;
2301 /// Determines whether a function uses struct return semantics.
2302 static StructReturnType
2303 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2305 return NotStructReturn;
2307 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2308 if (!Flags.isSRet())
2309 return NotStructReturn;
2310 if (Flags.isInReg())
2311 return RegStructReturn;
2312 return StackStructReturn;
2315 /// Make a copy of an aggregate at address specified by "Src" to address
2316 /// "Dst" with size and alignment information specified by the specific
2317 /// parameter attribute. The copy will be passed as a byval function parameter.
2319 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2320 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2322 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2324 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2325 /*isVolatile*/false, /*AlwaysInline=*/true,
2326 /*isTailCall*/false,
2327 MachinePointerInfo(), MachinePointerInfo());
2330 /// Return true if the calling convention is one that
2331 /// supports tail call optimization.
2332 static bool IsTailCallConvention(CallingConv::ID CC) {
2333 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2334 CC == CallingConv::HiPE);
2337 /// \brief Return true if the calling convention is a C calling convention.
2338 static bool IsCCallConvention(CallingConv::ID CC) {
2339 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2340 CC == CallingConv::X86_64_SysV);
2343 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2345 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2346 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2350 CallingConv::ID CalleeCC = CS.getCallingConv();
2351 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2357 /// Return true if the function is being made into
2358 /// a tailcall target by changing its ABI.
2359 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2360 bool GuaranteedTailCallOpt) {
2361 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2365 X86TargetLowering::LowerMemArgument(SDValue Chain,
2366 CallingConv::ID CallConv,
2367 const SmallVectorImpl<ISD::InputArg> &Ins,
2368 SDLoc dl, SelectionDAG &DAG,
2369 const CCValAssign &VA,
2370 MachineFrameInfo *MFI,
2372 // Create the nodes corresponding to a load from this parameter slot.
2373 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2374 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2375 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2376 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2379 // If value is passed by pointer we have address passed instead of the value
2381 bool ExtendedInMem = VA.isExtInLoc() &&
2382 VA.getValVT().getScalarType() == MVT::i1;
2384 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2385 ValVT = VA.getLocVT();
2387 ValVT = VA.getValVT();
2389 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2390 // changed with more analysis.
2391 // In case of tail call optimization mark all arguments mutable. Since they
2392 // could be overwritten by lowering of arguments in case of a tail call.
2393 if (Flags.isByVal()) {
2394 unsigned Bytes = Flags.getByValSize();
2395 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2396 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2397 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2399 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2400 VA.getLocMemOffset(), isImmutable);
2401 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2402 SDValue Val = DAG.getLoad(
2403 ValVT, dl, Chain, FIN,
2404 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2406 return ExtendedInMem ?
2407 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2411 // FIXME: Get this from tablegen.
2412 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2413 const X86Subtarget *Subtarget) {
2414 assert(Subtarget->is64Bit());
2416 if (Subtarget->isCallingConvWin64(CallConv)) {
2417 static const MCPhysReg GPR64ArgRegsWin64[] = {
2418 X86::RCX, X86::RDX, X86::R8, X86::R9
2420 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2423 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2424 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2426 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2429 // FIXME: Get this from tablegen.
2430 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2431 CallingConv::ID CallConv,
2432 const X86Subtarget *Subtarget) {
2433 assert(Subtarget->is64Bit());
2434 if (Subtarget->isCallingConvWin64(CallConv)) {
2435 // The XMM registers which might contain var arg parameters are shadowed
2436 // in their paired GPR. So we only need to save the GPR to their home
2438 // TODO: __vectorcall will change this.
2442 const Function *Fn = MF.getFunction();
2443 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2444 bool isSoftFloat = Subtarget->useSoftFloat();
2445 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2446 "SSE register cannot be used when SSE is disabled!");
2447 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2448 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2452 static const MCPhysReg XMMArgRegs64Bit[] = {
2453 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2454 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2456 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2460 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2461 CallingConv::ID CallConv,
2463 const SmallVectorImpl<ISD::InputArg> &Ins,
2466 SmallVectorImpl<SDValue> &InVals)
2468 MachineFunction &MF = DAG.getMachineFunction();
2469 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2470 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2472 const Function* Fn = MF.getFunction();
2473 if (Fn->hasExternalLinkage() &&
2474 Subtarget->isTargetCygMing() &&
2475 Fn->getName() == "main")
2476 FuncInfo->setForceFramePointer(true);
2478 MachineFrameInfo *MFI = MF.getFrameInfo();
2479 bool Is64Bit = Subtarget->is64Bit();
2480 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2482 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2483 "Var args not supported with calling convention fastcc, ghc or hipe");
2485 // Assign locations to all of the incoming arguments.
2486 SmallVector<CCValAssign, 16> ArgLocs;
2487 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2489 // Allocate shadow area for Win64
2491 CCInfo.AllocateStack(32, 8);
2493 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2495 unsigned LastVal = ~0U;
2497 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2498 CCValAssign &VA = ArgLocs[i];
2499 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2501 assert(VA.getValNo() != LastVal &&
2502 "Don't support value assigned to multiple locs yet");
2504 LastVal = VA.getValNo();
2506 if (VA.isRegLoc()) {
2507 EVT RegVT = VA.getLocVT();
2508 const TargetRegisterClass *RC;
2509 if (RegVT == MVT::i32)
2510 RC = &X86::GR32RegClass;
2511 else if (Is64Bit && RegVT == MVT::i64)
2512 RC = &X86::GR64RegClass;
2513 else if (RegVT == MVT::f32)
2514 RC = &X86::FR32RegClass;
2515 else if (RegVT == MVT::f64)
2516 RC = &X86::FR64RegClass;
2517 else if (RegVT.is512BitVector())
2518 RC = &X86::VR512RegClass;
2519 else if (RegVT.is256BitVector())
2520 RC = &X86::VR256RegClass;
2521 else if (RegVT.is128BitVector())
2522 RC = &X86::VR128RegClass;
2523 else if (RegVT == MVT::x86mmx)
2524 RC = &X86::VR64RegClass;
2525 else if (RegVT == MVT::i1)
2526 RC = &X86::VK1RegClass;
2527 else if (RegVT == MVT::v8i1)
2528 RC = &X86::VK8RegClass;
2529 else if (RegVT == MVT::v16i1)
2530 RC = &X86::VK16RegClass;
2531 else if (RegVT == MVT::v32i1)
2532 RC = &X86::VK32RegClass;
2533 else if (RegVT == MVT::v64i1)
2534 RC = &X86::VK64RegClass;
2536 llvm_unreachable("Unknown argument type!");
2538 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2539 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2541 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2542 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2544 if (VA.getLocInfo() == CCValAssign::SExt)
2545 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2546 DAG.getValueType(VA.getValVT()));
2547 else if (VA.getLocInfo() == CCValAssign::ZExt)
2548 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2549 DAG.getValueType(VA.getValVT()));
2550 else if (VA.getLocInfo() == CCValAssign::BCvt)
2551 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2553 if (VA.isExtInLoc()) {
2554 // Handle MMX values passed in XMM regs.
2555 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2556 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2558 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2561 assert(VA.isMemLoc());
2562 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2565 // If value is passed via pointer - do a load.
2566 if (VA.getLocInfo() == CCValAssign::Indirect)
2567 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2568 MachinePointerInfo(), false, false, false, 0);
2570 InVals.push_back(ArgValue);
2573 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2574 // All x86 ABIs require that for returning structs by value we copy the
2575 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2576 // the argument into a virtual register so that we can access it from the
2578 if (Ins[i].Flags.isSRet()) {
2579 unsigned Reg = FuncInfo->getSRetReturnReg();
2581 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2582 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2583 FuncInfo->setSRetReturnReg(Reg);
2585 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2586 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2591 unsigned StackSize = CCInfo.getNextStackOffset();
2592 // Align stack specially for tail calls.
2593 if (FuncIsMadeTailCallSafe(CallConv,
2594 MF.getTarget().Options.GuaranteedTailCallOpt))
2595 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2597 // If the function takes variable number of arguments, make a frame index for
2598 // the start of the first vararg value... for expansion of llvm.va_start. We
2599 // can skip this if there are no va_start calls.
2600 if (MFI->hasVAStart() &&
2601 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2602 CallConv != CallingConv::X86_ThisCall))) {
2603 FuncInfo->setVarArgsFrameIndex(
2604 MFI->CreateFixedObject(1, StackSize, true));
2607 MachineModuleInfo &MMI = MF.getMMI();
2608 const Function *WinEHParent = nullptr;
2609 if (MMI.hasWinEHFuncInfo(Fn))
2610 WinEHParent = MMI.getWinEHParent(Fn);
2611 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2612 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2614 // Figure out if XMM registers are in use.
2615 assert(!(Subtarget->useSoftFloat() &&
2616 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2617 "SSE register cannot be used when SSE is disabled!");
2619 // 64-bit calling conventions support varargs and register parameters, so we
2620 // have to do extra work to spill them in the prologue.
2621 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2622 // Find the first unallocated argument registers.
2623 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2624 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2625 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2626 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2627 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2628 "SSE register cannot be used when SSE is disabled!");
2630 // Gather all the live in physical registers.
2631 SmallVector<SDValue, 6> LiveGPRs;
2632 SmallVector<SDValue, 8> LiveXMMRegs;
2634 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2635 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2637 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2639 if (!ArgXMMs.empty()) {
2640 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2641 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2642 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2643 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2644 LiveXMMRegs.push_back(
2645 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2650 // Get to the caller-allocated home save location. Add 8 to account
2651 // for the return address.
2652 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2653 FuncInfo->setRegSaveFrameIndex(
2654 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2655 // Fixup to set vararg frame on shadow area (4 x i64).
2657 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2659 // For X86-64, if there are vararg parameters that are passed via
2660 // registers, then we must store them to their spots on the stack so
2661 // they may be loaded by deferencing the result of va_next.
2662 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2663 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2664 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2665 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2668 // Store the integer parameter registers.
2669 SmallVector<SDValue, 8> MemOps;
2670 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2671 getPointerTy(DAG.getDataLayout()));
2672 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2673 for (SDValue Val : LiveGPRs) {
2674 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2675 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2677 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2678 MachinePointerInfo::getFixedStack(
2679 DAG.getMachineFunction(),
2680 FuncInfo->getRegSaveFrameIndex(), Offset),
2682 MemOps.push_back(Store);
2686 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2687 // Now store the XMM (fp + vector) parameter registers.
2688 SmallVector<SDValue, 12> SaveXMMOps;
2689 SaveXMMOps.push_back(Chain);
2690 SaveXMMOps.push_back(ALVal);
2691 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2692 FuncInfo->getRegSaveFrameIndex(), dl));
2693 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2694 FuncInfo->getVarArgsFPOffset(), dl));
2695 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2697 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2698 MVT::Other, SaveXMMOps));
2701 if (!MemOps.empty())
2702 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2703 } else if (IsWin64 && IsWinEHOutlined) {
2704 // Get to the caller-allocated home save location. Add 8 to account
2705 // for the return address.
2706 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2707 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2708 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2710 MMI.getWinEHFuncInfo(Fn)
2711 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2712 FuncInfo->getRegSaveFrameIndex();
2714 // Store the second integer parameter (rdx) into rsp+16 relative to the
2715 // stack pointer at the entry of the function.
2716 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2717 getPointerTy(DAG.getDataLayout()));
2718 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2719 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2720 Chain = DAG.getStore(
2721 Val.getValue(1), dl, Val, RSFIN,
2722 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2723 FuncInfo->getRegSaveFrameIndex()),
2724 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2727 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2728 // Find the largest legal vector type.
2729 MVT VecVT = MVT::Other;
2730 // FIXME: Only some x86_32 calling conventions support AVX512.
2731 if (Subtarget->hasAVX512() &&
2732 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2733 CallConv == CallingConv::Intel_OCL_BI)))
2734 VecVT = MVT::v16f32;
2735 else if (Subtarget->hasAVX())
2737 else if (Subtarget->hasSSE2())
2740 // We forward some GPRs and some vector types.
2741 SmallVector<MVT, 2> RegParmTypes;
2742 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2743 RegParmTypes.push_back(IntVT);
2744 if (VecVT != MVT::Other)
2745 RegParmTypes.push_back(VecVT);
2747 // Compute the set of forwarded registers. The rest are scratch.
2748 SmallVectorImpl<ForwardedRegister> &Forwards =
2749 FuncInfo->getForwardedMustTailRegParms();
2750 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2752 // Conservatively forward AL on x86_64, since it might be used for varargs.
2753 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2754 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2755 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2758 // Copy all forwards from physical to virtual registers.
2759 for (ForwardedRegister &F : Forwards) {
2760 // FIXME: Can we use a less constrained schedule?
2761 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2762 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2763 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2767 // Some CCs need callee pop.
2768 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2769 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2770 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2772 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2773 // If this is an sret function, the return should pop the hidden pointer.
2774 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2775 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2776 argsAreStructReturn(Ins) == StackStructReturn)
2777 FuncInfo->setBytesToPopOnReturn(4);
2781 // RegSaveFrameIndex is X86-64 only.
2782 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2783 if (CallConv == CallingConv::X86_FastCall ||
2784 CallConv == CallingConv::X86_ThisCall)
2785 // fastcc functions can't have varargs.
2786 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2789 FuncInfo->setArgumentStackSize(StackSize);
2791 if (IsWinEHParent) {
2793 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2794 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2795 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2796 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2797 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2798 MachinePointerInfo::getFixedStack(
2799 DAG.getMachineFunction(), UnwindHelpFI),
2800 /*isVolatile=*/true,
2801 /*isNonTemporal=*/false, /*Alignment=*/0);
2803 // Functions using Win32 EH are considered to have opaque SP adjustments
2804 // to force local variables to be addressed from the frame or base
2806 MFI->setHasOpaqueSPAdjustment(true);
2814 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2815 SDValue StackPtr, SDValue Arg,
2816 SDLoc dl, SelectionDAG &DAG,
2817 const CCValAssign &VA,
2818 ISD::ArgFlagsTy Flags) const {
2819 unsigned LocMemOffset = VA.getLocMemOffset();
2820 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2821 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2823 if (Flags.isByVal())
2824 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2826 return DAG.getStore(
2827 Chain, dl, Arg, PtrOff,
2828 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2832 /// Emit a load of return address if tail call
2833 /// optimization is performed and it is required.
2835 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2836 SDValue &OutRetAddr, SDValue Chain,
2837 bool IsTailCall, bool Is64Bit,
2838 int FPDiff, SDLoc dl) const {
2839 // Adjust the Return address stack slot.
2840 EVT VT = getPointerTy(DAG.getDataLayout());
2841 OutRetAddr = getReturnAddressFrameIndex(DAG);
2843 // Load the "old" Return address.
2844 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2845 false, false, false, 0);
2846 return SDValue(OutRetAddr.getNode(), 1);
2849 /// Emit a store of the return address if tail call
2850 /// optimization is performed and it is required (FPDiff!=0).
2851 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2852 SDValue Chain, SDValue RetAddrFrIdx,
2853 EVT PtrVT, unsigned SlotSize,
2854 int FPDiff, SDLoc dl) {
2855 // Store the return address to the appropriate stack slot.
2856 if (!FPDiff) return Chain;
2857 // Calculate the new stack slot for the return address.
2858 int NewReturnAddrFI =
2859 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2861 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2862 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2863 MachinePointerInfo::getFixedStack(
2864 DAG.getMachineFunction(), NewReturnAddrFI),
2869 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2870 /// operation of specified width.
2871 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2873 unsigned NumElems = VT.getVectorNumElements();
2874 SmallVector<int, 8> Mask;
2875 Mask.push_back(NumElems);
2876 for (unsigned i = 1; i != NumElems; ++i)
2878 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2882 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2883 SmallVectorImpl<SDValue> &InVals) const {
2884 SelectionDAG &DAG = CLI.DAG;
2886 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2887 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2888 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2889 SDValue Chain = CLI.Chain;
2890 SDValue Callee = CLI.Callee;
2891 CallingConv::ID CallConv = CLI.CallConv;
2892 bool &isTailCall = CLI.IsTailCall;
2893 bool isVarArg = CLI.IsVarArg;
2895 MachineFunction &MF = DAG.getMachineFunction();
2896 bool Is64Bit = Subtarget->is64Bit();
2897 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2898 StructReturnType SR = callIsStructReturn(Outs);
2899 bool IsSibcall = false;
2900 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2901 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2903 if (Attr.getValueAsString() == "true")
2906 if (Subtarget->isPICStyleGOT() &&
2907 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2908 // If we are using a GOT, disable tail calls to external symbols with
2909 // default visibility. Tail calling such a symbol requires using a GOT
2910 // relocation, which forces early binding of the symbol. This breaks code
2911 // that require lazy function symbol resolution. Using musttail or
2912 // GuaranteedTailCallOpt will override this.
2913 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2914 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2915 G->getGlobal()->hasDefaultVisibility()))
2919 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2921 // Force this to be a tail call. The verifier rules are enough to ensure
2922 // that we can lower this successfully without moving the return address
2925 } else if (isTailCall) {
2926 // Check if it's really possible to do a tail call.
2927 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2928 isVarArg, SR != NotStructReturn,
2929 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2930 Outs, OutVals, Ins, DAG);
2932 // Sibcalls are automatically detected tailcalls which do not require
2934 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2941 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2942 "Var args not supported with calling convention fastcc, ghc or hipe");
2944 // Analyze operands of the call, assigning locations to each operand.
2945 SmallVector<CCValAssign, 16> ArgLocs;
2946 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2948 // Allocate shadow area for Win64
2950 CCInfo.AllocateStack(32, 8);
2952 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2954 // Get a count of how many bytes are to be pushed on the stack.
2955 unsigned NumBytes = CCInfo.getNextStackOffset();
2957 // This is a sibcall. The memory operands are available in caller's
2958 // own caller's stack.
2960 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2961 IsTailCallConvention(CallConv))
2962 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2965 if (isTailCall && !IsSibcall && !IsMustTail) {
2966 // Lower arguments at fp - stackoffset + fpdiff.
2967 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2969 FPDiff = NumBytesCallerPushed - NumBytes;
2971 // Set the delta of movement of the returnaddr stackslot.
2972 // But only set if delta is greater than previous delta.
2973 if (FPDiff < X86Info->getTCReturnAddrDelta())
2974 X86Info->setTCReturnAddrDelta(FPDiff);
2977 unsigned NumBytesToPush = NumBytes;
2978 unsigned NumBytesToPop = NumBytes;
2980 // If we have an inalloca argument, all stack space has already been allocated
2981 // for us and be right at the top of the stack. We don't support multiple
2982 // arguments passed in memory when using inalloca.
2983 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2985 if (!ArgLocs.back().isMemLoc())
2986 report_fatal_error("cannot use inalloca attribute on a register "
2988 if (ArgLocs.back().getLocMemOffset() != 0)
2989 report_fatal_error("any parameter with the inalloca attribute must be "
2990 "the only memory argument");
2994 Chain = DAG.getCALLSEQ_START(
2995 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2997 SDValue RetAddrFrIdx;
2998 // Load return address for tail calls.
2999 if (isTailCall && FPDiff)
3000 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3001 Is64Bit, FPDiff, dl);
3003 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3004 SmallVector<SDValue, 8> MemOpChains;
3007 // Walk the register/memloc assignments, inserting copies/loads. In the case
3008 // of tail call optimization arguments are handle later.
3009 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3010 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3011 // Skip inalloca arguments, they have already been written.
3012 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3013 if (Flags.isInAlloca())
3016 CCValAssign &VA = ArgLocs[i];
3017 EVT RegVT = VA.getLocVT();
3018 SDValue Arg = OutVals[i];
3019 bool isByVal = Flags.isByVal();
3021 // Promote the value if needed.
3022 switch (VA.getLocInfo()) {
3023 default: llvm_unreachable("Unknown loc info!");
3024 case CCValAssign::Full: break;
3025 case CCValAssign::SExt:
3026 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3028 case CCValAssign::ZExt:
3029 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3031 case CCValAssign::AExt:
3032 if (Arg.getValueType().isVector() &&
3033 Arg.getValueType().getScalarType() == MVT::i1)
3034 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3035 else if (RegVT.is128BitVector()) {
3036 // Special case: passing MMX values in XMM registers.
3037 Arg = DAG.getBitcast(MVT::i64, Arg);
3038 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3039 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3041 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3043 case CCValAssign::BCvt:
3044 Arg = DAG.getBitcast(RegVT, Arg);
3046 case CCValAssign::Indirect: {
3047 // Store the argument.
3048 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3049 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3050 Chain = DAG.getStore(
3051 Chain, dl, Arg, SpillSlot,
3052 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3059 if (VA.isRegLoc()) {
3060 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3061 if (isVarArg && IsWin64) {
3062 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3063 // shadow reg if callee is a varargs function.
3064 unsigned ShadowReg = 0;
3065 switch (VA.getLocReg()) {
3066 case X86::XMM0: ShadowReg = X86::RCX; break;
3067 case X86::XMM1: ShadowReg = X86::RDX; break;
3068 case X86::XMM2: ShadowReg = X86::R8; break;
3069 case X86::XMM3: ShadowReg = X86::R9; break;
3072 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3074 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3075 assert(VA.isMemLoc());
3076 if (!StackPtr.getNode())
3077 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3078 getPointerTy(DAG.getDataLayout()));
3079 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3080 dl, DAG, VA, Flags));
3084 if (!MemOpChains.empty())
3085 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3087 if (Subtarget->isPICStyleGOT()) {
3088 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3091 RegsToPass.push_back(std::make_pair(
3092 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3093 getPointerTy(DAG.getDataLayout()))));
3095 // If we are tail calling and generating PIC/GOT style code load the
3096 // address of the callee into ECX. The value in ecx is used as target of
3097 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3098 // for tail calls on PIC/GOT architectures. Normally we would just put the
3099 // address of GOT into ebx and then call target@PLT. But for tail calls
3100 // ebx would be restored (since ebx is callee saved) before jumping to the
3103 // Note: The actual moving to ECX is done further down.
3104 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3105 if (G && !G->getGlobal()->hasLocalLinkage() &&
3106 G->getGlobal()->hasDefaultVisibility())
3107 Callee = LowerGlobalAddress(Callee, DAG);
3108 else if (isa<ExternalSymbolSDNode>(Callee))
3109 Callee = LowerExternalSymbol(Callee, DAG);
3113 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3114 // From AMD64 ABI document:
3115 // For calls that may call functions that use varargs or stdargs
3116 // (prototype-less calls or calls to functions containing ellipsis (...) in
3117 // the declaration) %al is used as hidden argument to specify the number
3118 // of SSE registers used. The contents of %al do not need to match exactly
3119 // the number of registers, but must be an ubound on the number of SSE
3120 // registers used and is in the range 0 - 8 inclusive.
3122 // Count the number of XMM registers allocated.
3123 static const MCPhysReg XMMArgRegs[] = {
3124 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3125 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3127 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3128 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3129 && "SSE registers cannot be used when SSE is disabled");
3131 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3132 DAG.getConstant(NumXMMRegs, dl,
3136 if (isVarArg && IsMustTail) {
3137 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3138 for (const auto &F : Forwards) {
3139 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3140 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3144 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3145 // don't need this because the eligibility check rejects calls that require
3146 // shuffling arguments passed in memory.
3147 if (!IsSibcall && isTailCall) {
3148 // Force all the incoming stack arguments to be loaded from the stack
3149 // before any new outgoing arguments are stored to the stack, because the
3150 // outgoing stack slots may alias the incoming argument stack slots, and
3151 // the alias isn't otherwise explicit. This is slightly more conservative
3152 // than necessary, because it means that each store effectively depends
3153 // on every argument instead of just those arguments it would clobber.
3154 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3156 SmallVector<SDValue, 8> MemOpChains2;
3159 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3160 CCValAssign &VA = ArgLocs[i];
3163 assert(VA.isMemLoc());
3164 SDValue Arg = OutVals[i];
3165 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3166 // Skip inalloca arguments. They don't require any work.
3167 if (Flags.isInAlloca())
3169 // Create frame index.
3170 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3171 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3172 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3173 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3175 if (Flags.isByVal()) {
3176 // Copy relative to framepointer.
3177 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3178 if (!StackPtr.getNode())
3179 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3180 getPointerTy(DAG.getDataLayout()));
3181 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3184 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3188 // Store relative to framepointer.
3189 MemOpChains2.push_back(DAG.getStore(
3190 ArgChain, dl, Arg, FIN,
3191 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3196 if (!MemOpChains2.empty())
3197 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3199 // Store the return address to the appropriate stack slot.
3200 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3201 getPointerTy(DAG.getDataLayout()),
3202 RegInfo->getSlotSize(), FPDiff, dl);
3205 // Build a sequence of copy-to-reg nodes chained together with token chain
3206 // and flag operands which copy the outgoing args into registers.
3208 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3209 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3210 RegsToPass[i].second, InFlag);
3211 InFlag = Chain.getValue(1);
3214 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3215 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3216 // In the 64-bit large code model, we have to make all calls
3217 // through a register, since the call instruction's 32-bit
3218 // pc-relative offset may not be large enough to hold the whole
3220 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3221 // If the callee is a GlobalAddress node (quite common, every direct call
3222 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3224 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3226 // We should use extra load for direct calls to dllimported functions in
3228 const GlobalValue *GV = G->getGlobal();
3229 if (!GV->hasDLLImportStorageClass()) {
3230 unsigned char OpFlags = 0;
3231 bool ExtraLoad = false;
3232 unsigned WrapperKind = ISD::DELETED_NODE;
3234 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3235 // external symbols most go through the PLT in PIC mode. If the symbol
3236 // has hidden or protected visibility, or if it is static or local, then
3237 // we don't need to use the PLT - we can directly call it.
3238 if (Subtarget->isTargetELF() &&
3239 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3240 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3241 OpFlags = X86II::MO_PLT;
3242 } else if (Subtarget->isPICStyleStubAny() &&
3243 !GV->isStrongDefinitionForLinker() &&
3244 (!Subtarget->getTargetTriple().isMacOSX() ||
3245 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3246 // PC-relative references to external symbols should go through $stub,
3247 // unless we're building with the leopard linker or later, which
3248 // automatically synthesizes these stubs.
3249 OpFlags = X86II::MO_DARWIN_STUB;
3250 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3251 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3252 // If the function is marked as non-lazy, generate an indirect call
3253 // which loads from the GOT directly. This avoids runtime overhead
3254 // at the cost of eager binding (and one extra byte of encoding).
3255 OpFlags = X86II::MO_GOTPCREL;
3256 WrapperKind = X86ISD::WrapperRIP;
3260 Callee = DAG.getTargetGlobalAddress(
3261 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3263 // Add a wrapper if needed.
3264 if (WrapperKind != ISD::DELETED_NODE)
3265 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3266 getPointerTy(DAG.getDataLayout()), Callee);
3267 // Add extra indirection if needed.
3269 Callee = DAG.getLoad(
3270 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3271 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3274 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3275 unsigned char OpFlags = 0;
3277 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3278 // external symbols should go through the PLT.
3279 if (Subtarget->isTargetELF() &&
3280 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3281 OpFlags = X86II::MO_PLT;
3282 } else if (Subtarget->isPICStyleStubAny() &&
3283 (!Subtarget->getTargetTriple().isMacOSX() ||
3284 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3285 // PC-relative references to external symbols should go through $stub,
3286 // unless we're building with the leopard linker or later, which
3287 // automatically synthesizes these stubs.
3288 OpFlags = X86II::MO_DARWIN_STUB;
3291 Callee = DAG.getTargetExternalSymbol(
3292 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3293 } else if (Subtarget->isTarget64BitILP32() &&
3294 Callee->getValueType(0) == MVT::i32) {
3295 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3296 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3299 // Returns a chain & a flag for retval copy to use.
3300 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3301 SmallVector<SDValue, 8> Ops;
3303 if (!IsSibcall && isTailCall) {
3304 Chain = DAG.getCALLSEQ_END(Chain,
3305 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3306 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3307 InFlag = Chain.getValue(1);
3310 Ops.push_back(Chain);
3311 Ops.push_back(Callee);
3314 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3316 // Add argument registers to the end of the list so that they are known live
3318 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3319 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3320 RegsToPass[i].second.getValueType()));
3322 // Add a register mask operand representing the call-preserved registers.
3323 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3324 assert(Mask && "Missing call preserved mask for calling convention");
3326 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3327 // the function clobbers all registers. If an exception is thrown, the runtime
3328 // will not restore CSRs.
3329 // FIXME: Model this more precisely so that we can register allocate across
3330 // the normal edge and spill and fill across the exceptional edge.
3331 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3332 const Function *CallerFn = MF.getFunction();
3333 EHPersonality Pers =
3334 CallerFn->hasPersonalityFn()
3335 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3336 : EHPersonality::Unknown;
3337 if (isMSVCEHPersonality(Pers))
3338 Mask = RegInfo->getNoPreservedMask();
3341 Ops.push_back(DAG.getRegisterMask(Mask));
3343 if (InFlag.getNode())
3344 Ops.push_back(InFlag);
3348 //// If this is the first return lowered for this function, add the regs
3349 //// to the liveout set for the function.
3350 // This isn't right, although it's probably harmless on x86; liveouts
3351 // should be computed from returns not tail calls. Consider a void
3352 // function making a tail call to a function returning int.
3353 MF.getFrameInfo()->setHasTailCall();
3354 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3357 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3358 InFlag = Chain.getValue(1);
3360 // Create the CALLSEQ_END node.
3361 unsigned NumBytesForCalleeToPop;
3362 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3363 DAG.getTarget().Options.GuaranteedTailCallOpt))
3364 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3365 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3366 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3367 SR == StackStructReturn)
3368 // If this is a call to a struct-return function, the callee
3369 // pops the hidden struct pointer, so we have to push it back.
3370 // This is common for Darwin/X86, Linux & Mingw32 targets.
3371 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3372 NumBytesForCalleeToPop = 4;
3374 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3376 // Returns a flag for retval copy to use.
3378 Chain = DAG.getCALLSEQ_END(Chain,
3379 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3380 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3383 InFlag = Chain.getValue(1);
3386 // Handle result values, copying them out of physregs into vregs that we
3388 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3389 Ins, dl, DAG, InVals);
3392 //===----------------------------------------------------------------------===//
3393 // Fast Calling Convention (tail call) implementation
3394 //===----------------------------------------------------------------------===//
3396 // Like std call, callee cleans arguments, convention except that ECX is
3397 // reserved for storing the tail called function address. Only 2 registers are
3398 // free for argument passing (inreg). Tail call optimization is performed
3400 // * tailcallopt is enabled
3401 // * caller/callee are fastcc
3402 // On X86_64 architecture with GOT-style position independent code only local
3403 // (within module) calls are supported at the moment.
3404 // To keep the stack aligned according to platform abi the function
3405 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3406 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3407 // If a tail called function callee has more arguments than the caller the
3408 // caller needs to make sure that there is room to move the RETADDR to. This is
3409 // achieved by reserving an area the size of the argument delta right after the
3410 // original RETADDR, but before the saved framepointer or the spilled registers
3411 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3423 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3426 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3427 SelectionDAG& DAG) const {
3428 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3429 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3430 unsigned StackAlignment = TFI.getStackAlignment();
3431 uint64_t AlignMask = StackAlignment - 1;
3432 int64_t Offset = StackSize;
3433 unsigned SlotSize = RegInfo->getSlotSize();
3434 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3435 // Number smaller than 12 so just add the difference.
3436 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3438 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3439 Offset = ((~AlignMask) & Offset) + StackAlignment +
3440 (StackAlignment-SlotSize);
3445 /// Return true if the given stack call argument is already available in the
3446 /// same position (relatively) of the caller's incoming argument stack.
3448 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3449 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3450 const X86InstrInfo *TII) {
3451 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3453 if (Arg.getOpcode() == ISD::CopyFromReg) {
3454 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3455 if (!TargetRegisterInfo::isVirtualRegister(VR))
3457 MachineInstr *Def = MRI->getVRegDef(VR);
3460 if (!Flags.isByVal()) {
3461 if (!TII->isLoadFromStackSlot(Def, FI))
3464 unsigned Opcode = Def->getOpcode();
3465 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3466 Opcode == X86::LEA64_32r) &&
3467 Def->getOperand(1).isFI()) {
3468 FI = Def->getOperand(1).getIndex();
3469 Bytes = Flags.getByValSize();
3473 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3474 if (Flags.isByVal())
3475 // ByVal argument is passed in as a pointer but it's now being
3476 // dereferenced. e.g.
3477 // define @foo(%struct.X* %A) {
3478 // tail call @bar(%struct.X* byval %A)
3481 SDValue Ptr = Ld->getBasePtr();
3482 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3485 FI = FINode->getIndex();
3486 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3487 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3488 FI = FINode->getIndex();
3489 Bytes = Flags.getByValSize();
3493 assert(FI != INT_MAX);
3494 if (!MFI->isFixedObjectIndex(FI))
3496 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3499 /// Check whether the call is eligible for tail call optimization. Targets
3500 /// that want to do tail call optimization should implement this function.
3502 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3503 CallingConv::ID CalleeCC,
3505 bool isCalleeStructRet,
3506 bool isCallerStructRet,
3508 const SmallVectorImpl<ISD::OutputArg> &Outs,
3509 const SmallVectorImpl<SDValue> &OutVals,
3510 const SmallVectorImpl<ISD::InputArg> &Ins,
3511 SelectionDAG &DAG) const {
3512 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3515 // If -tailcallopt is specified, make fastcc functions tail-callable.
3516 const MachineFunction &MF = DAG.getMachineFunction();
3517 const Function *CallerF = MF.getFunction();
3519 // If the function return type is x86_fp80 and the callee return type is not,
3520 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3521 // perform a tailcall optimization here.
3522 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3525 CallingConv::ID CallerCC = CallerF->getCallingConv();
3526 bool CCMatch = CallerCC == CalleeCC;
3527 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3528 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3530 // Win64 functions have extra shadow space for argument homing. Don't do the
3531 // sibcall if the caller and callee have mismatched expectations for this
3533 if (IsCalleeWin64 != IsCallerWin64)
3536 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3537 if (IsTailCallConvention(CalleeCC) && CCMatch)
3542 // Look for obvious safe cases to perform tail call optimization that do not
3543 // require ABI changes. This is what gcc calls sibcall.
3545 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3546 // emit a special epilogue.
3547 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3548 if (RegInfo->needsStackRealignment(MF))
3551 // Also avoid sibcall optimization if either caller or callee uses struct
3552 // return semantics.
3553 if (isCalleeStructRet || isCallerStructRet)
3556 // An stdcall/thiscall caller is expected to clean up its arguments; the
3557 // callee isn't going to do that.
3558 // FIXME: this is more restrictive than needed. We could produce a tailcall
3559 // when the stack adjustment matches. For example, with a thiscall that takes
3560 // only one argument.
3561 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3562 CallerCC == CallingConv::X86_ThisCall))
3565 // Do not sibcall optimize vararg calls unless all arguments are passed via
3567 if (isVarArg && !Outs.empty()) {
3569 // Optimizing for varargs on Win64 is unlikely to be safe without
3570 // additional testing.
3571 if (IsCalleeWin64 || IsCallerWin64)
3574 SmallVector<CCValAssign, 16> ArgLocs;
3575 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3578 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3579 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3580 if (!ArgLocs[i].isRegLoc())
3584 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3585 // stack. Therefore, if it's not used by the call it is not safe to optimize
3586 // this into a sibcall.
3587 bool Unused = false;
3588 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3595 SmallVector<CCValAssign, 16> RVLocs;
3596 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3598 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3599 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3600 CCValAssign &VA = RVLocs[i];
3601 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3606 // If the calling conventions do not match, then we'd better make sure the
3607 // results are returned in the same way as what the caller expects.
3609 SmallVector<CCValAssign, 16> RVLocs1;
3610 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3612 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3614 SmallVector<CCValAssign, 16> RVLocs2;
3615 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3617 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3619 if (RVLocs1.size() != RVLocs2.size())
3621 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3622 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3624 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3626 if (RVLocs1[i].isRegLoc()) {
3627 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3630 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3636 // If the callee takes no arguments then go on to check the results of the
3638 if (!Outs.empty()) {
3639 // Check if stack adjustment is needed. For now, do not do this if any
3640 // argument is passed on the stack.
3641 SmallVector<CCValAssign, 16> ArgLocs;
3642 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3645 // Allocate shadow area for Win64
3647 CCInfo.AllocateStack(32, 8);
3649 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3650 if (CCInfo.getNextStackOffset()) {
3651 MachineFunction &MF = DAG.getMachineFunction();
3652 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3655 // Check if the arguments are already laid out in the right way as
3656 // the caller's fixed stack objects.
3657 MachineFrameInfo *MFI = MF.getFrameInfo();
3658 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3659 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3660 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3661 CCValAssign &VA = ArgLocs[i];
3662 SDValue Arg = OutVals[i];
3663 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3664 if (VA.getLocInfo() == CCValAssign::Indirect)
3666 if (!VA.isRegLoc()) {
3667 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3674 // If the tailcall address may be in a register, then make sure it's
3675 // possible to register allocate for it. In 32-bit, the call address can
3676 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3677 // callee-saved registers are restored. These happen to be the same
3678 // registers used to pass 'inreg' arguments so watch out for those.
3679 if (!Subtarget->is64Bit() &&
3680 ((!isa<GlobalAddressSDNode>(Callee) &&
3681 !isa<ExternalSymbolSDNode>(Callee)) ||
3682 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3683 unsigned NumInRegs = 0;
3684 // In PIC we need an extra register to formulate the address computation
3686 unsigned MaxInRegs =
3687 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3689 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3690 CCValAssign &VA = ArgLocs[i];
3693 unsigned Reg = VA.getLocReg();
3696 case X86::EAX: case X86::EDX: case X86::ECX:
3697 if (++NumInRegs == MaxInRegs)
3709 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3710 const TargetLibraryInfo *libInfo) const {
3711 return X86::createFastISel(funcInfo, libInfo);
3714 //===----------------------------------------------------------------------===//
3715 // Other Lowering Hooks
3716 //===----------------------------------------------------------------------===//
3718 static bool MayFoldLoad(SDValue Op) {
3719 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3722 static bool MayFoldIntoStore(SDValue Op) {
3723 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3726 static bool isTargetShuffle(unsigned Opcode) {
3728 default: return false;
3729 case X86ISD::BLENDI:
3730 case X86ISD::PSHUFB:
3731 case X86ISD::PSHUFD:
3732 case X86ISD::PSHUFHW:
3733 case X86ISD::PSHUFLW:
3735 case X86ISD::PALIGNR:
3736 case X86ISD::MOVLHPS:
3737 case X86ISD::MOVLHPD:
3738 case X86ISD::MOVHLPS:
3739 case X86ISD::MOVLPS:
3740 case X86ISD::MOVLPD:
3741 case X86ISD::MOVSHDUP:
3742 case X86ISD::MOVSLDUP:
3743 case X86ISD::MOVDDUP:
3746 case X86ISD::UNPCKL:
3747 case X86ISD::UNPCKH:
3748 case X86ISD::VPERMILPI:
3749 case X86ISD::VPERM2X128:
3750 case X86ISD::VPERMI:
3755 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3756 SDValue V1, unsigned TargetMask,
3757 SelectionDAG &DAG) {
3759 default: llvm_unreachable("Unknown x86 shuffle node");
3760 case X86ISD::PSHUFD:
3761 case X86ISD::PSHUFHW:
3762 case X86ISD::PSHUFLW:
3763 case X86ISD::VPERMILPI:
3764 case X86ISD::VPERMI:
3765 return DAG.getNode(Opc, dl, VT, V1,
3766 DAG.getConstant(TargetMask, dl, MVT::i8));
3770 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3771 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3773 default: llvm_unreachable("Unknown x86 shuffle node");
3774 case X86ISD::MOVLHPS:
3775 case X86ISD::MOVLHPD:
3776 case X86ISD::MOVHLPS:
3777 case X86ISD::MOVLPS:
3778 case X86ISD::MOVLPD:
3781 case X86ISD::UNPCKL:
3782 case X86ISD::UNPCKH:
3783 return DAG.getNode(Opc, dl, VT, V1, V2);
3787 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3788 MachineFunction &MF = DAG.getMachineFunction();
3789 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3790 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3791 int ReturnAddrIndex = FuncInfo->getRAIndex();
3793 if (ReturnAddrIndex == 0) {
3794 // Set up a frame object for the return address.
3795 unsigned SlotSize = RegInfo->getSlotSize();
3796 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3799 FuncInfo->setRAIndex(ReturnAddrIndex);
3802 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3805 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3806 bool hasSymbolicDisplacement) {
3807 // Offset should fit into 32 bit immediate field.
3808 if (!isInt<32>(Offset))
3811 // If we don't have a symbolic displacement - we don't have any extra
3813 if (!hasSymbolicDisplacement)
3816 // FIXME: Some tweaks might be needed for medium code model.
3817 if (M != CodeModel::Small && M != CodeModel::Kernel)
3820 // For small code model we assume that latest object is 16MB before end of 31
3821 // bits boundary. We may also accept pretty large negative constants knowing
3822 // that all objects are in the positive half of address space.
3823 if (M == CodeModel::Small && Offset < 16*1024*1024)
3826 // For kernel code model we know that all object resist in the negative half
3827 // of 32bits address space. We may not accept negative offsets, since they may
3828 // be just off and we may accept pretty large positive ones.
3829 if (M == CodeModel::Kernel && Offset >= 0)
3835 /// Determines whether the callee is required to pop its own arguments.
3836 /// Callee pop is necessary to support tail calls.
3837 bool X86::isCalleePop(CallingConv::ID CallingConv,
3838 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3839 switch (CallingConv) {
3842 case CallingConv::X86_StdCall:
3843 case CallingConv::X86_FastCall:
3844 case CallingConv::X86_ThisCall:
3846 case CallingConv::Fast:
3847 case CallingConv::GHC:
3848 case CallingConv::HiPE:
3855 /// \brief Return true if the condition is an unsigned comparison operation.
3856 static bool isX86CCUnsigned(unsigned X86CC) {
3858 default: llvm_unreachable("Invalid integer condition!");
3859 case X86::COND_E: return true;
3860 case X86::COND_G: return false;
3861 case X86::COND_GE: return false;
3862 case X86::COND_L: return false;
3863 case X86::COND_LE: return false;
3864 case X86::COND_NE: return true;
3865 case X86::COND_B: return true;
3866 case X86::COND_A: return true;
3867 case X86::COND_BE: return true;
3868 case X86::COND_AE: return true;
3870 llvm_unreachable("covered switch fell through?!");
3873 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3874 /// condition code, returning the condition code and the LHS/RHS of the
3875 /// comparison to make.
3876 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3877 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3879 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3880 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3881 // X > -1 -> X == 0, jump !sign.
3882 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3883 return X86::COND_NS;
3885 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3886 // X < 0 -> X == 0, jump on sign.
3889 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3891 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3892 return X86::COND_LE;
3896 switch (SetCCOpcode) {
3897 default: llvm_unreachable("Invalid integer condition!");
3898 case ISD::SETEQ: return X86::COND_E;
3899 case ISD::SETGT: return X86::COND_G;
3900 case ISD::SETGE: return X86::COND_GE;
3901 case ISD::SETLT: return X86::COND_L;
3902 case ISD::SETLE: return X86::COND_LE;
3903 case ISD::SETNE: return X86::COND_NE;
3904 case ISD::SETULT: return X86::COND_B;
3905 case ISD::SETUGT: return X86::COND_A;
3906 case ISD::SETULE: return X86::COND_BE;
3907 case ISD::SETUGE: return X86::COND_AE;
3911 // First determine if it is required or is profitable to flip the operands.
3913 // If LHS is a foldable load, but RHS is not, flip the condition.
3914 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3915 !ISD::isNON_EXTLoad(RHS.getNode())) {
3916 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3917 std::swap(LHS, RHS);
3920 switch (SetCCOpcode) {
3926 std::swap(LHS, RHS);
3930 // On a floating point condition, the flags are set as follows:
3932 // 0 | 0 | 0 | X > Y
3933 // 0 | 0 | 1 | X < Y
3934 // 1 | 0 | 0 | X == Y
3935 // 1 | 1 | 1 | unordered
3936 switch (SetCCOpcode) {
3937 default: llvm_unreachable("Condcode should be pre-legalized away");
3939 case ISD::SETEQ: return X86::COND_E;
3940 case ISD::SETOLT: // flipped
3942 case ISD::SETGT: return X86::COND_A;
3943 case ISD::SETOLE: // flipped
3945 case ISD::SETGE: return X86::COND_AE;
3946 case ISD::SETUGT: // flipped
3948 case ISD::SETLT: return X86::COND_B;
3949 case ISD::SETUGE: // flipped
3951 case ISD::SETLE: return X86::COND_BE;
3953 case ISD::SETNE: return X86::COND_NE;
3954 case ISD::SETUO: return X86::COND_P;
3955 case ISD::SETO: return X86::COND_NP;
3957 case ISD::SETUNE: return X86::COND_INVALID;
3961 /// Is there a floating point cmov for the specific X86 condition code?
3962 /// Current x86 isa includes the following FP cmov instructions:
3963 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3964 static bool hasFPCMov(unsigned X86CC) {
3980 /// Returns true if the target can instruction select the
3981 /// specified FP immediate natively. If false, the legalizer will
3982 /// materialize the FP immediate as a load from a constant pool.
3983 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3984 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3985 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3991 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3992 ISD::LoadExtType ExtTy,
3994 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3995 // relocation target a movq or addq instruction: don't let the load shrink.
3996 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3997 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3998 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3999 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4003 /// \brief Returns true if it is beneficial to convert a load of a constant
4004 /// to just the constant itself.
4005 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4007 assert(Ty->isIntegerTy());
4009 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4010 if (BitSize == 0 || BitSize > 64)
4015 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4016 unsigned Index) const {
4017 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4020 return (Index == 0 || Index == ResVT.getVectorNumElements());
4023 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4024 // Speculate cttz only if we can directly use TZCNT.
4025 return Subtarget->hasBMI();
4028 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4029 // Speculate ctlz only if we can directly use LZCNT.
4030 return Subtarget->hasLZCNT();
4033 /// Return true if every element in Mask, beginning
4034 /// from position Pos and ending in Pos+Size is undef.
4035 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4036 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4042 /// Return true if Val is undef or if its value falls within the
4043 /// specified range (L, H].
4044 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4045 return (Val < 0) || (Val >= Low && Val < Hi);
4048 /// Val is either less than zero (undef) or equal to the specified value.
4049 static bool isUndefOrEqual(int Val, int CmpVal) {
4050 return (Val < 0 || Val == CmpVal);
4053 /// Return true if every element in Mask, beginning
4054 /// from position Pos and ending in Pos+Size, falls within the specified
4055 /// sequential range (Low, Low+Size]. or is undef.
4056 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4057 unsigned Pos, unsigned Size, int Low) {
4058 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4059 if (!isUndefOrEqual(Mask[i], Low))
4064 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4065 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4066 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4067 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4068 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4071 // The index should be aligned on a vecWidth-bit boundary.
4073 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4075 MVT VT = N->getSimpleValueType(0);
4076 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4077 bool Result = (Index * ElSize) % vecWidth == 0;
4082 /// Return true if the specified INSERT_SUBVECTOR
4083 /// operand specifies a subvector insert that is suitable for input to
4084 /// insertion of 128 or 256-bit subvectors
4085 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4086 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4087 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4089 // The index should be aligned on a vecWidth-bit boundary.
4091 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4093 MVT VT = N->getSimpleValueType(0);
4094 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4095 bool Result = (Index * ElSize) % vecWidth == 0;
4100 bool X86::isVINSERT128Index(SDNode *N) {
4101 return isVINSERTIndex(N, 128);
4104 bool X86::isVINSERT256Index(SDNode *N) {
4105 return isVINSERTIndex(N, 256);
4108 bool X86::isVEXTRACT128Index(SDNode *N) {
4109 return isVEXTRACTIndex(N, 128);
4112 bool X86::isVEXTRACT256Index(SDNode *N) {
4113 return isVEXTRACTIndex(N, 256);
4116 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4117 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4118 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4119 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4122 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4124 MVT VecVT = N->getOperand(0).getSimpleValueType();
4125 MVT ElVT = VecVT.getVectorElementType();
4127 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4128 return Index / NumElemsPerChunk;
4131 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4132 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4133 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4134 llvm_unreachable("Illegal insert subvector for VINSERT");
4137 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4139 MVT VecVT = N->getSimpleValueType(0);
4140 MVT ElVT = VecVT.getVectorElementType();
4142 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4143 return Index / NumElemsPerChunk;
4146 /// Return the appropriate immediate to extract the specified
4147 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4148 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4149 return getExtractVEXTRACTImmediate(N, 128);
4152 /// Return the appropriate immediate to extract the specified
4153 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4154 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4155 return getExtractVEXTRACTImmediate(N, 256);
4158 /// Return the appropriate immediate to insert at the specified
4159 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4160 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4161 return getInsertVINSERTImmediate(N, 128);
4164 /// Return the appropriate immediate to insert at the specified
4165 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4166 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4167 return getInsertVINSERTImmediate(N, 256);
4170 /// Returns true if Elt is a constant integer zero
4171 static bool isZero(SDValue V) {
4172 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4173 return C && C->isNullValue();
4176 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4177 bool X86::isZeroNode(SDValue Elt) {
4180 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4181 return CFP->getValueAPF().isPosZero();
4185 /// Returns a vector of specified type with all zero elements.
4186 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4187 SelectionDAG &DAG, SDLoc dl) {
4188 assert(VT.isVector() && "Expected a vector type");
4190 // Always build SSE zero vectors as <4 x i32> bitcasted
4191 // to their dest type. This ensures they get CSE'd.
4193 if (VT.is128BitVector()) { // SSE
4194 if (Subtarget->hasSSE2()) { // SSE2
4195 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4196 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4198 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4199 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4201 } else if (VT.is256BitVector()) { // AVX
4202 if (Subtarget->hasInt256()) { // AVX2
4203 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4204 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4205 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4207 // 256-bit logic and arithmetic instructions in AVX are all
4208 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4209 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4210 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4211 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4213 } else if (VT.is512BitVector()) { // AVX-512
4214 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4215 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4216 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4217 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4218 } else if (VT.getScalarType() == MVT::i1) {
4220 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4221 && "Unexpected vector type");
4222 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4223 && "Unexpected vector type");
4224 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4225 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4226 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4228 llvm_unreachable("Unexpected vector type");
4230 return DAG.getBitcast(VT, Vec);
4233 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4234 SelectionDAG &DAG, SDLoc dl,
4235 unsigned vectorWidth) {
4236 assert((vectorWidth == 128 || vectorWidth == 256) &&
4237 "Unsupported vector width");
4238 EVT VT = Vec.getValueType();
4239 EVT ElVT = VT.getVectorElementType();
4240 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4241 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4242 VT.getVectorNumElements()/Factor);
4244 // Extract from UNDEF is UNDEF.
4245 if (Vec.getOpcode() == ISD::UNDEF)
4246 return DAG.getUNDEF(ResultVT);
4248 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4249 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4251 // This is the index of the first element of the vectorWidth-bit chunk
4253 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4256 // If the input is a buildvector just emit a smaller one.
4257 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4258 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4259 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4262 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4263 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4266 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4267 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4268 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4269 /// instructions or a simple subregister reference. Idx is an index in the
4270 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4271 /// lowering EXTRACT_VECTOR_ELT operations easier.
4272 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4273 SelectionDAG &DAG, SDLoc dl) {
4274 assert((Vec.getValueType().is256BitVector() ||
4275 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4276 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4279 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4280 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4281 SelectionDAG &DAG, SDLoc dl) {
4282 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4283 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4286 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4287 unsigned IdxVal, SelectionDAG &DAG,
4288 SDLoc dl, unsigned vectorWidth) {
4289 assert((vectorWidth == 128 || vectorWidth == 256) &&
4290 "Unsupported vector width");
4291 // Inserting UNDEF is Result
4292 if (Vec.getOpcode() == ISD::UNDEF)
4294 EVT VT = Vec.getValueType();
4295 EVT ElVT = VT.getVectorElementType();
4296 EVT ResultVT = Result.getValueType();
4298 // Insert the relevant vectorWidth bits.
4299 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4301 // This is the index of the first element of the vectorWidth-bit chunk
4303 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4306 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4307 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4310 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4311 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4312 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4313 /// simple superregister reference. Idx is an index in the 128 bits
4314 /// we want. It need not be aligned to a 128-bit boundary. That makes
4315 /// lowering INSERT_VECTOR_ELT operations easier.
4316 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4317 SelectionDAG &DAG, SDLoc dl) {
4318 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4320 // For insertion into the zero index (low half) of a 256-bit vector, it is
4321 // more efficient to generate a blend with immediate instead of an insert*128.
4322 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4323 // extend the subvector to the size of the result vector. Make sure that
4324 // we are not recursing on that node by checking for undef here.
4325 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4326 Result.getOpcode() != ISD::UNDEF) {
4327 EVT ResultVT = Result.getValueType();
4328 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4329 SDValue Undef = DAG.getUNDEF(ResultVT);
4330 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4333 // The blend instruction, and therefore its mask, depend on the data type.
4334 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4335 if (ScalarType.isFloatingPoint()) {
4336 // Choose either vblendps (float) or vblendpd (double).
4337 unsigned ScalarSize = ScalarType.getSizeInBits();
4338 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4339 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4340 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4341 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4344 const X86Subtarget &Subtarget =
4345 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4347 // AVX2 is needed for 256-bit integer blend support.
4348 // Integers must be cast to 32-bit because there is only vpblendd;
4349 // vpblendw can't be used for this because it has a handicapped mask.
4351 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4352 // is still more efficient than using the wrong domain vinsertf128 that
4353 // will be created by InsertSubVector().
4354 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4356 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4357 Vec256 = DAG.getBitcast(CastVT, Vec256);
4358 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4359 return DAG.getBitcast(ResultVT, Vec256);
4362 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4365 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4366 SelectionDAG &DAG, SDLoc dl) {
4367 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4368 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4371 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4372 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4373 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4374 /// large BUILD_VECTORS.
4375 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4376 unsigned NumElems, SelectionDAG &DAG,
4378 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4379 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4382 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4383 unsigned NumElems, SelectionDAG &DAG,
4385 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4386 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4389 /// Returns a vector of specified type with all bits set.
4390 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4391 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4392 /// Then bitcast to their original type, ensuring they get CSE'd.
4393 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4395 assert(VT.isVector() && "Expected a vector type");
4397 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4399 if (VT.is256BitVector()) {
4400 if (HasInt256) { // AVX2
4401 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4402 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4404 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4405 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4407 } else if (VT.is128BitVector()) {
4408 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4410 llvm_unreachable("Unexpected vector type");
4412 return DAG.getBitcast(VT, Vec);
4415 /// Returns a vector_shuffle node for an unpackl operation.
4416 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4418 unsigned NumElems = VT.getVectorNumElements();
4419 SmallVector<int, 8> Mask;
4420 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4422 Mask.push_back(i + NumElems);
4424 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4427 /// Returns a vector_shuffle node for an unpackh operation.
4428 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4430 unsigned NumElems = VT.getVectorNumElements();
4431 SmallVector<int, 8> Mask;
4432 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4433 Mask.push_back(i + Half);
4434 Mask.push_back(i + NumElems + Half);
4436 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4439 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4440 /// This produces a shuffle where the low element of V2 is swizzled into the
4441 /// zero/undef vector, landing at element Idx.
4442 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4443 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4445 const X86Subtarget *Subtarget,
4446 SelectionDAG &DAG) {
4447 MVT VT = V2.getSimpleValueType();
4449 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4450 unsigned NumElems = VT.getVectorNumElements();
4451 SmallVector<int, 16> MaskVec;
4452 for (unsigned i = 0; i != NumElems; ++i)
4453 // If this is the insertion idx, put the low elt of V2 here.
4454 MaskVec.push_back(i == Idx ? NumElems : i);
4455 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4458 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4459 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4460 /// uses one source. Note that this will set IsUnary for shuffles which use a
4461 /// single input multiple times, and in those cases it will
4462 /// adjust the mask to only have indices within that single input.
4463 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4464 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4465 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4466 unsigned NumElems = VT.getVectorNumElements();
4470 bool IsFakeUnary = false;
4471 switch(N->getOpcode()) {
4472 case X86ISD::BLENDI:
4473 ImmN = N->getOperand(N->getNumOperands()-1);
4474 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4477 ImmN = N->getOperand(N->getNumOperands()-1);
4478 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4479 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4481 case X86ISD::UNPCKH:
4482 DecodeUNPCKHMask(VT, Mask);
4483 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4485 case X86ISD::UNPCKL:
4486 DecodeUNPCKLMask(VT, Mask);
4487 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4489 case X86ISD::MOVHLPS:
4490 DecodeMOVHLPSMask(NumElems, Mask);
4491 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4493 case X86ISD::MOVLHPS:
4494 DecodeMOVLHPSMask(NumElems, Mask);
4495 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4497 case X86ISD::PALIGNR:
4498 ImmN = N->getOperand(N->getNumOperands()-1);
4499 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4501 case X86ISD::PSHUFD:
4502 case X86ISD::VPERMILPI:
4503 ImmN = N->getOperand(N->getNumOperands()-1);
4504 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4507 case X86ISD::PSHUFHW:
4508 ImmN = N->getOperand(N->getNumOperands()-1);
4509 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4512 case X86ISD::PSHUFLW:
4513 ImmN = N->getOperand(N->getNumOperands()-1);
4514 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4517 case X86ISD::PSHUFB: {
4519 SDValue MaskNode = N->getOperand(1);
4520 while (MaskNode->getOpcode() == ISD::BITCAST)
4521 MaskNode = MaskNode->getOperand(0);
4523 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4524 // If we have a build-vector, then things are easy.
4525 EVT VT = MaskNode.getValueType();
4526 assert(VT.isVector() &&
4527 "Can't produce a non-vector with a build_vector!");
4528 if (!VT.isInteger())
4531 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4533 SmallVector<uint64_t, 32> RawMask;
4534 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4535 SDValue Op = MaskNode->getOperand(i);
4536 if (Op->getOpcode() == ISD::UNDEF) {
4537 RawMask.push_back((uint64_t)SM_SentinelUndef);
4540 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4543 APInt MaskElement = CN->getAPIntValue();
4545 // We now have to decode the element which could be any integer size and
4546 // extract each byte of it.
4547 for (int j = 0; j < NumBytesPerElement; ++j) {
4548 // Note that this is x86 and so always little endian: the low byte is
4549 // the first byte of the mask.
4550 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4551 MaskElement = MaskElement.lshr(8);
4554 DecodePSHUFBMask(RawMask, Mask);
4558 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4562 SDValue Ptr = MaskLoad->getBasePtr();
4563 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4564 Ptr->getOpcode() == X86ISD::WrapperRIP)
4565 Ptr = Ptr->getOperand(0);
4567 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4568 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4571 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4572 DecodePSHUFBMask(C, Mask);
4580 case X86ISD::VPERMI:
4581 ImmN = N->getOperand(N->getNumOperands()-1);
4582 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4587 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4589 case X86ISD::VPERM2X128:
4590 ImmN = N->getOperand(N->getNumOperands()-1);
4591 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4592 if (Mask.empty()) return false;
4593 // Mask only contains negative index if an element is zero.
4594 if (std::any_of(Mask.begin(), Mask.end(),
4595 [](int M){ return M == SM_SentinelZero; }))
4598 case X86ISD::MOVSLDUP:
4599 DecodeMOVSLDUPMask(VT, Mask);
4602 case X86ISD::MOVSHDUP:
4603 DecodeMOVSHDUPMask(VT, Mask);
4606 case X86ISD::MOVDDUP:
4607 DecodeMOVDDUPMask(VT, Mask);
4610 case X86ISD::MOVLHPD:
4611 case X86ISD::MOVLPD:
4612 case X86ISD::MOVLPS:
4613 // Not yet implemented
4615 default: llvm_unreachable("unknown target shuffle node");
4618 // If we have a fake unary shuffle, the shuffle mask is spread across two
4619 // inputs that are actually the same node. Re-map the mask to always point
4620 // into the first input.
4623 if (M >= (int)Mask.size())
4629 /// Returns the scalar element that will make up the ith
4630 /// element of the result of the vector shuffle.
4631 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4634 return SDValue(); // Limit search depth.
4636 SDValue V = SDValue(N, 0);
4637 EVT VT = V.getValueType();
4638 unsigned Opcode = V.getOpcode();
4640 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4641 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4642 int Elt = SV->getMaskElt(Index);
4645 return DAG.getUNDEF(VT.getVectorElementType());
4647 unsigned NumElems = VT.getVectorNumElements();
4648 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4649 : SV->getOperand(1);
4650 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4653 // Recurse into target specific vector shuffles to find scalars.
4654 if (isTargetShuffle(Opcode)) {
4655 MVT ShufVT = V.getSimpleValueType();
4656 unsigned NumElems = ShufVT.getVectorNumElements();
4657 SmallVector<int, 16> ShuffleMask;
4660 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4663 int Elt = ShuffleMask[Index];
4665 return DAG.getUNDEF(ShufVT.getVectorElementType());
4667 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4669 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4673 // Actual nodes that may contain scalar elements
4674 if (Opcode == ISD::BITCAST) {
4675 V = V.getOperand(0);
4676 EVT SrcVT = V.getValueType();
4677 unsigned NumElems = VT.getVectorNumElements();
4679 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4683 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4684 return (Index == 0) ? V.getOperand(0)
4685 : DAG.getUNDEF(VT.getVectorElementType());
4687 if (V.getOpcode() == ISD::BUILD_VECTOR)
4688 return V.getOperand(Index);
4693 /// Custom lower build_vector of v16i8.
4694 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4695 unsigned NumNonZero, unsigned NumZero,
4697 const X86Subtarget* Subtarget,
4698 const TargetLowering &TLI) {
4706 // SSE4.1 - use PINSRB to insert each byte directly.
4707 if (Subtarget->hasSSE41()) {
4708 for (unsigned i = 0; i < 16; ++i) {
4709 bool isNonZero = (NonZeros & (1 << i)) != 0;
4713 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4715 V = DAG.getUNDEF(MVT::v16i8);
4718 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4719 MVT::v16i8, V, Op.getOperand(i),
4720 DAG.getIntPtrConstant(i, dl));
4727 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4728 for (unsigned i = 0; i < 16; ++i) {
4729 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4730 if (ThisIsNonZero && First) {
4732 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4734 V = DAG.getUNDEF(MVT::v8i16);
4739 SDValue ThisElt, LastElt;
4740 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4741 if (LastIsNonZero) {
4742 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4743 MVT::i16, Op.getOperand(i-1));
4745 if (ThisIsNonZero) {
4746 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4747 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4748 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4750 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4754 if (ThisElt.getNode())
4755 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4756 DAG.getIntPtrConstant(i/2, dl));
4760 return DAG.getBitcast(MVT::v16i8, V);
4763 /// Custom lower build_vector of v8i16.
4764 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4765 unsigned NumNonZero, unsigned NumZero,
4767 const X86Subtarget* Subtarget,
4768 const TargetLowering &TLI) {
4775 for (unsigned i = 0; i < 8; ++i) {
4776 bool isNonZero = (NonZeros & (1 << i)) != 0;
4780 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4782 V = DAG.getUNDEF(MVT::v8i16);
4785 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4786 MVT::v8i16, V, Op.getOperand(i),
4787 DAG.getIntPtrConstant(i, dl));
4794 /// Custom lower build_vector of v4i32 or v4f32.
4795 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4796 const X86Subtarget *Subtarget,
4797 const TargetLowering &TLI) {
4798 // Find all zeroable elements.
4799 std::bitset<4> Zeroable;
4800 for (int i=0; i < 4; ++i) {
4801 SDValue Elt = Op->getOperand(i);
4802 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4804 assert(Zeroable.size() - Zeroable.count() > 1 &&
4805 "We expect at least two non-zero elements!");
4807 // We only know how to deal with build_vector nodes where elements are either
4808 // zeroable or extract_vector_elt with constant index.
4809 SDValue FirstNonZero;
4810 unsigned FirstNonZeroIdx;
4811 for (unsigned i=0; i < 4; ++i) {
4814 SDValue Elt = Op->getOperand(i);
4815 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4816 !isa<ConstantSDNode>(Elt.getOperand(1)))
4818 // Make sure that this node is extracting from a 128-bit vector.
4819 MVT VT = Elt.getOperand(0).getSimpleValueType();
4820 if (!VT.is128BitVector())
4822 if (!FirstNonZero.getNode()) {
4824 FirstNonZeroIdx = i;
4828 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4829 SDValue V1 = FirstNonZero.getOperand(0);
4830 MVT VT = V1.getSimpleValueType();
4832 // See if this build_vector can be lowered as a blend with zero.
4834 unsigned EltMaskIdx, EltIdx;
4836 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4837 if (Zeroable[EltIdx]) {
4838 // The zero vector will be on the right hand side.
4839 Mask[EltIdx] = EltIdx+4;
4843 Elt = Op->getOperand(EltIdx);
4844 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4845 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4846 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4848 Mask[EltIdx] = EltIdx;
4852 // Let the shuffle legalizer deal with blend operations.
4853 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4854 if (V1.getSimpleValueType() != VT)
4855 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4856 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4859 // See if we can lower this build_vector to a INSERTPS.
4860 if (!Subtarget->hasSSE41())
4863 SDValue V2 = Elt.getOperand(0);
4864 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4867 bool CanFold = true;
4868 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4872 SDValue Current = Op->getOperand(i);
4873 SDValue SrcVector = Current->getOperand(0);
4876 CanFold = SrcVector == V1 &&
4877 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4883 assert(V1.getNode() && "Expected at least two non-zero elements!");
4884 if (V1.getSimpleValueType() != MVT::v4f32)
4885 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4886 if (V2.getSimpleValueType() != MVT::v4f32)
4887 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4889 // Ok, we can emit an INSERTPS instruction.
4890 unsigned ZMask = Zeroable.to_ulong();
4892 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4893 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4895 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4896 DAG.getIntPtrConstant(InsertPSMask, DL));
4897 return DAG.getBitcast(VT, Result);
4900 /// Return a vector logical shift node.
4901 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4902 unsigned NumBits, SelectionDAG &DAG,
4903 const TargetLowering &TLI, SDLoc dl) {
4904 assert(VT.is128BitVector() && "Unknown type for VShift");
4905 MVT ShVT = MVT::v2i64;
4906 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4907 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4908 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4909 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4910 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4911 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4915 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4917 // Check if the scalar load can be widened into a vector load. And if
4918 // the address is "base + cst" see if the cst can be "absorbed" into
4919 // the shuffle mask.
4920 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4921 SDValue Ptr = LD->getBasePtr();
4922 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4924 EVT PVT = LD->getValueType(0);
4925 if (PVT != MVT::i32 && PVT != MVT::f32)
4930 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4931 FI = FINode->getIndex();
4933 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4934 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4935 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4936 Offset = Ptr.getConstantOperandVal(1);
4937 Ptr = Ptr.getOperand(0);
4942 // FIXME: 256-bit vector instructions don't require a strict alignment,
4943 // improve this code to support it better.
4944 unsigned RequiredAlign = VT.getSizeInBits()/8;
4945 SDValue Chain = LD->getChain();
4946 // Make sure the stack object alignment is at least 16 or 32.
4947 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4948 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4949 if (MFI->isFixedObjectIndex(FI)) {
4950 // Can't change the alignment. FIXME: It's possible to compute
4951 // the exact stack offset and reference FI + adjust offset instead.
4952 // If someone *really* cares about this. That's the way to implement it.
4955 MFI->setObjectAlignment(FI, RequiredAlign);
4959 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4960 // Ptr + (Offset & ~15).
4963 if ((Offset % RequiredAlign) & 3)
4965 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4968 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4969 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4972 int EltNo = (Offset - StartOffset) >> 2;
4973 unsigned NumElems = VT.getVectorNumElements();
4975 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4976 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4977 LD->getPointerInfo().getWithOffset(StartOffset),
4978 false, false, false, 0);
4980 SmallVector<int, 8> Mask(NumElems, EltNo);
4982 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4988 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4989 /// elements can be replaced by a single large load which has the same value as
4990 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4992 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4994 /// FIXME: we'd also like to handle the case where the last elements are zero
4995 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4996 /// There's even a handy isZeroNode for that purpose.
4997 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4998 SDLoc &DL, SelectionDAG &DAG,
4999 bool isAfterLegalize) {
5000 unsigned NumElems = Elts.size();
5002 LoadSDNode *LDBase = nullptr;
5003 unsigned LastLoadedElt = -1U;
5005 // For each element in the initializer, see if we've found a load or an undef.
5006 // If we don't find an initial load element, or later load elements are
5007 // non-consecutive, bail out.
5008 for (unsigned i = 0; i < NumElems; ++i) {
5009 SDValue Elt = Elts[i];
5010 // Look through a bitcast.
5011 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5012 Elt = Elt.getOperand(0);
5013 if (!Elt.getNode() ||
5014 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5017 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5019 LDBase = cast<LoadSDNode>(Elt.getNode());
5023 if (Elt.getOpcode() == ISD::UNDEF)
5026 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5027 EVT LdVT = Elt.getValueType();
5028 // Each loaded element must be the correct fractional portion of the
5029 // requested vector load.
5030 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5032 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5037 // If we have found an entire vector of loads and undefs, then return a large
5038 // load of the entire vector width starting at the base pointer. If we found
5039 // consecutive loads for the low half, generate a vzext_load node.
5040 if (LastLoadedElt == NumElems - 1) {
5041 assert(LDBase && "Did not find base load for merging consecutive loads");
5042 EVT EltVT = LDBase->getValueType(0);
5043 // Ensure that the input vector size for the merged loads matches the
5044 // cumulative size of the input elements.
5045 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5048 if (isAfterLegalize &&
5049 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5052 SDValue NewLd = SDValue();
5054 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5055 LDBase->getPointerInfo(), LDBase->isVolatile(),
5056 LDBase->isNonTemporal(), LDBase->isInvariant(),
5057 LDBase->getAlignment());
5059 if (LDBase->hasAnyUseOfValue(1)) {
5060 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5062 SDValue(NewLd.getNode(), 1));
5063 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5064 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5065 SDValue(NewLd.getNode(), 1));
5071 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5072 //of a v4i32 / v4f32. It's probably worth generalizing.
5073 EVT EltVT = VT.getVectorElementType();
5074 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5075 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5076 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5077 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5079 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5080 LDBase->getPointerInfo(),
5081 LDBase->getAlignment(),
5082 false/*isVolatile*/, true/*ReadMem*/,
5085 // Make sure the newly-created LOAD is in the same position as LDBase in
5086 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5087 // update uses of LDBase's output chain to use the TokenFactor.
5088 if (LDBase->hasAnyUseOfValue(1)) {
5089 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5090 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5091 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5092 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5093 SDValue(ResNode.getNode(), 1));
5096 return DAG.getBitcast(VT, ResNode);
5101 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5102 /// to generate a splat value for the following cases:
5103 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5104 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5105 /// a scalar load, or a constant.
5106 /// The VBROADCAST node is returned when a pattern is found,
5107 /// or SDValue() otherwise.
5108 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5109 SelectionDAG &DAG) {
5110 // VBROADCAST requires AVX.
5111 // TODO: Splats could be generated for non-AVX CPUs using SSE
5112 // instructions, but there's less potential gain for only 128-bit vectors.
5113 if (!Subtarget->hasAVX())
5116 MVT VT = Op.getSimpleValueType();
5119 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5120 "Unsupported vector type for broadcast.");
5125 switch (Op.getOpcode()) {
5127 // Unknown pattern found.
5130 case ISD::BUILD_VECTOR: {
5131 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5132 BitVector UndefElements;
5133 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5135 // We need a splat of a single value to use broadcast, and it doesn't
5136 // make any sense if the value is only in one element of the vector.
5137 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5141 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5142 Ld.getOpcode() == ISD::ConstantFP);
5144 // Make sure that all of the users of a non-constant load are from the
5145 // BUILD_VECTOR node.
5146 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5151 case ISD::VECTOR_SHUFFLE: {
5152 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5154 // Shuffles must have a splat mask where the first element is
5156 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5159 SDValue Sc = Op.getOperand(0);
5160 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5161 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5163 if (!Subtarget->hasInt256())
5166 // Use the register form of the broadcast instruction available on AVX2.
5167 if (VT.getSizeInBits() >= 256)
5168 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5169 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5172 Ld = Sc.getOperand(0);
5173 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5174 Ld.getOpcode() == ISD::ConstantFP);
5176 // The scalar_to_vector node and the suspected
5177 // load node must have exactly one user.
5178 // Constants may have multiple users.
5180 // AVX-512 has register version of the broadcast
5181 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5182 Ld.getValueType().getSizeInBits() >= 32;
5183 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5190 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5191 bool IsGE256 = (VT.getSizeInBits() >= 256);
5193 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5194 // instruction to save 8 or more bytes of constant pool data.
5195 // TODO: If multiple splats are generated to load the same constant,
5196 // it may be detrimental to overall size. There needs to be a way to detect
5197 // that condition to know if this is truly a size win.
5198 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5200 // Handle broadcasting a single constant scalar from the constant pool
5202 // On Sandybridge (no AVX2), it is still better to load a constant vector
5203 // from the constant pool and not to broadcast it from a scalar.
5204 // But override that restriction when optimizing for size.
5205 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5206 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5207 EVT CVT = Ld.getValueType();
5208 assert(!CVT.isVector() && "Must not broadcast a vector type");
5210 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5211 // For size optimization, also splat v2f64 and v2i64, and for size opt
5212 // with AVX2, also splat i8 and i16.
5213 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5214 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5215 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5216 const Constant *C = nullptr;
5217 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5218 C = CI->getConstantIntValue();
5219 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5220 C = CF->getConstantFPValue();
5222 assert(C && "Invalid constant type");
5224 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5226 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5227 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5229 CVT, dl, DAG.getEntryNode(), CP,
5230 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5231 false, false, Alignment);
5233 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5237 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5239 // Handle AVX2 in-register broadcasts.
5240 if (!IsLoad && Subtarget->hasInt256() &&
5241 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5242 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5244 // The scalar source must be a normal load.
5248 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5249 (Subtarget->hasVLX() && ScalarSize == 64))
5250 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5252 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5253 // double since there is no vbroadcastsd xmm
5254 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5255 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5256 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5259 // Unsupported broadcast.
5263 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5264 /// underlying vector and index.
5266 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5268 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5270 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5271 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5274 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5276 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5278 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5279 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5282 // In this case the vector is the extract_subvector expression and the index
5283 // is 2, as specified by the shuffle.
5284 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5285 SDValue ShuffleVec = SVOp->getOperand(0);
5286 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5287 assert(ShuffleVecVT.getVectorElementType() ==
5288 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5290 int ShuffleIdx = SVOp->getMaskElt(Idx);
5291 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5292 ExtractedFromVec = ShuffleVec;
5298 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5299 MVT VT = Op.getSimpleValueType();
5301 // Skip if insert_vec_elt is not supported.
5302 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5303 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5307 unsigned NumElems = Op.getNumOperands();
5311 SmallVector<unsigned, 4> InsertIndices;
5312 SmallVector<int, 8> Mask(NumElems, -1);
5314 for (unsigned i = 0; i != NumElems; ++i) {
5315 unsigned Opc = Op.getOperand(i).getOpcode();
5317 if (Opc == ISD::UNDEF)
5320 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5321 // Quit if more than 1 elements need inserting.
5322 if (InsertIndices.size() > 1)
5325 InsertIndices.push_back(i);
5329 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5330 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5331 // Quit if non-constant index.
5332 if (!isa<ConstantSDNode>(ExtIdx))
5334 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5336 // Quit if extracted from vector of different type.
5337 if (ExtractedFromVec.getValueType() != VT)
5340 if (!VecIn1.getNode())
5341 VecIn1 = ExtractedFromVec;
5342 else if (VecIn1 != ExtractedFromVec) {
5343 if (!VecIn2.getNode())
5344 VecIn2 = ExtractedFromVec;
5345 else if (VecIn2 != ExtractedFromVec)
5346 // Quit if more than 2 vectors to shuffle
5350 if (ExtractedFromVec == VecIn1)
5352 else if (ExtractedFromVec == VecIn2)
5353 Mask[i] = Idx + NumElems;
5356 if (!VecIn1.getNode())
5359 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5360 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5361 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5362 unsigned Idx = InsertIndices[i];
5363 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5364 DAG.getIntPtrConstant(Idx, DL));
5370 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5371 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5372 Op.getScalarValueSizeInBits() == 1 &&
5373 "Can not convert non-constant vector");
5374 uint64_t Immediate = 0;
5375 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5376 SDValue In = Op.getOperand(idx);
5377 if (In.getOpcode() != ISD::UNDEF)
5378 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5382 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5383 return DAG.getConstant(Immediate, dl, VT);
5385 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5387 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5389 MVT VT = Op.getSimpleValueType();
5390 assert((VT.getVectorElementType() == MVT::i1) &&
5391 "Unexpected type in LowerBUILD_VECTORvXi1!");
5394 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5395 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5396 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5397 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5400 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5401 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5402 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5403 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5406 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5407 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5408 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5409 return DAG.getBitcast(VT, Imm);
5410 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5411 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5412 DAG.getIntPtrConstant(0, dl));
5415 // Vector has one or more non-const elements
5416 uint64_t Immediate = 0;
5417 SmallVector<unsigned, 16> NonConstIdx;
5418 bool IsSplat = true;
5419 bool HasConstElts = false;
5421 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5422 SDValue In = Op.getOperand(idx);
5423 if (In.getOpcode() == ISD::UNDEF)
5425 if (!isa<ConstantSDNode>(In))
5426 NonConstIdx.push_back(idx);
5428 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5429 HasConstElts = true;
5433 else if (In != Op.getOperand(SplatIdx))
5437 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5439 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5440 DAG.getConstant(1, dl, VT),
5441 DAG.getConstant(0, dl, VT));
5443 // insert elements one by one
5447 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5448 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5450 else if (HasConstElts)
5451 Imm = DAG.getConstant(0, dl, VT);
5453 Imm = DAG.getUNDEF(VT);
5454 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5455 DstVec = DAG.getBitcast(VT, Imm);
5457 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5458 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5459 DAG.getIntPtrConstant(0, dl));
5462 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5463 unsigned InsertIdx = NonConstIdx[i];
5464 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5465 Op.getOperand(InsertIdx),
5466 DAG.getIntPtrConstant(InsertIdx, dl));
5471 /// \brief Return true if \p N implements a horizontal binop and return the
5472 /// operands for the horizontal binop into V0 and V1.
5474 /// This is a helper function of LowerToHorizontalOp().
5475 /// This function checks that the build_vector \p N in input implements a
5476 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5477 /// operation to match.
5478 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5479 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5480 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5483 /// This function only analyzes elements of \p N whose indices are
5484 /// in range [BaseIdx, LastIdx).
5485 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5487 unsigned BaseIdx, unsigned LastIdx,
5488 SDValue &V0, SDValue &V1) {
5489 EVT VT = N->getValueType(0);
5491 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5492 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5493 "Invalid Vector in input!");
5495 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5496 bool CanFold = true;
5497 unsigned ExpectedVExtractIdx = BaseIdx;
5498 unsigned NumElts = LastIdx - BaseIdx;
5499 V0 = DAG.getUNDEF(VT);
5500 V1 = DAG.getUNDEF(VT);
5502 // Check if N implements a horizontal binop.
5503 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5504 SDValue Op = N->getOperand(i + BaseIdx);
5507 if (Op->getOpcode() == ISD::UNDEF) {
5508 // Update the expected vector extract index.
5509 if (i * 2 == NumElts)
5510 ExpectedVExtractIdx = BaseIdx;
5511 ExpectedVExtractIdx += 2;
5515 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5520 SDValue Op0 = Op.getOperand(0);
5521 SDValue Op1 = Op.getOperand(1);
5523 // Try to match the following pattern:
5524 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5525 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5526 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5527 Op0.getOperand(0) == Op1.getOperand(0) &&
5528 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5529 isa<ConstantSDNode>(Op1.getOperand(1)));
5533 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5534 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5536 if (i * 2 < NumElts) {
5537 if (V0.getOpcode() == ISD::UNDEF) {
5538 V0 = Op0.getOperand(0);
5539 if (V0.getValueType() != VT)
5543 if (V1.getOpcode() == ISD::UNDEF) {
5544 V1 = Op0.getOperand(0);
5545 if (V1.getValueType() != VT)
5548 if (i * 2 == NumElts)
5549 ExpectedVExtractIdx = BaseIdx;
5552 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5553 if (I0 == ExpectedVExtractIdx)
5554 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5555 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5556 // Try to match the following dag sequence:
5557 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5558 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5562 ExpectedVExtractIdx += 2;
5568 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5569 /// a concat_vector.
5571 /// This is a helper function of LowerToHorizontalOp().
5572 /// This function expects two 256-bit vectors called V0 and V1.
5573 /// At first, each vector is split into two separate 128-bit vectors.
5574 /// Then, the resulting 128-bit vectors are used to implement two
5575 /// horizontal binary operations.
5577 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5579 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5580 /// the two new horizontal binop.
5581 /// When Mode is set, the first horizontal binop dag node would take as input
5582 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5583 /// horizontal binop dag node would take as input the lower 128-bit of V1
5584 /// and the upper 128-bit of V1.
5586 /// HADD V0_LO, V0_HI
5587 /// HADD V1_LO, V1_HI
5589 /// Otherwise, the first horizontal binop dag node takes as input the lower
5590 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5591 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5593 /// HADD V0_LO, V1_LO
5594 /// HADD V0_HI, V1_HI
5596 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5597 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5598 /// the upper 128-bits of the result.
5599 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5600 SDLoc DL, SelectionDAG &DAG,
5601 unsigned X86Opcode, bool Mode,
5602 bool isUndefLO, bool isUndefHI) {
5603 EVT VT = V0.getValueType();
5604 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5605 "Invalid nodes in input!");
5607 unsigned NumElts = VT.getVectorNumElements();
5608 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5609 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5610 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5611 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5612 EVT NewVT = V0_LO.getValueType();
5614 SDValue LO = DAG.getUNDEF(NewVT);
5615 SDValue HI = DAG.getUNDEF(NewVT);
5618 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5619 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5620 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5621 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5622 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5624 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5625 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5626 V1_LO->getOpcode() != ISD::UNDEF))
5627 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5629 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5630 V1_HI->getOpcode() != ISD::UNDEF))
5631 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5634 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5637 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5639 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5640 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5641 EVT VT = BV->getValueType(0);
5642 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5643 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5647 unsigned NumElts = VT.getVectorNumElements();
5648 SDValue InVec0 = DAG.getUNDEF(VT);
5649 SDValue InVec1 = DAG.getUNDEF(VT);
5651 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5652 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5654 // Odd-numbered elements in the input build vector are obtained from
5655 // adding two integer/float elements.
5656 // Even-numbered elements in the input build vector are obtained from
5657 // subtracting two integer/float elements.
5658 unsigned ExpectedOpcode = ISD::FSUB;
5659 unsigned NextExpectedOpcode = ISD::FADD;
5660 bool AddFound = false;
5661 bool SubFound = false;
5663 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5664 SDValue Op = BV->getOperand(i);
5666 // Skip 'undef' values.
5667 unsigned Opcode = Op.getOpcode();
5668 if (Opcode == ISD::UNDEF) {
5669 std::swap(ExpectedOpcode, NextExpectedOpcode);
5673 // Early exit if we found an unexpected opcode.
5674 if (Opcode != ExpectedOpcode)
5677 SDValue Op0 = Op.getOperand(0);
5678 SDValue Op1 = Op.getOperand(1);
5680 // Try to match the following pattern:
5681 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5682 // Early exit if we cannot match that sequence.
5683 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5684 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5685 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5686 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5687 Op0.getOperand(1) != Op1.getOperand(1))
5690 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5694 // We found a valid add/sub node. Update the information accordingly.
5700 // Update InVec0 and InVec1.
5701 if (InVec0.getOpcode() == ISD::UNDEF) {
5702 InVec0 = Op0.getOperand(0);
5703 if (InVec0.getValueType() != VT)
5706 if (InVec1.getOpcode() == ISD::UNDEF) {
5707 InVec1 = Op1.getOperand(0);
5708 if (InVec1.getValueType() != VT)
5712 // Make sure that operands in input to each add/sub node always
5713 // come from a same pair of vectors.
5714 if (InVec0 != Op0.getOperand(0)) {
5715 if (ExpectedOpcode == ISD::FSUB)
5718 // FADD is commutable. Try to commute the operands
5719 // and then test again.
5720 std::swap(Op0, Op1);
5721 if (InVec0 != Op0.getOperand(0))
5725 if (InVec1 != Op1.getOperand(0))
5728 // Update the pair of expected opcodes.
5729 std::swap(ExpectedOpcode, NextExpectedOpcode);
5732 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5733 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5734 InVec1.getOpcode() != ISD::UNDEF)
5735 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5740 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5741 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5742 const X86Subtarget *Subtarget,
5743 SelectionDAG &DAG) {
5744 EVT VT = BV->getValueType(0);
5745 unsigned NumElts = VT.getVectorNumElements();
5746 unsigned NumUndefsLO = 0;
5747 unsigned NumUndefsHI = 0;
5748 unsigned Half = NumElts/2;
5750 // Count the number of UNDEF operands in the build_vector in input.
5751 for (unsigned i = 0, e = Half; i != e; ++i)
5752 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5755 for (unsigned i = Half, e = NumElts; i != e; ++i)
5756 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5759 // Early exit if this is either a build_vector of all UNDEFs or all the
5760 // operands but one are UNDEF.
5761 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5765 SDValue InVec0, InVec1;
5766 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5767 // Try to match an SSE3 float HADD/HSUB.
5768 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5769 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5771 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5772 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5773 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5774 // Try to match an SSSE3 integer HADD/HSUB.
5775 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5776 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5778 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5779 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5782 if (!Subtarget->hasAVX())
5785 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5786 // Try to match an AVX horizontal add/sub of packed single/double
5787 // precision floating point values from 256-bit vectors.
5788 SDValue InVec2, InVec3;
5789 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5790 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5791 ((InVec0.getOpcode() == ISD::UNDEF ||
5792 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5793 ((InVec1.getOpcode() == ISD::UNDEF ||
5794 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5795 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5797 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5798 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5799 ((InVec0.getOpcode() == ISD::UNDEF ||
5800 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5801 ((InVec1.getOpcode() == ISD::UNDEF ||
5802 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5803 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5804 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5805 // Try to match an AVX2 horizontal add/sub of signed integers.
5806 SDValue InVec2, InVec3;
5808 bool CanFold = true;
5810 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5811 isHorizontalBinOp(BV, ISD::ADD, 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 X86Opcode = X86ISD::HADD;
5817 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5818 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5819 ((InVec0.getOpcode() == ISD::UNDEF ||
5820 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5821 ((InVec1.getOpcode() == ISD::UNDEF ||
5822 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5823 X86Opcode = X86ISD::HSUB;
5828 // Fold this build_vector into a single horizontal add/sub.
5829 // Do this only if the target has AVX2.
5830 if (Subtarget->hasAVX2())
5831 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5833 // Do not try to expand this build_vector into a pair of horizontal
5834 // add/sub if we can emit a pair of scalar add/sub.
5835 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5838 // Convert this build_vector into a pair of horizontal binop followed by
5840 bool isUndefLO = NumUndefsLO == Half;
5841 bool isUndefHI = NumUndefsHI == Half;
5842 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5843 isUndefLO, isUndefHI);
5847 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5848 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5850 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5851 X86Opcode = X86ISD::HADD;
5852 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5853 X86Opcode = X86ISD::HSUB;
5854 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5855 X86Opcode = X86ISD::FHADD;
5856 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5857 X86Opcode = X86ISD::FHSUB;
5861 // Don't try to expand this build_vector into a pair of horizontal add/sub
5862 // if we can simply emit a pair of scalar add/sub.
5863 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5866 // Convert this build_vector into two horizontal add/sub followed by
5868 bool isUndefLO = NumUndefsLO == Half;
5869 bool isUndefHI = NumUndefsHI == Half;
5870 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5871 isUndefLO, isUndefHI);
5878 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5881 MVT VT = Op.getSimpleValueType();
5882 MVT ExtVT = VT.getVectorElementType();
5883 unsigned NumElems = Op.getNumOperands();
5885 // Generate vectors for predicate vectors.
5886 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5887 return LowerBUILD_VECTORvXi1(Op, DAG);
5889 // Vectors containing all zeros can be matched by pxor and xorps later
5890 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5891 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5892 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5893 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5896 return getZeroVector(VT, Subtarget, DAG, dl);
5899 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5900 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5901 // vpcmpeqd on 256-bit vectors.
5902 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5903 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5906 if (!VT.is512BitVector())
5907 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5910 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5911 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5913 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5914 return HorizontalOp;
5915 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5918 unsigned EVTBits = ExtVT.getSizeInBits();
5920 unsigned NumZero = 0;
5921 unsigned NumNonZero = 0;
5922 unsigned NonZeros = 0;
5923 bool IsAllConstants = true;
5924 SmallSet<SDValue, 8> Values;
5925 for (unsigned i = 0; i < NumElems; ++i) {
5926 SDValue Elt = Op.getOperand(i);
5927 if (Elt.getOpcode() == ISD::UNDEF)
5930 if (Elt.getOpcode() != ISD::Constant &&
5931 Elt.getOpcode() != ISD::ConstantFP)
5932 IsAllConstants = false;
5933 if (X86::isZeroNode(Elt))
5936 NonZeros |= (1 << i);
5941 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5942 if (NumNonZero == 0)
5943 return DAG.getUNDEF(VT);
5945 // Special case for single non-zero, non-undef, element.
5946 if (NumNonZero == 1) {
5947 unsigned Idx = countTrailingZeros(NonZeros);
5948 SDValue Item = Op.getOperand(Idx);
5950 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5951 // the value are obviously zero, truncate the value to i32 and do the
5952 // insertion that way. Only do this if the value is non-constant or if the
5953 // value is a constant being inserted into element 0. It is cheaper to do
5954 // a constant pool load than it is to do a movd + shuffle.
5955 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5956 (!IsAllConstants || Idx == 0)) {
5957 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5959 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5960 EVT VecVT = MVT::v4i32;
5962 // Truncate the value (which may itself be a constant) to i32, and
5963 // convert it to a vector with movd (S2V+shuffle to zero extend).
5964 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5965 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5966 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5967 Item, Idx * 2, true, Subtarget, DAG));
5971 // If we have a constant or non-constant insertion into the low element of
5972 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5973 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5974 // depending on what the source datatype is.
5977 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5979 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5980 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5981 if (VT.is512BitVector()) {
5982 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5983 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5984 Item, DAG.getIntPtrConstant(0, dl));
5986 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5987 "Expected an SSE value type!");
5988 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5989 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5990 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5993 // We can't directly insert an i8 or i16 into a vector, so zero extend
5995 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5996 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5997 if (VT.is256BitVector()) {
5998 if (Subtarget->hasAVX()) {
5999 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6000 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6002 // Without AVX, we need to extend to a 128-bit vector and then
6003 // insert into the 256-bit vector.
6004 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6005 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6006 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6009 assert(VT.is128BitVector() && "Expected an SSE value type!");
6010 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6011 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6013 return DAG.getBitcast(VT, Item);
6017 // Is it a vector logical left shift?
6018 if (NumElems == 2 && Idx == 1 &&
6019 X86::isZeroNode(Op.getOperand(0)) &&
6020 !X86::isZeroNode(Op.getOperand(1))) {
6021 unsigned NumBits = VT.getSizeInBits();
6022 return getVShift(true, VT,
6023 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6024 VT, Op.getOperand(1)),
6025 NumBits/2, DAG, *this, dl);
6028 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6031 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6032 // is a non-constant being inserted into an element other than the low one,
6033 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6034 // movd/movss) to move this into the low element, then shuffle it into
6036 if (EVTBits == 32) {
6037 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6038 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6042 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6043 if (Values.size() == 1) {
6044 if (EVTBits == 32) {
6045 // Instead of a shuffle like this:
6046 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6047 // Check if it's possible to issue this instead.
6048 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6049 unsigned Idx = countTrailingZeros(NonZeros);
6050 SDValue Item = Op.getOperand(Idx);
6051 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6052 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6057 // A vector full of immediates; various special cases are already
6058 // handled, so this is best done with a single constant-pool load.
6062 // For AVX-length vectors, see if we can use a vector load to get all of the
6063 // elements, otherwise build the individual 128-bit pieces and use
6064 // shuffles to put them in place.
6065 if (VT.is256BitVector() || VT.is512BitVector()) {
6066 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6068 // Check for a build vector of consecutive loads.
6069 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6072 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6074 // Build both the lower and upper subvector.
6075 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6076 makeArrayRef(&V[0], NumElems/2));
6077 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6078 makeArrayRef(&V[NumElems / 2], NumElems/2));
6080 // Recreate the wider vector with the lower and upper part.
6081 if (VT.is256BitVector())
6082 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6083 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6086 // Let legalizer expand 2-wide build_vectors.
6087 if (EVTBits == 64) {
6088 if (NumNonZero == 1) {
6089 // One half is zero or undef.
6090 unsigned Idx = countTrailingZeros(NonZeros);
6091 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6092 Op.getOperand(Idx));
6093 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6098 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6099 if (EVTBits == 8 && NumElems == 16)
6100 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6104 if (EVTBits == 16 && NumElems == 8)
6105 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6109 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6110 if (EVTBits == 32 && NumElems == 4)
6111 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6114 // If element VT is == 32 bits, turn it into a number of shuffles.
6115 SmallVector<SDValue, 8> V(NumElems);
6116 if (NumElems == 4 && NumZero > 0) {
6117 for (unsigned i = 0; i < 4; ++i) {
6118 bool isZero = !(NonZeros & (1 << i));
6120 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6122 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6125 for (unsigned i = 0; i < 2; ++i) {
6126 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6129 V[i] = V[i*2]; // Must be a zero vector.
6132 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6135 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6138 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6143 bool Reverse1 = (NonZeros & 0x3) == 2;
6144 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6148 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6149 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6151 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6154 if (Values.size() > 1 && VT.is128BitVector()) {
6155 // Check for a build vector of consecutive loads.
6156 for (unsigned i = 0; i < NumElems; ++i)
6157 V[i] = Op.getOperand(i);
6159 // Check for elements which are consecutive loads.
6160 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6163 // Check for a build vector from mostly shuffle plus few inserting.
6164 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6167 // For SSE 4.1, use insertps to put the high elements into the low element.
6168 if (Subtarget->hasSSE41()) {
6170 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6171 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6173 Result = DAG.getUNDEF(VT);
6175 for (unsigned i = 1; i < NumElems; ++i) {
6176 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6177 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6178 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6183 // Otherwise, expand into a number of unpckl*, start by extending each of
6184 // our (non-undef) elements to the full vector width with the element in the
6185 // bottom slot of the vector (which generates no code for SSE).
6186 for (unsigned i = 0; i < NumElems; ++i) {
6187 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6188 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6190 V[i] = DAG.getUNDEF(VT);
6193 // Next, we iteratively mix elements, e.g. for v4f32:
6194 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6195 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6196 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6197 unsigned EltStride = NumElems >> 1;
6198 while (EltStride != 0) {
6199 for (unsigned i = 0; i < EltStride; ++i) {
6200 // If V[i+EltStride] is undef and this is the first round of mixing,
6201 // then it is safe to just drop this shuffle: V[i] is already in the
6202 // right place, the one element (since it's the first round) being
6203 // inserted as undef can be dropped. This isn't safe for successive
6204 // rounds because they will permute elements within both vectors.
6205 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6206 EltStride == NumElems/2)
6209 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6218 // 256-bit AVX can use the vinsertf128 instruction
6219 // to create 256-bit vectors from two other 128-bit ones.
6220 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6222 MVT ResVT = Op.getSimpleValueType();
6224 assert((ResVT.is256BitVector() ||
6225 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6227 SDValue V1 = Op.getOperand(0);
6228 SDValue V2 = Op.getOperand(1);
6229 unsigned NumElems = ResVT.getVectorNumElements();
6230 if (ResVT.is256BitVector())
6231 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6233 if (Op.getNumOperands() == 4) {
6234 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6235 ResVT.getVectorNumElements()/2);
6236 SDValue V3 = Op.getOperand(2);
6237 SDValue V4 = Op.getOperand(3);
6238 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6239 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6241 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6244 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6245 const X86Subtarget *Subtarget,
6246 SelectionDAG & DAG) {
6248 MVT ResVT = Op.getSimpleValueType();
6249 unsigned NumOfOperands = Op.getNumOperands();
6251 assert(isPowerOf2_32(NumOfOperands) &&
6252 "Unexpected number of operands in CONCAT_VECTORS");
6254 if (NumOfOperands > 2) {
6255 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6256 ResVT.getVectorNumElements()/2);
6257 SmallVector<SDValue, 2> Ops;
6258 for (unsigned i = 0; i < NumOfOperands/2; i++)
6259 Ops.push_back(Op.getOperand(i));
6260 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6262 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6263 Ops.push_back(Op.getOperand(i));
6264 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6265 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6268 SDValue V1 = Op.getOperand(0);
6269 SDValue V2 = Op.getOperand(1);
6270 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6271 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6273 if (IsZeroV1 && IsZeroV2)
6274 return getZeroVector(ResVT, Subtarget, DAG, dl);
6276 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6277 SDValue Undef = DAG.getUNDEF(ResVT);
6278 unsigned NumElems = ResVT.getVectorNumElements();
6279 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6281 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6282 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6286 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6287 // Zero the upper bits of V1
6288 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6289 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6292 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6295 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6296 const X86Subtarget *Subtarget,
6297 SelectionDAG &DAG) {
6298 MVT VT = Op.getSimpleValueType();
6299 if (VT.getVectorElementType() == MVT::i1)
6300 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6302 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6303 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6304 Op.getNumOperands() == 4)));
6306 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6307 // from two other 128-bit ones.
6309 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6310 return LowerAVXCONCAT_VECTORS(Op, DAG);
6314 //===----------------------------------------------------------------------===//
6315 // Vector shuffle lowering
6317 // This is an experimental code path for lowering vector shuffles on x86. It is
6318 // designed to handle arbitrary vector shuffles and blends, gracefully
6319 // degrading performance as necessary. It works hard to recognize idiomatic
6320 // shuffles and lower them to optimal instruction patterns without leaving
6321 // a framework that allows reasonably efficient handling of all vector shuffle
6323 //===----------------------------------------------------------------------===//
6325 /// \brief Tiny helper function to identify a no-op mask.
6327 /// This is a somewhat boring predicate function. It checks whether the mask
6328 /// array input, which is assumed to be a single-input shuffle mask of the kind
6329 /// used by the X86 shuffle instructions (not a fully general
6330 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6331 /// in-place shuffle are 'no-op's.
6332 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6333 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6334 if (Mask[i] != -1 && Mask[i] != i)
6339 /// \brief Helper function to classify a mask as a single-input mask.
6341 /// This isn't a generic single-input test because in the vector shuffle
6342 /// lowering we canonicalize single inputs to be the first input operand. This
6343 /// means we can more quickly test for a single input by only checking whether
6344 /// an input from the second operand exists. We also assume that the size of
6345 /// mask corresponds to the size of the input vectors which isn't true in the
6346 /// fully general case.
6347 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6349 if (M >= (int)Mask.size())
6354 /// \brief Test whether there are elements crossing 128-bit lanes in this
6357 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6358 /// and we routinely test for these.
6359 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6360 int LaneSize = 128 / VT.getScalarSizeInBits();
6361 int Size = Mask.size();
6362 for (int i = 0; i < Size; ++i)
6363 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6368 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6370 /// This checks a shuffle mask to see if it is performing the same
6371 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6372 /// that it is also not lane-crossing. It may however involve a blend from the
6373 /// same lane of a second vector.
6375 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6376 /// non-trivial to compute in the face of undef lanes. The representation is
6377 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6378 /// entries from both V1 and V2 inputs to the wider mask.
6380 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6381 SmallVectorImpl<int> &RepeatedMask) {
6382 int LaneSize = 128 / VT.getScalarSizeInBits();
6383 RepeatedMask.resize(LaneSize, -1);
6384 int Size = Mask.size();
6385 for (int i = 0; i < Size; ++i) {
6388 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6389 // This entry crosses lanes, so there is no way to model this shuffle.
6392 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6393 if (RepeatedMask[i % LaneSize] == -1)
6394 // This is the first non-undef entry in this slot of a 128-bit lane.
6395 RepeatedMask[i % LaneSize] =
6396 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6397 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6398 // Found a mismatch with the repeated mask.
6404 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6407 /// This is a fast way to test a shuffle mask against a fixed pattern:
6409 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6411 /// It returns true if the mask is exactly as wide as the argument list, and
6412 /// each element of the mask is either -1 (signifying undef) or the value given
6413 /// in the argument.
6414 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6415 ArrayRef<int> ExpectedMask) {
6416 if (Mask.size() != ExpectedMask.size())
6419 int Size = Mask.size();
6421 // If the values are build vectors, we can look through them to find
6422 // equivalent inputs that make the shuffles equivalent.
6423 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6424 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6426 for (int i = 0; i < Size; ++i)
6427 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6428 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6429 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6430 if (!MaskBV || !ExpectedBV ||
6431 MaskBV->getOperand(Mask[i] % Size) !=
6432 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6439 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6441 /// This helper function produces an 8-bit shuffle immediate corresponding to
6442 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6443 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6446 /// NB: We rely heavily on "undef" masks preserving the input lane.
6447 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6448 SelectionDAG &DAG) {
6449 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6450 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6451 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6452 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6453 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6456 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6457 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6458 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6459 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6460 return DAG.getConstant(Imm, DL, MVT::i8);
6463 /// \brief Compute whether each element of a shuffle is zeroable.
6465 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6466 /// Either it is an undef element in the shuffle mask, the element of the input
6467 /// referenced is undef, or the element of the input referenced is known to be
6468 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6469 /// as many lanes with this technique as possible to simplify the remaining
6471 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6472 SDValue V1, SDValue V2) {
6473 SmallBitVector Zeroable(Mask.size(), false);
6475 while (V1.getOpcode() == ISD::BITCAST)
6476 V1 = V1->getOperand(0);
6477 while (V2.getOpcode() == ISD::BITCAST)
6478 V2 = V2->getOperand(0);
6480 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6481 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6483 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6485 // Handle the easy cases.
6486 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6491 // If this is an index into a build_vector node (which has the same number
6492 // of elements), dig out the input value and use it.
6493 SDValue V = M < Size ? V1 : V2;
6494 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6497 SDValue Input = V.getOperand(M % Size);
6498 // The UNDEF opcode check really should be dead code here, but not quite
6499 // worth asserting on (it isn't invalid, just unexpected).
6500 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6507 /// \brief Try to emit a bitmask instruction for a shuffle.
6509 /// This handles cases where we can model a blend exactly as a bitmask due to
6510 /// one of the inputs being zeroable.
6511 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6512 SDValue V2, ArrayRef<int> Mask,
6513 SelectionDAG &DAG) {
6514 MVT EltVT = VT.getScalarType();
6515 int NumEltBits = EltVT.getSizeInBits();
6516 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6517 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6518 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6520 if (EltVT.isFloatingPoint()) {
6521 Zero = DAG.getBitcast(EltVT, Zero);
6522 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6524 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6525 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6527 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6530 if (Mask[i] % Size != i)
6531 return SDValue(); // Not a blend.
6533 V = Mask[i] < Size ? V1 : V2;
6534 else if (V != (Mask[i] < Size ? V1 : V2))
6535 return SDValue(); // Can only let one input through the mask.
6537 VMaskOps[i] = AllOnes;
6540 return SDValue(); // No non-zeroable elements!
6542 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6543 V = DAG.getNode(VT.isFloatingPoint()
6544 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6549 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6551 /// This is used as a fallback approach when first class blend instructions are
6552 /// unavailable. Currently it is only suitable for integer vectors, but could
6553 /// be generalized for floating point vectors if desirable.
6554 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6555 SDValue V2, ArrayRef<int> Mask,
6556 SelectionDAG &DAG) {
6557 assert(VT.isInteger() && "Only supports integer vector types!");
6558 MVT EltVT = VT.getScalarType();
6559 int NumEltBits = EltVT.getSizeInBits();
6560 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6561 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6563 SmallVector<SDValue, 16> MaskOps;
6564 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6565 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6566 return SDValue(); // Shuffled input!
6567 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6570 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6571 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6572 // We have to cast V2 around.
6573 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6574 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6575 DAG.getBitcast(MaskVT, V1Mask),
6576 DAG.getBitcast(MaskVT, V2)));
6577 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6580 /// \brief Try to emit a blend instruction for a shuffle.
6582 /// This doesn't do any checks for the availability of instructions for blending
6583 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6584 /// be matched in the backend with the type given. What it does check for is
6585 /// that the shuffle mask is in fact a blend.
6586 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6587 SDValue V2, ArrayRef<int> Mask,
6588 const X86Subtarget *Subtarget,
6589 SelectionDAG &DAG) {
6590 unsigned BlendMask = 0;
6591 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6592 if (Mask[i] >= Size) {
6593 if (Mask[i] != i + Size)
6594 return SDValue(); // Shuffled V2 input!
6595 BlendMask |= 1u << i;
6598 if (Mask[i] >= 0 && Mask[i] != i)
6599 return SDValue(); // Shuffled V1 input!
6601 switch (VT.SimpleTy) {
6606 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6607 DAG.getConstant(BlendMask, DL, MVT::i8));
6611 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6615 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6616 // that instruction.
6617 if (Subtarget->hasAVX2()) {
6618 // Scale the blend by the number of 32-bit dwords per element.
6619 int Scale = VT.getScalarSizeInBits() / 32;
6621 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6622 if (Mask[i] >= Size)
6623 for (int j = 0; j < Scale; ++j)
6624 BlendMask |= 1u << (i * Scale + j);
6626 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6627 V1 = DAG.getBitcast(BlendVT, V1);
6628 V2 = DAG.getBitcast(BlendVT, V2);
6629 return DAG.getBitcast(
6630 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6631 DAG.getConstant(BlendMask, DL, MVT::i8)));
6635 // For integer shuffles we need to expand the mask and cast the inputs to
6636 // v8i16s prior to blending.
6637 int Scale = 8 / VT.getVectorNumElements();
6639 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6640 if (Mask[i] >= Size)
6641 for (int j = 0; j < Scale; ++j)
6642 BlendMask |= 1u << (i * Scale + j);
6644 V1 = DAG.getBitcast(MVT::v8i16, V1);
6645 V2 = DAG.getBitcast(MVT::v8i16, V2);
6646 return DAG.getBitcast(VT,
6647 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6648 DAG.getConstant(BlendMask, DL, MVT::i8)));
6652 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6653 SmallVector<int, 8> RepeatedMask;
6654 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6655 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6656 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6658 for (int i = 0; i < 8; ++i)
6659 if (RepeatedMask[i] >= 16)
6660 BlendMask |= 1u << i;
6661 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6662 DAG.getConstant(BlendMask, DL, MVT::i8));
6668 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6669 "256-bit byte-blends require AVX2 support!");
6671 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6672 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6675 // Scale the blend by the number of bytes per element.
6676 int Scale = VT.getScalarSizeInBits() / 8;
6678 // This form of blend is always done on bytes. Compute the byte vector
6680 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6682 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6683 // mix of LLVM's code generator and the x86 backend. We tell the code
6684 // generator that boolean values in the elements of an x86 vector register
6685 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6686 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6687 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6688 // of the element (the remaining are ignored) and 0 in that high bit would
6689 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6690 // the LLVM model for boolean values in vector elements gets the relevant
6691 // bit set, it is set backwards and over constrained relative to x86's
6693 SmallVector<SDValue, 32> VSELECTMask;
6694 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6695 for (int j = 0; j < Scale; ++j)
6696 VSELECTMask.push_back(
6697 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6698 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6701 V1 = DAG.getBitcast(BlendVT, V1);
6702 V2 = DAG.getBitcast(BlendVT, V2);
6703 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6704 DAG.getNode(ISD::BUILD_VECTOR, DL,
6705 BlendVT, VSELECTMask),
6710 llvm_unreachable("Not a supported integer vector type!");
6714 /// \brief Try to lower as a blend of elements from two inputs followed by
6715 /// a single-input permutation.
6717 /// This matches the pattern where we can blend elements from two inputs and
6718 /// then reduce the shuffle to a single-input permutation.
6719 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6722 SelectionDAG &DAG) {
6723 // We build up the blend mask while checking whether a blend is a viable way
6724 // to reduce the shuffle.
6725 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6726 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6728 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6732 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6734 if (BlendMask[Mask[i] % Size] == -1)
6735 BlendMask[Mask[i] % Size] = Mask[i];
6736 else if (BlendMask[Mask[i] % Size] != Mask[i])
6737 return SDValue(); // Can't blend in the needed input!
6739 PermuteMask[i] = Mask[i] % Size;
6742 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6743 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6746 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6747 /// blends and permutes.
6749 /// This matches the extremely common pattern for handling combined
6750 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6751 /// operations. It will try to pick the best arrangement of shuffles and
6753 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6757 SelectionDAG &DAG) {
6758 // Shuffle the input elements into the desired positions in V1 and V2 and
6759 // blend them together.
6760 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6761 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6762 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6763 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6764 if (Mask[i] >= 0 && Mask[i] < Size) {
6765 V1Mask[i] = Mask[i];
6767 } else if (Mask[i] >= Size) {
6768 V2Mask[i] = Mask[i] - Size;
6769 BlendMask[i] = i + Size;
6772 // Try to lower with the simpler initial blend strategy unless one of the
6773 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6774 // shuffle may be able to fold with a load or other benefit. However, when
6775 // we'll have to do 2x as many shuffles in order to achieve this, blending
6776 // first is a better strategy.
6777 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6778 if (SDValue BlendPerm =
6779 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6782 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6783 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6784 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6787 /// \brief Try to lower a vector shuffle as a byte rotation.
6789 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6790 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6791 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6792 /// try to generically lower a vector shuffle through such an pattern. It
6793 /// does not check for the profitability of lowering either as PALIGNR or
6794 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6795 /// This matches shuffle vectors that look like:
6797 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6799 /// Essentially it concatenates V1 and V2, shifts right by some number of
6800 /// elements, and takes the low elements as the result. Note that while this is
6801 /// specified as a *right shift* because x86 is little-endian, it is a *left
6802 /// rotate* of the vector lanes.
6803 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6806 const X86Subtarget *Subtarget,
6807 SelectionDAG &DAG) {
6808 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6810 int NumElts = Mask.size();
6811 int NumLanes = VT.getSizeInBits() / 128;
6812 int NumLaneElts = NumElts / NumLanes;
6814 // We need to detect various ways of spelling a rotation:
6815 // [11, 12, 13, 14, 15, 0, 1, 2]
6816 // [-1, 12, 13, 14, -1, -1, 1, -1]
6817 // [-1, -1, -1, -1, -1, -1, 1, 2]
6818 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6819 // [-1, 4, 5, 6, -1, -1, 9, -1]
6820 // [-1, 4, 5, 6, -1, -1, -1, -1]
6823 for (int l = 0; l < NumElts; l += NumLaneElts) {
6824 for (int i = 0; i < NumLaneElts; ++i) {
6825 if (Mask[l + i] == -1)
6827 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6829 // Get the mod-Size index and lane correct it.
6830 int LaneIdx = (Mask[l + i] % NumElts) - l;
6831 // Make sure it was in this lane.
6832 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6835 // Determine where a rotated vector would have started.
6836 int StartIdx = i - LaneIdx;
6838 // The identity rotation isn't interesting, stop.
6841 // If we found the tail of a vector the rotation must be the missing
6842 // front. If we found the head of a vector, it must be how much of the
6844 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6847 Rotation = CandidateRotation;
6848 else if (Rotation != CandidateRotation)
6849 // The rotations don't match, so we can't match this mask.
6852 // Compute which value this mask is pointing at.
6853 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6855 // Compute which of the two target values this index should be assigned
6856 // to. This reflects whether the high elements are remaining or the low
6857 // elements are remaining.
6858 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6860 // Either set up this value if we've not encountered it before, or check
6861 // that it remains consistent.
6864 else if (TargetV != MaskV)
6865 // This may be a rotation, but it pulls from the inputs in some
6866 // unsupported interleaving.
6871 // Check that we successfully analyzed the mask, and normalize the results.
6872 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6873 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6879 // The actual rotate instruction rotates bytes, so we need to scale the
6880 // rotation based on how many bytes are in the vector lane.
6881 int Scale = 16 / NumLaneElts;
6883 // SSSE3 targets can use the palignr instruction.
6884 if (Subtarget->hasSSSE3()) {
6885 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6886 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6887 Lo = DAG.getBitcast(AlignVT, Lo);
6888 Hi = DAG.getBitcast(AlignVT, Hi);
6890 return DAG.getBitcast(
6891 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6892 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6895 assert(VT.getSizeInBits() == 128 &&
6896 "Rotate-based lowering only supports 128-bit lowering!");
6897 assert(Mask.size() <= 16 &&
6898 "Can shuffle at most 16 bytes in a 128-bit vector!");
6900 // Default SSE2 implementation
6901 int LoByteShift = 16 - Rotation * Scale;
6902 int HiByteShift = Rotation * Scale;
6904 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6905 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6906 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6908 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6909 DAG.getConstant(LoByteShift, DL, MVT::i8));
6910 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6911 DAG.getConstant(HiByteShift, DL, MVT::i8));
6912 return DAG.getBitcast(VT,
6913 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6916 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6918 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6919 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6920 /// matches elements from one of the input vectors shuffled to the left or
6921 /// right with zeroable elements 'shifted in'. It handles both the strictly
6922 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6925 /// PSHL : (little-endian) left bit shift.
6926 /// [ zz, 0, zz, 2 ]
6927 /// [ -1, 4, zz, -1 ]
6928 /// PSRL : (little-endian) right bit shift.
6930 /// [ -1, -1, 7, zz]
6931 /// PSLLDQ : (little-endian) left byte shift
6932 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6933 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6934 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6935 /// PSRLDQ : (little-endian) right byte shift
6936 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6937 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6938 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6939 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6940 SDValue V2, ArrayRef<int> Mask,
6941 SelectionDAG &DAG) {
6942 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6944 int Size = Mask.size();
6945 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6947 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6948 for (int i = 0; i < Size; i += Scale)
6949 for (int j = 0; j < Shift; ++j)
6950 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6956 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6957 for (int i = 0; i != Size; i += Scale) {
6958 unsigned Pos = Left ? i + Shift : i;
6959 unsigned Low = Left ? i : i + Shift;
6960 unsigned Len = Scale - Shift;
6961 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6962 Low + (V == V1 ? 0 : Size)))
6966 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6967 bool ByteShift = ShiftEltBits > 64;
6968 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6969 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6970 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6972 // Normalize the scale for byte shifts to still produce an i64 element
6974 Scale = ByteShift ? Scale / 2 : Scale;
6976 // We need to round trip through the appropriate type for the shift.
6977 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6978 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6979 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6980 "Illegal integer vector type");
6981 V = DAG.getBitcast(ShiftVT, V);
6983 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6984 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6985 return DAG.getBitcast(VT, V);
6988 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6989 // keep doubling the size of the integer elements up to that. We can
6990 // then shift the elements of the integer vector by whole multiples of
6991 // their width within the elements of the larger integer vector. Test each
6992 // multiple to see if we can find a match with the moved element indices
6993 // and that the shifted in elements are all zeroable.
6994 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6995 for (int Shift = 1; Shift != Scale; ++Shift)
6996 for (bool Left : {true, false})
6997 if (CheckZeros(Shift, Scale, Left))
6998 for (SDValue V : {V1, V2})
6999 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7006 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7007 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7008 SDValue V2, ArrayRef<int> Mask,
7009 SelectionDAG &DAG) {
7010 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7011 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7013 int Size = Mask.size();
7014 int HalfSize = Size / 2;
7015 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7017 // Upper half must be undefined.
7018 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7021 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7022 // Remainder of lower half result is zero and upper half is all undef.
7023 auto LowerAsEXTRQ = [&]() {
7024 // Determine the extraction length from the part of the
7025 // lower half that isn't zeroable.
7027 for (; Len >= 0; --Len)
7028 if (!Zeroable[Len - 1])
7030 assert(Len > 0 && "Zeroable shuffle mask");
7032 // Attempt to match first Len sequential elements from the lower half.
7035 for (int i = 0; i != Len; ++i) {
7039 SDValue &V = (M < Size ? V1 : V2);
7042 // All mask elements must be in the lower half.
7046 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7057 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7058 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7059 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7060 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7061 DAG.getConstant(BitLen, DL, MVT::i8),
7062 DAG.getConstant(BitIdx, DL, MVT::i8));
7065 if (SDValue ExtrQ = LowerAsEXTRQ())
7068 // INSERTQ: Extract lowest Len elements from lower half of second source and
7069 // insert over first source, starting at Idx.
7070 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7071 auto LowerAsInsertQ = [&]() {
7072 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7075 // Attempt to match first source from mask before insertion point.
7076 if (isUndefInRange(Mask, 0, Idx)) {
7078 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7080 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7086 // Extend the extraction length looking to match both the insertion of
7087 // the second source and the remaining elements of the first.
7088 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7093 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7095 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7101 // Match the remaining elements of the lower half.
7102 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7104 } else if ((!Base || (Base == V1)) &&
7105 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7107 } else if ((!Base || (Base == V2)) &&
7108 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7115 // We may not have a base (first source) - this can safely be undefined.
7117 Base = DAG.getUNDEF(VT);
7119 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7120 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7121 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7122 DAG.getConstant(BitLen, DL, MVT::i8),
7123 DAG.getConstant(BitIdx, DL, MVT::i8));
7130 if (SDValue InsertQ = LowerAsInsertQ())
7136 /// \brief Lower a vector shuffle as a zero or any extension.
7138 /// Given a specific number of elements, element bit width, and extension
7139 /// stride, produce either a zero or any extension based on the available
7140 /// features of the subtarget.
7141 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7142 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7143 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7144 assert(Scale > 1 && "Need a scale to extend.");
7145 int NumElements = VT.getVectorNumElements();
7146 int EltBits = VT.getScalarSizeInBits();
7147 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7148 "Only 8, 16, and 32 bit elements can be extended.");
7149 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7151 // Found a valid zext mask! Try various lowering strategies based on the
7152 // input type and available ISA extensions.
7153 if (Subtarget->hasSSE41()) {
7154 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7155 NumElements / Scale);
7156 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7159 // For any extends we can cheat for larger element sizes and use shuffle
7160 // instructions that can fold with a load and/or copy.
7161 if (AnyExt && EltBits == 32) {
7162 int PSHUFDMask[4] = {0, -1, 1, -1};
7163 return DAG.getBitcast(
7164 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7165 DAG.getBitcast(MVT::v4i32, InputV),
7166 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7168 if (AnyExt && EltBits == 16 && Scale > 2) {
7169 int PSHUFDMask[4] = {0, -1, 0, -1};
7170 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7171 DAG.getBitcast(MVT::v4i32, InputV),
7172 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7173 int PSHUFHWMask[4] = {1, -1, -1, -1};
7174 return DAG.getBitcast(
7175 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7176 DAG.getBitcast(MVT::v8i16, InputV),
7177 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7180 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7182 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7183 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7184 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7186 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7187 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7188 DAG.getConstant(EltBits, DL, MVT::i8),
7189 DAG.getConstant(0, DL, MVT::i8)));
7190 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7191 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7194 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7195 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7196 DAG.getConstant(EltBits, DL, MVT::i8),
7197 DAG.getConstant(EltBits, DL, MVT::i8)));
7198 return DAG.getNode(ISD::BITCAST, DL, VT,
7199 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7202 // If this would require more than 2 unpack instructions to expand, use
7203 // pshufb when available. We can only use more than 2 unpack instructions
7204 // when zero extending i8 elements which also makes it easier to use pshufb.
7205 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7206 assert(NumElements == 16 && "Unexpected byte vector width!");
7207 SDValue PSHUFBMask[16];
7208 for (int i = 0; i < 16; ++i)
7210 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7211 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7212 return DAG.getBitcast(VT,
7213 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7214 DAG.getNode(ISD::BUILD_VECTOR, DL,
7215 MVT::v16i8, PSHUFBMask)));
7218 // Otherwise emit a sequence of unpacks.
7220 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7221 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7222 : getZeroVector(InputVT, Subtarget, DAG, DL);
7223 InputV = DAG.getBitcast(InputVT, InputV);
7224 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7228 } while (Scale > 1);
7229 return DAG.getBitcast(VT, InputV);
7232 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7234 /// This routine will try to do everything in its power to cleverly lower
7235 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7236 /// check for the profitability of this lowering, it tries to aggressively
7237 /// match this pattern. It will use all of the micro-architectural details it
7238 /// can to emit an efficient lowering. It handles both blends with all-zero
7239 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7240 /// masking out later).
7242 /// The reason we have dedicated lowering for zext-style shuffles is that they
7243 /// are both incredibly common and often quite performance sensitive.
7244 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7245 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7246 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7247 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7249 int Bits = VT.getSizeInBits();
7250 int NumElements = VT.getVectorNumElements();
7251 assert(VT.getScalarSizeInBits() <= 32 &&
7252 "Exceeds 32-bit integer zero extension limit");
7253 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7255 // Define a helper function to check a particular ext-scale and lower to it if
7257 auto Lower = [&](int Scale) -> SDValue {
7260 for (int i = 0; i < NumElements; ++i) {
7262 continue; // Valid anywhere but doesn't tell us anything.
7263 if (i % Scale != 0) {
7264 // Each of the extended elements need to be zeroable.
7268 // We no longer are in the anyext case.
7273 // Each of the base elements needs to be consecutive indices into the
7274 // same input vector.
7275 SDValue V = Mask[i] < NumElements ? V1 : V2;
7278 else if (InputV != V)
7279 return SDValue(); // Flip-flopping inputs.
7281 if (Mask[i] % NumElements != i / Scale)
7282 return SDValue(); // Non-consecutive strided elements.
7285 // If we fail to find an input, we have a zero-shuffle which should always
7286 // have already been handled.
7287 // FIXME: Maybe handle this here in case during blending we end up with one?
7291 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7292 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7295 // The widest scale possible for extending is to a 64-bit integer.
7296 assert(Bits % 64 == 0 &&
7297 "The number of bits in a vector must be divisible by 64 on x86!");
7298 int NumExtElements = Bits / 64;
7300 // Each iteration, try extending the elements half as much, but into twice as
7302 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7303 assert(NumElements % NumExtElements == 0 &&
7304 "The input vector size must be divisible by the extended size.");
7305 if (SDValue V = Lower(NumElements / NumExtElements))
7309 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7313 // Returns one of the source operands if the shuffle can be reduced to a
7314 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7315 auto CanZExtLowHalf = [&]() {
7316 for (int i = NumElements / 2; i != NumElements; ++i)
7319 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7321 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7326 if (SDValue V = CanZExtLowHalf()) {
7327 V = DAG.getBitcast(MVT::v2i64, V);
7328 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7329 return DAG.getBitcast(VT, V);
7332 // No viable ext lowering found.
7336 /// \brief Try to get a scalar value for a specific element of a vector.
7338 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7339 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7340 SelectionDAG &DAG) {
7341 MVT VT = V.getSimpleValueType();
7342 MVT EltVT = VT.getVectorElementType();
7343 while (V.getOpcode() == ISD::BITCAST)
7344 V = V.getOperand(0);
7345 // If the bitcasts shift the element size, we can't extract an equivalent
7347 MVT NewVT = V.getSimpleValueType();
7348 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7351 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7352 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7353 // Ensure the scalar operand is the same size as the destination.
7354 // FIXME: Add support for scalar truncation where possible.
7355 SDValue S = V.getOperand(Idx);
7356 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7357 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7363 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7365 /// This is particularly important because the set of instructions varies
7366 /// significantly based on whether the operand is a load or not.
7367 static bool isShuffleFoldableLoad(SDValue V) {
7368 while (V.getOpcode() == ISD::BITCAST)
7369 V = V.getOperand(0);
7371 return ISD::isNON_EXTLoad(V.getNode());
7374 /// \brief Try to lower insertion of a single element into a zero vector.
7376 /// This is a common pattern that we have especially efficient patterns to lower
7377 /// across all subtarget feature sets.
7378 static SDValue lowerVectorShuffleAsElementInsertion(
7379 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7380 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7381 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7383 MVT EltVT = VT.getVectorElementType();
7385 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7386 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7388 bool IsV1Zeroable = true;
7389 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7390 if (i != V2Index && !Zeroable[i]) {
7391 IsV1Zeroable = false;
7395 // Check for a single input from a SCALAR_TO_VECTOR node.
7396 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7397 // all the smarts here sunk into that routine. However, the current
7398 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7399 // vector shuffle lowering is dead.
7400 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7402 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7403 // We need to zext the scalar if it is smaller than an i32.
7404 V2S = DAG.getBitcast(EltVT, V2S);
7405 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7406 // Using zext to expand a narrow element won't work for non-zero
7411 // Zero-extend directly to i32.
7413 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7415 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7416 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7417 EltVT == MVT::i16) {
7418 // Either not inserting from the low element of the input or the input
7419 // element size is too small to use VZEXT_MOVL to clear the high bits.
7423 if (!IsV1Zeroable) {
7424 // If V1 can't be treated as a zero vector we have fewer options to lower
7425 // this. We can't support integer vectors or non-zero targets cheaply, and
7426 // the V1 elements can't be permuted in any way.
7427 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7428 if (!VT.isFloatingPoint() || V2Index != 0)
7430 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7431 V1Mask[V2Index] = -1;
7432 if (!isNoopShuffleMask(V1Mask))
7434 // This is essentially a special case blend operation, but if we have
7435 // general purpose blend operations, they are always faster. Bail and let
7436 // the rest of the lowering handle these as blends.
7437 if (Subtarget->hasSSE41())
7440 // Otherwise, use MOVSD or MOVSS.
7441 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7442 "Only two types of floating point element types to handle!");
7443 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7447 // This lowering only works for the low element with floating point vectors.
7448 if (VT.isFloatingPoint() && V2Index != 0)
7451 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7453 V2 = DAG.getBitcast(VT, V2);
7456 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7457 // the desired position. Otherwise it is more efficient to do a vector
7458 // shift left. We know that we can do a vector shift left because all
7459 // the inputs are zero.
7460 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7461 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7462 V2Shuffle[V2Index] = 0;
7463 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7465 V2 = DAG.getBitcast(MVT::v2i64, V2);
7467 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7468 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7469 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7470 DAG.getDataLayout(), VT)));
7471 V2 = DAG.getBitcast(VT, V2);
7477 /// \brief Try to lower broadcast of a single element.
7479 /// For convenience, this code also bundles all of the subtarget feature set
7480 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7481 /// a convenient way to factor it out.
7482 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7484 const X86Subtarget *Subtarget,
7485 SelectionDAG &DAG) {
7486 if (!Subtarget->hasAVX())
7488 if (VT.isInteger() && !Subtarget->hasAVX2())
7491 // Check that the mask is a broadcast.
7492 int BroadcastIdx = -1;
7494 if (M >= 0 && BroadcastIdx == -1)
7496 else if (M >= 0 && M != BroadcastIdx)
7499 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7500 "a sorted mask where the broadcast "
7503 // Go up the chain of (vector) values to find a scalar load that we can
7504 // combine with the broadcast.
7506 switch (V.getOpcode()) {
7507 case ISD::CONCAT_VECTORS: {
7508 int OperandSize = Mask.size() / V.getNumOperands();
7509 V = V.getOperand(BroadcastIdx / OperandSize);
7510 BroadcastIdx %= OperandSize;
7514 case ISD::INSERT_SUBVECTOR: {
7515 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7516 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7520 int BeginIdx = (int)ConstantIdx->getZExtValue();
7522 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7523 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7524 BroadcastIdx -= BeginIdx;
7535 // Check if this is a broadcast of a scalar. We special case lowering
7536 // for scalars so that we can more effectively fold with loads.
7537 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7538 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7539 V = V.getOperand(BroadcastIdx);
7541 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7542 // Only AVX2 has register broadcasts.
7543 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7545 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7546 // We can't broadcast from a vector register without AVX2, and we can only
7547 // broadcast from the zero-element of a vector register.
7551 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7554 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7555 // INSERTPS when the V1 elements are already in the correct locations
7556 // because otherwise we can just always use two SHUFPS instructions which
7557 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7558 // perform INSERTPS if a single V1 element is out of place and all V2
7559 // elements are zeroable.
7560 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7562 SelectionDAG &DAG) {
7563 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7564 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7565 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7566 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7568 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7571 int V1DstIndex = -1;
7572 int V2DstIndex = -1;
7573 bool V1UsedInPlace = false;
7575 for (int i = 0; i < 4; ++i) {
7576 // Synthesize a zero mask from the zeroable elements (includes undefs).
7582 // Flag if we use any V1 inputs in place.
7584 V1UsedInPlace = true;
7588 // We can only insert a single non-zeroable element.
7589 if (V1DstIndex != -1 || V2DstIndex != -1)
7593 // V1 input out of place for insertion.
7596 // V2 input for insertion.
7601 // Don't bother if we have no (non-zeroable) element for insertion.
7602 if (V1DstIndex == -1 && V2DstIndex == -1)
7605 // Determine element insertion src/dst indices. The src index is from the
7606 // start of the inserted vector, not the start of the concatenated vector.
7607 unsigned V2SrcIndex = 0;
7608 if (V1DstIndex != -1) {
7609 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7610 // and don't use the original V2 at all.
7611 V2SrcIndex = Mask[V1DstIndex];
7612 V2DstIndex = V1DstIndex;
7615 V2SrcIndex = Mask[V2DstIndex] - 4;
7618 // If no V1 inputs are used in place, then the result is created only from
7619 // the zero mask and the V2 insertion - so remove V1 dependency.
7621 V1 = DAG.getUNDEF(MVT::v4f32);
7623 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7624 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7626 // Insert the V2 element into the desired position.
7628 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7629 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7632 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7633 /// UNPCK instruction.
7635 /// This specifically targets cases where we end up with alternating between
7636 /// the two inputs, and so can permute them into something that feeds a single
7637 /// UNPCK instruction. Note that this routine only targets integer vectors
7638 /// because for floating point vectors we have a generalized SHUFPS lowering
7639 /// strategy that handles everything that doesn't *exactly* match an unpack,
7640 /// making this clever lowering unnecessary.
7641 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7642 SDValue V2, ArrayRef<int> Mask,
7643 SelectionDAG &DAG) {
7644 assert(!VT.isFloatingPoint() &&
7645 "This routine only supports integer vectors.");
7646 assert(!isSingleInputShuffleMask(Mask) &&
7647 "This routine should only be used when blending two inputs.");
7648 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7650 int Size = Mask.size();
7652 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7653 return M >= 0 && M % Size < Size / 2;
7655 int NumHiInputs = std::count_if(
7656 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7658 bool UnpackLo = NumLoInputs >= NumHiInputs;
7660 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7661 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7662 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7664 for (int i = 0; i < Size; ++i) {
7668 // Each element of the unpack contains Scale elements from this mask.
7669 int UnpackIdx = i / Scale;
7671 // We only handle the case where V1 feeds the first slots of the unpack.
7672 // We rely on canonicalization to ensure this is the case.
7673 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7676 // Setup the mask for this input. The indexing is tricky as we have to
7677 // handle the unpack stride.
7678 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7679 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7683 // If we will have to shuffle both inputs to use the unpack, check whether
7684 // we can just unpack first and shuffle the result. If so, skip this unpack.
7685 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7686 !isNoopShuffleMask(V2Mask))
7689 // Shuffle the inputs into place.
7690 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7691 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7693 // Cast the inputs to the type we will use to unpack them.
7694 V1 = DAG.getBitcast(UnpackVT, V1);
7695 V2 = DAG.getBitcast(UnpackVT, V2);
7697 // Unpack the inputs and cast the result back to the desired type.
7698 return DAG.getBitcast(
7699 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7703 // We try each unpack from the largest to the smallest to try and find one
7704 // that fits this mask.
7705 int OrigNumElements = VT.getVectorNumElements();
7706 int OrigScalarSize = VT.getScalarSizeInBits();
7707 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7708 int Scale = ScalarSize / OrigScalarSize;
7709 int NumElements = OrigNumElements / Scale;
7710 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7711 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7715 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7717 if (NumLoInputs == 0 || NumHiInputs == 0) {
7718 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7719 "We have to have *some* inputs!");
7720 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7722 // FIXME: We could consider the total complexity of the permute of each
7723 // possible unpacking. Or at the least we should consider how many
7724 // half-crossings are created.
7725 // FIXME: We could consider commuting the unpacks.
7727 SmallVector<int, 32> PermMask;
7728 PermMask.assign(Size, -1);
7729 for (int i = 0; i < Size; ++i) {
7733 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7736 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7738 return DAG.getVectorShuffle(
7739 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7741 DAG.getUNDEF(VT), PermMask);
7747 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7749 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7750 /// support for floating point shuffles but not integer shuffles. These
7751 /// instructions will incur a domain crossing penalty on some chips though so
7752 /// it is better to avoid lowering through this for integer vectors where
7754 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7755 const X86Subtarget *Subtarget,
7756 SelectionDAG &DAG) {
7758 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7759 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7760 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7761 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7762 ArrayRef<int> Mask = SVOp->getMask();
7763 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7765 if (isSingleInputShuffleMask(Mask)) {
7766 // Use low duplicate instructions for masks that match their pattern.
7767 if (Subtarget->hasSSE3())
7768 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7769 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7771 // Straight shuffle of a single input vector. Simulate this by using the
7772 // single input as both of the "inputs" to this instruction..
7773 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7775 if (Subtarget->hasAVX()) {
7776 // If we have AVX, we can use VPERMILPS which will allow folding a load
7777 // into the shuffle.
7778 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7779 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7782 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7783 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7785 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7786 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7788 // If we have a single input, insert that into V1 if we can do so cheaply.
7789 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7790 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7791 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7793 // Try inverting the insertion since for v2 masks it is easy to do and we
7794 // can't reliably sort the mask one way or the other.
7795 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7796 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7797 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7798 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7802 // Try to use one of the special instruction patterns to handle two common
7803 // blend patterns if a zero-blend above didn't work.
7804 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7805 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7806 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7807 // We can either use a special instruction to load over the low double or
7808 // to move just the low double.
7810 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7812 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7814 if (Subtarget->hasSSE41())
7815 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7819 // Use dedicated unpack instructions for masks that match their pattern.
7820 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7821 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7822 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7823 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7825 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7826 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7827 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7830 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7832 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7833 /// the integer unit to minimize domain crossing penalties. However, for blends
7834 /// it falls back to the floating point shuffle operation with appropriate bit
7836 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7837 const X86Subtarget *Subtarget,
7838 SelectionDAG &DAG) {
7840 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7841 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7842 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7843 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7844 ArrayRef<int> Mask = SVOp->getMask();
7845 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7847 if (isSingleInputShuffleMask(Mask)) {
7848 // Check for being able to broadcast a single element.
7849 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7850 Mask, Subtarget, DAG))
7853 // Straight shuffle of a single input vector. For everything from SSE2
7854 // onward this has a single fast instruction with no scary immediates.
7855 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7856 V1 = DAG.getBitcast(MVT::v4i32, V1);
7857 int WidenedMask[4] = {
7858 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7859 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7860 return DAG.getBitcast(
7862 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7863 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7865 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7866 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7867 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7868 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7870 // If we have a blend of two PACKUS operations an the blend aligns with the
7871 // low and half halves, we can just merge the PACKUS operations. This is
7872 // particularly important as it lets us merge shuffles that this routine itself
7874 auto GetPackNode = [](SDValue V) {
7875 while (V.getOpcode() == ISD::BITCAST)
7876 V = V.getOperand(0);
7878 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7880 if (SDValue V1Pack = GetPackNode(V1))
7881 if (SDValue V2Pack = GetPackNode(V2))
7882 return DAG.getBitcast(MVT::v2i64,
7883 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7884 Mask[0] == 0 ? V1Pack.getOperand(0)
7885 : V1Pack.getOperand(1),
7886 Mask[1] == 2 ? V2Pack.getOperand(0)
7887 : V2Pack.getOperand(1)));
7889 // Try to use shift instructions.
7891 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7894 // When loading a scalar and then shuffling it into a vector we can often do
7895 // the insertion cheaply.
7896 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7897 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7899 // Try inverting the insertion since for v2 masks it is easy to do and we
7900 // can't reliably sort the mask one way or the other.
7901 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7902 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7903 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7906 // We have different paths for blend lowering, but they all must use the
7907 // *exact* same predicate.
7908 bool IsBlendSupported = Subtarget->hasSSE41();
7909 if (IsBlendSupported)
7910 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7914 // Use dedicated unpack instructions for masks that match their pattern.
7915 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7916 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7917 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7918 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7920 // Try to use byte rotation instructions.
7921 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7922 if (Subtarget->hasSSSE3())
7923 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7924 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7927 // If we have direct support for blends, we should lower by decomposing into
7928 // a permute. That will be faster than the domain cross.
7929 if (IsBlendSupported)
7930 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7933 // We implement this with SHUFPD which is pretty lame because it will likely
7934 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7935 // However, all the alternatives are still more cycles and newer chips don't
7936 // have this problem. It would be really nice if x86 had better shuffles here.
7937 V1 = DAG.getBitcast(MVT::v2f64, V1);
7938 V2 = DAG.getBitcast(MVT::v2f64, V2);
7939 return DAG.getBitcast(MVT::v2i64,
7940 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7943 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7945 /// This is used to disable more specialized lowerings when the shufps lowering
7946 /// will happen to be efficient.
7947 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7948 // This routine only handles 128-bit shufps.
7949 assert(Mask.size() == 4 && "Unsupported mask size!");
7951 // To lower with a single SHUFPS we need to have the low half and high half
7952 // each requiring a single input.
7953 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7955 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7961 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7963 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7964 /// It makes no assumptions about whether this is the *best* lowering, it simply
7966 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7967 ArrayRef<int> Mask, SDValue V1,
7968 SDValue V2, SelectionDAG &DAG) {
7969 SDValue LowV = V1, HighV = V2;
7970 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7973 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7975 if (NumV2Elements == 1) {
7977 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7980 // Compute the index adjacent to V2Index and in the same half by toggling
7982 int V2AdjIndex = V2Index ^ 1;
7984 if (Mask[V2AdjIndex] == -1) {
7985 // Handles all the cases where we have a single V2 element and an undef.
7986 // This will only ever happen in the high lanes because we commute the
7987 // vector otherwise.
7989 std::swap(LowV, HighV);
7990 NewMask[V2Index] -= 4;
7992 // Handle the case where the V2 element ends up adjacent to a V1 element.
7993 // To make this work, blend them together as the first step.
7994 int V1Index = V2AdjIndex;
7995 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7996 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7997 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7999 // Now proceed to reconstruct the final blend as we have the necessary
8000 // high or low half formed.
8007 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8008 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8010 } else if (NumV2Elements == 2) {
8011 if (Mask[0] < 4 && Mask[1] < 4) {
8012 // Handle the easy case where we have V1 in the low lanes and V2 in the
8016 } else if (Mask[2] < 4 && Mask[3] < 4) {
8017 // We also handle the reversed case because this utility may get called
8018 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8019 // arrange things in the right direction.
8025 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8026 // trying to place elements directly, just blend them and set up the final
8027 // shuffle to place them.
8029 // The first two blend mask elements are for V1, the second two are for
8031 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8032 Mask[2] < 4 ? Mask[2] : Mask[3],
8033 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8034 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8035 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8036 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8038 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8041 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8042 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8043 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8044 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8047 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8048 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8051 /// \brief Lower 4-lane 32-bit floating point shuffles.
8053 /// Uses instructions exclusively from the floating point unit to minimize
8054 /// domain crossing penalties, as these are sufficient to implement all v4f32
8056 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8057 const X86Subtarget *Subtarget,
8058 SelectionDAG &DAG) {
8060 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8061 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8062 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8063 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8064 ArrayRef<int> Mask = SVOp->getMask();
8065 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8068 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8070 if (NumV2Elements == 0) {
8071 // Check for being able to broadcast a single element.
8072 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8073 Mask, Subtarget, DAG))
8076 // Use even/odd duplicate instructions for masks that match their pattern.
8077 if (Subtarget->hasSSE3()) {
8078 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8079 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8080 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8081 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8084 if (Subtarget->hasAVX()) {
8085 // If we have AVX, we can use VPERMILPS which will allow folding a load
8086 // into the shuffle.
8087 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8088 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8091 // Otherwise, use a straight shuffle of a single input vector. We pass the
8092 // input vector to both operands to simulate this with a SHUFPS.
8093 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8094 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8097 // There are special ways we can lower some single-element blends. However, we
8098 // have custom ways we can lower more complex single-element blends below that
8099 // we defer to if both this and BLENDPS fail to match, so restrict this to
8100 // when the V2 input is targeting element 0 of the mask -- that is the fast
8102 if (NumV2Elements == 1 && Mask[0] >= 4)
8103 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8104 Mask, Subtarget, DAG))
8107 if (Subtarget->hasSSE41()) {
8108 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8112 // Use INSERTPS if we can complete the shuffle efficiently.
8113 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8116 if (!isSingleSHUFPSMask(Mask))
8117 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8118 DL, MVT::v4f32, V1, V2, Mask, DAG))
8122 // Use dedicated unpack instructions for masks that match their pattern.
8123 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8124 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8125 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8126 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8127 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8128 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8129 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8130 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8132 // Otherwise fall back to a SHUFPS lowering strategy.
8133 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8136 /// \brief Lower 4-lane i32 vector shuffles.
8138 /// We try to handle these with integer-domain shuffles where we can, but for
8139 /// blends we use the floating point domain blend instructions.
8140 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8141 const X86Subtarget *Subtarget,
8142 SelectionDAG &DAG) {
8144 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8145 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8146 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8147 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8148 ArrayRef<int> Mask = SVOp->getMask();
8149 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8151 // Whenever we can lower this as a zext, that instruction is strictly faster
8152 // than any alternative. It also allows us to fold memory operands into the
8153 // shuffle in many cases.
8154 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8155 Mask, Subtarget, DAG))
8159 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8161 if (NumV2Elements == 0) {
8162 // Check for being able to broadcast a single element.
8163 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8164 Mask, Subtarget, DAG))
8167 // Straight shuffle of a single input vector. For everything from SSE2
8168 // onward this has a single fast instruction with no scary immediates.
8169 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8170 // but we aren't actually going to use the UNPCK instruction because doing
8171 // so prevents folding a load into this instruction or making a copy.
8172 const int UnpackLoMask[] = {0, 0, 1, 1};
8173 const int UnpackHiMask[] = {2, 2, 3, 3};
8174 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8175 Mask = UnpackLoMask;
8176 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8177 Mask = UnpackHiMask;
8179 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8180 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8183 // Try to use shift instructions.
8185 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8188 // There are special ways we can lower some single-element blends.
8189 if (NumV2Elements == 1)
8190 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8191 Mask, Subtarget, DAG))
8194 // We have different paths for blend lowering, but they all must use the
8195 // *exact* same predicate.
8196 bool IsBlendSupported = Subtarget->hasSSE41();
8197 if (IsBlendSupported)
8198 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8202 if (SDValue Masked =
8203 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8206 // Use dedicated unpack instructions for masks that match their pattern.
8207 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8208 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8209 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8210 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8211 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8212 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8213 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8214 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8216 // Try to use byte rotation instructions.
8217 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8218 if (Subtarget->hasSSSE3())
8219 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8220 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8223 // If we have direct support for blends, we should lower by decomposing into
8224 // a permute. That will be faster than the domain cross.
8225 if (IsBlendSupported)
8226 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8229 // Try to lower by permuting the inputs into an unpack instruction.
8230 if (SDValue Unpack =
8231 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8234 // We implement this with SHUFPS because it can blend from two vectors.
8235 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8236 // up the inputs, bypassing domain shift penalties that we would encur if we
8237 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8239 return DAG.getBitcast(
8241 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8242 DAG.getBitcast(MVT::v4f32, V2), Mask));
8245 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8246 /// shuffle lowering, and the most complex part.
8248 /// The lowering strategy is to try to form pairs of input lanes which are
8249 /// targeted at the same half of the final vector, and then use a dword shuffle
8250 /// to place them onto the right half, and finally unpack the paired lanes into
8251 /// their final position.
8253 /// The exact breakdown of how to form these dword pairs and align them on the
8254 /// correct sides is really tricky. See the comments within the function for
8255 /// more of the details.
8257 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8258 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8259 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8260 /// vector, form the analogous 128-bit 8-element Mask.
8261 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8262 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8263 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8264 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8265 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8267 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8268 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8269 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8271 SmallVector<int, 4> LoInputs;
8272 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8273 [](int M) { return M >= 0; });
8274 std::sort(LoInputs.begin(), LoInputs.end());
8275 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8276 SmallVector<int, 4> HiInputs;
8277 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8278 [](int M) { return M >= 0; });
8279 std::sort(HiInputs.begin(), HiInputs.end());
8280 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8282 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8283 int NumHToL = LoInputs.size() - NumLToL;
8285 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8286 int NumHToH = HiInputs.size() - NumLToH;
8287 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8288 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8289 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8290 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8292 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8293 // such inputs we can swap two of the dwords across the half mark and end up
8294 // with <=2 inputs to each half in each half. Once there, we can fall through
8295 // to the generic code below. For example:
8297 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8298 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8300 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8301 // and an existing 2-into-2 on the other half. In this case we may have to
8302 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8303 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8304 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8305 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8306 // half than the one we target for fixing) will be fixed when we re-enter this
8307 // path. We will also combine away any sequence of PSHUFD instructions that
8308 // result into a single instruction. Here is an example of the tricky case:
8310 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8311 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8313 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8315 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8316 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8318 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8319 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8321 // The result is fine to be handled by the generic logic.
8322 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8323 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8324 int AOffset, int BOffset) {
8325 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8326 "Must call this with A having 3 or 1 inputs from the A half.");
8327 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8328 "Must call this with B having 1 or 3 inputs from the B half.");
8329 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8330 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8332 bool ThreeAInputs = AToAInputs.size() == 3;
8334 // Compute the index of dword with only one word among the three inputs in
8335 // a half by taking the sum of the half with three inputs and subtracting
8336 // the sum of the actual three inputs. The difference is the remaining
8339 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8340 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8341 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8342 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8343 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8344 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8345 int TripleNonInputIdx =
8346 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8347 TripleDWord = TripleNonInputIdx / 2;
8349 // We use xor with one to compute the adjacent DWord to whichever one the
8351 OneInputDWord = (OneInput / 2) ^ 1;
8353 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8354 // and BToA inputs. If there is also such a problem with the BToB and AToB
8355 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8356 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8357 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8358 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8359 // Compute how many inputs will be flipped by swapping these DWords. We
8361 // to balance this to ensure we don't form a 3-1 shuffle in the other
8363 int NumFlippedAToBInputs =
8364 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8365 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8366 int NumFlippedBToBInputs =
8367 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8368 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8369 if ((NumFlippedAToBInputs == 1 &&
8370 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8371 (NumFlippedBToBInputs == 1 &&
8372 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8373 // We choose whether to fix the A half or B half based on whether that
8374 // half has zero flipped inputs. At zero, we may not be able to fix it
8375 // with that half. We also bias towards fixing the B half because that
8376 // will more commonly be the high half, and we have to bias one way.
8377 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8378 ArrayRef<int> Inputs) {
8379 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8380 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8381 PinnedIdx ^ 1) != Inputs.end();
8382 // Determine whether the free index is in the flipped dword or the
8383 // unflipped dword based on where the pinned index is. We use this bit
8384 // in an xor to conditionally select the adjacent dword.
8385 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8386 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8387 FixFreeIdx) != Inputs.end();
8388 if (IsFixIdxInput == IsFixFreeIdxInput)
8390 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8391 FixFreeIdx) != Inputs.end();
8392 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8393 "We need to be changing the number of flipped inputs!");
8394 int PSHUFHalfMask[] = {0, 1, 2, 3};
8395 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8396 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8398 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8401 if (M != -1 && M == FixIdx)
8403 else if (M != -1 && M == FixFreeIdx)
8406 if (NumFlippedBToBInputs != 0) {
8408 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8409 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8411 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8412 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8413 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8418 int PSHUFDMask[] = {0, 1, 2, 3};
8419 PSHUFDMask[ADWord] = BDWord;
8420 PSHUFDMask[BDWord] = ADWord;
8423 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8424 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8426 // Adjust the mask to match the new locations of A and B.
8428 if (M != -1 && M/2 == ADWord)
8429 M = 2 * BDWord + M % 2;
8430 else if (M != -1 && M/2 == BDWord)
8431 M = 2 * ADWord + M % 2;
8433 // Recurse back into this routine to re-compute state now that this isn't
8434 // a 3 and 1 problem.
8435 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8438 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8439 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8440 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8441 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8443 // At this point there are at most two inputs to the low and high halves from
8444 // each half. That means the inputs can always be grouped into dwords and
8445 // those dwords can then be moved to the correct half with a dword shuffle.
8446 // We use at most one low and one high word shuffle to collect these paired
8447 // inputs into dwords, and finally a dword shuffle to place them.
8448 int PSHUFLMask[4] = {-1, -1, -1, -1};
8449 int PSHUFHMask[4] = {-1, -1, -1, -1};
8450 int PSHUFDMask[4] = {-1, -1, -1, -1};
8452 // First fix the masks for all the inputs that are staying in their
8453 // original halves. This will then dictate the targets of the cross-half
8455 auto fixInPlaceInputs =
8456 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8457 MutableArrayRef<int> SourceHalfMask,
8458 MutableArrayRef<int> HalfMask, int HalfOffset) {
8459 if (InPlaceInputs.empty())
8461 if (InPlaceInputs.size() == 1) {
8462 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8463 InPlaceInputs[0] - HalfOffset;
8464 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8467 if (IncomingInputs.empty()) {
8468 // Just fix all of the in place inputs.
8469 for (int Input : InPlaceInputs) {
8470 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8471 PSHUFDMask[Input / 2] = Input / 2;
8476 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8477 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8478 InPlaceInputs[0] - HalfOffset;
8479 // Put the second input next to the first so that they are packed into
8480 // a dword. We find the adjacent index by toggling the low bit.
8481 int AdjIndex = InPlaceInputs[0] ^ 1;
8482 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8483 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8484 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8486 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8487 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8489 // Now gather the cross-half inputs and place them into a free dword of
8490 // their target half.
8491 // FIXME: This operation could almost certainly be simplified dramatically to
8492 // look more like the 3-1 fixing operation.
8493 auto moveInputsToRightHalf = [&PSHUFDMask](
8494 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8495 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8496 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8498 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8499 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8501 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8503 int LowWord = Word & ~1;
8504 int HighWord = Word | 1;
8505 return isWordClobbered(SourceHalfMask, LowWord) ||
8506 isWordClobbered(SourceHalfMask, HighWord);
8509 if (IncomingInputs.empty())
8512 if (ExistingInputs.empty()) {
8513 // Map any dwords with inputs from them into the right half.
8514 for (int Input : IncomingInputs) {
8515 // If the source half mask maps over the inputs, turn those into
8516 // swaps and use the swapped lane.
8517 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8518 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8519 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8520 Input - SourceOffset;
8521 // We have to swap the uses in our half mask in one sweep.
8522 for (int &M : HalfMask)
8523 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8525 else if (M == Input)
8526 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8528 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8529 Input - SourceOffset &&
8530 "Previous placement doesn't match!");
8532 // Note that this correctly re-maps both when we do a swap and when
8533 // we observe the other side of the swap above. We rely on that to
8534 // avoid swapping the members of the input list directly.
8535 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8538 // Map the input's dword into the correct half.
8539 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8540 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8542 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8544 "Previous placement doesn't match!");
8547 // And just directly shift any other-half mask elements to be same-half
8548 // as we will have mirrored the dword containing the element into the
8549 // same position within that half.
8550 for (int &M : HalfMask)
8551 if (M >= SourceOffset && M < SourceOffset + 4) {
8552 M = M - SourceOffset + DestOffset;
8553 assert(M >= 0 && "This should never wrap below zero!");
8558 // Ensure we have the input in a viable dword of its current half. This
8559 // is particularly tricky because the original position may be clobbered
8560 // by inputs being moved and *staying* in that half.
8561 if (IncomingInputs.size() == 1) {
8562 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8563 int InputFixed = std::find(std::begin(SourceHalfMask),
8564 std::end(SourceHalfMask), -1) -
8565 std::begin(SourceHalfMask) + SourceOffset;
8566 SourceHalfMask[InputFixed - SourceOffset] =
8567 IncomingInputs[0] - SourceOffset;
8568 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8570 IncomingInputs[0] = InputFixed;
8572 } else if (IncomingInputs.size() == 2) {
8573 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8574 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8575 // We have two non-adjacent or clobbered inputs we need to extract from
8576 // the source half. To do this, we need to map them into some adjacent
8577 // dword slot in the source mask.
8578 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8579 IncomingInputs[1] - SourceOffset};
8581 // If there is a free slot in the source half mask adjacent to one of
8582 // the inputs, place the other input in it. We use (Index XOR 1) to
8583 // compute an adjacent index.
8584 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8585 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8586 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8587 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8588 InputsFixed[1] = InputsFixed[0] ^ 1;
8589 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8590 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8591 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8592 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8593 InputsFixed[0] = InputsFixed[1] ^ 1;
8594 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8595 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8596 // The two inputs are in the same DWord but it is clobbered and the
8597 // adjacent DWord isn't used at all. Move both inputs to the free
8599 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8600 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8601 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8602 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8604 // The only way we hit this point is if there is no clobbering
8605 // (because there are no off-half inputs to this half) and there is no
8606 // free slot adjacent to one of the inputs. In this case, we have to
8607 // swap an input with a non-input.
8608 for (int i = 0; i < 4; ++i)
8609 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8610 "We can't handle any clobbers here!");
8611 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8612 "Cannot have adjacent inputs here!");
8614 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8615 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8617 // We also have to update the final source mask in this case because
8618 // it may need to undo the above swap.
8619 for (int &M : FinalSourceHalfMask)
8620 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8621 M = InputsFixed[1] + SourceOffset;
8622 else if (M == InputsFixed[1] + SourceOffset)
8623 M = (InputsFixed[0] ^ 1) + SourceOffset;
8625 InputsFixed[1] = InputsFixed[0] ^ 1;
8628 // Point everything at the fixed inputs.
8629 for (int &M : HalfMask)
8630 if (M == IncomingInputs[0])
8631 M = InputsFixed[0] + SourceOffset;
8632 else if (M == IncomingInputs[1])
8633 M = InputsFixed[1] + SourceOffset;
8635 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8636 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8639 llvm_unreachable("Unhandled input size!");
8642 // Now hoist the DWord down to the right half.
8643 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8644 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8645 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8646 for (int &M : HalfMask)
8647 for (int Input : IncomingInputs)
8649 M = FreeDWord * 2 + Input % 2;
8651 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8652 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8653 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8654 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8656 // Now enact all the shuffles we've computed to move the inputs into their
8658 if (!isNoopShuffleMask(PSHUFLMask))
8659 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8660 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8661 if (!isNoopShuffleMask(PSHUFHMask))
8662 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8663 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8664 if (!isNoopShuffleMask(PSHUFDMask))
8667 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8668 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8670 // At this point, each half should contain all its inputs, and we can then
8671 // just shuffle them into their final position.
8672 assert(std::count_if(LoMask.begin(), LoMask.end(),
8673 [](int M) { return M >= 4; }) == 0 &&
8674 "Failed to lift all the high half inputs to the low mask!");
8675 assert(std::count_if(HiMask.begin(), HiMask.end(),
8676 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8677 "Failed to lift all the low half inputs to the high mask!");
8679 // Do a half shuffle for the low mask.
8680 if (!isNoopShuffleMask(LoMask))
8681 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8682 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8684 // Do a half shuffle with the high mask after shifting its values down.
8685 for (int &M : HiMask)
8688 if (!isNoopShuffleMask(HiMask))
8689 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8690 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8695 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8696 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8697 SDValue V2, ArrayRef<int> Mask,
8698 SelectionDAG &DAG, bool &V1InUse,
8700 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8706 int Size = Mask.size();
8707 int Scale = 16 / Size;
8708 for (int i = 0; i < 16; ++i) {
8709 if (Mask[i / Scale] == -1) {
8710 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8712 const int ZeroMask = 0x80;
8713 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8715 int V2Idx = Mask[i / Scale] < Size
8717 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8718 if (Zeroable[i / Scale])
8719 V1Idx = V2Idx = ZeroMask;
8720 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8721 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8722 V1InUse |= (ZeroMask != V1Idx);
8723 V2InUse |= (ZeroMask != V2Idx);
8728 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8729 DAG.getBitcast(MVT::v16i8, V1),
8730 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8732 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8733 DAG.getBitcast(MVT::v16i8, V2),
8734 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8736 // If we need shuffled inputs from both, blend the two.
8738 if (V1InUse && V2InUse)
8739 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8741 V = V1InUse ? V1 : V2;
8743 // Cast the result back to the correct type.
8744 return DAG.getBitcast(VT, V);
8747 /// \brief Generic lowering of 8-lane i16 shuffles.
8749 /// This handles both single-input shuffles and combined shuffle/blends with
8750 /// two inputs. The single input shuffles are immediately delegated to
8751 /// a dedicated lowering routine.
8753 /// The blends are lowered in one of three fundamental ways. If there are few
8754 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8755 /// of the input is significantly cheaper when lowered as an interleaving of
8756 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8757 /// halves of the inputs separately (making them have relatively few inputs)
8758 /// and then concatenate them.
8759 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8760 const X86Subtarget *Subtarget,
8761 SelectionDAG &DAG) {
8763 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8764 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8765 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8766 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8767 ArrayRef<int> OrigMask = SVOp->getMask();
8768 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8769 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8770 MutableArrayRef<int> Mask(MaskStorage);
8772 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8774 // Whenever we can lower this as a zext, that instruction is strictly faster
8775 // than any alternative.
8776 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8777 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8780 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8782 auto isV2 = [](int M) { return M >= 8; };
8784 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8786 if (NumV2Inputs == 0) {
8787 // Check for being able to broadcast a single element.
8788 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8789 Mask, Subtarget, DAG))
8792 // Try to use shift instructions.
8794 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8797 // Use dedicated unpack instructions for masks that match their pattern.
8798 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8799 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8800 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8801 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8803 // Try to use byte rotation instructions.
8804 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8805 Mask, Subtarget, DAG))
8808 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8812 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8813 "All single-input shuffles should be canonicalized to be V1-input "
8816 // Try to use shift instructions.
8818 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8821 // See if we can use SSE4A Extraction / Insertion.
8822 if (Subtarget->hasSSE4A())
8823 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8826 // There are special ways we can lower some single-element blends.
8827 if (NumV2Inputs == 1)
8828 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8829 Mask, Subtarget, DAG))
8832 // We have different paths for blend lowering, but they all must use the
8833 // *exact* same predicate.
8834 bool IsBlendSupported = Subtarget->hasSSE41();
8835 if (IsBlendSupported)
8836 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8840 if (SDValue Masked =
8841 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8844 // Use dedicated unpack instructions for masks that match their pattern.
8845 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8846 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8847 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8848 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8850 // Try to use byte rotation instructions.
8851 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8852 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8855 if (SDValue BitBlend =
8856 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8859 if (SDValue Unpack =
8860 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8863 // If we can't directly blend but can use PSHUFB, that will be better as it
8864 // can both shuffle and set up the inefficient blend.
8865 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8866 bool V1InUse, V2InUse;
8867 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8871 // We can always bit-blend if we have to so the fallback strategy is to
8872 // decompose into single-input permutes and blends.
8873 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8877 /// \brief Check whether a compaction lowering can be done by dropping even
8878 /// elements and compute how many times even elements must be dropped.
8880 /// This handles shuffles which take every Nth element where N is a power of
8881 /// two. Example shuffle masks:
8883 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8884 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8885 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8886 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8887 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8888 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8890 /// Any of these lanes can of course be undef.
8892 /// This routine only supports N <= 3.
8893 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8896 /// \returns N above, or the number of times even elements must be dropped if
8897 /// there is such a number. Otherwise returns zero.
8898 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8899 // Figure out whether we're looping over two inputs or just one.
8900 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8902 // The modulus for the shuffle vector entries is based on whether this is
8903 // a single input or not.
8904 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8905 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8906 "We should only be called with masks with a power-of-2 size!");
8908 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8910 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8911 // and 2^3 simultaneously. This is because we may have ambiguity with
8912 // partially undef inputs.
8913 bool ViableForN[3] = {true, true, true};
8915 for (int i = 0, e = Mask.size(); i < e; ++i) {
8916 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8921 bool IsAnyViable = false;
8922 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8923 if (ViableForN[j]) {
8926 // The shuffle mask must be equal to (i * 2^N) % M.
8927 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8930 ViableForN[j] = false;
8932 // Early exit if we exhaust the possible powers of two.
8937 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8941 // Return 0 as there is no viable power of two.
8945 /// \brief Generic lowering of v16i8 shuffles.
8947 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8948 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8949 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8950 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8952 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8953 const X86Subtarget *Subtarget,
8954 SelectionDAG &DAG) {
8956 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8957 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8958 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8959 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8960 ArrayRef<int> Mask = SVOp->getMask();
8961 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8963 // Try to use shift instructions.
8965 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8968 // Try to use byte rotation instructions.
8969 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8970 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8973 // Try to use a zext lowering.
8974 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8975 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8978 // See if we can use SSE4A Extraction / Insertion.
8979 if (Subtarget->hasSSE4A())
8980 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8984 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8986 // For single-input shuffles, there are some nicer lowering tricks we can use.
8987 if (NumV2Elements == 0) {
8988 // Check for being able to broadcast a single element.
8989 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8990 Mask, Subtarget, DAG))
8993 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8994 // Notably, this handles splat and partial-splat shuffles more efficiently.
8995 // However, it only makes sense if the pre-duplication shuffle simplifies
8996 // things significantly. Currently, this means we need to be able to
8997 // express the pre-duplication shuffle as an i16 shuffle.
8999 // FIXME: We should check for other patterns which can be widened into an
9000 // i16 shuffle as well.
9001 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9002 for (int i = 0; i < 16; i += 2)
9003 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9008 auto tryToWidenViaDuplication = [&]() -> SDValue {
9009 if (!canWidenViaDuplication(Mask))
9011 SmallVector<int, 4> LoInputs;
9012 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9013 [](int M) { return M >= 0 && M < 8; });
9014 std::sort(LoInputs.begin(), LoInputs.end());
9015 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9017 SmallVector<int, 4> HiInputs;
9018 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9019 [](int M) { return M >= 8; });
9020 std::sort(HiInputs.begin(), HiInputs.end());
9021 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9024 bool TargetLo = LoInputs.size() >= HiInputs.size();
9025 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9026 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9028 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9029 SmallDenseMap<int, int, 8> LaneMap;
9030 for (int I : InPlaceInputs) {
9031 PreDupI16Shuffle[I/2] = I/2;
9034 int j = TargetLo ? 0 : 4, je = j + 4;
9035 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9036 // Check if j is already a shuffle of this input. This happens when
9037 // there are two adjacent bytes after we move the low one.
9038 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9039 // If we haven't yet mapped the input, search for a slot into which
9041 while (j < je && PreDupI16Shuffle[j] != -1)
9045 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9048 // Map this input with the i16 shuffle.
9049 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9052 // Update the lane map based on the mapping we ended up with.
9053 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9055 V1 = DAG.getBitcast(
9057 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9058 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9060 // Unpack the bytes to form the i16s that will be shuffled into place.
9061 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9062 MVT::v16i8, V1, V1);
9064 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9065 for (int i = 0; i < 16; ++i)
9066 if (Mask[i] != -1) {
9067 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9068 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9069 if (PostDupI16Shuffle[i / 2] == -1)
9070 PostDupI16Shuffle[i / 2] = MappedMask;
9072 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9073 "Conflicting entrties in the original shuffle!");
9075 return DAG.getBitcast(
9077 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9078 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9080 if (SDValue V = tryToWidenViaDuplication())
9084 if (SDValue Masked =
9085 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9088 // Use dedicated unpack instructions for masks that match their pattern.
9089 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9090 0, 16, 1, 17, 2, 18, 3, 19,
9092 4, 20, 5, 21, 6, 22, 7, 23}))
9093 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9094 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9095 8, 24, 9, 25, 10, 26, 11, 27,
9097 12, 28, 13, 29, 14, 30, 15, 31}))
9098 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9100 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9101 // with PSHUFB. It is important to do this before we attempt to generate any
9102 // blends but after all of the single-input lowerings. If the single input
9103 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9104 // want to preserve that and we can DAG combine any longer sequences into
9105 // a PSHUFB in the end. But once we start blending from multiple inputs,
9106 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9107 // and there are *very* few patterns that would actually be faster than the
9108 // PSHUFB approach because of its ability to zero lanes.
9110 // FIXME: The only exceptions to the above are blends which are exact
9111 // interleavings with direct instructions supporting them. We currently don't
9112 // handle those well here.
9113 if (Subtarget->hasSSSE3()) {
9114 bool V1InUse = false;
9115 bool V2InUse = false;
9117 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9118 DAG, V1InUse, V2InUse);
9120 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9121 // do so. This avoids using them to handle blends-with-zero which is
9122 // important as a single pshufb is significantly faster for that.
9123 if (V1InUse && V2InUse) {
9124 if (Subtarget->hasSSE41())
9125 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9126 Mask, Subtarget, DAG))
9129 // We can use an unpack to do the blending rather than an or in some
9130 // cases. Even though the or may be (very minorly) more efficient, we
9131 // preference this lowering because there are common cases where part of
9132 // the complexity of the shuffles goes away when we do the final blend as
9134 // FIXME: It might be worth trying to detect if the unpack-feeding
9135 // shuffles will both be pshufb, in which case we shouldn't bother with
9137 if (SDValue Unpack =
9138 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9145 // There are special ways we can lower some single-element blends.
9146 if (NumV2Elements == 1)
9147 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9148 Mask, Subtarget, DAG))
9151 if (SDValue BitBlend =
9152 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9155 // Check whether a compaction lowering can be done. This handles shuffles
9156 // which take every Nth element for some even N. See the helper function for
9159 // We special case these as they can be particularly efficiently handled with
9160 // the PACKUSB instruction on x86 and they show up in common patterns of
9161 // rearranging bytes to truncate wide elements.
9162 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9163 // NumEvenDrops is the power of two stride of the elements. Another way of
9164 // thinking about it is that we need to drop the even elements this many
9165 // times to get the original input.
9166 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9168 // First we need to zero all the dropped bytes.
9169 assert(NumEvenDrops <= 3 &&
9170 "No support for dropping even elements more than 3 times.");
9171 // We use the mask type to pick which bytes are preserved based on how many
9172 // elements are dropped.
9173 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9174 SDValue ByteClearMask = DAG.getBitcast(
9175 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9176 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9178 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9180 // Now pack things back together.
9181 V1 = DAG.getBitcast(MVT::v8i16, V1);
9182 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9183 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9184 for (int i = 1; i < NumEvenDrops; ++i) {
9185 Result = DAG.getBitcast(MVT::v8i16, Result);
9186 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9192 // Handle multi-input cases by blending single-input shuffles.
9193 if (NumV2Elements > 0)
9194 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9197 // The fallback path for single-input shuffles widens this into two v8i16
9198 // vectors with unpacks, shuffles those, and then pulls them back together
9202 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9203 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9204 for (int i = 0; i < 16; ++i)
9206 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9208 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9210 SDValue VLoHalf, VHiHalf;
9211 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9212 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9214 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9215 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9216 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9217 [](int M) { return M >= 0 && M % 2 == 1; })) {
9218 // Use a mask to drop the high bytes.
9219 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9220 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9221 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9223 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9224 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9226 // Squash the masks to point directly into VLoHalf.
9227 for (int &M : LoBlendMask)
9230 for (int &M : HiBlendMask)
9234 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9235 // VHiHalf so that we can blend them as i16s.
9236 VLoHalf = DAG.getBitcast(
9237 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9238 VHiHalf = DAG.getBitcast(
9239 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9242 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9243 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9245 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9248 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9250 /// This routine breaks down the specific type of 128-bit shuffle and
9251 /// dispatches to the lowering routines accordingly.
9252 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9253 MVT VT, const X86Subtarget *Subtarget,
9254 SelectionDAG &DAG) {
9255 switch (VT.SimpleTy) {
9257 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9259 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9261 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9263 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9265 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9267 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9270 llvm_unreachable("Unimplemented!");
9274 /// \brief Helper function to test whether a shuffle mask could be
9275 /// simplified by widening the elements being shuffled.
9277 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9278 /// leaves it in an unspecified state.
9280 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9281 /// shuffle masks. The latter have the special property of a '-2' representing
9282 /// a zero-ed lane of a vector.
9283 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9284 SmallVectorImpl<int> &WidenedMask) {
9285 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9286 // If both elements are undef, its trivial.
9287 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9288 WidenedMask.push_back(SM_SentinelUndef);
9292 // Check for an undef mask and a mask value properly aligned to fit with
9293 // a pair of values. If we find such a case, use the non-undef mask's value.
9294 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9295 WidenedMask.push_back(Mask[i + 1] / 2);
9298 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9299 WidenedMask.push_back(Mask[i] / 2);
9303 // When zeroing, we need to spread the zeroing across both lanes to widen.
9304 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9305 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9306 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9307 WidenedMask.push_back(SM_SentinelZero);
9313 // Finally check if the two mask values are adjacent and aligned with
9315 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9316 WidenedMask.push_back(Mask[i] / 2);
9320 // Otherwise we can't safely widen the elements used in this shuffle.
9323 assert(WidenedMask.size() == Mask.size() / 2 &&
9324 "Incorrect size of mask after widening the elements!");
9329 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9331 /// This routine just extracts two subvectors, shuffles them independently, and
9332 /// then concatenates them back together. This should work effectively with all
9333 /// AVX vector shuffle types.
9334 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9335 SDValue V2, ArrayRef<int> Mask,
9336 SelectionDAG &DAG) {
9337 assert(VT.getSizeInBits() >= 256 &&
9338 "Only for 256-bit or wider vector shuffles!");
9339 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9340 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9342 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9343 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9345 int NumElements = VT.getVectorNumElements();
9346 int SplitNumElements = NumElements / 2;
9347 MVT ScalarVT = VT.getScalarType();
9348 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9350 // Rather than splitting build-vectors, just build two narrower build
9351 // vectors. This helps shuffling with splats and zeros.
9352 auto SplitVector = [&](SDValue V) {
9353 while (V.getOpcode() == ISD::BITCAST)
9354 V = V->getOperand(0);
9356 MVT OrigVT = V.getSimpleValueType();
9357 int OrigNumElements = OrigVT.getVectorNumElements();
9358 int OrigSplitNumElements = OrigNumElements / 2;
9359 MVT OrigScalarVT = OrigVT.getScalarType();
9360 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9364 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9366 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9367 DAG.getIntPtrConstant(0, DL));
9368 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9369 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9372 SmallVector<SDValue, 16> LoOps, HiOps;
9373 for (int i = 0; i < OrigSplitNumElements; ++i) {
9374 LoOps.push_back(BV->getOperand(i));
9375 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9377 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9378 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9380 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9381 DAG.getBitcast(SplitVT, HiV));
9384 SDValue LoV1, HiV1, LoV2, HiV2;
9385 std::tie(LoV1, HiV1) = SplitVector(V1);
9386 std::tie(LoV2, HiV2) = SplitVector(V2);
9388 // Now create two 4-way blends of these half-width vectors.
9389 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9390 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9391 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9392 for (int i = 0; i < SplitNumElements; ++i) {
9393 int M = HalfMask[i];
9394 if (M >= NumElements) {
9395 if (M >= NumElements + SplitNumElements)
9399 V2BlendMask.push_back(M - NumElements);
9400 V1BlendMask.push_back(-1);
9401 BlendMask.push_back(SplitNumElements + i);
9402 } else if (M >= 0) {
9403 if (M >= SplitNumElements)
9407 V2BlendMask.push_back(-1);
9408 V1BlendMask.push_back(M);
9409 BlendMask.push_back(i);
9411 V2BlendMask.push_back(-1);
9412 V1BlendMask.push_back(-1);
9413 BlendMask.push_back(-1);
9417 // Because the lowering happens after all combining takes place, we need to
9418 // manually combine these blend masks as much as possible so that we create
9419 // a minimal number of high-level vector shuffle nodes.
9421 // First try just blending the halves of V1 or V2.
9422 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9423 return DAG.getUNDEF(SplitVT);
9424 if (!UseLoV2 && !UseHiV2)
9425 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9426 if (!UseLoV1 && !UseHiV1)
9427 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9429 SDValue V1Blend, V2Blend;
9430 if (UseLoV1 && UseHiV1) {
9432 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9434 // We only use half of V1 so map the usage down into the final blend mask.
9435 V1Blend = UseLoV1 ? LoV1 : HiV1;
9436 for (int i = 0; i < SplitNumElements; ++i)
9437 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9438 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9440 if (UseLoV2 && UseHiV2) {
9442 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9444 // We only use half of V2 so map the usage down into the final blend mask.
9445 V2Blend = UseLoV2 ? LoV2 : HiV2;
9446 for (int i = 0; i < SplitNumElements; ++i)
9447 if (BlendMask[i] >= SplitNumElements)
9448 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9450 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9452 SDValue Lo = HalfBlend(LoMask);
9453 SDValue Hi = HalfBlend(HiMask);
9454 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9457 /// \brief Either split a vector in halves or decompose the shuffles and the
9460 /// This is provided as a good fallback for many lowerings of non-single-input
9461 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9462 /// between splitting the shuffle into 128-bit components and stitching those
9463 /// back together vs. extracting the single-input shuffles and blending those
9465 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9466 SDValue V2, ArrayRef<int> Mask,
9467 SelectionDAG &DAG) {
9468 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9469 "lower single-input shuffles as it "
9470 "could then recurse on itself.");
9471 int Size = Mask.size();
9473 // If this can be modeled as a broadcast of two elements followed by a blend,
9474 // prefer that lowering. This is especially important because broadcasts can
9475 // often fold with memory operands.
9476 auto DoBothBroadcast = [&] {
9477 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9480 if (V2BroadcastIdx == -1)
9481 V2BroadcastIdx = M - Size;
9482 else if (M - Size != V2BroadcastIdx)
9484 } else if (M >= 0) {
9485 if (V1BroadcastIdx == -1)
9487 else if (M != V1BroadcastIdx)
9492 if (DoBothBroadcast())
9493 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9496 // If the inputs all stem from a single 128-bit lane of each input, then we
9497 // split them rather than blending because the split will decompose to
9498 // unusually few instructions.
9499 int LaneCount = VT.getSizeInBits() / 128;
9500 int LaneSize = Size / LaneCount;
9501 SmallBitVector LaneInputs[2];
9502 LaneInputs[0].resize(LaneCount, false);
9503 LaneInputs[1].resize(LaneCount, false);
9504 for (int i = 0; i < Size; ++i)
9506 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9507 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9508 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9510 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9511 // that the decomposed single-input shuffles don't end up here.
9512 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9515 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9516 /// a permutation and blend of those lanes.
9518 /// This essentially blends the out-of-lane inputs to each lane into the lane
9519 /// from a permuted copy of the vector. This lowering strategy results in four
9520 /// instructions in the worst case for a single-input cross lane shuffle which
9521 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9522 /// of. Special cases for each particular shuffle pattern should be handled
9523 /// prior to trying this lowering.
9524 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9525 SDValue V1, SDValue V2,
9527 SelectionDAG &DAG) {
9528 // FIXME: This should probably be generalized for 512-bit vectors as well.
9529 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9530 int LaneSize = Mask.size() / 2;
9532 // If there are only inputs from one 128-bit lane, splitting will in fact be
9533 // less expensive. The flags track whether the given lane contains an element
9534 // that crosses to another lane.
9535 bool LaneCrossing[2] = {false, false};
9536 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9537 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9538 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9539 if (!LaneCrossing[0] || !LaneCrossing[1])
9540 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9542 if (isSingleInputShuffleMask(Mask)) {
9543 SmallVector<int, 32> FlippedBlendMask;
9544 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9545 FlippedBlendMask.push_back(
9546 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9548 : Mask[i] % LaneSize +
9549 (i / LaneSize) * LaneSize + Size));
9551 // Flip the vector, and blend the results which should now be in-lane. The
9552 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9553 // 5 for the high source. The value 3 selects the high half of source 2 and
9554 // the value 2 selects the low half of source 2. We only use source 2 to
9555 // allow folding it into a memory operand.
9556 unsigned PERMMask = 3 | 2 << 4;
9557 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9558 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9559 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9562 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9563 // will be handled by the above logic and a blend of the results, much like
9564 // other patterns in AVX.
9565 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9568 /// \brief Handle lowering 2-lane 128-bit shuffles.
9569 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9570 SDValue V2, ArrayRef<int> Mask,
9571 const X86Subtarget *Subtarget,
9572 SelectionDAG &DAG) {
9573 // TODO: If minimizing size and one of the inputs is a zero vector and the
9574 // the zero vector has only one use, we could use a VPERM2X128 to save the
9575 // instruction bytes needed to explicitly generate the zero vector.
9577 // Blends are faster and handle all the non-lane-crossing cases.
9578 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9582 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9583 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9585 // If either input operand is a zero vector, use VPERM2X128 because its mask
9586 // allows us to replace the zero input with an implicit zero.
9587 if (!IsV1Zero && !IsV2Zero) {
9588 // Check for patterns which can be matched with a single insert of a 128-bit
9590 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9591 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9592 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9593 VT.getVectorNumElements() / 2);
9594 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9595 DAG.getIntPtrConstant(0, DL));
9596 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9597 OnlyUsesV1 ? V1 : V2,
9598 DAG.getIntPtrConstant(0, DL));
9599 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9603 // Otherwise form a 128-bit permutation. After accounting for undefs,
9604 // convert the 64-bit shuffle mask selection values into 128-bit
9605 // selection bits by dividing the indexes by 2 and shifting into positions
9606 // defined by a vperm2*128 instruction's immediate control byte.
9608 // The immediate permute control byte looks like this:
9609 // [1:0] - select 128 bits from sources for low half of destination
9611 // [3] - zero low half of destination
9612 // [5:4] - select 128 bits from sources for high half of destination
9614 // [7] - zero high half of destination
9616 int MaskLO = Mask[0];
9617 if (MaskLO == SM_SentinelUndef)
9618 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9620 int MaskHI = Mask[2];
9621 if (MaskHI == SM_SentinelUndef)
9622 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9624 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9626 // If either input is a zero vector, replace it with an undef input.
9627 // Shuffle mask values < 4 are selecting elements of V1.
9628 // Shuffle mask values >= 4 are selecting elements of V2.
9629 // Adjust each half of the permute mask by clearing the half that was
9630 // selecting the zero vector and setting the zero mask bit.
9632 V1 = DAG.getUNDEF(VT);
9634 PermMask = (PermMask & 0xf0) | 0x08;
9636 PermMask = (PermMask & 0x0f) | 0x80;
9639 V2 = DAG.getUNDEF(VT);
9641 PermMask = (PermMask & 0xf0) | 0x08;
9643 PermMask = (PermMask & 0x0f) | 0x80;
9646 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9647 DAG.getConstant(PermMask, DL, MVT::i8));
9650 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9651 /// shuffling each lane.
9653 /// This will only succeed when the result of fixing the 128-bit lanes results
9654 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9655 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9656 /// the lane crosses early and then use simpler shuffles within each lane.
9658 /// FIXME: It might be worthwhile at some point to support this without
9659 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9660 /// in x86 only floating point has interesting non-repeating shuffles, and even
9661 /// those are still *marginally* more expensive.
9662 static SDValue lowerVectorShuffleByMerging128BitLanes(
9663 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9664 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9665 assert(!isSingleInputShuffleMask(Mask) &&
9666 "This is only useful with multiple inputs.");
9668 int Size = Mask.size();
9669 int LaneSize = 128 / VT.getScalarSizeInBits();
9670 int NumLanes = Size / LaneSize;
9671 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9673 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9674 // check whether the in-128-bit lane shuffles share a repeating pattern.
9675 SmallVector<int, 4> Lanes;
9676 Lanes.resize(NumLanes, -1);
9677 SmallVector<int, 4> InLaneMask;
9678 InLaneMask.resize(LaneSize, -1);
9679 for (int i = 0; i < Size; ++i) {
9683 int j = i / LaneSize;
9686 // First entry we've seen for this lane.
9687 Lanes[j] = Mask[i] / LaneSize;
9688 } else if (Lanes[j] != Mask[i] / LaneSize) {
9689 // This doesn't match the lane selected previously!
9693 // Check that within each lane we have a consistent shuffle mask.
9694 int k = i % LaneSize;
9695 if (InLaneMask[k] < 0) {
9696 InLaneMask[k] = Mask[i] % LaneSize;
9697 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9698 // This doesn't fit a repeating in-lane mask.
9703 // First shuffle the lanes into place.
9704 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9705 VT.getSizeInBits() / 64);
9706 SmallVector<int, 8> LaneMask;
9707 LaneMask.resize(NumLanes * 2, -1);
9708 for (int i = 0; i < NumLanes; ++i)
9709 if (Lanes[i] >= 0) {
9710 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9711 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9714 V1 = DAG.getBitcast(LaneVT, V1);
9715 V2 = DAG.getBitcast(LaneVT, V2);
9716 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9718 // Cast it back to the type we actually want.
9719 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9721 // Now do a simple shuffle that isn't lane crossing.
9722 SmallVector<int, 8> NewMask;
9723 NewMask.resize(Size, -1);
9724 for (int i = 0; i < Size; ++i)
9726 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9727 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9728 "Must not introduce lane crosses at this point!");
9730 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9733 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9736 /// This returns true if the elements from a particular input are already in the
9737 /// slot required by the given mask and require no permutation.
9738 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9739 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9740 int Size = Mask.size();
9741 for (int i = 0; i < Size; ++i)
9742 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9748 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9749 ArrayRef<int> Mask, SDValue V1,
9750 SDValue V2, SelectionDAG &DAG) {
9752 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9753 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9754 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9755 int NumElts = VT.getVectorNumElements();
9756 bool ShufpdMask = true;
9757 bool CommutableMask = true;
9758 unsigned Immediate = 0;
9759 for (int i = 0; i < NumElts; ++i) {
9762 int Val = (i & 6) + NumElts * (i & 1);
9763 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9764 if (Mask[i] < Val || Mask[i] > Val + 1)
9766 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9767 CommutableMask = false;
9768 Immediate |= (Mask[i] % 2) << i;
9771 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9772 DAG.getConstant(Immediate, DL, MVT::i8));
9774 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9775 DAG.getConstant(Immediate, DL, MVT::i8));
9779 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9781 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9782 /// isn't available.
9783 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9784 const X86Subtarget *Subtarget,
9785 SelectionDAG &DAG) {
9787 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9788 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9789 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9790 ArrayRef<int> Mask = SVOp->getMask();
9791 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9793 SmallVector<int, 4> WidenedMask;
9794 if (canWidenShuffleElements(Mask, WidenedMask))
9795 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9798 if (isSingleInputShuffleMask(Mask)) {
9799 // Check for being able to broadcast a single element.
9800 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9801 Mask, Subtarget, DAG))
9804 // Use low duplicate instructions for masks that match their pattern.
9805 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9806 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9808 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9809 // Non-half-crossing single input shuffles can be lowerid with an
9810 // interleaved permutation.
9811 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9812 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9813 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9814 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9817 // With AVX2 we have direct support for this permutation.
9818 if (Subtarget->hasAVX2())
9819 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9820 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9822 // Otherwise, fall back.
9823 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9827 // X86 has dedicated unpack instructions that can handle specific blend
9828 // operations: UNPCKH and UNPCKL.
9829 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9830 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9831 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9832 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9833 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9834 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9835 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9836 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9838 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9842 // Check if the blend happens to exactly fit that of SHUFPD.
9844 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9847 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9848 // shuffle. However, if we have AVX2 and either inputs are already in place,
9849 // we will be able to shuffle even across lanes the other input in a single
9850 // instruction so skip this pattern.
9851 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9852 isShuffleMaskInputInPlace(1, Mask))))
9853 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9854 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9857 // If we have AVX2 then we always want to lower with a blend because an v4 we
9858 // can fully permute the elements.
9859 if (Subtarget->hasAVX2())
9860 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9863 // Otherwise fall back on generic lowering.
9864 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9867 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9869 /// This routine is only called when we have AVX2 and thus a reasonable
9870 /// instruction set for v4i64 shuffling..
9871 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9872 const X86Subtarget *Subtarget,
9873 SelectionDAG &DAG) {
9875 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9876 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9877 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9878 ArrayRef<int> Mask = SVOp->getMask();
9879 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9880 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9882 SmallVector<int, 4> WidenedMask;
9883 if (canWidenShuffleElements(Mask, WidenedMask))
9884 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9887 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9891 // Check for being able to broadcast a single element.
9892 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9893 Mask, Subtarget, DAG))
9896 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9897 // use lower latency instructions that will operate on both 128-bit lanes.
9898 SmallVector<int, 2> RepeatedMask;
9899 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9900 if (isSingleInputShuffleMask(Mask)) {
9901 int PSHUFDMask[] = {-1, -1, -1, -1};
9902 for (int i = 0; i < 2; ++i)
9903 if (RepeatedMask[i] >= 0) {
9904 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9905 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9907 return DAG.getBitcast(
9909 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9910 DAG.getBitcast(MVT::v8i32, V1),
9911 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9915 // AVX2 provides a direct instruction for permuting a single input across
9917 if (isSingleInputShuffleMask(Mask))
9918 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9919 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9921 // Try to use shift instructions.
9923 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9926 // Use dedicated unpack instructions for masks that match their pattern.
9927 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9928 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9929 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9930 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9931 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9932 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9933 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9934 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9936 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9937 // shuffle. However, if we have AVX2 and either inputs are already in place,
9938 // we will be able to shuffle even across lanes the other input in a single
9939 // instruction so skip this pattern.
9940 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9941 isShuffleMaskInputInPlace(1, Mask))))
9942 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9943 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9946 // Otherwise fall back on generic blend lowering.
9947 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9951 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9953 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9954 /// isn't available.
9955 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9956 const X86Subtarget *Subtarget,
9957 SelectionDAG &DAG) {
9959 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9960 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9961 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9962 ArrayRef<int> Mask = SVOp->getMask();
9963 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9965 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9969 // Check for being able to broadcast a single element.
9970 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9971 Mask, Subtarget, DAG))
9974 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9975 // options to efficiently lower the shuffle.
9976 SmallVector<int, 4> RepeatedMask;
9977 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9978 assert(RepeatedMask.size() == 4 &&
9979 "Repeated masks must be half the mask width!");
9981 // Use even/odd duplicate instructions for masks that match their pattern.
9982 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9983 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9984 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9985 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9987 if (isSingleInputShuffleMask(Mask))
9988 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9989 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9991 // Use dedicated unpack instructions for masks that match their pattern.
9992 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9993 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9994 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9995 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9996 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9997 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9998 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9999 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10001 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10002 // have already handled any direct blends. We also need to squash the
10003 // repeated mask into a simulated v4f32 mask.
10004 for (int i = 0; i < 4; ++i)
10005 if (RepeatedMask[i] >= 8)
10006 RepeatedMask[i] -= 4;
10007 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10010 // If we have a single input shuffle with different shuffle patterns in the
10011 // two 128-bit lanes use the variable mask to VPERMILPS.
10012 if (isSingleInputShuffleMask(Mask)) {
10013 SDValue VPermMask[8];
10014 for (int i = 0; i < 8; ++i)
10015 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10016 : DAG.getConstant(Mask[i], DL, MVT::i32);
10017 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10018 return DAG.getNode(
10019 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10020 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10022 if (Subtarget->hasAVX2())
10023 return DAG.getNode(
10024 X86ISD::VPERMV, DL, MVT::v8f32,
10025 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10026 MVT::v8i32, VPermMask)),
10029 // Otherwise, fall back.
10030 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10034 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10036 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10037 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10040 // If we have AVX2 then we always want to lower with a blend because at v8 we
10041 // can fully permute the elements.
10042 if (Subtarget->hasAVX2())
10043 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10046 // Otherwise fall back on generic lowering.
10047 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10050 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10052 /// This routine is only called when we have AVX2 and thus a reasonable
10053 /// instruction set for v8i32 shuffling..
10054 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10055 const X86Subtarget *Subtarget,
10056 SelectionDAG &DAG) {
10058 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10059 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10060 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10061 ArrayRef<int> Mask = SVOp->getMask();
10062 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10063 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10065 // Whenever we can lower this as a zext, that instruction is strictly faster
10066 // than any alternative. It also allows us to fold memory operands into the
10067 // shuffle in many cases.
10068 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10069 Mask, Subtarget, DAG))
10072 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10076 // Check for being able to broadcast a single element.
10077 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10078 Mask, Subtarget, DAG))
10081 // If the shuffle mask is repeated in each 128-bit lane we can use more
10082 // efficient instructions that mirror the shuffles across the two 128-bit
10084 SmallVector<int, 4> RepeatedMask;
10085 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10086 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10087 if (isSingleInputShuffleMask(Mask))
10088 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10089 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10091 // Use dedicated unpack instructions for masks that match their pattern.
10092 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10093 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10094 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10095 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10096 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10097 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10098 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10099 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10102 // Try to use shift instructions.
10103 if (SDValue Shift =
10104 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10107 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10108 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10111 // If the shuffle patterns aren't repeated but it is a single input, directly
10112 // generate a cross-lane VPERMD instruction.
10113 if (isSingleInputShuffleMask(Mask)) {
10114 SDValue VPermMask[8];
10115 for (int i = 0; i < 8; ++i)
10116 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10117 : DAG.getConstant(Mask[i], DL, MVT::i32);
10118 return DAG.getNode(
10119 X86ISD::VPERMV, DL, MVT::v8i32,
10120 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10123 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10125 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10126 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10129 // Otherwise fall back on generic blend lowering.
10130 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10134 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10136 /// This routine is only called when we have AVX2 and thus a reasonable
10137 /// instruction set for v16i16 shuffling..
10138 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10139 const X86Subtarget *Subtarget,
10140 SelectionDAG &DAG) {
10142 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10143 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10144 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10145 ArrayRef<int> Mask = SVOp->getMask();
10146 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10147 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10149 // Whenever we can lower this as a zext, that instruction is strictly faster
10150 // than any alternative. It also allows us to fold memory operands into the
10151 // shuffle in many cases.
10152 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10153 Mask, Subtarget, DAG))
10156 // Check for being able to broadcast a single element.
10157 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10158 Mask, Subtarget, DAG))
10161 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10165 // Use dedicated unpack instructions for masks that match their pattern.
10166 if (isShuffleEquivalent(V1, V2, Mask,
10167 {// First 128-bit lane:
10168 0, 16, 1, 17, 2, 18, 3, 19,
10169 // Second 128-bit lane:
10170 8, 24, 9, 25, 10, 26, 11, 27}))
10171 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10172 if (isShuffleEquivalent(V1, V2, Mask,
10173 {// First 128-bit lane:
10174 4, 20, 5, 21, 6, 22, 7, 23,
10175 // Second 128-bit lane:
10176 12, 28, 13, 29, 14, 30, 15, 31}))
10177 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10179 // Try to use shift instructions.
10180 if (SDValue Shift =
10181 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10184 // Try to use byte rotation instructions.
10185 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10186 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10189 if (isSingleInputShuffleMask(Mask)) {
10190 // There are no generalized cross-lane shuffle operations available on i16
10192 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10193 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10196 SmallVector<int, 8> RepeatedMask;
10197 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10198 // As this is a single-input shuffle, the repeated mask should be
10199 // a strictly valid v8i16 mask that we can pass through to the v8i16
10200 // lowering to handle even the v16 case.
10201 return lowerV8I16GeneralSingleInputVectorShuffle(
10202 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10205 SDValue PSHUFBMask[32];
10206 for (int i = 0; i < 16; ++i) {
10207 if (Mask[i] == -1) {
10208 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10212 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10213 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10214 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10215 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10217 return DAG.getBitcast(MVT::v16i16,
10218 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10219 DAG.getBitcast(MVT::v32i8, V1),
10220 DAG.getNode(ISD::BUILD_VECTOR, DL,
10221 MVT::v32i8, PSHUFBMask)));
10224 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10226 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10227 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10230 // Otherwise fall back on generic lowering.
10231 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10234 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10236 /// This routine is only called when we have AVX2 and thus a reasonable
10237 /// instruction set for v32i8 shuffling..
10238 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10239 const X86Subtarget *Subtarget,
10240 SelectionDAG &DAG) {
10242 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10243 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10244 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10245 ArrayRef<int> Mask = SVOp->getMask();
10246 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10247 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10249 // Whenever we can lower this as a zext, that instruction is strictly faster
10250 // than any alternative. It also allows us to fold memory operands into the
10251 // shuffle in many cases.
10252 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10253 Mask, Subtarget, DAG))
10256 // Check for being able to broadcast a single element.
10257 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10258 Mask, Subtarget, DAG))
10261 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10265 // Use dedicated unpack instructions for masks that match their pattern.
10266 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10268 if (isShuffleEquivalent(
10270 {// First 128-bit lane:
10271 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10272 // Second 128-bit lane:
10273 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10274 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10275 if (isShuffleEquivalent(
10277 {// First 128-bit lane:
10278 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10279 // Second 128-bit lane:
10280 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10281 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10283 // Try to use shift instructions.
10284 if (SDValue Shift =
10285 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10288 // Try to use byte rotation instructions.
10289 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10290 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10293 if (isSingleInputShuffleMask(Mask)) {
10294 // There are no generalized cross-lane shuffle operations available on i8
10296 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10297 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10300 SDValue PSHUFBMask[32];
10301 for (int i = 0; i < 32; ++i)
10304 ? DAG.getUNDEF(MVT::i8)
10305 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10308 return DAG.getNode(
10309 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10310 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10313 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10315 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10316 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10319 // Otherwise fall back on generic lowering.
10320 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10323 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10325 /// This routine either breaks down the specific type of a 256-bit x86 vector
10326 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10327 /// together based on the available instructions.
10328 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10329 MVT VT, const X86Subtarget *Subtarget,
10330 SelectionDAG &DAG) {
10332 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10333 ArrayRef<int> Mask = SVOp->getMask();
10335 // If we have a single input to the zero element, insert that into V1 if we
10336 // can do so cheaply.
10337 int NumElts = VT.getVectorNumElements();
10338 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10339 return M >= NumElts;
10342 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10343 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10344 DL, VT, V1, V2, Mask, Subtarget, DAG))
10347 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10348 // check for those subtargets here and avoid much of the subtarget querying in
10349 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10350 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10351 // floating point types there eventually, just immediately cast everything to
10352 // a float and operate entirely in that domain.
10353 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10354 int ElementBits = VT.getScalarSizeInBits();
10355 if (ElementBits < 32)
10356 // No floating point type available, decompose into 128-bit vectors.
10357 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10359 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10360 VT.getVectorNumElements());
10361 V1 = DAG.getBitcast(FpVT, V1);
10362 V2 = DAG.getBitcast(FpVT, V2);
10363 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10366 switch (VT.SimpleTy) {
10368 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10370 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10372 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10374 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10376 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10378 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10381 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10385 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10386 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10387 const X86Subtarget *Subtarget,
10388 SelectionDAG &DAG) {
10390 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10391 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10392 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10393 ArrayRef<int> Mask = SVOp->getMask();
10394 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10396 // X86 has dedicated unpack instructions that can handle specific blend
10397 // operations: UNPCKH and UNPCKL.
10398 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10399 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10400 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10401 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10403 // FIXME: Implement direct support for this type!
10404 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10407 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10408 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10409 const X86Subtarget *Subtarget,
10410 SelectionDAG &DAG) {
10412 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10413 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10414 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10415 ArrayRef<int> Mask = SVOp->getMask();
10416 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10418 // Use dedicated unpack instructions for masks that match their pattern.
10419 if (isShuffleEquivalent(V1, V2, Mask,
10420 {// First 128-bit lane.
10421 0, 16, 1, 17, 4, 20, 5, 21,
10422 // Second 128-bit lane.
10423 8, 24, 9, 25, 12, 28, 13, 29}))
10424 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10425 if (isShuffleEquivalent(V1, V2, Mask,
10426 {// First 128-bit lane.
10427 2, 18, 3, 19, 6, 22, 7, 23,
10428 // Second 128-bit lane.
10429 10, 26, 11, 27, 14, 30, 15, 31}))
10430 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10432 // FIXME: Implement direct support for this type!
10433 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10436 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10437 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10438 const X86Subtarget *Subtarget,
10439 SelectionDAG &DAG) {
10441 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10442 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10443 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10444 ArrayRef<int> Mask = SVOp->getMask();
10445 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10447 // X86 has dedicated unpack instructions that can handle specific blend
10448 // operations: UNPCKH and UNPCKL.
10449 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10450 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10451 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10452 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10454 // FIXME: Implement direct support for this type!
10455 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10458 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10459 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10460 const X86Subtarget *Subtarget,
10461 SelectionDAG &DAG) {
10463 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10464 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10465 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10466 ArrayRef<int> Mask = SVOp->getMask();
10467 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10469 // Use dedicated unpack instructions for masks that match their pattern.
10470 if (isShuffleEquivalent(V1, V2, Mask,
10471 {// First 128-bit lane.
10472 0, 16, 1, 17, 4, 20, 5, 21,
10473 // Second 128-bit lane.
10474 8, 24, 9, 25, 12, 28, 13, 29}))
10475 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10476 if (isShuffleEquivalent(V1, V2, Mask,
10477 {// First 128-bit lane.
10478 2, 18, 3, 19, 6, 22, 7, 23,
10479 // Second 128-bit lane.
10480 10, 26, 11, 27, 14, 30, 15, 31}))
10481 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10483 // FIXME: Implement direct support for this type!
10484 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10487 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10488 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10489 const X86Subtarget *Subtarget,
10490 SelectionDAG &DAG) {
10492 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10493 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10494 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10495 ArrayRef<int> Mask = SVOp->getMask();
10496 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10497 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10499 // FIXME: Implement direct support for this type!
10500 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10503 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10504 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10505 const X86Subtarget *Subtarget,
10506 SelectionDAG &DAG) {
10508 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10509 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10510 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10511 ArrayRef<int> Mask = SVOp->getMask();
10512 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10513 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10515 // FIXME: Implement direct support for this type!
10516 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10519 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10521 /// This routine either breaks down the specific type of a 512-bit x86 vector
10522 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10523 /// together based on the available instructions.
10524 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10525 MVT VT, const X86Subtarget *Subtarget,
10526 SelectionDAG &DAG) {
10528 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10529 ArrayRef<int> Mask = SVOp->getMask();
10530 assert(Subtarget->hasAVX512() &&
10531 "Cannot lower 512-bit vectors w/ basic ISA!");
10533 // Check for being able to broadcast a single element.
10534 if (SDValue Broadcast =
10535 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10538 // Dispatch to each element type for lowering. If we don't have supprot for
10539 // specific element type shuffles at 512 bits, immediately split them and
10540 // lower them. Each lowering routine of a given type is allowed to assume that
10541 // the requisite ISA extensions for that element type are available.
10542 switch (VT.SimpleTy) {
10544 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10546 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10548 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10550 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10552 if (Subtarget->hasBWI())
10553 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10556 if (Subtarget->hasBWI())
10557 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10561 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10564 // Otherwise fall back on splitting.
10565 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10568 /// \brief Top-level lowering for x86 vector shuffles.
10570 /// This handles decomposition, canonicalization, and lowering of all x86
10571 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10572 /// above in helper routines. The canonicalization attempts to widen shuffles
10573 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10574 /// s.t. only one of the two inputs needs to be tested, etc.
10575 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10576 SelectionDAG &DAG) {
10577 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10578 ArrayRef<int> Mask = SVOp->getMask();
10579 SDValue V1 = Op.getOperand(0);
10580 SDValue V2 = Op.getOperand(1);
10581 MVT VT = Op.getSimpleValueType();
10582 int NumElements = VT.getVectorNumElements();
10585 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10587 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10588 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10589 if (V1IsUndef && V2IsUndef)
10590 return DAG.getUNDEF(VT);
10592 // When we create a shuffle node we put the UNDEF node to second operand,
10593 // but in some cases the first operand may be transformed to UNDEF.
10594 // In this case we should just commute the node.
10596 return DAG.getCommutedVectorShuffle(*SVOp);
10598 // Check for non-undef masks pointing at an undef vector and make the masks
10599 // undef as well. This makes it easier to match the shuffle based solely on
10603 if (M >= NumElements) {
10604 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10605 for (int &M : NewMask)
10606 if (M >= NumElements)
10608 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10611 // We actually see shuffles that are entirely re-arrangements of a set of
10612 // zero inputs. This mostly happens while decomposing complex shuffles into
10613 // simple ones. Directly lower these as a buildvector of zeros.
10614 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10615 if (Zeroable.all())
10616 return getZeroVector(VT, Subtarget, DAG, dl);
10618 // Try to collapse shuffles into using a vector type with fewer elements but
10619 // wider element types. We cap this to not form integers or floating point
10620 // elements wider than 64 bits, but it might be interesting to form i128
10621 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10622 SmallVector<int, 16> WidenedMask;
10623 if (VT.getScalarSizeInBits() < 64 &&
10624 canWidenShuffleElements(Mask, WidenedMask)) {
10625 MVT NewEltVT = VT.isFloatingPoint()
10626 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10627 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10628 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10629 // Make sure that the new vector type is legal. For example, v2f64 isn't
10631 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10632 V1 = DAG.getBitcast(NewVT, V1);
10633 V2 = DAG.getBitcast(NewVT, V2);
10634 return DAG.getBitcast(
10635 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10639 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10640 for (int M : SVOp->getMask())
10642 ++NumUndefElements;
10643 else if (M < NumElements)
10648 // Commute the shuffle as needed such that more elements come from V1 than
10649 // V2. This allows us to match the shuffle pattern strictly on how many
10650 // elements come from V1 without handling the symmetric cases.
10651 if (NumV2Elements > NumV1Elements)
10652 return DAG.getCommutedVectorShuffle(*SVOp);
10654 // When the number of V1 and V2 elements are the same, try to minimize the
10655 // number of uses of V2 in the low half of the vector. When that is tied,
10656 // ensure that the sum of indices for V1 is equal to or lower than the sum
10657 // indices for V2. When those are equal, try to ensure that the number of odd
10658 // indices for V1 is lower than the number of odd indices for V2.
10659 if (NumV1Elements == NumV2Elements) {
10660 int LowV1Elements = 0, LowV2Elements = 0;
10661 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10662 if (M >= NumElements)
10666 if (LowV2Elements > LowV1Elements) {
10667 return DAG.getCommutedVectorShuffle(*SVOp);
10668 } else if (LowV2Elements == LowV1Elements) {
10669 int SumV1Indices = 0, SumV2Indices = 0;
10670 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10671 if (SVOp->getMask()[i] >= NumElements)
10673 else if (SVOp->getMask()[i] >= 0)
10675 if (SumV2Indices < SumV1Indices) {
10676 return DAG.getCommutedVectorShuffle(*SVOp);
10677 } else if (SumV2Indices == SumV1Indices) {
10678 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10679 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10680 if (SVOp->getMask()[i] >= NumElements)
10681 NumV2OddIndices += i % 2;
10682 else if (SVOp->getMask()[i] >= 0)
10683 NumV1OddIndices += i % 2;
10684 if (NumV2OddIndices < NumV1OddIndices)
10685 return DAG.getCommutedVectorShuffle(*SVOp);
10690 // For each vector width, delegate to a specialized lowering routine.
10691 if (VT.getSizeInBits() == 128)
10692 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10694 if (VT.getSizeInBits() == 256)
10695 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10697 // Force AVX-512 vectors to be scalarized for now.
10698 // FIXME: Implement AVX-512 support!
10699 if (VT.getSizeInBits() == 512)
10700 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10702 llvm_unreachable("Unimplemented!");
10705 // This function assumes its argument is a BUILD_VECTOR of constants or
10706 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10708 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10709 unsigned &MaskValue) {
10711 unsigned NumElems = BuildVector->getNumOperands();
10712 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10713 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10714 unsigned NumElemsInLane = NumElems / NumLanes;
10716 // Blend for v16i16 should be symetric for the both lanes.
10717 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10718 SDValue EltCond = BuildVector->getOperand(i);
10719 SDValue SndLaneEltCond =
10720 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10722 int Lane1Cond = -1, Lane2Cond = -1;
10723 if (isa<ConstantSDNode>(EltCond))
10724 Lane1Cond = !isZero(EltCond);
10725 if (isa<ConstantSDNode>(SndLaneEltCond))
10726 Lane2Cond = !isZero(SndLaneEltCond);
10728 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10729 // Lane1Cond != 0, means we want the first argument.
10730 // Lane1Cond == 0, means we want the second argument.
10731 // The encoding of this argument is 0 for the first argument, 1
10732 // for the second. Therefore, invert the condition.
10733 MaskValue |= !Lane1Cond << i;
10734 else if (Lane1Cond < 0)
10735 MaskValue |= !Lane2Cond << i;
10742 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10743 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10744 const X86Subtarget *Subtarget,
10745 SelectionDAG &DAG) {
10746 SDValue Cond = Op.getOperand(0);
10747 SDValue LHS = Op.getOperand(1);
10748 SDValue RHS = Op.getOperand(2);
10750 MVT VT = Op.getSimpleValueType();
10752 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10754 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10756 // Only non-legal VSELECTs reach this lowering, convert those into generic
10757 // shuffles and re-use the shuffle lowering path for blends.
10758 SmallVector<int, 32> Mask;
10759 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10760 SDValue CondElt = CondBV->getOperand(i);
10762 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10764 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10767 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10768 // A vselect where all conditions and data are constants can be optimized into
10769 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10770 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10771 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10772 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10775 // Try to lower this to a blend-style vector shuffle. This can handle all
10776 // constant condition cases.
10777 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10780 // Variable blends are only legal from SSE4.1 onward.
10781 if (!Subtarget->hasSSE41())
10784 // Only some types will be legal on some subtargets. If we can emit a legal
10785 // VSELECT-matching blend, return Op, and but if we need to expand, return
10787 switch (Op.getSimpleValueType().SimpleTy) {
10789 // Most of the vector types have blends past SSE4.1.
10793 // The byte blends for AVX vectors were introduced only in AVX2.
10794 if (Subtarget->hasAVX2())
10801 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10802 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10805 // FIXME: We should custom lower this by fixing the condition and using i8
10811 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10812 MVT VT = Op.getSimpleValueType();
10815 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10818 if (VT.getSizeInBits() == 8) {
10819 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10820 Op.getOperand(0), Op.getOperand(1));
10821 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10822 DAG.getValueType(VT));
10823 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10826 if (VT.getSizeInBits() == 16) {
10827 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10828 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10830 return DAG.getNode(
10831 ISD::TRUNCATE, dl, MVT::i16,
10832 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10833 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10834 Op.getOperand(1)));
10835 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10836 Op.getOperand(0), Op.getOperand(1));
10837 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10838 DAG.getValueType(VT));
10839 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10842 if (VT == MVT::f32) {
10843 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10844 // the result back to FR32 register. It's only worth matching if the
10845 // result has a single use which is a store or a bitcast to i32. And in
10846 // the case of a store, it's not worth it if the index is a constant 0,
10847 // because a MOVSSmr can be used instead, which is smaller and faster.
10848 if (!Op.hasOneUse())
10850 SDNode *User = *Op.getNode()->use_begin();
10851 if ((User->getOpcode() != ISD::STORE ||
10852 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10853 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10854 (User->getOpcode() != ISD::BITCAST ||
10855 User->getValueType(0) != MVT::i32))
10857 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10858 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10860 return DAG.getBitcast(MVT::f32, Extract);
10863 if (VT == MVT::i32 || VT == MVT::i64) {
10864 // ExtractPS/pextrq works with constant index.
10865 if (isa<ConstantSDNode>(Op.getOperand(1)))
10871 /// Extract one bit from mask vector, like v16i1 or v8i1.
10872 /// AVX-512 feature.
10874 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10875 SDValue Vec = Op.getOperand(0);
10877 MVT VecVT = Vec.getSimpleValueType();
10878 SDValue Idx = Op.getOperand(1);
10879 MVT EltVT = Op.getSimpleValueType();
10881 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10882 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10883 "Unexpected vector type in ExtractBitFromMaskVector");
10885 // variable index can't be handled in mask registers,
10886 // extend vector to VR512
10887 if (!isa<ConstantSDNode>(Idx)) {
10888 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10889 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10890 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10891 ExtVT.getVectorElementType(), Ext, Idx);
10892 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10895 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10896 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10897 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10898 rc = getRegClassFor(MVT::v16i1);
10899 unsigned MaxSift = rc->getSize()*8 - 1;
10900 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10901 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10902 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10903 DAG.getConstant(MaxSift, dl, MVT::i8));
10904 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10905 DAG.getIntPtrConstant(0, dl));
10909 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10910 SelectionDAG &DAG) const {
10912 SDValue Vec = Op.getOperand(0);
10913 MVT VecVT = Vec.getSimpleValueType();
10914 SDValue Idx = Op.getOperand(1);
10916 if (Op.getSimpleValueType() == MVT::i1)
10917 return ExtractBitFromMaskVector(Op, DAG);
10919 if (!isa<ConstantSDNode>(Idx)) {
10920 if (VecVT.is512BitVector() ||
10921 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10922 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10925 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10926 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10927 MaskEltVT.getSizeInBits());
10929 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10930 auto PtrVT = getPointerTy(DAG.getDataLayout());
10931 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10932 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10933 DAG.getConstant(0, dl, PtrVT));
10934 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10935 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10936 DAG.getConstant(0, dl, PtrVT));
10941 // If this is a 256-bit vector result, first extract the 128-bit vector and
10942 // then extract the element from the 128-bit vector.
10943 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10945 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10946 // Get the 128-bit vector.
10947 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10948 MVT EltVT = VecVT.getVectorElementType();
10950 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10952 //if (IdxVal >= NumElems/2)
10953 // IdxVal -= NumElems/2;
10954 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10955 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10956 DAG.getConstant(IdxVal, dl, MVT::i32));
10959 assert(VecVT.is128BitVector() && "Unexpected vector length");
10961 if (Subtarget->hasSSE41())
10962 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10965 MVT VT = Op.getSimpleValueType();
10966 // TODO: handle v16i8.
10967 if (VT.getSizeInBits() == 16) {
10968 SDValue Vec = Op.getOperand(0);
10969 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10971 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10972 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10973 DAG.getBitcast(MVT::v4i32, Vec),
10974 Op.getOperand(1)));
10975 // Transform it so it match pextrw which produces a 32-bit result.
10976 MVT EltVT = MVT::i32;
10977 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10978 Op.getOperand(0), Op.getOperand(1));
10979 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10980 DAG.getValueType(VT));
10981 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10984 if (VT.getSizeInBits() == 32) {
10985 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10989 // SHUFPS the element to the lowest double word, then movss.
10990 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10991 MVT VVT = Op.getOperand(0).getSimpleValueType();
10992 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10993 DAG.getUNDEF(VVT), Mask);
10994 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10995 DAG.getIntPtrConstant(0, dl));
10998 if (VT.getSizeInBits() == 64) {
10999 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11000 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11001 // to match extract_elt for f64.
11002 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11006 // UNPCKHPD the element to the lowest double word, then movsd.
11007 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11008 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11009 int Mask[2] = { 1, -1 };
11010 MVT VVT = Op.getOperand(0).getSimpleValueType();
11011 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11012 DAG.getUNDEF(VVT), Mask);
11013 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11014 DAG.getIntPtrConstant(0, dl));
11020 /// Insert one bit to mask vector, like v16i1 or v8i1.
11021 /// AVX-512 feature.
11023 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11025 SDValue Vec = Op.getOperand(0);
11026 SDValue Elt = Op.getOperand(1);
11027 SDValue Idx = Op.getOperand(2);
11028 MVT VecVT = Vec.getSimpleValueType();
11030 if (!isa<ConstantSDNode>(Idx)) {
11031 // Non constant index. Extend source and destination,
11032 // insert element and then truncate the result.
11033 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11034 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11035 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11036 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11037 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11038 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11041 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11042 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11044 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11045 DAG.getConstant(IdxVal, dl, MVT::i8));
11046 if (Vec.getOpcode() == ISD::UNDEF)
11048 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11051 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11052 SelectionDAG &DAG) const {
11053 MVT VT = Op.getSimpleValueType();
11054 MVT EltVT = VT.getVectorElementType();
11056 if (EltVT == MVT::i1)
11057 return InsertBitToMaskVector(Op, DAG);
11060 SDValue N0 = Op.getOperand(0);
11061 SDValue N1 = Op.getOperand(1);
11062 SDValue N2 = Op.getOperand(2);
11063 if (!isa<ConstantSDNode>(N2))
11065 auto *N2C = cast<ConstantSDNode>(N2);
11066 unsigned IdxVal = N2C->getZExtValue();
11068 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11069 // into that, and then insert the subvector back into the result.
11070 if (VT.is256BitVector() || VT.is512BitVector()) {
11071 // With a 256-bit vector, we can insert into the zero element efficiently
11072 // using a blend if we have AVX or AVX2 and the right data type.
11073 if (VT.is256BitVector() && IdxVal == 0) {
11074 // TODO: It is worthwhile to cast integer to floating point and back
11075 // and incur a domain crossing penalty if that's what we'll end up
11076 // doing anyway after extracting to a 128-bit vector.
11077 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11078 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11079 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11080 N2 = DAG.getIntPtrConstant(1, dl);
11081 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11085 // Get the desired 128-bit vector chunk.
11086 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11088 // Insert the element into the desired chunk.
11089 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11090 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11092 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11093 DAG.getConstant(IdxIn128, dl, MVT::i32));
11095 // Insert the changed part back into the bigger vector
11096 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11098 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11100 if (Subtarget->hasSSE41()) {
11101 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11103 if (VT == MVT::v8i16) {
11104 Opc = X86ISD::PINSRW;
11106 assert(VT == MVT::v16i8);
11107 Opc = X86ISD::PINSRB;
11110 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11112 if (N1.getValueType() != MVT::i32)
11113 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11114 if (N2.getValueType() != MVT::i32)
11115 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11116 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11119 if (EltVT == MVT::f32) {
11120 // Bits [7:6] of the constant are the source select. This will always be
11121 // zero here. The DAG Combiner may combine an extract_elt index into
11122 // these bits. For example (insert (extract, 3), 2) could be matched by
11123 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11124 // Bits [5:4] of the constant are the destination select. This is the
11125 // value of the incoming immediate.
11126 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11127 // combine either bitwise AND or insert of float 0.0 to set these bits.
11129 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11130 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11131 // If this is an insertion of 32-bits into the low 32-bits of
11132 // a vector, we prefer to generate a blend with immediate rather
11133 // than an insertps. Blends are simpler operations in hardware and so
11134 // will always have equal or better performance than insertps.
11135 // But if optimizing for size and there's a load folding opportunity,
11136 // generate insertps because blendps does not have a 32-bit memory
11138 N2 = DAG.getIntPtrConstant(1, dl);
11139 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11140 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11142 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11143 // Create this as a scalar to vector..
11144 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11145 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11148 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11149 // PINSR* works with constant index.
11154 if (EltVT == MVT::i8)
11157 if (EltVT.getSizeInBits() == 16) {
11158 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11159 // as its second argument.
11160 if (N1.getValueType() != MVT::i32)
11161 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11162 if (N2.getValueType() != MVT::i32)
11163 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11164 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11169 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11171 MVT OpVT = Op.getSimpleValueType();
11173 // If this is a 256-bit vector result, first insert into a 128-bit
11174 // vector and then insert into the 256-bit vector.
11175 if (!OpVT.is128BitVector()) {
11176 // Insert into a 128-bit vector.
11177 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11178 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11179 OpVT.getVectorNumElements() / SizeFactor);
11181 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11183 // Insert the 128-bit vector.
11184 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11187 if (OpVT == MVT::v1i64 &&
11188 Op.getOperand(0).getValueType() == MVT::i64)
11189 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11191 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11192 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11193 return DAG.getBitcast(
11194 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11197 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11198 // a simple subregister reference or explicit instructions to grab
11199 // upper bits of a vector.
11200 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11201 SelectionDAG &DAG) {
11203 SDValue In = Op.getOperand(0);
11204 SDValue Idx = Op.getOperand(1);
11205 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11206 MVT ResVT = Op.getSimpleValueType();
11207 MVT InVT = In.getSimpleValueType();
11209 if (Subtarget->hasFp256()) {
11210 if (ResVT.is128BitVector() &&
11211 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11212 isa<ConstantSDNode>(Idx)) {
11213 return Extract128BitVector(In, IdxVal, DAG, dl);
11215 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11216 isa<ConstantSDNode>(Idx)) {
11217 return Extract256BitVector(In, IdxVal, DAG, dl);
11223 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11224 // simple superregister reference or explicit instructions to insert
11225 // the upper bits of a vector.
11226 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11227 SelectionDAG &DAG) {
11228 if (!Subtarget->hasAVX())
11232 SDValue Vec = Op.getOperand(0);
11233 SDValue SubVec = Op.getOperand(1);
11234 SDValue Idx = Op.getOperand(2);
11236 if (!isa<ConstantSDNode>(Idx))
11239 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11240 MVT OpVT = Op.getSimpleValueType();
11241 MVT SubVecVT = SubVec.getSimpleValueType();
11243 // Fold two 16-byte subvector loads into one 32-byte load:
11244 // (insert_subvector (insert_subvector undef, (load addr), 0),
11245 // (load addr + 16), Elts/2)
11247 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11248 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11249 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11250 !Subtarget->isUnalignedMem32Slow()) {
11251 SDValue SubVec2 = Vec.getOperand(1);
11252 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11253 if (Idx2->getZExtValue() == 0) {
11254 SDValue Ops[] = { SubVec2, SubVec };
11255 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11261 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11262 SubVecVT.is128BitVector())
11263 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11265 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11266 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11268 if (OpVT.getVectorElementType() == MVT::i1) {
11269 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11271 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11272 SDValue Undef = DAG.getUNDEF(OpVT);
11273 unsigned NumElems = OpVT.getVectorNumElements();
11274 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11276 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11277 // Zero upper bits of the Vec
11278 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11279 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11281 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11283 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11284 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11287 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11289 // Zero upper bits of the Vec2
11290 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11291 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11292 // Zero lower bits of the Vec
11293 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11294 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11295 // Merge them together
11296 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11302 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11303 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11304 // one of the above mentioned nodes. It has to be wrapped because otherwise
11305 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11306 // be used to form addressing mode. These wrapped nodes will be selected
11309 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11310 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11312 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11313 // global base reg.
11314 unsigned char OpFlag = 0;
11315 unsigned WrapperKind = X86ISD::Wrapper;
11316 CodeModel::Model M = DAG.getTarget().getCodeModel();
11318 if (Subtarget->isPICStyleRIPRel() &&
11319 (M == CodeModel::Small || M == CodeModel::Kernel))
11320 WrapperKind = X86ISD::WrapperRIP;
11321 else if (Subtarget->isPICStyleGOT())
11322 OpFlag = X86II::MO_GOTOFF;
11323 else if (Subtarget->isPICStyleStubPIC())
11324 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11326 auto PtrVT = getPointerTy(DAG.getDataLayout());
11327 SDValue Result = DAG.getTargetConstantPool(
11328 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11330 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11331 // With PIC, the address is actually $g + Offset.
11334 DAG.getNode(ISD::ADD, DL, PtrVT,
11335 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11341 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11342 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11344 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11345 // global base reg.
11346 unsigned char OpFlag = 0;
11347 unsigned WrapperKind = X86ISD::Wrapper;
11348 CodeModel::Model M = DAG.getTarget().getCodeModel();
11350 if (Subtarget->isPICStyleRIPRel() &&
11351 (M == CodeModel::Small || M == CodeModel::Kernel))
11352 WrapperKind = X86ISD::WrapperRIP;
11353 else if (Subtarget->isPICStyleGOT())
11354 OpFlag = X86II::MO_GOTOFF;
11355 else if (Subtarget->isPICStyleStubPIC())
11356 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11358 auto PtrVT = getPointerTy(DAG.getDataLayout());
11359 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11361 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11363 // With PIC, the address is actually $g + Offset.
11366 DAG.getNode(ISD::ADD, DL, PtrVT,
11367 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11373 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11374 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11376 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11377 // global base reg.
11378 unsigned char OpFlag = 0;
11379 unsigned WrapperKind = X86ISD::Wrapper;
11380 CodeModel::Model M = DAG.getTarget().getCodeModel();
11382 if (Subtarget->isPICStyleRIPRel() &&
11383 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11384 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11385 OpFlag = X86II::MO_GOTPCREL;
11386 WrapperKind = X86ISD::WrapperRIP;
11387 } else if (Subtarget->isPICStyleGOT()) {
11388 OpFlag = X86II::MO_GOT;
11389 } else if (Subtarget->isPICStyleStubPIC()) {
11390 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11391 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11392 OpFlag = X86II::MO_DARWIN_NONLAZY;
11395 auto PtrVT = getPointerTy(DAG.getDataLayout());
11396 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11399 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11401 // With PIC, the address is actually $g + Offset.
11402 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11403 !Subtarget->is64Bit()) {
11405 DAG.getNode(ISD::ADD, DL, PtrVT,
11406 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11409 // For symbols that require a load from a stub to get the address, emit the
11411 if (isGlobalStubReference(OpFlag))
11412 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11413 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11414 false, false, false, 0);
11420 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11421 // Create the TargetBlockAddressAddress node.
11422 unsigned char OpFlags =
11423 Subtarget->ClassifyBlockAddressReference();
11424 CodeModel::Model M = DAG.getTarget().getCodeModel();
11425 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11426 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11428 auto PtrVT = getPointerTy(DAG.getDataLayout());
11429 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11431 if (Subtarget->isPICStyleRIPRel() &&
11432 (M == CodeModel::Small || M == CodeModel::Kernel))
11433 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11435 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11437 // With PIC, the address is actually $g + Offset.
11438 if (isGlobalRelativeToPICBase(OpFlags)) {
11439 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11440 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11447 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11448 int64_t Offset, SelectionDAG &DAG) const {
11449 // Create the TargetGlobalAddress node, folding in the constant
11450 // offset if it is legal.
11451 unsigned char OpFlags =
11452 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11453 CodeModel::Model M = DAG.getTarget().getCodeModel();
11454 auto PtrVT = getPointerTy(DAG.getDataLayout());
11456 if (OpFlags == X86II::MO_NO_FLAG &&
11457 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11458 // A direct static reference to a global.
11459 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11462 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11465 if (Subtarget->isPICStyleRIPRel() &&
11466 (M == CodeModel::Small || M == CodeModel::Kernel))
11467 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11469 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11471 // With PIC, the address is actually $g + Offset.
11472 if (isGlobalRelativeToPICBase(OpFlags)) {
11473 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11474 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11477 // For globals that require a load from a stub to get the address, emit the
11479 if (isGlobalStubReference(OpFlags))
11480 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11481 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11482 false, false, false, 0);
11484 // If there was a non-zero offset that we didn't fold, create an explicit
11485 // addition for it.
11487 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11488 DAG.getConstant(Offset, dl, PtrVT));
11494 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11495 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11496 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11497 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11501 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11502 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11503 unsigned char OperandFlags, bool LocalDynamic = false) {
11504 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11505 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11507 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11508 GA->getValueType(0),
11512 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11516 SDValue Ops[] = { Chain, TGA, *InFlag };
11517 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11519 SDValue Ops[] = { Chain, TGA };
11520 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11523 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11524 MFI->setAdjustsStack(true);
11525 MFI->setHasCalls(true);
11527 SDValue Flag = Chain.getValue(1);
11528 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11531 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11533 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11536 SDLoc dl(GA); // ? function entry point might be better
11537 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11538 DAG.getNode(X86ISD::GlobalBaseReg,
11539 SDLoc(), PtrVT), InFlag);
11540 InFlag = Chain.getValue(1);
11542 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11545 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11547 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11549 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11550 X86::RAX, X86II::MO_TLSGD);
11553 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11559 // Get the start address of the TLS block for this module.
11560 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11561 .getInfo<X86MachineFunctionInfo>();
11562 MFI->incNumLocalDynamicTLSAccesses();
11566 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11567 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11570 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11571 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11572 InFlag = Chain.getValue(1);
11573 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11574 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11577 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11581 unsigned char OperandFlags = X86II::MO_DTPOFF;
11582 unsigned WrapperKind = X86ISD::Wrapper;
11583 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11584 GA->getValueType(0),
11585 GA->getOffset(), OperandFlags);
11586 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11588 // Add x@dtpoff with the base.
11589 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11592 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11593 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11594 const EVT PtrVT, TLSModel::Model model,
11595 bool is64Bit, bool isPIC) {
11598 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11599 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11600 is64Bit ? 257 : 256));
11602 SDValue ThreadPointer =
11603 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11604 MachinePointerInfo(Ptr), false, false, false, 0);
11606 unsigned char OperandFlags = 0;
11607 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11609 unsigned WrapperKind = X86ISD::Wrapper;
11610 if (model == TLSModel::LocalExec) {
11611 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11612 } else if (model == TLSModel::InitialExec) {
11614 OperandFlags = X86II::MO_GOTTPOFF;
11615 WrapperKind = X86ISD::WrapperRIP;
11617 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11620 llvm_unreachable("Unexpected model");
11623 // emit "addl x@ntpoff,%eax" (local exec)
11624 // or "addl x@indntpoff,%eax" (initial exec)
11625 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11627 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11628 GA->getOffset(), OperandFlags);
11629 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11631 if (model == TLSModel::InitialExec) {
11632 if (isPIC && !is64Bit) {
11633 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11634 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11638 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11639 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11640 false, false, false, 0);
11643 // The address of the thread local variable is the add of the thread
11644 // pointer with the offset of the variable.
11645 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11649 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11651 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11652 const GlobalValue *GV = GA->getGlobal();
11653 auto PtrVT = getPointerTy(DAG.getDataLayout());
11655 if (Subtarget->isTargetELF()) {
11656 if (DAG.getTarget().Options.EmulatedTLS)
11657 return LowerToTLSEmulatedModel(GA, DAG);
11658 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11660 case TLSModel::GeneralDynamic:
11661 if (Subtarget->is64Bit())
11662 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11663 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11664 case TLSModel::LocalDynamic:
11665 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11666 Subtarget->is64Bit());
11667 case TLSModel::InitialExec:
11668 case TLSModel::LocalExec:
11669 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11670 DAG.getTarget().getRelocationModel() ==
11673 llvm_unreachable("Unknown TLS model.");
11676 if (Subtarget->isTargetDarwin()) {
11677 // Darwin only has one model of TLS. Lower to that.
11678 unsigned char OpFlag = 0;
11679 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11680 X86ISD::WrapperRIP : X86ISD::Wrapper;
11682 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11683 // global base reg.
11684 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11685 !Subtarget->is64Bit();
11687 OpFlag = X86II::MO_TLVP_PIC_BASE;
11689 OpFlag = X86II::MO_TLVP;
11691 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11692 GA->getValueType(0),
11693 GA->getOffset(), OpFlag);
11694 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11696 // With PIC32, the address is actually $g + Offset.
11698 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11699 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11702 // Lowering the machine isd will make sure everything is in the right
11704 SDValue Chain = DAG.getEntryNode();
11705 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11706 SDValue Args[] = { Chain, Offset };
11707 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11709 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11710 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11711 MFI->setAdjustsStack(true);
11713 // And our return value (tls address) is in the standard call return value
11715 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11716 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11719 if (Subtarget->isTargetKnownWindowsMSVC() ||
11720 Subtarget->isTargetWindowsGNU()) {
11721 // Just use the implicit TLS architecture
11722 // Need to generate someting similar to:
11723 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11725 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11726 // mov rcx, qword [rdx+rcx*8]
11727 // mov eax, .tls$:tlsvar
11728 // [rax+rcx] contains the address
11729 // Windows 64bit: gs:0x58
11730 // Windows 32bit: fs:__tls_array
11733 SDValue Chain = DAG.getEntryNode();
11735 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11736 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11737 // use its literal value of 0x2C.
11738 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11739 ? Type::getInt8PtrTy(*DAG.getContext(),
11741 : Type::getInt32PtrTy(*DAG.getContext(),
11744 SDValue TlsArray = Subtarget->is64Bit()
11745 ? DAG.getIntPtrConstant(0x58, dl)
11746 : (Subtarget->isTargetWindowsGNU()
11747 ? DAG.getIntPtrConstant(0x2C, dl)
11748 : DAG.getExternalSymbol("_tls_array", PtrVT));
11750 SDValue ThreadPointer =
11751 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11755 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11756 res = ThreadPointer;
11758 // Load the _tls_index variable
11759 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11760 if (Subtarget->is64Bit())
11761 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11762 MachinePointerInfo(), MVT::i32, false, false,
11765 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11768 auto &DL = DAG.getDataLayout();
11770 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11771 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11773 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11776 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11779 // Get the offset of start of .tls section
11780 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11781 GA->getValueType(0),
11782 GA->getOffset(), X86II::MO_SECREL);
11783 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11785 // The address of the thread local variable is the add of the thread
11786 // pointer with the offset of the variable.
11787 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11790 llvm_unreachable("TLS not implemented for this target.");
11793 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11794 /// and take a 2 x i32 value to shift plus a shift amount.
11795 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11796 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11797 MVT VT = Op.getSimpleValueType();
11798 unsigned VTBits = VT.getSizeInBits();
11800 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11801 SDValue ShOpLo = Op.getOperand(0);
11802 SDValue ShOpHi = Op.getOperand(1);
11803 SDValue ShAmt = Op.getOperand(2);
11804 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11805 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11807 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11808 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11809 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11810 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11811 : DAG.getConstant(0, dl, VT);
11813 SDValue Tmp2, Tmp3;
11814 if (Op.getOpcode() == ISD::SHL_PARTS) {
11815 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11816 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11818 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11819 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11822 // If the shift amount is larger or equal than the width of a part we can't
11823 // rely on the results of shld/shrd. Insert a test and select the appropriate
11824 // values for large shift amounts.
11825 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11826 DAG.getConstant(VTBits, dl, MVT::i8));
11827 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11828 AndNode, DAG.getConstant(0, dl, MVT::i8));
11831 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11832 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11833 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11835 if (Op.getOpcode() == ISD::SHL_PARTS) {
11836 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11837 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11839 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11840 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11843 SDValue Ops[2] = { Lo, Hi };
11844 return DAG.getMergeValues(Ops, dl);
11847 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11848 SelectionDAG &DAG) const {
11849 SDValue Src = Op.getOperand(0);
11850 MVT SrcVT = Src.getSimpleValueType();
11851 MVT VT = Op.getSimpleValueType();
11854 if (SrcVT.isVector()) {
11855 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11856 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11857 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11858 DAG.getUNDEF(SrcVT)));
11860 if (SrcVT.getVectorElementType() == MVT::i1) {
11861 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11862 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11863 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11868 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11869 "Unknown SINT_TO_FP to lower!");
11871 // These are really Legal; return the operand so the caller accepts it as
11873 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11875 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11876 Subtarget->is64Bit()) {
11880 unsigned Size = SrcVT.getSizeInBits()/8;
11881 MachineFunction &MF = DAG.getMachineFunction();
11882 auto PtrVT = getPointerTy(MF.getDataLayout());
11883 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11884 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11885 SDValue Chain = DAG.getStore(
11886 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11887 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11889 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11892 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11894 SelectionDAG &DAG) const {
11898 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11900 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11902 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11904 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11906 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11907 MachineMemOperand *MMO;
11909 int SSFI = FI->getIndex();
11910 MMO = DAG.getMachineFunction().getMachineMemOperand(
11911 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11912 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11914 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11915 StackSlot = StackSlot.getOperand(1);
11917 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11918 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11920 Tys, Ops, SrcVT, MMO);
11923 Chain = Result.getValue(1);
11924 SDValue InFlag = Result.getValue(2);
11926 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11927 // shouldn't be necessary except that RFP cannot be live across
11928 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11929 MachineFunction &MF = DAG.getMachineFunction();
11930 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11931 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11932 auto PtrVT = getPointerTy(MF.getDataLayout());
11933 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11934 Tys = DAG.getVTList(MVT::Other);
11936 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11938 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11939 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11940 MachineMemOperand::MOStore, SSFISize, SSFISize);
11942 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11943 Ops, Op.getValueType(), MMO);
11944 Result = DAG.getLoad(
11945 Op.getValueType(), DL, Chain, StackSlot,
11946 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11947 false, false, false, 0);
11953 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11954 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11955 SelectionDAG &DAG) const {
11956 // This algorithm is not obvious. Here it is what we're trying to output:
11959 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11960 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11962 haddpd %xmm0, %xmm0
11964 pshufd $0x4e, %xmm0, %xmm1
11970 LLVMContext *Context = DAG.getContext();
11972 // Build some magic constants.
11973 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11974 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11975 auto PtrVT = getPointerTy(DAG.getDataLayout());
11976 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11978 SmallVector<Constant*,2> CV1;
11980 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11981 APInt(64, 0x4330000000000000ULL))));
11983 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11984 APInt(64, 0x4530000000000000ULL))));
11985 Constant *C1 = ConstantVector::get(CV1);
11986 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11988 // Load the 64-bit value into an XMM register.
11989 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11992 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11993 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
11994 false, false, false, 16);
11996 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11999 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12000 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12001 false, false, false, 16);
12002 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12003 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12006 if (Subtarget->hasSSE3()) {
12007 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12008 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12010 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12011 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12013 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12014 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12017 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12018 DAG.getIntPtrConstant(0, dl));
12021 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12022 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12023 SelectionDAG &DAG) const {
12025 // FP constant to bias correct the final result.
12026 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12029 // Load the 32-bit value into an XMM register.
12030 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12033 // Zero out the upper parts of the register.
12034 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12036 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12037 DAG.getBitcast(MVT::v2f64, Load),
12038 DAG.getIntPtrConstant(0, dl));
12040 // Or the load with the bias.
12041 SDValue Or = DAG.getNode(
12042 ISD::OR, dl, MVT::v2i64,
12043 DAG.getBitcast(MVT::v2i64,
12044 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12045 DAG.getBitcast(MVT::v2i64,
12046 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12048 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12049 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12051 // Subtract the bias.
12052 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12054 // Handle final rounding.
12055 EVT DestVT = Op.getValueType();
12057 if (DestVT.bitsLT(MVT::f64))
12058 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12059 DAG.getIntPtrConstant(0, dl));
12060 if (DestVT.bitsGT(MVT::f64))
12061 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12063 // Handle final rounding.
12067 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12068 const X86Subtarget &Subtarget) {
12069 // The algorithm is the following:
12070 // #ifdef __SSE4_1__
12071 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12072 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12073 // (uint4) 0x53000000, 0xaa);
12075 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12076 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12078 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12079 // return (float4) lo + fhi;
12082 SDValue V = Op->getOperand(0);
12083 EVT VecIntVT = V.getValueType();
12084 bool Is128 = VecIntVT == MVT::v4i32;
12085 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12086 // If we convert to something else than the supported type, e.g., to v4f64,
12088 if (VecFloatVT != Op->getValueType(0))
12091 unsigned NumElts = VecIntVT.getVectorNumElements();
12092 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12093 "Unsupported custom type");
12094 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12096 // In the #idef/#else code, we have in common:
12097 // - The vector of constants:
12103 // Create the splat vector for 0x4b000000.
12104 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12105 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12106 CstLow, CstLow, CstLow, CstLow};
12107 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12108 makeArrayRef(&CstLowArray[0], NumElts));
12109 // Create the splat vector for 0x53000000.
12110 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12111 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12112 CstHigh, CstHigh, CstHigh, CstHigh};
12113 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12114 makeArrayRef(&CstHighArray[0], NumElts));
12116 // Create the right shift.
12117 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12118 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12119 CstShift, CstShift, CstShift, CstShift};
12120 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12121 makeArrayRef(&CstShiftArray[0], NumElts));
12122 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12125 if (Subtarget.hasSSE41()) {
12126 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12127 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12128 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12129 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12130 // Low will be bitcasted right away, so do not bother bitcasting back to its
12132 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12133 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12134 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12135 // (uint4) 0x53000000, 0xaa);
12136 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12137 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12138 // High will be bitcasted right away, so do not bother bitcasting back to
12139 // its original type.
12140 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12141 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12143 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12144 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12145 CstMask, CstMask, CstMask);
12146 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12147 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12148 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12150 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12151 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12154 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12155 SDValue CstFAdd = DAG.getConstantFP(
12156 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12157 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12158 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12159 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12160 makeArrayRef(&CstFAddArray[0], NumElts));
12162 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12163 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12165 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12166 // return (float4) lo + fhi;
12167 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12168 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12171 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12172 SelectionDAG &DAG) const {
12173 SDValue N0 = Op.getOperand(0);
12174 MVT SVT = N0.getSimpleValueType();
12177 switch (SVT.SimpleTy) {
12179 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12184 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12185 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12186 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12190 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12193 if (Subtarget->hasAVX512())
12194 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12195 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12197 llvm_unreachable(nullptr);
12200 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12201 SelectionDAG &DAG) const {
12202 SDValue N0 = Op.getOperand(0);
12204 auto PtrVT = getPointerTy(DAG.getDataLayout());
12206 if (Op.getValueType().isVector())
12207 return lowerUINT_TO_FP_vec(Op, DAG);
12209 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12210 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12211 // the optimization here.
12212 if (DAG.SignBitIsZero(N0))
12213 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12215 MVT SrcVT = N0.getSimpleValueType();
12216 MVT DstVT = Op.getSimpleValueType();
12217 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12218 return LowerUINT_TO_FP_i64(Op, DAG);
12219 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12220 return LowerUINT_TO_FP_i32(Op, DAG);
12221 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12224 // Make a 64-bit buffer, and use it to build an FILD.
12225 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12226 if (SrcVT == MVT::i32) {
12227 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12228 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12229 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12230 StackSlot, MachinePointerInfo(),
12232 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12233 OffsetSlot, MachinePointerInfo(),
12235 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12239 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12240 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12241 StackSlot, MachinePointerInfo(),
12243 // For i64 source, we need to add the appropriate power of 2 if the input
12244 // was negative. This is the same as the optimization in
12245 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12246 // we must be careful to do the computation in x87 extended precision, not
12247 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12248 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12249 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12250 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12251 MachineMemOperand::MOLoad, 8, 8);
12253 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12254 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12255 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12258 APInt FF(32, 0x5F800000ULL);
12260 // Check whether the sign bit is set.
12261 SDValue SignSet = DAG.getSetCC(
12262 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12263 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12265 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12266 SDValue FudgePtr = DAG.getConstantPool(
12267 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12269 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12270 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12271 SDValue Four = DAG.getIntPtrConstant(4, dl);
12272 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12274 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12276 // Load the value out, extending it from f32 to f80.
12277 // FIXME: Avoid the extend by constructing the right constant pool?
12278 SDValue Fudge = DAG.getExtLoad(
12279 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12280 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12281 false, false, false, 4);
12282 // Extend everything to 80 bits to force it to be done on x87.
12283 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12284 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12285 DAG.getIntPtrConstant(0, dl));
12288 std::pair<SDValue,SDValue>
12289 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12290 bool IsSigned, bool IsReplace) const {
12293 EVT DstTy = Op.getValueType();
12294 auto PtrVT = getPointerTy(DAG.getDataLayout());
12296 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12297 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12301 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12302 DstTy.getSimpleVT() >= MVT::i16 &&
12303 "Unknown FP_TO_INT to lower!");
12305 // These are really Legal.
12306 if (DstTy == MVT::i32 &&
12307 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12308 return std::make_pair(SDValue(), SDValue());
12309 if (Subtarget->is64Bit() &&
12310 DstTy == MVT::i64 &&
12311 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12312 return std::make_pair(SDValue(), SDValue());
12314 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12315 // stack slot, or into the FTOL runtime function.
12316 MachineFunction &MF = DAG.getMachineFunction();
12317 unsigned MemSize = DstTy.getSizeInBits()/8;
12318 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12319 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12322 if (!IsSigned && isIntegerTypeFTOL(DstTy))
12323 Opc = X86ISD::WIN_FTOL;
12325 switch (DstTy.getSimpleVT().SimpleTy) {
12326 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12327 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12328 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12329 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12332 SDValue Chain = DAG.getEntryNode();
12333 SDValue Value = Op.getOperand(0);
12334 EVT TheVT = Op.getOperand(0).getValueType();
12335 // FIXME This causes a redundant load/store if the SSE-class value is already
12336 // in memory, such as if it is on the callstack.
12337 if (isScalarFPTypeInSSEReg(TheVT)) {
12338 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12339 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12340 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12342 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12344 Chain, StackSlot, DAG.getValueType(TheVT)
12347 MachineMemOperand *MMO =
12348 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12349 MachineMemOperand::MOLoad, MemSize, MemSize);
12350 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12351 Chain = Value.getValue(1);
12352 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12353 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12356 MachineMemOperand *MMO =
12357 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12358 MachineMemOperand::MOStore, MemSize, MemSize);
12360 if (Opc != X86ISD::WIN_FTOL) {
12361 // Build the FP_TO_INT*_IN_MEM
12362 SDValue Ops[] = { Chain, Value, StackSlot };
12363 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12365 return std::make_pair(FIST, StackSlot);
12367 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12368 DAG.getVTList(MVT::Other, MVT::Glue),
12370 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12371 MVT::i32, ftol.getValue(1));
12372 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12373 MVT::i32, eax.getValue(2));
12374 SDValue Ops[] = { eax, edx };
12375 SDValue pair = IsReplace
12376 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12377 : DAG.getMergeValues(Ops, DL);
12378 return std::make_pair(pair, SDValue());
12382 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12383 const X86Subtarget *Subtarget) {
12384 MVT VT = Op->getSimpleValueType(0);
12385 SDValue In = Op->getOperand(0);
12386 MVT InVT = In.getSimpleValueType();
12389 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12390 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12392 // Optimize vectors in AVX mode:
12395 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12396 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12397 // Concat upper and lower parts.
12400 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12401 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12402 // Concat upper and lower parts.
12405 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12406 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12407 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12410 if (Subtarget->hasInt256())
12411 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12413 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12414 SDValue Undef = DAG.getUNDEF(InVT);
12415 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12416 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12417 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12419 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12420 VT.getVectorNumElements()/2);
12422 OpLo = DAG.getBitcast(HVT, OpLo);
12423 OpHi = DAG.getBitcast(HVT, OpHi);
12425 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12428 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12429 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12430 MVT VT = Op->getSimpleValueType(0);
12431 SDValue In = Op->getOperand(0);
12432 MVT InVT = In.getSimpleValueType();
12434 unsigned int NumElts = VT.getVectorNumElements();
12435 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12438 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12439 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12441 assert(InVT.getVectorElementType() == MVT::i1);
12442 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12444 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12446 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12448 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12449 if (VT.is512BitVector())
12451 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12454 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12455 SelectionDAG &DAG) {
12456 if (Subtarget->hasFp256())
12457 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12463 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12464 SelectionDAG &DAG) {
12466 MVT VT = Op.getSimpleValueType();
12467 SDValue In = Op.getOperand(0);
12468 MVT SVT = In.getSimpleValueType();
12470 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12471 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12473 if (Subtarget->hasFp256())
12474 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12477 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12478 VT.getVectorNumElements() != SVT.getVectorNumElements());
12482 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12484 MVT VT = Op.getSimpleValueType();
12485 SDValue In = Op.getOperand(0);
12486 MVT InVT = In.getSimpleValueType();
12488 if (VT == MVT::i1) {
12489 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12490 "Invalid scalar TRUNCATE operation");
12491 if (InVT.getSizeInBits() >= 32)
12493 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12494 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12496 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12497 "Invalid TRUNCATE operation");
12499 // move vector to mask - truncate solution for SKX
12500 if (VT.getVectorElementType() == MVT::i1) {
12501 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12502 Subtarget->hasBWI())
12503 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12504 if ((InVT.is256BitVector() || InVT.is128BitVector())
12505 && InVT.getScalarSizeInBits() <= 16 &&
12506 Subtarget->hasBWI() && Subtarget->hasVLX())
12507 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12508 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12509 Subtarget->hasDQI())
12510 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12511 if ((InVT.is256BitVector() || InVT.is128BitVector())
12512 && InVT.getScalarSizeInBits() >= 32 &&
12513 Subtarget->hasDQI() && Subtarget->hasVLX())
12514 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12517 if (VT.getVectorElementType() == MVT::i1) {
12518 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12519 unsigned NumElts = InVT.getVectorNumElements();
12520 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12521 if (InVT.getSizeInBits() < 512) {
12522 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12523 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12528 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12529 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12530 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12533 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12534 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12535 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12536 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12538 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12539 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12540 if (Subtarget->hasInt256()) {
12541 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12542 In = DAG.getBitcast(MVT::v8i32, In);
12543 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12545 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12546 DAG.getIntPtrConstant(0, DL));
12549 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12550 DAG.getIntPtrConstant(0, DL));
12551 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12552 DAG.getIntPtrConstant(2, DL));
12553 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12554 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12555 static const int ShufMask[] = {0, 2, 4, 6};
12556 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12559 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12560 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12561 if (Subtarget->hasInt256()) {
12562 In = DAG.getBitcast(MVT::v32i8, In);
12564 SmallVector<SDValue,32> pshufbMask;
12565 for (unsigned i = 0; i < 2; ++i) {
12566 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12567 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12568 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12569 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12570 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12571 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12572 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12573 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12574 for (unsigned j = 0; j < 8; ++j)
12575 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12577 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12578 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12579 In = DAG.getBitcast(MVT::v4i64, In);
12581 static const int ShufMask[] = {0, 2, -1, -1};
12582 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12584 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12585 DAG.getIntPtrConstant(0, DL));
12586 return DAG.getBitcast(VT, In);
12589 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12590 DAG.getIntPtrConstant(0, DL));
12592 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12593 DAG.getIntPtrConstant(4, DL));
12595 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12596 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12598 // The PSHUFB mask:
12599 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12600 -1, -1, -1, -1, -1, -1, -1, -1};
12602 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12603 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12604 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12606 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12607 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12609 // The MOVLHPS Mask:
12610 static const int ShufMask2[] = {0, 1, 4, 5};
12611 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12612 return DAG.getBitcast(MVT::v8i16, res);
12615 // Handle truncation of V256 to V128 using shuffles.
12616 if (!VT.is128BitVector() || !InVT.is256BitVector())
12619 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12621 unsigned NumElems = VT.getVectorNumElements();
12622 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12624 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12625 // Prepare truncation shuffle mask
12626 for (unsigned i = 0; i != NumElems; ++i)
12627 MaskVec[i] = i * 2;
12628 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12629 DAG.getUNDEF(NVT), &MaskVec[0]);
12630 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12631 DAG.getIntPtrConstant(0, DL));
12634 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12635 SelectionDAG &DAG) const {
12636 assert(!Op.getSimpleValueType().isVector());
12638 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12639 /*IsSigned=*/ true, /*IsReplace=*/ false);
12640 SDValue FIST = Vals.first, StackSlot = Vals.second;
12641 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12642 if (!FIST.getNode()) return Op;
12644 if (StackSlot.getNode())
12645 // Load the result.
12646 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12647 FIST, StackSlot, MachinePointerInfo(),
12648 false, false, false, 0);
12650 // The node is the result.
12654 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12655 SelectionDAG &DAG) const {
12656 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12657 /*IsSigned=*/ false, /*IsReplace=*/ false);
12658 SDValue FIST = Vals.first, StackSlot = Vals.second;
12659 assert(FIST.getNode() && "Unexpected failure");
12661 if (StackSlot.getNode())
12662 // Load the result.
12663 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12664 FIST, StackSlot, MachinePointerInfo(),
12665 false, false, false, 0);
12667 // The node is the result.
12671 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12673 MVT VT = Op.getSimpleValueType();
12674 SDValue In = Op.getOperand(0);
12675 MVT SVT = In.getSimpleValueType();
12677 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12679 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12680 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12681 In, DAG.getUNDEF(SVT)));
12684 /// The only differences between FABS and FNEG are the mask and the logic op.
12685 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12686 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12687 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12688 "Wrong opcode for lowering FABS or FNEG.");
12690 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12692 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12693 // into an FNABS. We'll lower the FABS after that if it is still in use.
12695 for (SDNode *User : Op->uses())
12696 if (User->getOpcode() == ISD::FNEG)
12700 MVT VT = Op.getSimpleValueType();
12702 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12703 // decide if we should generate a 16-byte constant mask when we only need 4 or
12704 // 8 bytes for the scalar case.
12710 if (VT.isVector()) {
12712 EltVT = VT.getVectorElementType();
12713 NumElts = VT.getVectorNumElements();
12715 // There are no scalar bitwise logical SSE/AVX instructions, so we
12716 // generate a 16-byte vector constant and logic op even for the scalar case.
12717 // Using a 16-byte mask allows folding the load of the mask with
12718 // the logic op, so it can save (~4 bytes) on code size.
12719 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12721 NumElts = (VT == MVT::f64) ? 2 : 4;
12724 unsigned EltBits = EltVT.getSizeInBits();
12725 LLVMContext *Context = DAG.getContext();
12726 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12728 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12729 Constant *C = ConstantInt::get(*Context, MaskElt);
12730 C = ConstantVector::getSplat(NumElts, C);
12731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12732 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12733 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12735 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12736 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12737 false, false, false, Alignment);
12739 SDValue Op0 = Op.getOperand(0);
12740 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12742 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12743 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12746 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12748 // For the scalar case extend to a 128-bit vector, perform the logic op,
12749 // and extract the scalar result back out.
12750 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12751 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12752 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12753 DAG.getIntPtrConstant(0, dl));
12756 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12758 LLVMContext *Context = DAG.getContext();
12759 SDValue Op0 = Op.getOperand(0);
12760 SDValue Op1 = Op.getOperand(1);
12762 MVT VT = Op.getSimpleValueType();
12763 MVT SrcVT = Op1.getSimpleValueType();
12765 // If second operand is smaller, extend it first.
12766 if (SrcVT.bitsLT(VT)) {
12767 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12770 // And if it is bigger, shrink it first.
12771 if (SrcVT.bitsGT(VT)) {
12772 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12776 // At this point the operands and the result should have the same
12777 // type, and that won't be f80 since that is not custom lowered.
12779 const fltSemantics &Sem =
12780 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12781 const unsigned SizeInBits = VT.getSizeInBits();
12783 SmallVector<Constant *, 4> CV(
12784 VT == MVT::f64 ? 2 : 4,
12785 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12787 // First, clear all bits but the sign bit from the second operand (sign).
12788 CV[0] = ConstantFP::get(*Context,
12789 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12790 Constant *C = ConstantVector::get(CV);
12791 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12792 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12794 // Perform all logic operations as 16-byte vectors because there are no
12795 // scalar FP logic instructions in SSE. This allows load folding of the
12796 // constants into the logic instructions.
12797 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12799 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12800 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12801 false, false, false, 16);
12802 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12803 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12805 // Next, clear the sign bit from the first operand (magnitude).
12806 // If it's a constant, we can clear it here.
12807 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12808 APFloat APF = Op0CN->getValueAPF();
12809 // If the magnitude is a positive zero, the sign bit alone is enough.
12810 if (APF.isPosZero())
12811 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12812 DAG.getIntPtrConstant(0, dl));
12814 CV[0] = ConstantFP::get(*Context, APF);
12816 CV[0] = ConstantFP::get(
12818 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12820 C = ConstantVector::get(CV);
12821 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12823 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12824 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12825 false, false, false, 16);
12826 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12827 if (!isa<ConstantFPSDNode>(Op0)) {
12828 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12829 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12831 // OR the magnitude value with the sign bit.
12832 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12833 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12834 DAG.getIntPtrConstant(0, dl));
12837 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12838 SDValue N0 = Op.getOperand(0);
12840 MVT VT = Op.getSimpleValueType();
12842 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12843 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12844 DAG.getConstant(1, dl, VT));
12845 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12848 // Check whether an OR'd tree is PTEST-able.
12849 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12850 SelectionDAG &DAG) {
12851 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12853 if (!Subtarget->hasSSE41())
12856 if (!Op->hasOneUse())
12859 SDNode *N = Op.getNode();
12862 SmallVector<SDValue, 8> Opnds;
12863 DenseMap<SDValue, unsigned> VecInMap;
12864 SmallVector<SDValue, 8> VecIns;
12865 EVT VT = MVT::Other;
12867 // Recognize a special case where a vector is casted into wide integer to
12869 Opnds.push_back(N->getOperand(0));
12870 Opnds.push_back(N->getOperand(1));
12872 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12873 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12874 // BFS traverse all OR'd operands.
12875 if (I->getOpcode() == ISD::OR) {
12876 Opnds.push_back(I->getOperand(0));
12877 Opnds.push_back(I->getOperand(1));
12878 // Re-evaluate the number of nodes to be traversed.
12879 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12883 // Quit if a non-EXTRACT_VECTOR_ELT
12884 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12887 // Quit if without a constant index.
12888 SDValue Idx = I->getOperand(1);
12889 if (!isa<ConstantSDNode>(Idx))
12892 SDValue ExtractedFromVec = I->getOperand(0);
12893 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12894 if (M == VecInMap.end()) {
12895 VT = ExtractedFromVec.getValueType();
12896 // Quit if not 128/256-bit vector.
12897 if (!VT.is128BitVector() && !VT.is256BitVector())
12899 // Quit if not the same type.
12900 if (VecInMap.begin() != VecInMap.end() &&
12901 VT != VecInMap.begin()->first.getValueType())
12903 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12904 VecIns.push_back(ExtractedFromVec);
12906 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12909 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12910 "Not extracted from 128-/256-bit vector.");
12912 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12914 for (DenseMap<SDValue, unsigned>::const_iterator
12915 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12916 // Quit if not all elements are used.
12917 if (I->second != FullMask)
12921 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12923 // Cast all vectors into TestVT for PTEST.
12924 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12925 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12927 // If more than one full vectors are evaluated, OR them first before PTEST.
12928 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12929 // Each iteration will OR 2 nodes and append the result until there is only
12930 // 1 node left, i.e. the final OR'd value of all vectors.
12931 SDValue LHS = VecIns[Slot];
12932 SDValue RHS = VecIns[Slot + 1];
12933 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12936 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12937 VecIns.back(), VecIns.back());
12940 /// \brief return true if \c Op has a use that doesn't just read flags.
12941 static bool hasNonFlagsUse(SDValue Op) {
12942 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12944 SDNode *User = *UI;
12945 unsigned UOpNo = UI.getOperandNo();
12946 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12947 // Look pass truncate.
12948 UOpNo = User->use_begin().getOperandNo();
12949 User = *User->use_begin();
12952 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12953 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12959 /// Emit nodes that will be selected as "test Op0,Op0", or something
12961 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12962 SelectionDAG &DAG) const {
12963 if (Op.getValueType() == MVT::i1) {
12964 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12965 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12966 DAG.getConstant(0, dl, MVT::i8));
12968 // CF and OF aren't always set the way we want. Determine which
12969 // of these we need.
12970 bool NeedCF = false;
12971 bool NeedOF = false;
12974 case X86::COND_A: case X86::COND_AE:
12975 case X86::COND_B: case X86::COND_BE:
12978 case X86::COND_G: case X86::COND_GE:
12979 case X86::COND_L: case X86::COND_LE:
12980 case X86::COND_O: case X86::COND_NO: {
12981 // Check if we really need to set the
12982 // Overflow flag. If NoSignedWrap is present
12983 // that is not actually needed.
12984 switch (Op->getOpcode()) {
12989 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12990 if (BinNode->Flags.hasNoSignedWrap())
13000 // See if we can use the EFLAGS value from the operand instead of
13001 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13002 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13003 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13004 // Emit a CMP with 0, which is the TEST pattern.
13005 //if (Op.getValueType() == MVT::i1)
13006 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13007 // DAG.getConstant(0, MVT::i1));
13008 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13009 DAG.getConstant(0, dl, Op.getValueType()));
13011 unsigned Opcode = 0;
13012 unsigned NumOperands = 0;
13014 // Truncate operations may prevent the merge of the SETCC instruction
13015 // and the arithmetic instruction before it. Attempt to truncate the operands
13016 // of the arithmetic instruction and use a reduced bit-width instruction.
13017 bool NeedTruncation = false;
13018 SDValue ArithOp = Op;
13019 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13020 SDValue Arith = Op->getOperand(0);
13021 // Both the trunc and the arithmetic op need to have one user each.
13022 if (Arith->hasOneUse())
13023 switch (Arith.getOpcode()) {
13030 NeedTruncation = true;
13036 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13037 // which may be the result of a CAST. We use the variable 'Op', which is the
13038 // non-casted variable when we check for possible users.
13039 switch (ArithOp.getOpcode()) {
13041 // Due to an isel shortcoming, be conservative if this add is likely to be
13042 // selected as part of a load-modify-store instruction. When the root node
13043 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13044 // uses of other nodes in the match, such as the ADD in this case. This
13045 // leads to the ADD being left around and reselected, with the result being
13046 // two adds in the output. Alas, even if none our users are stores, that
13047 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13048 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13049 // climbing the DAG back to the root, and it doesn't seem to be worth the
13051 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13052 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13053 if (UI->getOpcode() != ISD::CopyToReg &&
13054 UI->getOpcode() != ISD::SETCC &&
13055 UI->getOpcode() != ISD::STORE)
13058 if (ConstantSDNode *C =
13059 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13060 // An add of one will be selected as an INC.
13061 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13062 Opcode = X86ISD::INC;
13067 // An add of negative one (subtract of one) will be selected as a DEC.
13068 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13069 Opcode = X86ISD::DEC;
13075 // Otherwise use a regular EFLAGS-setting add.
13076 Opcode = X86ISD::ADD;
13081 // If we have a constant logical shift that's only used in a comparison
13082 // against zero turn it into an equivalent AND. This allows turning it into
13083 // a TEST instruction later.
13084 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13085 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13086 EVT VT = Op.getValueType();
13087 unsigned BitWidth = VT.getSizeInBits();
13088 unsigned ShAmt = Op->getConstantOperandVal(1);
13089 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13091 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13092 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13093 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13094 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13096 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13097 DAG.getConstant(Mask, dl, VT));
13098 DAG.ReplaceAllUsesWith(Op, New);
13104 // If the primary and result isn't used, don't bother using X86ISD::AND,
13105 // because a TEST instruction will be better.
13106 if (!hasNonFlagsUse(Op))
13112 // Due to the ISEL shortcoming noted above, be conservative if this op is
13113 // likely to be selected as part of a load-modify-store instruction.
13114 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13115 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13116 if (UI->getOpcode() == ISD::STORE)
13119 // Otherwise use a regular EFLAGS-setting instruction.
13120 switch (ArithOp.getOpcode()) {
13121 default: llvm_unreachable("unexpected operator!");
13122 case ISD::SUB: Opcode = X86ISD::SUB; break;
13123 case ISD::XOR: Opcode = X86ISD::XOR; break;
13124 case ISD::AND: Opcode = X86ISD::AND; break;
13126 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13127 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13128 if (EFLAGS.getNode())
13131 Opcode = X86ISD::OR;
13145 return SDValue(Op.getNode(), 1);
13151 // If we found that truncation is beneficial, perform the truncation and
13153 if (NeedTruncation) {
13154 EVT VT = Op.getValueType();
13155 SDValue WideVal = Op->getOperand(0);
13156 EVT WideVT = WideVal.getValueType();
13157 unsigned ConvertedOp = 0;
13158 // Use a target machine opcode to prevent further DAGCombine
13159 // optimizations that may separate the arithmetic operations
13160 // from the setcc node.
13161 switch (WideVal.getOpcode()) {
13163 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13164 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13165 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13166 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13167 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13171 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13172 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13173 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13174 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13175 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13181 // Emit a CMP with 0, which is the TEST pattern.
13182 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13183 DAG.getConstant(0, dl, Op.getValueType()));
13185 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13186 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13188 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13189 DAG.ReplaceAllUsesWith(Op, New);
13190 return SDValue(New.getNode(), 1);
13193 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13195 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13196 SDLoc dl, SelectionDAG &DAG) const {
13197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13198 if (C->getAPIntValue() == 0)
13199 return EmitTest(Op0, X86CC, dl, DAG);
13201 if (Op0.getValueType() == MVT::i1)
13202 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13205 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13206 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13207 // Do the comparison at i32 if it's smaller, besides the Atom case.
13208 // This avoids subregister aliasing issues. Keep the smaller reference
13209 // if we're optimizing for size, however, as that'll allow better folding
13210 // of memory operations.
13211 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13212 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13213 !Subtarget->isAtom()) {
13214 unsigned ExtendOp =
13215 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13216 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13217 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13219 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13220 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13221 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13223 return SDValue(Sub.getNode(), 1);
13225 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13228 /// Convert a comparison if required by the subtarget.
13229 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13230 SelectionDAG &DAG) const {
13231 // If the subtarget does not support the FUCOMI instruction, floating-point
13232 // comparisons have to be converted.
13233 if (Subtarget->hasCMov() ||
13234 Cmp.getOpcode() != X86ISD::CMP ||
13235 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13236 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13239 // The instruction selector will select an FUCOM instruction instead of
13240 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13241 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13242 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13244 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13245 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13246 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13247 DAG.getConstant(8, dl, MVT::i8));
13248 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13249 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13252 /// The minimum architected relative accuracy is 2^-12. We need one
13253 /// Newton-Raphson step to have a good float result (24 bits of precision).
13254 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13255 DAGCombinerInfo &DCI,
13256 unsigned &RefinementSteps,
13257 bool &UseOneConstNR) const {
13258 EVT VT = Op.getValueType();
13259 const char *RecipOp;
13261 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13262 // TODO: Add support for AVX512 (v16f32).
13263 // It is likely not profitable to do this for f64 because a double-precision
13264 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13265 // instructions: convert to single, rsqrtss, convert back to double, refine
13266 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13267 // along with FMA, this could be a throughput win.
13268 if (VT == MVT::f32 && Subtarget->hasSSE1())
13270 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13271 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13272 RecipOp = "vec-sqrtf";
13276 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13277 if (!Recips.isEnabled(RecipOp))
13280 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13281 UseOneConstNR = false;
13282 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13285 /// The minimum architected relative accuracy is 2^-12. We need one
13286 /// Newton-Raphson step to have a good float result (24 bits of precision).
13287 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13288 DAGCombinerInfo &DCI,
13289 unsigned &RefinementSteps) const {
13290 EVT VT = Op.getValueType();
13291 const char *RecipOp;
13293 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13294 // TODO: Add support for AVX512 (v16f32).
13295 // It is likely not profitable to do this for f64 because a double-precision
13296 // reciprocal estimate with refinement on x86 prior to FMA requires
13297 // 15 instructions: convert to single, rcpss, convert back to double, refine
13298 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13299 // along with FMA, this could be a throughput win.
13300 if (VT == MVT::f32 && Subtarget->hasSSE1())
13302 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13303 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13304 RecipOp = "vec-divf";
13308 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13309 if (!Recips.isEnabled(RecipOp))
13312 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13313 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13316 /// If we have at least two divisions that use the same divisor, convert to
13317 /// multplication by a reciprocal. This may need to be adjusted for a given
13318 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13319 /// This is because we still need one division to calculate the reciprocal and
13320 /// then we need two multiplies by that reciprocal as replacements for the
13321 /// original divisions.
13322 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13326 static bool isAllOnes(SDValue V) {
13327 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13328 return C && C->isAllOnesValue();
13331 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13332 /// if it's possible.
13333 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13334 SDLoc dl, SelectionDAG &DAG) const {
13335 SDValue Op0 = And.getOperand(0);
13336 SDValue Op1 = And.getOperand(1);
13337 if (Op0.getOpcode() == ISD::TRUNCATE)
13338 Op0 = Op0.getOperand(0);
13339 if (Op1.getOpcode() == ISD::TRUNCATE)
13340 Op1 = Op1.getOperand(0);
13343 if (Op1.getOpcode() == ISD::SHL)
13344 std::swap(Op0, Op1);
13345 if (Op0.getOpcode() == ISD::SHL) {
13346 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13347 if (And00C->getZExtValue() == 1) {
13348 // If we looked past a truncate, check that it's only truncating away
13350 unsigned BitWidth = Op0.getValueSizeInBits();
13351 unsigned AndBitWidth = And.getValueSizeInBits();
13352 if (BitWidth > AndBitWidth) {
13354 DAG.computeKnownBits(Op0, Zeros, Ones);
13355 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13359 RHS = Op0.getOperand(1);
13361 } else if (Op1.getOpcode() == ISD::Constant) {
13362 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13363 uint64_t AndRHSVal = AndRHS->getZExtValue();
13364 SDValue AndLHS = Op0;
13366 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13367 LHS = AndLHS.getOperand(0);
13368 RHS = AndLHS.getOperand(1);
13371 // Use BT if the immediate can't be encoded in a TEST instruction.
13372 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13374 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13378 if (LHS.getNode()) {
13379 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13380 // instruction. Since the shift amount is in-range-or-undefined, we know
13381 // that doing a bittest on the i32 value is ok. We extend to i32 because
13382 // the encoding for the i16 version is larger than the i32 version.
13383 // Also promote i16 to i32 for performance / code size reason.
13384 if (LHS.getValueType() == MVT::i8 ||
13385 LHS.getValueType() == MVT::i16)
13386 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13388 // If the operand types disagree, extend the shift amount to match. Since
13389 // BT ignores high bits (like shifts) we can use anyextend.
13390 if (LHS.getValueType() != RHS.getValueType())
13391 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13393 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13394 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13395 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13396 DAG.getConstant(Cond, dl, MVT::i8), BT);
13402 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13404 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13409 // SSE Condition code mapping:
13418 switch (SetCCOpcode) {
13419 default: llvm_unreachable("Unexpected SETCC condition");
13421 case ISD::SETEQ: SSECC = 0; break;
13423 case ISD::SETGT: Swap = true; // Fallthrough
13425 case ISD::SETOLT: SSECC = 1; break;
13427 case ISD::SETGE: Swap = true; // Fallthrough
13429 case ISD::SETOLE: SSECC = 2; break;
13430 case ISD::SETUO: SSECC = 3; break;
13432 case ISD::SETNE: SSECC = 4; break;
13433 case ISD::SETULE: Swap = true; // Fallthrough
13434 case ISD::SETUGE: SSECC = 5; break;
13435 case ISD::SETULT: Swap = true; // Fallthrough
13436 case ISD::SETUGT: SSECC = 6; break;
13437 case ISD::SETO: SSECC = 7; break;
13439 case ISD::SETONE: SSECC = 8; break;
13442 std::swap(Op0, Op1);
13447 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13448 // ones, and then concatenate the result back.
13449 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13450 MVT VT = Op.getSimpleValueType();
13452 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13453 "Unsupported value type for operation");
13455 unsigned NumElems = VT.getVectorNumElements();
13457 SDValue CC = Op.getOperand(2);
13459 // Extract the LHS vectors
13460 SDValue LHS = Op.getOperand(0);
13461 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13462 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13464 // Extract the RHS vectors
13465 SDValue RHS = Op.getOperand(1);
13466 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13467 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13469 // Issue the operation on the smaller types and concatenate the result back
13470 MVT EltVT = VT.getVectorElementType();
13471 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13472 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13473 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13474 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13477 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13478 SDValue Op0 = Op.getOperand(0);
13479 SDValue Op1 = Op.getOperand(1);
13480 SDValue CC = Op.getOperand(2);
13481 MVT VT = Op.getSimpleValueType();
13484 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13485 "Unexpected type for boolean compare operation");
13486 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13487 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13488 DAG.getConstant(-1, dl, VT));
13489 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13490 DAG.getConstant(-1, dl, VT));
13491 switch (SetCCOpcode) {
13492 default: llvm_unreachable("Unexpected SETCC condition");
13494 // (x == y) -> ~(x ^ y)
13495 return DAG.getNode(ISD::XOR, dl, VT,
13496 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13497 DAG.getConstant(-1, dl, VT));
13499 // (x != y) -> (x ^ y)
13500 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13503 // (x > y) -> (x & ~y)
13504 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13507 // (x < y) -> (~x & y)
13508 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13511 // (x <= y) -> (~x | y)
13512 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13515 // (x >=y) -> (x | ~y)
13516 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13520 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13521 const X86Subtarget *Subtarget) {
13522 SDValue Op0 = Op.getOperand(0);
13523 SDValue Op1 = Op.getOperand(1);
13524 SDValue CC = Op.getOperand(2);
13525 MVT VT = Op.getSimpleValueType();
13528 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13529 Op.getValueType().getScalarType() == MVT::i1 &&
13530 "Cannot set masked compare for this operation");
13532 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13534 bool Unsigned = false;
13537 switch (SetCCOpcode) {
13538 default: llvm_unreachable("Unexpected SETCC condition");
13539 case ISD::SETNE: SSECC = 4; break;
13540 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13541 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13542 case ISD::SETLT: Swap = true; //fall-through
13543 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13544 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13545 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13546 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13547 case ISD::SETULE: Unsigned = true; //fall-through
13548 case ISD::SETLE: SSECC = 2; break;
13552 std::swap(Op0, Op1);
13554 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13555 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13556 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13557 DAG.getConstant(SSECC, dl, MVT::i8));
13560 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13561 /// operand \p Op1. If non-trivial (for example because it's not constant)
13562 /// return an empty value.
13563 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13565 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13569 MVT VT = Op1.getSimpleValueType();
13570 MVT EVT = VT.getVectorElementType();
13571 unsigned n = VT.getVectorNumElements();
13572 SmallVector<SDValue, 8> ULTOp1;
13574 for (unsigned i = 0; i < n; ++i) {
13575 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13576 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13579 // Avoid underflow.
13580 APInt Val = Elt->getAPIntValue();
13584 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13587 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13590 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13591 SelectionDAG &DAG) {
13592 SDValue Op0 = Op.getOperand(0);
13593 SDValue Op1 = Op.getOperand(1);
13594 SDValue CC = Op.getOperand(2);
13595 MVT VT = Op.getSimpleValueType();
13596 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13597 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13602 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13603 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13606 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13607 unsigned Opc = X86ISD::CMPP;
13608 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13609 assert(VT.getVectorNumElements() <= 16);
13610 Opc = X86ISD::CMPM;
13612 // In the two special cases we can't handle, emit two comparisons.
13615 unsigned CombineOpc;
13616 if (SetCCOpcode == ISD::SETUEQ) {
13617 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13619 assert(SetCCOpcode == ISD::SETONE);
13620 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13623 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13624 DAG.getConstant(CC0, dl, MVT::i8));
13625 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13626 DAG.getConstant(CC1, dl, MVT::i8));
13627 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13629 // Handle all other FP comparisons here.
13630 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13631 DAG.getConstant(SSECC, dl, MVT::i8));
13634 // Break 256-bit integer vector compare into smaller ones.
13635 if (VT.is256BitVector() && !Subtarget->hasInt256())
13636 return Lower256IntVSETCC(Op, DAG);
13638 EVT OpVT = Op1.getValueType();
13639 if (OpVT.getVectorElementType() == MVT::i1)
13640 return LowerBoolVSETCC_AVX512(Op, DAG);
13642 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13643 if (Subtarget->hasAVX512()) {
13644 if (Op1.getValueType().is512BitVector() ||
13645 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13646 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13647 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13649 // In AVX-512 architecture setcc returns mask with i1 elements,
13650 // But there is no compare instruction for i8 and i16 elements in KNL.
13651 // We are not talking about 512-bit operands in this case, these
13652 // types are illegal.
13654 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13655 OpVT.getVectorElementType().getSizeInBits() >= 8))
13656 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13657 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13660 // We are handling one of the integer comparisons here. Since SSE only has
13661 // GT and EQ comparisons for integer, swapping operands and multiple
13662 // operations may be required for some comparisons.
13664 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13665 bool Subus = false;
13667 switch (SetCCOpcode) {
13668 default: llvm_unreachable("Unexpected SETCC condition");
13669 case ISD::SETNE: Invert = true;
13670 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13671 case ISD::SETLT: Swap = true;
13672 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13673 case ISD::SETGE: Swap = true;
13674 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13675 Invert = true; break;
13676 case ISD::SETULT: Swap = true;
13677 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13678 FlipSigns = true; break;
13679 case ISD::SETUGE: Swap = true;
13680 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13681 FlipSigns = true; Invert = true; break;
13684 // Special case: Use min/max operations for SETULE/SETUGE
13685 MVT VET = VT.getVectorElementType();
13687 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13688 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13691 switch (SetCCOpcode) {
13693 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13694 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13697 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13700 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13701 if (!MinMax && hasSubus) {
13702 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13704 // t = psubus Op0, Op1
13705 // pcmpeq t, <0..0>
13706 switch (SetCCOpcode) {
13708 case ISD::SETULT: {
13709 // If the comparison is against a constant we can turn this into a
13710 // setule. With psubus, setule does not require a swap. This is
13711 // beneficial because the constant in the register is no longer
13712 // destructed as the destination so it can be hoisted out of a loop.
13713 // Only do this pre-AVX since vpcmp* is no longer destructive.
13714 if (Subtarget->hasAVX())
13716 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13717 if (ULEOp1.getNode()) {
13719 Subus = true; Invert = false; Swap = false;
13723 // Psubus is better than flip-sign because it requires no inversion.
13724 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13725 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13729 Opc = X86ISD::SUBUS;
13735 std::swap(Op0, Op1);
13737 // Check that the operation in question is available (most are plain SSE2,
13738 // but PCMPGTQ and PCMPEQQ have different requirements).
13739 if (VT == MVT::v2i64) {
13740 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13741 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13743 // First cast everything to the right type.
13744 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13745 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13747 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13748 // bits of the inputs before performing those operations. The lower
13749 // compare is always unsigned.
13752 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13754 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13755 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13756 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13757 Sign, Zero, Sign, Zero);
13759 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13760 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13762 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13763 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13764 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13766 // Create masks for only the low parts/high parts of the 64 bit integers.
13767 static const int MaskHi[] = { 1, 1, 3, 3 };
13768 static const int MaskLo[] = { 0, 0, 2, 2 };
13769 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13770 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13771 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13773 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13774 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13777 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13779 return DAG.getBitcast(VT, Result);
13782 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13783 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13784 // pcmpeqd + pshufd + pand.
13785 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13787 // First cast everything to the right type.
13788 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13789 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13792 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13794 // Make sure the lower and upper halves are both all-ones.
13795 static const int Mask[] = { 1, 0, 3, 2 };
13796 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13797 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13800 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13802 return DAG.getBitcast(VT, Result);
13806 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13807 // bits of the inputs before performing those operations.
13809 EVT EltVT = VT.getVectorElementType();
13810 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13812 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13813 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13816 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13818 // If the logical-not of the result is required, perform that now.
13820 Result = DAG.getNOT(dl, Result, VT);
13823 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13826 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13827 getZeroVector(VT, Subtarget, DAG, dl));
13832 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13834 MVT VT = Op.getSimpleValueType();
13836 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13838 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13839 && "SetCC type must be 8-bit or 1-bit integer");
13840 SDValue Op0 = Op.getOperand(0);
13841 SDValue Op1 = Op.getOperand(1);
13843 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13845 // Optimize to BT if possible.
13846 // Lower (X & (1 << N)) == 0 to BT(X, N).
13847 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13848 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13849 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13850 Op1.getOpcode() == ISD::Constant &&
13851 cast<ConstantSDNode>(Op1)->isNullValue() &&
13852 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13853 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13854 if (NewSetCC.getNode()) {
13856 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13861 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13863 if (Op1.getOpcode() == ISD::Constant &&
13864 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13865 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13866 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13868 // If the input is a setcc, then reuse the input setcc or use a new one with
13869 // the inverted condition.
13870 if (Op0.getOpcode() == X86ISD::SETCC) {
13871 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13872 bool Invert = (CC == ISD::SETNE) ^
13873 cast<ConstantSDNode>(Op1)->isNullValue();
13877 CCode = X86::GetOppositeBranchCondition(CCode);
13878 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13879 DAG.getConstant(CCode, dl, MVT::i8),
13880 Op0.getOperand(1));
13882 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13886 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13887 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13888 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13890 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13891 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13894 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13895 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13896 if (X86CC == X86::COND_INVALID)
13899 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13900 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13901 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13902 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13904 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13908 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13909 static bool isX86LogicalCmp(SDValue Op) {
13910 unsigned Opc = Op.getNode()->getOpcode();
13911 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13912 Opc == X86ISD::SAHF)
13914 if (Op.getResNo() == 1 &&
13915 (Opc == X86ISD::ADD ||
13916 Opc == X86ISD::SUB ||
13917 Opc == X86ISD::ADC ||
13918 Opc == X86ISD::SBB ||
13919 Opc == X86ISD::SMUL ||
13920 Opc == X86ISD::UMUL ||
13921 Opc == X86ISD::INC ||
13922 Opc == X86ISD::DEC ||
13923 Opc == X86ISD::OR ||
13924 Opc == X86ISD::XOR ||
13925 Opc == X86ISD::AND))
13928 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13934 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13935 if (V.getOpcode() != ISD::TRUNCATE)
13938 SDValue VOp0 = V.getOperand(0);
13939 unsigned InBits = VOp0.getValueSizeInBits();
13940 unsigned Bits = V.getValueSizeInBits();
13941 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13944 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13945 bool addTest = true;
13946 SDValue Cond = Op.getOperand(0);
13947 SDValue Op1 = Op.getOperand(1);
13948 SDValue Op2 = Op.getOperand(2);
13950 EVT VT = Op1.getValueType();
13953 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13954 // are available or VBLENDV if AVX is available.
13955 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13956 if (Cond.getOpcode() == ISD::SETCC &&
13957 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13958 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13959 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13960 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13961 int SSECC = translateX86FSETCC(
13962 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13965 if (Subtarget->hasAVX512()) {
13966 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13967 DAG.getConstant(SSECC, DL, MVT::i8));
13968 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13971 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13972 DAG.getConstant(SSECC, DL, MVT::i8));
13974 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13975 // of 3 logic instructions for size savings and potentially speed.
13976 // Unfortunately, there is no scalar form of VBLENDV.
13978 // If either operand is a constant, don't try this. We can expect to
13979 // optimize away at least one of the logic instructions later in that
13980 // case, so that sequence would be faster than a variable blend.
13982 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13983 // uses XMM0 as the selection register. That may need just as many
13984 // instructions as the AND/ANDN/OR sequence due to register moves, so
13987 if (Subtarget->hasAVX() &&
13988 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13990 // Convert to vectors, do a VSELECT, and convert back to scalar.
13991 // All of the conversions should be optimized away.
13993 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13994 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13995 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13996 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13998 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13999 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14001 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14003 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14004 VSel, DAG.getIntPtrConstant(0, DL));
14006 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14007 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14008 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14012 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14014 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14015 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14016 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14017 Op1Scalar = Op1.getOperand(0);
14019 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14020 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14021 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14022 Op2Scalar = Op2.getOperand(0);
14023 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14024 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14025 Op1Scalar.getValueType(),
14026 Cond, Op1Scalar, Op2Scalar);
14027 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14028 return DAG.getBitcast(VT, newSelect);
14029 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14030 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14031 DAG.getIntPtrConstant(0, DL));
14035 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14036 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14037 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14038 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14039 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14040 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14041 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14043 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14046 if (Cond.getOpcode() == ISD::SETCC) {
14047 SDValue NewCond = LowerSETCC(Cond, DAG);
14048 if (NewCond.getNode())
14052 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14053 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14054 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14055 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14056 if (Cond.getOpcode() == X86ISD::SETCC &&
14057 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14058 isZero(Cond.getOperand(1).getOperand(1))) {
14059 SDValue Cmp = Cond.getOperand(1);
14061 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14063 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14064 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14065 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14067 SDValue CmpOp0 = Cmp.getOperand(0);
14068 // Apply further optimizations for special cases
14069 // (select (x != 0), -1, 0) -> neg & sbb
14070 // (select (x == 0), 0, -1) -> neg & sbb
14071 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14072 if (YC->isNullValue() &&
14073 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14074 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14075 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14076 DAG.getConstant(0, DL,
14077 CmpOp0.getValueType()),
14079 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14080 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14081 SDValue(Neg.getNode(), 1));
14085 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14086 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14087 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14089 SDValue Res = // Res = 0 or -1.
14090 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14091 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14093 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14094 Res = DAG.getNOT(DL, Res, Res.getValueType());
14096 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14097 if (!N2C || !N2C->isNullValue())
14098 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14103 // Look past (and (setcc_carry (cmp ...)), 1).
14104 if (Cond.getOpcode() == ISD::AND &&
14105 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14106 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14107 if (C && C->getAPIntValue() == 1)
14108 Cond = Cond.getOperand(0);
14111 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14112 // setting operand in place of the X86ISD::SETCC.
14113 unsigned CondOpcode = Cond.getOpcode();
14114 if (CondOpcode == X86ISD::SETCC ||
14115 CondOpcode == X86ISD::SETCC_CARRY) {
14116 CC = Cond.getOperand(0);
14118 SDValue Cmp = Cond.getOperand(1);
14119 unsigned Opc = Cmp.getOpcode();
14120 MVT VT = Op.getSimpleValueType();
14122 bool IllegalFPCMov = false;
14123 if (VT.isFloatingPoint() && !VT.isVector() &&
14124 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14125 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14127 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14128 Opc == X86ISD::BT) { // FIXME
14132 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14133 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14134 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14135 Cond.getOperand(0).getValueType() != MVT::i8)) {
14136 SDValue LHS = Cond.getOperand(0);
14137 SDValue RHS = Cond.getOperand(1);
14138 unsigned X86Opcode;
14141 switch (CondOpcode) {
14142 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14143 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14144 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14145 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14146 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14147 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14148 default: llvm_unreachable("unexpected overflowing operator");
14150 if (CondOpcode == ISD::UMULO)
14151 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14154 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14156 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14158 if (CondOpcode == ISD::UMULO)
14159 Cond = X86Op.getValue(2);
14161 Cond = X86Op.getValue(1);
14163 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14168 // Look past the truncate if the high bits are known zero.
14169 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14170 Cond = Cond.getOperand(0);
14172 // We know the result of AND is compared against zero. Try to match
14174 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14175 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14176 if (NewSetCC.getNode()) {
14177 CC = NewSetCC.getOperand(0);
14178 Cond = NewSetCC.getOperand(1);
14185 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14186 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14189 // a < b ? -1 : 0 -> RES = ~setcc_carry
14190 // a < b ? 0 : -1 -> RES = setcc_carry
14191 // a >= b ? -1 : 0 -> RES = setcc_carry
14192 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14193 if (Cond.getOpcode() == X86ISD::SUB) {
14194 Cond = ConvertCmpIfNecessary(Cond, DAG);
14195 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14197 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14198 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14199 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14200 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14202 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14203 return DAG.getNOT(DL, Res, Res.getValueType());
14208 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14209 // widen the cmov and push the truncate through. This avoids introducing a new
14210 // branch during isel and doesn't add any extensions.
14211 if (Op.getValueType() == MVT::i8 &&
14212 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14213 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14214 if (T1.getValueType() == T2.getValueType() &&
14215 // Blacklist CopyFromReg to avoid partial register stalls.
14216 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14217 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14218 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14219 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14223 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14224 // condition is true.
14225 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14226 SDValue Ops[] = { Op2, Op1, CC, Cond };
14227 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14230 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14231 const X86Subtarget *Subtarget,
14232 SelectionDAG &DAG) {
14233 MVT VT = Op->getSimpleValueType(0);
14234 SDValue In = Op->getOperand(0);
14235 MVT InVT = In.getSimpleValueType();
14236 MVT VTElt = VT.getVectorElementType();
14237 MVT InVTElt = InVT.getVectorElementType();
14241 if ((InVTElt == MVT::i1) &&
14242 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14243 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14245 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14246 VTElt.getSizeInBits() <= 16)) ||
14248 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14249 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14251 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14252 VTElt.getSizeInBits() >= 32))))
14253 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14255 unsigned int NumElts = VT.getVectorNumElements();
14257 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14260 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14261 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14262 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14263 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14266 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14267 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14269 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14272 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14274 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14275 if (VT.is512BitVector())
14277 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14280 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14281 const X86Subtarget *Subtarget,
14282 SelectionDAG &DAG) {
14283 SDValue In = Op->getOperand(0);
14284 MVT VT = Op->getSimpleValueType(0);
14285 MVT InVT = In.getSimpleValueType();
14286 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14288 MVT InSVT = InVT.getScalarType();
14289 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14291 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14293 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14298 // SSE41 targets can use the pmovsx* instructions directly.
14299 if (Subtarget->hasSSE41())
14300 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14302 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14306 // As SRAI is only available on i16/i32 types, we expand only up to i32
14307 // and handle i64 separately.
14308 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14309 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14310 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14311 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14312 Curr = DAG.getBitcast(CurrVT, Curr);
14315 SDValue SignExt = Curr;
14316 if (CurrVT != InVT) {
14317 unsigned SignExtShift =
14318 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14319 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14320 DAG.getConstant(SignExtShift, dl, MVT::i8));
14326 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14327 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14328 DAG.getConstant(31, dl, MVT::i8));
14329 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14330 return DAG.getBitcast(VT, Ext);
14336 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14337 SelectionDAG &DAG) {
14338 MVT VT = Op->getSimpleValueType(0);
14339 SDValue In = Op->getOperand(0);
14340 MVT InVT = In.getSimpleValueType();
14343 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14344 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14346 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14347 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14348 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14351 if (Subtarget->hasInt256())
14352 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14354 // Optimize vectors in AVX mode
14355 // Sign extend v8i16 to v8i32 and
14358 // Divide input vector into two parts
14359 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14360 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14361 // concat the vectors to original VT
14363 unsigned NumElems = InVT.getVectorNumElements();
14364 SDValue Undef = DAG.getUNDEF(InVT);
14366 SmallVector<int,8> ShufMask1(NumElems, -1);
14367 for (unsigned i = 0; i != NumElems/2; ++i)
14370 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14372 SmallVector<int,8> ShufMask2(NumElems, -1);
14373 for (unsigned i = 0; i != NumElems/2; ++i)
14374 ShufMask2[i] = i + NumElems/2;
14376 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14378 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14379 VT.getVectorNumElements()/2);
14381 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14382 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14384 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14387 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14388 // may emit an illegal shuffle but the expansion is still better than scalar
14389 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14390 // we'll emit a shuffle and a arithmetic shift.
14391 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14392 // TODO: It is possible to support ZExt by zeroing the undef values during
14393 // the shuffle phase or after the shuffle.
14394 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14395 SelectionDAG &DAG) {
14396 MVT RegVT = Op.getSimpleValueType();
14397 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14398 assert(RegVT.isInteger() &&
14399 "We only custom lower integer vector sext loads.");
14401 // Nothing useful we can do without SSE2 shuffles.
14402 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14404 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14406 EVT MemVT = Ld->getMemoryVT();
14407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14408 unsigned RegSz = RegVT.getSizeInBits();
14410 ISD::LoadExtType Ext = Ld->getExtensionType();
14412 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14413 && "Only anyext and sext are currently implemented.");
14414 assert(MemVT != RegVT && "Cannot extend to the same type");
14415 assert(MemVT.isVector() && "Must load a vector from memory");
14417 unsigned NumElems = RegVT.getVectorNumElements();
14418 unsigned MemSz = MemVT.getSizeInBits();
14419 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14421 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14422 // The only way in which we have a legal 256-bit vector result but not the
14423 // integer 256-bit operations needed to directly lower a sextload is if we
14424 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14425 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14426 // correctly legalized. We do this late to allow the canonical form of
14427 // sextload to persist throughout the rest of the DAG combiner -- it wants
14428 // to fold together any extensions it can, and so will fuse a sign_extend
14429 // of an sextload into a sextload targeting a wider value.
14431 if (MemSz == 128) {
14432 // Just switch this to a normal load.
14433 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14434 "it must be a legal 128-bit vector "
14436 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14437 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14438 Ld->isInvariant(), Ld->getAlignment());
14440 assert(MemSz < 128 &&
14441 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14442 // Do an sext load to a 128-bit vector type. We want to use the same
14443 // number of elements, but elements half as wide. This will end up being
14444 // recursively lowered by this routine, but will succeed as we definitely
14445 // have all the necessary features if we're using AVX1.
14447 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14448 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14450 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14451 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14452 Ld->isNonTemporal(), Ld->isInvariant(),
14453 Ld->getAlignment());
14456 // Replace chain users with the new chain.
14457 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14458 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14460 // Finally, do a normal sign-extend to the desired register.
14461 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14464 // All sizes must be a power of two.
14465 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14466 "Non-power-of-two elements are not custom lowered!");
14468 // Attempt to load the original value using scalar loads.
14469 // Find the largest scalar type that divides the total loaded size.
14470 MVT SclrLoadTy = MVT::i8;
14471 for (MVT Tp : MVT::integer_valuetypes()) {
14472 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14477 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14478 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14480 SclrLoadTy = MVT::f64;
14482 // Calculate the number of scalar loads that we need to perform
14483 // in order to load our vector from memory.
14484 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14486 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14487 "Can only lower sext loads with a single scalar load!");
14489 unsigned loadRegZize = RegSz;
14490 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14493 // Represent our vector as a sequence of elements which are the
14494 // largest scalar that we can load.
14495 EVT LoadUnitVecVT = EVT::getVectorVT(
14496 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14498 // Represent the data using the same element type that is stored in
14499 // memory. In practice, we ''widen'' MemVT.
14501 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14502 loadRegZize / MemVT.getScalarType().getSizeInBits());
14504 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14505 "Invalid vector type");
14507 // We can't shuffle using an illegal type.
14508 assert(TLI.isTypeLegal(WideVecVT) &&
14509 "We only lower types that form legal widened vector types");
14511 SmallVector<SDValue, 8> Chains;
14512 SDValue Ptr = Ld->getBasePtr();
14513 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14514 TLI.getPointerTy(DAG.getDataLayout()));
14515 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14517 for (unsigned i = 0; i < NumLoads; ++i) {
14518 // Perform a single load.
14519 SDValue ScalarLoad =
14520 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14521 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14522 Ld->getAlignment());
14523 Chains.push_back(ScalarLoad.getValue(1));
14524 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14525 // another round of DAGCombining.
14527 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14529 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14530 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14532 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14535 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14537 // Bitcast the loaded value to a vector of the original element type, in
14538 // the size of the target vector type.
14539 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14540 unsigned SizeRatio = RegSz / MemSz;
14542 if (Ext == ISD::SEXTLOAD) {
14543 // If we have SSE4.1, we can directly emit a VSEXT node.
14544 if (Subtarget->hasSSE41()) {
14545 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14546 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14550 // Otherwise we'll shuffle the small elements in the high bits of the
14551 // larger type and perform an arithmetic shift. If the shift is not legal
14552 // it's better to scalarize.
14553 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14554 "We can't implement a sext load without an arithmetic right shift!");
14556 // Redistribute the loaded elements into the different locations.
14557 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14558 for (unsigned i = 0; i != NumElems; ++i)
14559 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14561 SDValue Shuff = DAG.getVectorShuffle(
14562 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14564 Shuff = DAG.getBitcast(RegVT, Shuff);
14566 // Build the arithmetic shift.
14567 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14568 MemVT.getVectorElementType().getSizeInBits();
14570 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14571 DAG.getConstant(Amt, dl, RegVT));
14573 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14577 // Redistribute the loaded elements into the different locations.
14578 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14579 for (unsigned i = 0; i != NumElems; ++i)
14580 ShuffleVec[i * SizeRatio] = i;
14582 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14583 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14585 // Bitcast to the requested type.
14586 Shuff = DAG.getBitcast(RegVT, Shuff);
14587 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14591 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14592 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14593 // from the AND / OR.
14594 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14595 Opc = Op.getOpcode();
14596 if (Opc != ISD::OR && Opc != ISD::AND)
14598 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14599 Op.getOperand(0).hasOneUse() &&
14600 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14601 Op.getOperand(1).hasOneUse());
14604 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14605 // 1 and that the SETCC node has a single use.
14606 static bool isXor1OfSetCC(SDValue Op) {
14607 if (Op.getOpcode() != ISD::XOR)
14609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14610 if (N1C && N1C->getAPIntValue() == 1) {
14611 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14612 Op.getOperand(0).hasOneUse();
14617 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14618 bool addTest = true;
14619 SDValue Chain = Op.getOperand(0);
14620 SDValue Cond = Op.getOperand(1);
14621 SDValue Dest = Op.getOperand(2);
14624 bool Inverted = false;
14626 if (Cond.getOpcode() == ISD::SETCC) {
14627 // Check for setcc([su]{add,sub,mul}o == 0).
14628 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14629 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14630 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14631 Cond.getOperand(0).getResNo() == 1 &&
14632 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14633 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14634 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14635 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14636 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14637 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14639 Cond = Cond.getOperand(0);
14641 SDValue NewCond = LowerSETCC(Cond, DAG);
14642 if (NewCond.getNode())
14647 // FIXME: LowerXALUO doesn't handle these!!
14648 else if (Cond.getOpcode() == X86ISD::ADD ||
14649 Cond.getOpcode() == X86ISD::SUB ||
14650 Cond.getOpcode() == X86ISD::SMUL ||
14651 Cond.getOpcode() == X86ISD::UMUL)
14652 Cond = LowerXALUO(Cond, DAG);
14655 // Look pass (and (setcc_carry (cmp ...)), 1).
14656 if (Cond.getOpcode() == ISD::AND &&
14657 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14658 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14659 if (C && C->getAPIntValue() == 1)
14660 Cond = Cond.getOperand(0);
14663 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14664 // setting operand in place of the X86ISD::SETCC.
14665 unsigned CondOpcode = Cond.getOpcode();
14666 if (CondOpcode == X86ISD::SETCC ||
14667 CondOpcode == X86ISD::SETCC_CARRY) {
14668 CC = Cond.getOperand(0);
14670 SDValue Cmp = Cond.getOperand(1);
14671 unsigned Opc = Cmp.getOpcode();
14672 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14673 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14677 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14681 // These can only come from an arithmetic instruction with overflow,
14682 // e.g. SADDO, UADDO.
14683 Cond = Cond.getNode()->getOperand(1);
14689 CondOpcode = Cond.getOpcode();
14690 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14691 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14692 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14693 Cond.getOperand(0).getValueType() != MVT::i8)) {
14694 SDValue LHS = Cond.getOperand(0);
14695 SDValue RHS = Cond.getOperand(1);
14696 unsigned X86Opcode;
14699 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14700 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14702 switch (CondOpcode) {
14703 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14707 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14710 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14711 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14715 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14718 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14719 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14720 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14721 default: llvm_unreachable("unexpected overflowing operator");
14724 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14725 if (CondOpcode == ISD::UMULO)
14726 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14729 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14731 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14733 if (CondOpcode == ISD::UMULO)
14734 Cond = X86Op.getValue(2);
14736 Cond = X86Op.getValue(1);
14738 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14742 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14743 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14744 if (CondOpc == ISD::OR) {
14745 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14746 // two branches instead of an explicit OR instruction with a
14748 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14749 isX86LogicalCmp(Cmp)) {
14750 CC = Cond.getOperand(0).getOperand(0);
14751 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14752 Chain, Dest, CC, Cmp);
14753 CC = Cond.getOperand(1).getOperand(0);
14757 } else { // ISD::AND
14758 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14759 // two branches instead of an explicit AND instruction with a
14760 // separate test. However, we only do this if this block doesn't
14761 // have a fall-through edge, because this requires an explicit
14762 // jmp when the condition is false.
14763 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14764 isX86LogicalCmp(Cmp) &&
14765 Op.getNode()->hasOneUse()) {
14766 X86::CondCode CCode =
14767 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14768 CCode = X86::GetOppositeBranchCondition(CCode);
14769 CC = DAG.getConstant(CCode, dl, MVT::i8);
14770 SDNode *User = *Op.getNode()->use_begin();
14771 // Look for an unconditional branch following this conditional branch.
14772 // We need this because we need to reverse the successors in order
14773 // to implement FCMP_OEQ.
14774 if (User->getOpcode() == ISD::BR) {
14775 SDValue FalseBB = User->getOperand(1);
14777 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14778 assert(NewBR == User);
14782 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14783 Chain, Dest, CC, Cmp);
14784 X86::CondCode CCode =
14785 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14786 CCode = X86::GetOppositeBranchCondition(CCode);
14787 CC = DAG.getConstant(CCode, dl, MVT::i8);
14793 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14794 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14795 // It should be transformed during dag combiner except when the condition
14796 // is set by a arithmetics with overflow node.
14797 X86::CondCode CCode =
14798 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14799 CCode = X86::GetOppositeBranchCondition(CCode);
14800 CC = DAG.getConstant(CCode, dl, MVT::i8);
14801 Cond = Cond.getOperand(0).getOperand(1);
14803 } else if (Cond.getOpcode() == ISD::SETCC &&
14804 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14805 // For FCMP_OEQ, we can emit
14806 // two branches instead of an explicit AND instruction with a
14807 // separate test. However, we only do this if this block doesn't
14808 // have a fall-through edge, because this requires an explicit
14809 // jmp when the condition is false.
14810 if (Op.getNode()->hasOneUse()) {
14811 SDNode *User = *Op.getNode()->use_begin();
14812 // Look for an unconditional branch following this conditional branch.
14813 // We need this because we need to reverse the successors in order
14814 // to implement FCMP_OEQ.
14815 if (User->getOpcode() == ISD::BR) {
14816 SDValue FalseBB = User->getOperand(1);
14818 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14819 assert(NewBR == User);
14823 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14824 Cond.getOperand(0), Cond.getOperand(1));
14825 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14826 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14827 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14828 Chain, Dest, CC, Cmp);
14829 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14834 } else if (Cond.getOpcode() == ISD::SETCC &&
14835 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14836 // For FCMP_UNE, we can emit
14837 // two branches instead of an explicit AND instruction with a
14838 // separate test. However, we only do this if this block doesn't
14839 // have a fall-through edge, because this requires an explicit
14840 // jmp when the condition is false.
14841 if (Op.getNode()->hasOneUse()) {
14842 SDNode *User = *Op.getNode()->use_begin();
14843 // Look for an unconditional branch following this conditional branch.
14844 // We need this because we need to reverse the successors in order
14845 // to implement FCMP_UNE.
14846 if (User->getOpcode() == ISD::BR) {
14847 SDValue FalseBB = User->getOperand(1);
14849 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14850 assert(NewBR == User);
14853 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14854 Cond.getOperand(0), Cond.getOperand(1));
14855 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14856 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14857 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14858 Chain, Dest, CC, Cmp);
14859 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14869 // Look pass the truncate if the high bits are known zero.
14870 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14871 Cond = Cond.getOperand(0);
14873 // We know the result of AND is compared against zero. Try to match
14875 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14876 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14877 if (NewSetCC.getNode()) {
14878 CC = NewSetCC.getOperand(0);
14879 Cond = NewSetCC.getOperand(1);
14886 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14887 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14888 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14890 Cond = ConvertCmpIfNecessary(Cond, DAG);
14891 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14892 Chain, Dest, CC, Cond);
14895 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14896 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14897 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14898 // that the guard pages used by the OS virtual memory manager are allocated in
14899 // correct sequence.
14901 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14902 SelectionDAG &DAG) const {
14903 MachineFunction &MF = DAG.getMachineFunction();
14904 bool SplitStack = MF.shouldSplitStack();
14905 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14910 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14911 SDNode* Node = Op.getNode();
14913 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14914 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14915 " not tell us which reg is the stack pointer!");
14916 EVT VT = Node->getValueType(0);
14917 SDValue Tmp1 = SDValue(Node, 0);
14918 SDValue Tmp2 = SDValue(Node, 1);
14919 SDValue Tmp3 = Node->getOperand(2);
14920 SDValue Chain = Tmp1.getOperand(0);
14922 // Chain the dynamic stack allocation so that it doesn't modify the stack
14923 // pointer when other instructions are using the stack.
14924 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14927 SDValue Size = Tmp2.getOperand(1);
14928 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14929 Chain = SP.getValue(1);
14930 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14931 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14932 unsigned StackAlign = TFI.getStackAlignment();
14933 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14934 if (Align > StackAlign)
14935 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14936 DAG.getConstant(-(uint64_t)Align, dl, VT));
14937 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14939 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14940 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14943 SDValue Ops[2] = { Tmp1, Tmp2 };
14944 return DAG.getMergeValues(Ops, dl);
14948 SDValue Chain = Op.getOperand(0);
14949 SDValue Size = Op.getOperand(1);
14950 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14951 EVT VT = Op.getNode()->getValueType(0);
14953 bool Is64Bit = Subtarget->is64Bit();
14954 MVT SPTy = getPointerTy(DAG.getDataLayout());
14957 MachineRegisterInfo &MRI = MF.getRegInfo();
14960 // The 64 bit implementation of segmented stacks needs to clobber both r10
14961 // r11. This makes it impossible to use it along with nested parameters.
14962 const Function *F = MF.getFunction();
14964 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14966 if (I->hasNestAttr())
14967 report_fatal_error("Cannot use segmented stacks with functions that "
14968 "have nested arguments.");
14971 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14972 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14973 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14974 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14975 DAG.getRegister(Vreg, SPTy));
14976 SDValue Ops1[2] = { Value, Chain };
14977 return DAG.getMergeValues(Ops1, dl);
14980 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14982 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14983 Flag = Chain.getValue(1);
14984 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14986 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14988 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14989 unsigned SPReg = RegInfo->getStackRegister();
14990 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14991 Chain = SP.getValue(1);
14994 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14995 DAG.getConstant(-(uint64_t)Align, dl, VT));
14996 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14999 SDValue Ops1[2] = { SP, Chain };
15000 return DAG.getMergeValues(Ops1, dl);
15004 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15005 MachineFunction &MF = DAG.getMachineFunction();
15006 auto PtrVT = getPointerTy(MF.getDataLayout());
15007 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15009 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15012 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
15013 // vastart just stores the address of the VarArgsFrameIndex slot into the
15014 // memory location argument.
15015 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15016 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15017 MachinePointerInfo(SV), false, false, 0);
15021 // gp_offset (0 - 6 * 8)
15022 // fp_offset (48 - 48 + 8 * 16)
15023 // overflow_arg_area (point to parameters coming in memory).
15025 SmallVector<SDValue, 8> MemOps;
15026 SDValue FIN = Op.getOperand(1);
15028 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15029 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15031 FIN, MachinePointerInfo(SV), false, false, 0);
15032 MemOps.push_back(Store);
15035 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15036 Store = DAG.getStore(Op.getOperand(0), DL,
15037 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15039 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15040 MemOps.push_back(Store);
15042 // Store ptr to overflow_arg_area
15043 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15044 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15045 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15046 MachinePointerInfo(SV, 8),
15048 MemOps.push_back(Store);
15050 // Store ptr to reg_save_area.
15051 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15052 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15053 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15054 MachinePointerInfo(SV, 16), false, false, 0);
15055 MemOps.push_back(Store);
15056 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15059 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15060 assert(Subtarget->is64Bit() &&
15061 "LowerVAARG only handles 64-bit va_arg!");
15062 assert((Subtarget->isTargetLinux() ||
15063 Subtarget->isTargetDarwin()) &&
15064 "Unhandled target in LowerVAARG");
15065 assert(Op.getNode()->getNumOperands() == 4);
15066 SDValue Chain = Op.getOperand(0);
15067 SDValue SrcPtr = Op.getOperand(1);
15068 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15069 unsigned Align = Op.getConstantOperandVal(3);
15072 EVT ArgVT = Op.getNode()->getValueType(0);
15073 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15074 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15077 // Decide which area this value should be read from.
15078 // TODO: Implement the AMD64 ABI in its entirety. This simple
15079 // selection mechanism works only for the basic types.
15080 if (ArgVT == MVT::f80) {
15081 llvm_unreachable("va_arg for f80 not yet implemented");
15082 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15083 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15084 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15085 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15087 llvm_unreachable("Unhandled argument type in LowerVAARG");
15090 if (ArgMode == 2) {
15091 // Sanity Check: Make sure using fp_offset makes sense.
15092 assert(!Subtarget->useSoftFloat() &&
15093 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15094 Attribute::NoImplicitFloat)) &&
15095 Subtarget->hasSSE1());
15098 // Insert VAARG_64 node into the DAG
15099 // VAARG_64 returns two values: Variable Argument Address, Chain
15100 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15101 DAG.getConstant(ArgMode, dl, MVT::i8),
15102 DAG.getConstant(Align, dl, MVT::i32)};
15103 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15104 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15105 VTs, InstOps, MVT::i64,
15106 MachinePointerInfo(SV),
15108 /*Volatile=*/false,
15110 /*WriteMem=*/true);
15111 Chain = VAARG.getValue(1);
15113 // Load the next argument and return it
15114 return DAG.getLoad(ArgVT, dl,
15117 MachinePointerInfo(),
15118 false, false, false, 0);
15121 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15122 SelectionDAG &DAG) {
15123 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15124 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15125 SDValue Chain = Op.getOperand(0);
15126 SDValue DstPtr = Op.getOperand(1);
15127 SDValue SrcPtr = Op.getOperand(2);
15128 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15129 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15132 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15133 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15135 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15138 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15139 // amount is a constant. Takes immediate version of shift as input.
15140 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15141 SDValue SrcOp, uint64_t ShiftAmt,
15142 SelectionDAG &DAG) {
15143 MVT ElementType = VT.getVectorElementType();
15145 // Fold this packed shift into its first operand if ShiftAmt is 0.
15149 // Check for ShiftAmt >= element width
15150 if (ShiftAmt >= ElementType.getSizeInBits()) {
15151 if (Opc == X86ISD::VSRAI)
15152 ShiftAmt = ElementType.getSizeInBits() - 1;
15154 return DAG.getConstant(0, dl, VT);
15157 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15158 && "Unknown target vector shift-by-constant node");
15160 // Fold this packed vector shift into a build vector if SrcOp is a
15161 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15162 if (VT == SrcOp.getSimpleValueType() &&
15163 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15164 SmallVector<SDValue, 8> Elts;
15165 unsigned NumElts = SrcOp->getNumOperands();
15166 ConstantSDNode *ND;
15169 default: llvm_unreachable(nullptr);
15170 case X86ISD::VSHLI:
15171 for (unsigned i=0; i!=NumElts; ++i) {
15172 SDValue CurrentOp = SrcOp->getOperand(i);
15173 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15174 Elts.push_back(CurrentOp);
15177 ND = cast<ConstantSDNode>(CurrentOp);
15178 const APInt &C = ND->getAPIntValue();
15179 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15182 case X86ISD::VSRLI:
15183 for (unsigned i=0; i!=NumElts; ++i) {
15184 SDValue CurrentOp = SrcOp->getOperand(i);
15185 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15186 Elts.push_back(CurrentOp);
15189 ND = cast<ConstantSDNode>(CurrentOp);
15190 const APInt &C = ND->getAPIntValue();
15191 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15194 case X86ISD::VSRAI:
15195 for (unsigned i=0; i!=NumElts; ++i) {
15196 SDValue CurrentOp = SrcOp->getOperand(i);
15197 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15198 Elts.push_back(CurrentOp);
15201 ND = cast<ConstantSDNode>(CurrentOp);
15202 const APInt &C = ND->getAPIntValue();
15203 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15208 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15211 return DAG.getNode(Opc, dl, VT, SrcOp,
15212 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15215 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15216 // may or may not be a constant. Takes immediate version of shift as input.
15217 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15218 SDValue SrcOp, SDValue ShAmt,
15219 SelectionDAG &DAG) {
15220 MVT SVT = ShAmt.getSimpleValueType();
15221 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15223 // Catch shift-by-constant.
15224 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15225 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15226 CShAmt->getZExtValue(), DAG);
15228 // Change opcode to non-immediate version
15230 default: llvm_unreachable("Unknown target vector shift node");
15231 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15232 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15233 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15236 const X86Subtarget &Subtarget =
15237 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15238 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15239 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15240 // Let the shuffle legalizer expand this shift amount node.
15241 SDValue Op0 = ShAmt.getOperand(0);
15242 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15243 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15245 // Need to build a vector containing shift amount.
15246 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15247 SmallVector<SDValue, 4> ShOps;
15248 ShOps.push_back(ShAmt);
15249 if (SVT == MVT::i32) {
15250 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15251 ShOps.push_back(DAG.getUNDEF(SVT));
15253 ShOps.push_back(DAG.getUNDEF(SVT));
15255 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15256 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15259 // The return type has to be a 128-bit type with the same element
15260 // type as the input type.
15261 MVT EltVT = VT.getVectorElementType();
15262 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15264 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15265 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15268 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15269 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15270 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15271 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15272 SDValue PreservedSrc,
15273 const X86Subtarget *Subtarget,
15274 SelectionDAG &DAG) {
15275 EVT VT = Op.getValueType();
15276 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15277 MVT::i1, VT.getVectorNumElements());
15278 SDValue VMask = SDValue();
15279 unsigned OpcodeSelect = ISD::VSELECT;
15282 assert(MaskVT.isSimple() && "invalid mask type");
15284 if (isAllOnes(Mask))
15287 if (MaskVT.bitsGT(Mask.getValueType())) {
15288 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15289 MaskVT.getSizeInBits());
15290 VMask = DAG.getBitcast(MaskVT,
15291 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15293 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15294 Mask.getValueType().getSizeInBits());
15295 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15296 // are extracted by EXTRACT_SUBVECTOR.
15297 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15298 DAG.getBitcast(BitcastVT, Mask),
15299 DAG.getIntPtrConstant(0, dl));
15302 switch (Op.getOpcode()) {
15304 case X86ISD::PCMPEQM:
15305 case X86ISD::PCMPGTM:
15307 case X86ISD::CMPMU:
15308 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15309 case X86ISD::VTRUNC:
15310 case X86ISD::VTRUNCS:
15311 case X86ISD::VTRUNCUS:
15312 // We can't use ISD::VSELECT here because it is not always "Legal"
15313 // for the destination type. For example vpmovqb require only AVX512
15314 // and vselect that can operate on byte element type require BWI
15315 OpcodeSelect = X86ISD::SELECT;
15318 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15319 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15320 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15323 /// \brief Creates an SDNode for a predicated scalar operation.
15324 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15325 /// The mask is coming as MVT::i8 and it should be truncated
15326 /// to MVT::i1 while lowering masking intrinsics.
15327 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15328 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15329 /// for a scalar instruction.
15330 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15331 SDValue PreservedSrc,
15332 const X86Subtarget *Subtarget,
15333 SelectionDAG &DAG) {
15334 if (isAllOnes(Mask))
15337 EVT VT = Op.getValueType();
15339 // The mask should be of type MVT::i1
15340 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15342 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15343 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15344 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15347 static int getSEHRegistrationNodeSize(const Function *Fn) {
15348 if (!Fn->hasPersonalityFn())
15349 report_fatal_error(
15350 "querying registration node size for function without personality");
15351 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15352 // WinEHStatePass for the full struct definition.
15353 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15354 case EHPersonality::MSVC_X86SEH: return 24;
15355 case EHPersonality::MSVC_CXX: return 16;
15358 report_fatal_error("can only recover FP for MSVC EH personality functions");
15361 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15362 /// function or when returning to a parent frame after catching an exception, we
15363 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15364 /// Here's the math:
15365 /// RegNodeBase = EntryEBP - RegNodeSize
15366 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15367 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15368 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15369 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15370 SDValue EntryEBP) {
15371 MachineFunction &MF = DAG.getMachineFunction();
15374 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15375 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15377 // It's possible that the parent function no longer has a personality function
15378 // if the exceptional code was optimized away, in which case we just return
15379 // the incoming EBP.
15380 if (!Fn->hasPersonalityFn())
15383 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15385 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15387 MCSymbol *OffsetSym =
15388 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15389 GlobalValue::getRealLinkageName(Fn->getName()));
15390 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15391 SDValue RegNodeFrameOffset =
15392 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15394 // RegNodeBase = EntryEBP - RegNodeSize
15395 // ParentFP = RegNodeBase - RegNodeFrameOffset
15396 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15397 DAG.getConstant(RegNodeSize, dl, PtrVT));
15398 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15401 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15402 SelectionDAG &DAG) {
15404 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15405 EVT VT = Op.getValueType();
15406 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15408 switch(IntrData->Type) {
15409 case INTR_TYPE_1OP:
15410 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15411 case INTR_TYPE_2OP:
15412 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15414 case INTR_TYPE_3OP:
15415 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15416 Op.getOperand(2), Op.getOperand(3));
15417 case INTR_TYPE_4OP:
15418 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15419 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15420 case INTR_TYPE_1OP_MASK_RM: {
15421 SDValue Src = Op.getOperand(1);
15422 SDValue PassThru = Op.getOperand(2);
15423 SDValue Mask = Op.getOperand(3);
15424 SDValue RoundingMode;
15425 // We allways add rounding mode to the Node.
15426 // If the rounding mode is not specified, we add the
15427 // "current direction" mode.
15428 if (Op.getNumOperands() == 4)
15430 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15432 RoundingMode = Op.getOperand(4);
15433 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15434 if (IntrWithRoundingModeOpcode != 0)
15435 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15436 X86::STATIC_ROUNDING::CUR_DIRECTION)
15437 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15438 dl, Op.getValueType(), Src, RoundingMode),
15439 Mask, PassThru, Subtarget, DAG);
15440 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15442 Mask, PassThru, Subtarget, DAG);
15444 case INTR_TYPE_1OP_MASK: {
15445 SDValue Src = Op.getOperand(1);
15446 SDValue PassThru = Op.getOperand(2);
15447 SDValue Mask = Op.getOperand(3);
15448 // We add rounding mode to the Node when
15449 // - RM Opcode is specified and
15450 // - RM is not "current direction".
15451 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15452 if (IntrWithRoundingModeOpcode != 0) {
15453 SDValue Rnd = Op.getOperand(4);
15454 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15455 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15456 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15457 dl, Op.getValueType(),
15459 Mask, PassThru, Subtarget, DAG);
15462 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15463 Mask, PassThru, Subtarget, DAG);
15465 case INTR_TYPE_SCALAR_MASK_RM: {
15466 SDValue Src1 = Op.getOperand(1);
15467 SDValue Src2 = Op.getOperand(2);
15468 SDValue Src0 = Op.getOperand(3);
15469 SDValue Mask = Op.getOperand(4);
15470 // There are 2 kinds of intrinsics in this group:
15471 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15472 // (2) With rounding mode and sae - 7 operands.
15473 if (Op.getNumOperands() == 6) {
15474 SDValue Sae = Op.getOperand(5);
15475 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15476 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15478 Mask, Src0, Subtarget, DAG);
15480 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15481 SDValue RoundingMode = Op.getOperand(5);
15482 SDValue Sae = Op.getOperand(6);
15483 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15484 RoundingMode, Sae),
15485 Mask, Src0, Subtarget, DAG);
15487 case INTR_TYPE_2OP_MASK: {
15488 SDValue Src1 = Op.getOperand(1);
15489 SDValue Src2 = Op.getOperand(2);
15490 SDValue PassThru = Op.getOperand(3);
15491 SDValue Mask = Op.getOperand(4);
15492 // We specify 2 possible opcodes for intrinsics with rounding modes.
15493 // First, we check if the intrinsic may have non-default rounding mode,
15494 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15495 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15496 if (IntrWithRoundingModeOpcode != 0) {
15497 SDValue Rnd = Op.getOperand(5);
15498 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15499 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15500 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15501 dl, Op.getValueType(),
15503 Mask, PassThru, Subtarget, DAG);
15506 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15508 Mask, PassThru, Subtarget, DAG);
15510 case INTR_TYPE_2OP_MASK_RM: {
15511 SDValue Src1 = Op.getOperand(1);
15512 SDValue Src2 = Op.getOperand(2);
15513 SDValue PassThru = Op.getOperand(3);
15514 SDValue Mask = Op.getOperand(4);
15515 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15516 // First, we check if the intrinsic have rounding mode (6 operands),
15517 // if not, we set rounding mode to "current".
15519 if (Op.getNumOperands() == 6)
15520 Rnd = Op.getOperand(5);
15522 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15523 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15525 Mask, PassThru, Subtarget, DAG);
15527 case INTR_TYPE_3OP_MASK_RM: {
15528 SDValue Src1 = Op.getOperand(1);
15529 SDValue Src2 = Op.getOperand(2);
15530 SDValue Imm = Op.getOperand(3);
15531 SDValue PassThru = Op.getOperand(4);
15532 SDValue Mask = Op.getOperand(5);
15533 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15534 // First, we check if the intrinsic have rounding mode (7 operands),
15535 // if not, we set rounding mode to "current".
15537 if (Op.getNumOperands() == 7)
15538 Rnd = Op.getOperand(6);
15540 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15541 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15542 Src1, Src2, Imm, Rnd),
15543 Mask, PassThru, Subtarget, DAG);
15545 case INTR_TYPE_3OP_MASK: {
15546 SDValue Src1 = Op.getOperand(1);
15547 SDValue Src2 = Op.getOperand(2);
15548 SDValue Src3 = Op.getOperand(3);
15549 SDValue PassThru = Op.getOperand(4);
15550 SDValue Mask = Op.getOperand(5);
15551 // We specify 2 possible opcodes for intrinsics with rounding modes.
15552 // First, we check if the intrinsic may have non-default rounding mode,
15553 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15554 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15555 if (IntrWithRoundingModeOpcode != 0) {
15556 SDValue Rnd = Op.getOperand(6);
15557 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15558 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15559 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15560 dl, Op.getValueType(),
15561 Src1, Src2, Src3, Rnd),
15562 Mask, PassThru, Subtarget, DAG);
15565 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15567 Mask, PassThru, Subtarget, DAG);
15569 case VPERM_3OP_MASKZ:
15570 case VPERM_3OP_MASK:
15573 case FMA_OP_MASK: {
15574 SDValue Src1 = Op.getOperand(1);
15575 SDValue Src2 = Op.getOperand(2);
15576 SDValue Src3 = Op.getOperand(3);
15577 SDValue Mask = Op.getOperand(4);
15578 EVT VT = Op.getValueType();
15579 SDValue PassThru = SDValue();
15581 // set PassThru element
15582 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15583 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15584 else if (IntrData->Type == FMA_OP_MASK3)
15589 // We specify 2 possible opcodes for intrinsics with rounding modes.
15590 // First, we check if the intrinsic may have non-default rounding mode,
15591 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15592 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15593 if (IntrWithRoundingModeOpcode != 0) {
15594 SDValue Rnd = Op.getOperand(5);
15595 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15596 X86::STATIC_ROUNDING::CUR_DIRECTION)
15597 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15598 dl, Op.getValueType(),
15599 Src1, Src2, Src3, Rnd),
15600 Mask, PassThru, Subtarget, DAG);
15602 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15603 dl, Op.getValueType(),
15605 Mask, PassThru, Subtarget, DAG);
15608 case CMP_MASK_CC: {
15609 // Comparison intrinsics with masks.
15610 // Example of transformation:
15611 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15612 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15614 // (v8i1 (insert_subvector undef,
15615 // (v2i1 (and (PCMPEQM %a, %b),
15616 // (extract_subvector
15617 // (v8i1 (bitcast %mask)), 0))), 0))))
15618 EVT VT = Op.getOperand(1).getValueType();
15619 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15620 VT.getVectorNumElements());
15621 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15622 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15623 Mask.getValueType().getSizeInBits());
15625 if (IntrData->Type == CMP_MASK_CC) {
15626 SDValue CC = Op.getOperand(3);
15627 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15628 // We specify 2 possible opcodes for intrinsics with rounding modes.
15629 // First, we check if the intrinsic may have non-default rounding mode,
15630 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15631 if (IntrData->Opc1 != 0) {
15632 SDValue Rnd = Op.getOperand(5);
15633 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15634 X86::STATIC_ROUNDING::CUR_DIRECTION)
15635 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15636 Op.getOperand(2), CC, Rnd);
15638 //default rounding mode
15640 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15641 Op.getOperand(2), CC);
15644 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15645 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15648 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15649 DAG.getTargetConstant(0, dl,
15652 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15653 DAG.getUNDEF(BitcastVT), CmpMask,
15654 DAG.getIntPtrConstant(0, dl));
15655 return DAG.getBitcast(Op.getValueType(), Res);
15657 case COMI: { // Comparison intrinsics
15658 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15659 SDValue LHS = Op.getOperand(1);
15660 SDValue RHS = Op.getOperand(2);
15661 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15662 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15663 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15664 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15665 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15666 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15669 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15670 Op.getOperand(1), Op.getOperand(2), DAG);
15672 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15673 Op.getSimpleValueType(),
15675 Op.getOperand(2), DAG),
15676 Op.getOperand(4), Op.getOperand(3), Subtarget,
15678 case COMPRESS_EXPAND_IN_REG: {
15679 SDValue Mask = Op.getOperand(3);
15680 SDValue DataToCompress = Op.getOperand(1);
15681 SDValue PassThru = Op.getOperand(2);
15682 if (isAllOnes(Mask)) // return data as is
15683 return Op.getOperand(1);
15685 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15687 Mask, PassThru, Subtarget, DAG);
15690 SDValue Mask = Op.getOperand(3);
15691 EVT VT = Op.getValueType();
15692 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15693 VT.getVectorNumElements());
15694 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15695 Mask.getValueType().getSizeInBits());
15697 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15698 DAG.getBitcast(BitcastVT, Mask),
15699 DAG.getIntPtrConstant(0, dl));
15700 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15709 default: return SDValue(); // Don't custom lower most intrinsics.
15711 case Intrinsic::x86_avx2_permd:
15712 case Intrinsic::x86_avx2_permps:
15713 // Operands intentionally swapped. Mask is last operand to intrinsic,
15714 // but second operand for node/instruction.
15715 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15716 Op.getOperand(2), Op.getOperand(1));
15718 // ptest and testp intrinsics. The intrinsic these come from are designed to
15719 // return an integer value, not just an instruction so lower it to the ptest
15720 // or testp pattern and a setcc for the result.
15721 case Intrinsic::x86_sse41_ptestz:
15722 case Intrinsic::x86_sse41_ptestc:
15723 case Intrinsic::x86_sse41_ptestnzc:
15724 case Intrinsic::x86_avx_ptestz_256:
15725 case Intrinsic::x86_avx_ptestc_256:
15726 case Intrinsic::x86_avx_ptestnzc_256:
15727 case Intrinsic::x86_avx_vtestz_ps:
15728 case Intrinsic::x86_avx_vtestc_ps:
15729 case Intrinsic::x86_avx_vtestnzc_ps:
15730 case Intrinsic::x86_avx_vtestz_pd:
15731 case Intrinsic::x86_avx_vtestc_pd:
15732 case Intrinsic::x86_avx_vtestnzc_pd:
15733 case Intrinsic::x86_avx_vtestz_ps_256:
15734 case Intrinsic::x86_avx_vtestc_ps_256:
15735 case Intrinsic::x86_avx_vtestnzc_ps_256:
15736 case Intrinsic::x86_avx_vtestz_pd_256:
15737 case Intrinsic::x86_avx_vtestc_pd_256:
15738 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15739 bool IsTestPacked = false;
15742 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15743 case Intrinsic::x86_avx_vtestz_ps:
15744 case Intrinsic::x86_avx_vtestz_pd:
15745 case Intrinsic::x86_avx_vtestz_ps_256:
15746 case Intrinsic::x86_avx_vtestz_pd_256:
15747 IsTestPacked = true; // Fallthrough
15748 case Intrinsic::x86_sse41_ptestz:
15749 case Intrinsic::x86_avx_ptestz_256:
15751 X86CC = X86::COND_E;
15753 case Intrinsic::x86_avx_vtestc_ps:
15754 case Intrinsic::x86_avx_vtestc_pd:
15755 case Intrinsic::x86_avx_vtestc_ps_256:
15756 case Intrinsic::x86_avx_vtestc_pd_256:
15757 IsTestPacked = true; // Fallthrough
15758 case Intrinsic::x86_sse41_ptestc:
15759 case Intrinsic::x86_avx_ptestc_256:
15761 X86CC = X86::COND_B;
15763 case Intrinsic::x86_avx_vtestnzc_ps:
15764 case Intrinsic::x86_avx_vtestnzc_pd:
15765 case Intrinsic::x86_avx_vtestnzc_ps_256:
15766 case Intrinsic::x86_avx_vtestnzc_pd_256:
15767 IsTestPacked = true; // Fallthrough
15768 case Intrinsic::x86_sse41_ptestnzc:
15769 case Intrinsic::x86_avx_ptestnzc_256:
15771 X86CC = X86::COND_A;
15775 SDValue LHS = Op.getOperand(1);
15776 SDValue RHS = Op.getOperand(2);
15777 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15778 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15779 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15780 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15781 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15783 case Intrinsic::x86_avx512_kortestz_w:
15784 case Intrinsic::x86_avx512_kortestc_w: {
15785 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15786 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15787 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15788 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15789 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15790 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15791 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15794 case Intrinsic::x86_sse42_pcmpistria128:
15795 case Intrinsic::x86_sse42_pcmpestria128:
15796 case Intrinsic::x86_sse42_pcmpistric128:
15797 case Intrinsic::x86_sse42_pcmpestric128:
15798 case Intrinsic::x86_sse42_pcmpistrio128:
15799 case Intrinsic::x86_sse42_pcmpestrio128:
15800 case Intrinsic::x86_sse42_pcmpistris128:
15801 case Intrinsic::x86_sse42_pcmpestris128:
15802 case Intrinsic::x86_sse42_pcmpistriz128:
15803 case Intrinsic::x86_sse42_pcmpestriz128: {
15807 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15808 case Intrinsic::x86_sse42_pcmpistria128:
15809 Opcode = X86ISD::PCMPISTRI;
15810 X86CC = X86::COND_A;
15812 case Intrinsic::x86_sse42_pcmpestria128:
15813 Opcode = X86ISD::PCMPESTRI;
15814 X86CC = X86::COND_A;
15816 case Intrinsic::x86_sse42_pcmpistric128:
15817 Opcode = X86ISD::PCMPISTRI;
15818 X86CC = X86::COND_B;
15820 case Intrinsic::x86_sse42_pcmpestric128:
15821 Opcode = X86ISD::PCMPESTRI;
15822 X86CC = X86::COND_B;
15824 case Intrinsic::x86_sse42_pcmpistrio128:
15825 Opcode = X86ISD::PCMPISTRI;
15826 X86CC = X86::COND_O;
15828 case Intrinsic::x86_sse42_pcmpestrio128:
15829 Opcode = X86ISD::PCMPESTRI;
15830 X86CC = X86::COND_O;
15832 case Intrinsic::x86_sse42_pcmpistris128:
15833 Opcode = X86ISD::PCMPISTRI;
15834 X86CC = X86::COND_S;
15836 case Intrinsic::x86_sse42_pcmpestris128:
15837 Opcode = X86ISD::PCMPESTRI;
15838 X86CC = X86::COND_S;
15840 case Intrinsic::x86_sse42_pcmpistriz128:
15841 Opcode = X86ISD::PCMPISTRI;
15842 X86CC = X86::COND_E;
15844 case Intrinsic::x86_sse42_pcmpestriz128:
15845 Opcode = X86ISD::PCMPESTRI;
15846 X86CC = X86::COND_E;
15849 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15850 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15851 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15852 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15853 DAG.getConstant(X86CC, dl, MVT::i8),
15854 SDValue(PCMP.getNode(), 1));
15855 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15858 case Intrinsic::x86_sse42_pcmpistri128:
15859 case Intrinsic::x86_sse42_pcmpestri128: {
15861 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15862 Opcode = X86ISD::PCMPISTRI;
15864 Opcode = X86ISD::PCMPESTRI;
15866 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15867 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15868 return DAG.getNode(Opcode, dl, VTs, NewOps);
15871 case Intrinsic::x86_seh_lsda: {
15872 // Compute the symbol for the LSDA. We know it'll get emitted later.
15873 MachineFunction &MF = DAG.getMachineFunction();
15874 SDValue Op1 = Op.getOperand(1);
15875 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15876 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15877 GlobalValue::getRealLinkageName(Fn->getName()));
15879 // Generate a simple absolute symbol reference. This intrinsic is only
15880 // supported on 32-bit Windows, which isn't PIC.
15881 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15882 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15885 case Intrinsic::x86_seh_recoverfp: {
15886 SDValue FnOp = Op.getOperand(1);
15887 SDValue IncomingFPOp = Op.getOperand(2);
15888 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15889 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15891 report_fatal_error(
15892 "llvm.x86.seh.recoverfp must take a function as the first argument");
15893 return recoverFramePointer(DAG, Fn, IncomingFPOp);
15896 case Intrinsic::localaddress: {
15897 // Returns one of the stack, base, or frame pointer registers, depending on
15898 // which is used to reference local variables.
15899 MachineFunction &MF = DAG.getMachineFunction();
15900 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15902 if (RegInfo->hasBasePointer(MF))
15903 Reg = RegInfo->getBaseRegister();
15904 else // This function handles the SP or FP case.
15905 Reg = RegInfo->getPtrSizedFrameRegister(MF);
15906 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15911 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15912 SDValue Src, SDValue Mask, SDValue Base,
15913 SDValue Index, SDValue ScaleOp, SDValue Chain,
15914 const X86Subtarget * Subtarget) {
15916 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15918 llvm_unreachable("Invalid scale type");
15919 unsigned ScaleVal = C->getZExtValue();
15920 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15921 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15923 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15924 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15925 Index.getSimpleValueType().getVectorNumElements());
15927 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15929 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15931 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15932 Mask.getValueType().getSizeInBits());
15934 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15935 // are extracted by EXTRACT_SUBVECTOR.
15936 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15937 DAG.getBitcast(BitcastVT, Mask),
15938 DAG.getIntPtrConstant(0, dl));
15940 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15941 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15942 SDValue Segment = DAG.getRegister(0, MVT::i32);
15943 if (Src.getOpcode() == ISD::UNDEF)
15944 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15945 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15946 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15947 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15948 return DAG.getMergeValues(RetOps, dl);
15951 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15952 SDValue Src, SDValue Mask, SDValue Base,
15953 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15955 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15957 llvm_unreachable("Invalid scale type");
15958 unsigned ScaleVal = C->getZExtValue();
15959 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15960 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15962 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15963 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15964 SDValue Segment = DAG.getRegister(0, MVT::i32);
15965 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15966 Index.getSimpleValueType().getVectorNumElements());
15968 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15970 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15972 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15973 Mask.getValueType().getSizeInBits());
15975 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15976 // are extracted by EXTRACT_SUBVECTOR.
15977 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15978 DAG.getBitcast(BitcastVT, Mask),
15979 DAG.getIntPtrConstant(0, dl));
15981 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15982 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15983 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15984 return SDValue(Res, 1);
15987 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15988 SDValue Mask, SDValue Base, SDValue Index,
15989 SDValue ScaleOp, SDValue Chain) {
15991 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15992 assert(C && "Invalid scale type");
15993 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15994 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15995 SDValue Segment = DAG.getRegister(0, MVT::i32);
15997 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15999 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16001 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16003 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16004 //SDVTList VTs = DAG.getVTList(MVT::Other);
16005 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16006 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16007 return SDValue(Res, 0);
16010 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16011 // read performance monitor counters (x86_rdpmc).
16012 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16013 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16014 SmallVectorImpl<SDValue> &Results) {
16015 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16016 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16019 // The ECX register is used to select the index of the performance counter
16021 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16023 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16025 // Reads the content of a 64-bit performance counter and returns it in the
16026 // registers EDX:EAX.
16027 if (Subtarget->is64Bit()) {
16028 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16029 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16032 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16033 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16036 Chain = HI.getValue(1);
16038 if (Subtarget->is64Bit()) {
16039 // The EAX register is loaded with the low-order 32 bits. The EDX register
16040 // is loaded with the supported high-order bits of the counter.
16041 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16042 DAG.getConstant(32, DL, MVT::i8));
16043 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16044 Results.push_back(Chain);
16048 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16049 SDValue Ops[] = { LO, HI };
16050 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16051 Results.push_back(Pair);
16052 Results.push_back(Chain);
16055 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16056 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16057 // also used to custom lower READCYCLECOUNTER nodes.
16058 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16059 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16060 SmallVectorImpl<SDValue> &Results) {
16061 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16062 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16065 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16066 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16067 // and the EAX register is loaded with the low-order 32 bits.
16068 if (Subtarget->is64Bit()) {
16069 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16070 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16073 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16074 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16077 SDValue Chain = HI.getValue(1);
16079 if (Opcode == X86ISD::RDTSCP_DAG) {
16080 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16082 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16083 // the ECX register. Add 'ecx' explicitly to the chain.
16084 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16086 // Explicitly store the content of ECX at the location passed in input
16087 // to the 'rdtscp' intrinsic.
16088 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16089 MachinePointerInfo(), false, false, 0);
16092 if (Subtarget->is64Bit()) {
16093 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16094 // the EAX register is loaded with the low-order 32 bits.
16095 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16096 DAG.getConstant(32, DL, MVT::i8));
16097 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16098 Results.push_back(Chain);
16102 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16103 SDValue Ops[] = { LO, HI };
16104 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16105 Results.push_back(Pair);
16106 Results.push_back(Chain);
16109 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16110 SelectionDAG &DAG) {
16111 SmallVector<SDValue, 2> Results;
16113 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16115 return DAG.getMergeValues(Results, DL);
16118 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16119 SelectionDAG &DAG) {
16120 MachineFunction &MF = DAG.getMachineFunction();
16121 const Function *Fn = MF.getFunction();
16123 SDValue Chain = Op.getOperand(0);
16125 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16126 "using llvm.x86.seh.restoreframe requires a frame pointer");
16128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16129 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16131 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16132 unsigned FrameReg =
16133 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16134 unsigned SPReg = RegInfo->getStackRegister();
16135 unsigned SlotSize = RegInfo->getSlotSize();
16137 // Get incoming EBP.
16138 SDValue IncomingEBP =
16139 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16141 // SP is saved in the first field of every registration node, so load
16142 // [EBP-RegNodeSize] into SP.
16143 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16144 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16145 DAG.getConstant(-RegNodeSize, dl, VT));
16147 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16148 false, VT.getScalarSizeInBits() / 8);
16149 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16151 if (!RegInfo->needsStackRealignment(MF)) {
16152 // Adjust EBP to point back to the original frame position.
16153 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16154 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16156 assert(RegInfo->hasBasePointer(MF) &&
16157 "functions with Win32 EH must use frame or base pointer register");
16159 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16160 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16161 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16163 // Reload the spilled EBP value, now that the stack and base pointers are
16165 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16166 X86FI->setHasSEHFramePtrSave(true);
16167 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16168 X86FI->setSEHFramePtrSaveIndex(FI);
16169 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16170 MachinePointerInfo(), false, false, false,
16171 VT.getScalarSizeInBits() / 8);
16172 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16178 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16179 /// return truncate Store/MaskedStore Node
16180 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16184 SDValue Mask = Op.getOperand(4);
16185 SDValue DataToTruncate = Op.getOperand(3);
16186 SDValue Addr = Op.getOperand(2);
16187 SDValue Chain = Op.getOperand(0);
16189 EVT VT = DataToTruncate.getValueType();
16190 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16191 ElementType, VT.getVectorNumElements());
16193 if (isAllOnes(Mask)) // return just a truncate store
16194 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16195 MachinePointerInfo(), SVT, false, false,
16196 SVT.getScalarSizeInBits()/8);
16198 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16199 MVT::i1, VT.getVectorNumElements());
16200 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16201 Mask.getValueType().getSizeInBits());
16202 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16203 // are extracted by EXTRACT_SUBVECTOR.
16204 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16205 DAG.getBitcast(BitcastVT, Mask),
16206 DAG.getIntPtrConstant(0, dl));
16208 MachineMemOperand *MMO = DAG.getMachineFunction().
16209 getMachineMemOperand(MachinePointerInfo(),
16210 MachineMemOperand::MOStore, SVT.getStoreSize(),
16211 SVT.getScalarSizeInBits()/8);
16213 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16214 VMask, SVT, MMO, true);
16217 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16218 SelectionDAG &DAG) {
16219 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16221 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16223 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16224 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16229 switch(IntrData->Type) {
16231 llvm_unreachable("Unknown Intrinsic Type");
16235 // Emit the node with the right value type.
16236 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16237 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16239 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16240 // Otherwise return the value from Rand, which is always 0, casted to i32.
16241 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16242 DAG.getConstant(1, dl, Op->getValueType(1)),
16243 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16244 SDValue(Result.getNode(), 1) };
16245 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16246 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16249 // Return { result, isValid, chain }.
16250 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16251 SDValue(Result.getNode(), 2));
16254 //gather(v1, mask, index, base, scale);
16255 SDValue Chain = Op.getOperand(0);
16256 SDValue Src = Op.getOperand(2);
16257 SDValue Base = Op.getOperand(3);
16258 SDValue Index = Op.getOperand(4);
16259 SDValue Mask = Op.getOperand(5);
16260 SDValue Scale = Op.getOperand(6);
16261 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16265 //scatter(base, mask, index, v1, scale);
16266 SDValue Chain = Op.getOperand(0);
16267 SDValue Base = Op.getOperand(2);
16268 SDValue Mask = Op.getOperand(3);
16269 SDValue Index = Op.getOperand(4);
16270 SDValue Src = Op.getOperand(5);
16271 SDValue Scale = Op.getOperand(6);
16272 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16276 SDValue Hint = Op.getOperand(6);
16277 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16278 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16279 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16280 SDValue Chain = Op.getOperand(0);
16281 SDValue Mask = Op.getOperand(2);
16282 SDValue Index = Op.getOperand(3);
16283 SDValue Base = Op.getOperand(4);
16284 SDValue Scale = Op.getOperand(5);
16285 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16287 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16289 SmallVector<SDValue, 2> Results;
16290 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16292 return DAG.getMergeValues(Results, dl);
16294 // Read Performance Monitoring Counters.
16296 SmallVector<SDValue, 2> Results;
16297 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16298 return DAG.getMergeValues(Results, dl);
16300 // XTEST intrinsics.
16302 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16303 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16304 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16305 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16307 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16308 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16309 Ret, SDValue(InTrans.getNode(), 1));
16313 SmallVector<SDValue, 2> Results;
16314 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16315 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16316 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16317 DAG.getConstant(-1, dl, MVT::i8));
16318 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16319 Op.getOperand(4), GenCF.getValue(1));
16320 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16321 Op.getOperand(5), MachinePointerInfo(),
16323 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16324 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16326 Results.push_back(SetCC);
16327 Results.push_back(Store);
16328 return DAG.getMergeValues(Results, dl);
16330 case COMPRESS_TO_MEM: {
16332 SDValue Mask = Op.getOperand(4);
16333 SDValue DataToCompress = Op.getOperand(3);
16334 SDValue Addr = Op.getOperand(2);
16335 SDValue Chain = Op.getOperand(0);
16337 EVT VT = DataToCompress.getValueType();
16338 if (isAllOnes(Mask)) // return just a store
16339 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16340 MachinePointerInfo(), false, false,
16341 VT.getScalarSizeInBits()/8);
16343 SDValue Compressed =
16344 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16345 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16346 return DAG.getStore(Chain, dl, Compressed, Addr,
16347 MachinePointerInfo(), false, false,
16348 VT.getScalarSizeInBits()/8);
16350 case TRUNCATE_TO_MEM_VI8:
16351 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16352 case TRUNCATE_TO_MEM_VI16:
16353 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16354 case TRUNCATE_TO_MEM_VI32:
16355 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16356 case EXPAND_FROM_MEM: {
16358 SDValue Mask = Op.getOperand(4);
16359 SDValue PassThru = Op.getOperand(3);
16360 SDValue Addr = Op.getOperand(2);
16361 SDValue Chain = Op.getOperand(0);
16362 EVT VT = Op.getValueType();
16364 if (isAllOnes(Mask)) // return just a load
16365 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16366 false, VT.getScalarSizeInBits()/8);
16368 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16369 false, false, false,
16370 VT.getScalarSizeInBits()/8);
16372 SDValue Results[] = {
16373 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16374 Mask, PassThru, Subtarget, DAG), Chain};
16375 return DAG.getMergeValues(Results, dl);
16380 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16381 SelectionDAG &DAG) const {
16382 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16383 MFI->setReturnAddressIsTaken(true);
16385 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16388 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16390 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16393 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16394 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16395 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16396 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16397 DAG.getNode(ISD::ADD, dl, PtrVT,
16398 FrameAddr, Offset),
16399 MachinePointerInfo(), false, false, false, 0);
16402 // Just load the return address.
16403 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16404 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16405 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16408 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16409 MachineFunction &MF = DAG.getMachineFunction();
16410 MachineFrameInfo *MFI = MF.getFrameInfo();
16411 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16412 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16413 EVT VT = Op.getValueType();
16415 MFI->setFrameAddressIsTaken(true);
16417 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16418 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16419 // is not possible to crawl up the stack without looking at the unwind codes
16421 int FrameAddrIndex = FuncInfo->getFAIndex();
16422 if (!FrameAddrIndex) {
16423 // Set up a frame object for the return address.
16424 unsigned SlotSize = RegInfo->getSlotSize();
16425 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16426 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16427 FuncInfo->setFAIndex(FrameAddrIndex);
16429 return DAG.getFrameIndex(FrameAddrIndex, VT);
16432 unsigned FrameReg =
16433 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16434 SDLoc dl(Op); // FIXME probably not meaningful
16435 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16436 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16437 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16438 "Invalid Frame Register!");
16439 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16441 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16442 MachinePointerInfo(),
16443 false, false, false, 0);
16447 // FIXME? Maybe this could be a TableGen attribute on some registers and
16448 // this table could be generated automatically from RegInfo.
16449 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16450 SelectionDAG &DAG) const {
16451 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16452 const MachineFunction &MF = DAG.getMachineFunction();
16454 unsigned Reg = StringSwitch<unsigned>(RegName)
16455 .Case("esp", X86::ESP)
16456 .Case("rsp", X86::RSP)
16457 .Case("ebp", X86::EBP)
16458 .Case("rbp", X86::RBP)
16461 if (Reg == X86::EBP || Reg == X86::RBP) {
16462 if (!TFI.hasFP(MF))
16463 report_fatal_error("register " + StringRef(RegName) +
16464 " is allocatable: function has no frame pointer");
16467 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16468 unsigned FrameReg =
16469 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16470 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16471 "Invalid Frame Register!");
16479 report_fatal_error("Invalid register name global variable");
16482 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16483 SelectionDAG &DAG) const {
16484 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16485 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16488 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16489 SDValue Chain = Op.getOperand(0);
16490 SDValue Offset = Op.getOperand(1);
16491 SDValue Handler = Op.getOperand(2);
16494 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16495 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16496 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16497 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16498 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16499 "Invalid Frame Register!");
16500 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16501 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16503 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16504 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16506 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16507 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16509 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16511 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16512 DAG.getRegister(StoreAddrReg, PtrVT));
16515 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16516 SelectionDAG &DAG) const {
16518 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16519 DAG.getVTList(MVT::i32, MVT::Other),
16520 Op.getOperand(0), Op.getOperand(1));
16523 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16524 SelectionDAG &DAG) const {
16526 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16527 Op.getOperand(0), Op.getOperand(1));
16530 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16531 return Op.getOperand(0);
16534 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16535 SelectionDAG &DAG) const {
16536 SDValue Root = Op.getOperand(0);
16537 SDValue Trmp = Op.getOperand(1); // trampoline
16538 SDValue FPtr = Op.getOperand(2); // nested function
16539 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16542 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16543 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16545 if (Subtarget->is64Bit()) {
16546 SDValue OutChains[6];
16548 // Large code-model.
16549 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16550 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16552 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16553 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16555 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16557 // Load the pointer to the nested function into R11.
16558 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16559 SDValue Addr = Trmp;
16560 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16561 Addr, MachinePointerInfo(TrmpAddr),
16564 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16565 DAG.getConstant(2, dl, MVT::i64));
16566 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16567 MachinePointerInfo(TrmpAddr, 2),
16570 // Load the 'nest' parameter value into R10.
16571 // R10 is specified in X86CallingConv.td
16572 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16573 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16574 DAG.getConstant(10, dl, MVT::i64));
16575 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16576 Addr, MachinePointerInfo(TrmpAddr, 10),
16579 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16580 DAG.getConstant(12, dl, MVT::i64));
16581 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16582 MachinePointerInfo(TrmpAddr, 12),
16585 // Jump to the nested function.
16586 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16587 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16588 DAG.getConstant(20, dl, MVT::i64));
16589 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16590 Addr, MachinePointerInfo(TrmpAddr, 20),
16593 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16594 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16595 DAG.getConstant(22, dl, MVT::i64));
16596 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16597 Addr, MachinePointerInfo(TrmpAddr, 22),
16600 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16602 const Function *Func =
16603 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16604 CallingConv::ID CC = Func->getCallingConv();
16609 llvm_unreachable("Unsupported calling convention");
16610 case CallingConv::C:
16611 case CallingConv::X86_StdCall: {
16612 // Pass 'nest' parameter in ECX.
16613 // Must be kept in sync with X86CallingConv.td
16614 NestReg = X86::ECX;
16616 // Check that ECX wasn't needed by an 'inreg' parameter.
16617 FunctionType *FTy = Func->getFunctionType();
16618 const AttributeSet &Attrs = Func->getAttributes();
16620 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16621 unsigned InRegCount = 0;
16624 for (FunctionType::param_iterator I = FTy->param_begin(),
16625 E = FTy->param_end(); I != E; ++I, ++Idx)
16626 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16627 auto &DL = DAG.getDataLayout();
16628 // FIXME: should only count parameters that are lowered to integers.
16629 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16632 if (InRegCount > 2) {
16633 report_fatal_error("Nest register in use - reduce number of inreg"
16639 case CallingConv::X86_FastCall:
16640 case CallingConv::X86_ThisCall:
16641 case CallingConv::Fast:
16642 // Pass 'nest' parameter in EAX.
16643 // Must be kept in sync with X86CallingConv.td
16644 NestReg = X86::EAX;
16648 SDValue OutChains[4];
16649 SDValue Addr, Disp;
16651 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16652 DAG.getConstant(10, dl, MVT::i32));
16653 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16655 // This is storing the opcode for MOV32ri.
16656 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16657 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16658 OutChains[0] = DAG.getStore(Root, dl,
16659 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16660 Trmp, MachinePointerInfo(TrmpAddr),
16663 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16664 DAG.getConstant(1, dl, MVT::i32));
16665 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16666 MachinePointerInfo(TrmpAddr, 1),
16669 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16670 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16671 DAG.getConstant(5, dl, MVT::i32));
16672 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16673 Addr, MachinePointerInfo(TrmpAddr, 5),
16676 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16677 DAG.getConstant(6, dl, MVT::i32));
16678 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16679 MachinePointerInfo(TrmpAddr, 6),
16682 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16686 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16687 SelectionDAG &DAG) const {
16689 The rounding mode is in bits 11:10 of FPSR, and has the following
16691 00 Round to nearest
16696 FLT_ROUNDS, on the other hand, expects the following:
16703 To perform the conversion, we do:
16704 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16707 MachineFunction &MF = DAG.getMachineFunction();
16708 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16709 unsigned StackAlignment = TFI.getStackAlignment();
16710 MVT VT = Op.getSimpleValueType();
16713 // Save FP Control Word to stack slot
16714 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16715 SDValue StackSlot =
16716 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16718 MachineMemOperand *MMO =
16719 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16720 MachineMemOperand::MOStore, 2, 2);
16722 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16723 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16724 DAG.getVTList(MVT::Other),
16725 Ops, MVT::i16, MMO);
16727 // Load FP Control Word from stack slot
16728 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16729 MachinePointerInfo(), false, false, false, 0);
16731 // Transform as necessary
16733 DAG.getNode(ISD::SRL, DL, MVT::i16,
16734 DAG.getNode(ISD::AND, DL, MVT::i16,
16735 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16736 DAG.getConstant(11, DL, MVT::i8));
16738 DAG.getNode(ISD::SRL, DL, MVT::i16,
16739 DAG.getNode(ISD::AND, DL, MVT::i16,
16740 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16741 DAG.getConstant(9, DL, MVT::i8));
16744 DAG.getNode(ISD::AND, DL, MVT::i16,
16745 DAG.getNode(ISD::ADD, DL, MVT::i16,
16746 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16747 DAG.getConstant(1, DL, MVT::i16)),
16748 DAG.getConstant(3, DL, MVT::i16));
16750 return DAG.getNode((VT.getSizeInBits() < 16 ?
16751 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16754 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16755 MVT VT = Op.getSimpleValueType();
16757 unsigned NumBits = VT.getSizeInBits();
16760 Op = Op.getOperand(0);
16761 if (VT == MVT::i8) {
16762 // Zero extend to i32 since there is not an i8 bsr.
16764 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16767 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16768 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16769 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16771 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16774 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16775 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16778 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16780 // Finally xor with NumBits-1.
16781 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16782 DAG.getConstant(NumBits - 1, dl, OpVT));
16785 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16789 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16790 MVT VT = Op.getSimpleValueType();
16792 unsigned NumBits = VT.getSizeInBits();
16795 Op = Op.getOperand(0);
16796 if (VT == MVT::i8) {
16797 // Zero extend to i32 since there is not an i8 bsr.
16799 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16802 // Issue a bsr (scan bits in reverse).
16803 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16804 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16806 // And xor with NumBits-1.
16807 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16808 DAG.getConstant(NumBits - 1, dl, OpVT));
16811 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16815 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16816 MVT VT = Op.getSimpleValueType();
16817 unsigned NumBits = VT.getSizeInBits();
16819 Op = Op.getOperand(0);
16821 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16822 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16823 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16825 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16828 DAG.getConstant(NumBits, dl, VT),
16829 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16832 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16835 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16836 // ones, and then concatenate the result back.
16837 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16838 MVT VT = Op.getSimpleValueType();
16840 assert(VT.is256BitVector() && VT.isInteger() &&
16841 "Unsupported value type for operation");
16843 unsigned NumElems = VT.getVectorNumElements();
16846 // Extract the LHS vectors
16847 SDValue LHS = Op.getOperand(0);
16848 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16849 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16851 // Extract the RHS vectors
16852 SDValue RHS = Op.getOperand(1);
16853 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16854 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16856 MVT EltVT = VT.getVectorElementType();
16857 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16859 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16860 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16861 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16864 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16865 if (Op.getValueType() == MVT::i1)
16866 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16867 Op.getOperand(0), Op.getOperand(1));
16868 assert(Op.getSimpleValueType().is256BitVector() &&
16869 Op.getSimpleValueType().isInteger() &&
16870 "Only handle AVX 256-bit vector integer operation");
16871 return Lower256IntArith(Op, DAG);
16874 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16875 if (Op.getValueType() == MVT::i1)
16876 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16877 Op.getOperand(0), Op.getOperand(1));
16878 assert(Op.getSimpleValueType().is256BitVector() &&
16879 Op.getSimpleValueType().isInteger() &&
16880 "Only handle AVX 256-bit vector integer operation");
16881 return Lower256IntArith(Op, DAG);
16884 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16885 SelectionDAG &DAG) {
16887 MVT VT = Op.getSimpleValueType();
16890 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16892 // Decompose 256-bit ops into smaller 128-bit ops.
16893 if (VT.is256BitVector() && !Subtarget->hasInt256())
16894 return Lower256IntArith(Op, DAG);
16896 SDValue A = Op.getOperand(0);
16897 SDValue B = Op.getOperand(1);
16899 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16900 // pairs, multiply and truncate.
16901 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16902 if (Subtarget->hasInt256()) {
16903 if (VT == MVT::v32i8) {
16904 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16905 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16906 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16907 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16908 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16909 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16910 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16911 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16912 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16913 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16916 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16917 return DAG.getNode(
16918 ISD::TRUNCATE, dl, VT,
16919 DAG.getNode(ISD::MUL, dl, ExVT,
16920 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16921 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16924 assert(VT == MVT::v16i8 &&
16925 "Pre-AVX2 support only supports v16i8 multiplication");
16926 MVT ExVT = MVT::v8i16;
16928 // Extract the lo parts and sign extend to i16
16930 if (Subtarget->hasSSE41()) {
16931 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16932 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16934 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16935 -1, 4, -1, 5, -1, 6, -1, 7};
16936 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16937 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16938 ALo = DAG.getBitcast(ExVT, ALo);
16939 BLo = DAG.getBitcast(ExVT, BLo);
16940 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16941 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16944 // Extract the hi parts and sign extend to i16
16946 if (Subtarget->hasSSE41()) {
16947 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16948 -1, -1, -1, -1, -1, -1, -1, -1};
16949 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16950 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16951 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16952 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16954 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16955 -1, 12, -1, 13, -1, 14, -1, 15};
16956 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16957 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16958 AHi = DAG.getBitcast(ExVT, AHi);
16959 BHi = DAG.getBitcast(ExVT, BHi);
16960 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16961 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16964 // Multiply, mask the lower 8bits of the lo/hi results and pack
16965 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16966 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16967 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16968 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16969 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16972 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16973 if (VT == MVT::v4i32) {
16974 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16975 "Should not custom lower when pmuldq is available!");
16977 // Extract the odd parts.
16978 static const int UnpackMask[] = { 1, -1, 3, -1 };
16979 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16980 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16982 // Multiply the even parts.
16983 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16984 // Now multiply odd parts.
16985 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16987 Evens = DAG.getBitcast(VT, Evens);
16988 Odds = DAG.getBitcast(VT, Odds);
16990 // Merge the two vectors back together with a shuffle. This expands into 2
16992 static const int ShufMask[] = { 0, 4, 2, 6 };
16993 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16996 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16997 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16999 // Ahi = psrlqi(a, 32);
17000 // Bhi = psrlqi(b, 32);
17002 // AloBlo = pmuludq(a, b);
17003 // AloBhi = pmuludq(a, Bhi);
17004 // AhiBlo = pmuludq(Ahi, b);
17006 // AloBhi = psllqi(AloBhi, 32);
17007 // AhiBlo = psllqi(AhiBlo, 32);
17008 // return AloBlo + AloBhi + AhiBlo;
17010 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17011 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17013 SDValue AhiBlo = Ahi;
17014 SDValue AloBhi = Bhi;
17015 // Bit cast to 32-bit vectors for MULUDQ
17016 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17017 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17018 A = DAG.getBitcast(MulVT, A);
17019 B = DAG.getBitcast(MulVT, B);
17020 Ahi = DAG.getBitcast(MulVT, Ahi);
17021 Bhi = DAG.getBitcast(MulVT, Bhi);
17023 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17024 // After shifting right const values the result may be all-zero.
17025 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17026 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17027 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17029 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17030 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17031 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17034 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17035 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17038 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17039 assert(Subtarget->isTargetWin64() && "Unexpected target");
17040 EVT VT = Op.getValueType();
17041 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17042 "Unexpected return type for lowering");
17046 switch (Op->getOpcode()) {
17047 default: llvm_unreachable("Unexpected request for libcall!");
17048 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17049 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17050 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17051 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17052 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17053 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17057 SDValue InChain = DAG.getEntryNode();
17059 TargetLowering::ArgListTy Args;
17060 TargetLowering::ArgListEntry Entry;
17061 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17062 EVT ArgVT = Op->getOperand(i).getValueType();
17063 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17064 "Unexpected argument type for lowering");
17065 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17066 Entry.Node = StackPtr;
17067 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17069 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17070 Entry.Ty = PointerType::get(ArgTy,0);
17071 Entry.isSExt = false;
17072 Entry.isZExt = false;
17073 Args.push_back(Entry);
17076 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17077 getPointerTy(DAG.getDataLayout()));
17079 TargetLowering::CallLoweringInfo CLI(DAG);
17080 CLI.setDebugLoc(dl).setChain(InChain)
17081 .setCallee(getLibcallCallingConv(LC),
17082 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17083 Callee, std::move(Args), 0)
17084 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17086 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17087 return DAG.getBitcast(VT, CallInfo.first);
17090 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17091 SelectionDAG &DAG) {
17092 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17093 EVT VT = Op0.getValueType();
17096 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17097 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17099 // PMULxD operations multiply each even value (starting at 0) of LHS with
17100 // the related value of RHS and produce a widen result.
17101 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17102 // => <2 x i64> <ae|cg>
17104 // In other word, to have all the results, we need to perform two PMULxD:
17105 // 1. one with the even values.
17106 // 2. one with the odd values.
17107 // To achieve #2, with need to place the odd values at an even position.
17109 // Place the odd value at an even position (basically, shift all values 1
17110 // step to the left):
17111 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17112 // <a|b|c|d> => <b|undef|d|undef>
17113 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17114 // <e|f|g|h> => <f|undef|h|undef>
17115 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17117 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17119 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17120 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17122 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17123 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17124 // => <2 x i64> <ae|cg>
17125 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17126 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17127 // => <2 x i64> <bf|dh>
17128 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17130 // Shuffle it back into the right order.
17131 SDValue Highs, Lows;
17132 if (VT == MVT::v8i32) {
17133 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17134 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17135 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17136 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17138 const int HighMask[] = {1, 5, 3, 7};
17139 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17140 const int LowMask[] = {0, 4, 2, 6};
17141 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17144 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17145 // unsigned multiply.
17146 if (IsSigned && !Subtarget->hasSSE41()) {
17147 SDValue ShAmt = DAG.getConstant(
17149 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17150 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17151 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17152 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17153 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17155 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17156 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17159 // The first result of MUL_LOHI is actually the low value, followed by the
17161 SDValue Ops[] = {Lows, Highs};
17162 return DAG.getMergeValues(Ops, dl);
17165 // Return true if the required (according to Opcode) shift-imm form is natively
17166 // supported by the Subtarget
17167 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17169 if (VT.getScalarSizeInBits() < 16)
17172 if (VT.is512BitVector() &&
17173 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17176 bool LShift = VT.is128BitVector() ||
17177 (VT.is256BitVector() && Subtarget->hasInt256());
17179 bool AShift = LShift && (Subtarget->hasVLX() ||
17180 (VT != MVT::v2i64 && VT != MVT::v4i64));
17181 return (Opcode == ISD::SRA) ? AShift : LShift;
17184 // The shift amount is a variable, but it is the same for all vector lanes.
17185 // These instructions are defined together with shift-immediate.
17187 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17189 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17192 // Return true if the required (according to Opcode) variable-shift form is
17193 // natively supported by the Subtarget
17194 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17197 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17200 // vXi16 supported only on AVX-512, BWI
17201 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17204 if (VT.is512BitVector() || Subtarget->hasVLX())
17207 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17208 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17209 return (Opcode == ISD::SRA) ? AShift : LShift;
17212 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17213 const X86Subtarget *Subtarget) {
17214 MVT VT = Op.getSimpleValueType();
17216 SDValue R = Op.getOperand(0);
17217 SDValue Amt = Op.getOperand(1);
17219 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17220 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17222 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17223 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17224 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17225 SDValue Ex = DAG.getBitcast(ExVT, R);
17227 if (ShiftAmt >= 32) {
17228 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17230 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17231 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17232 ShiftAmt - 32, DAG);
17233 if (VT == MVT::v2i64)
17234 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17235 if (VT == MVT::v4i64)
17236 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17237 {9, 1, 11, 3, 13, 5, 15, 7});
17239 // SRA upper i32, SHL whole i64 and select lower i32.
17240 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17243 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17244 Lower = DAG.getBitcast(ExVT, Lower);
17245 if (VT == MVT::v2i64)
17246 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17247 if (VT == MVT::v4i64)
17248 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17249 {8, 1, 10, 3, 12, 5, 14, 7});
17251 return DAG.getBitcast(VT, Ex);
17254 // Optimize shl/srl/sra with constant shift amount.
17255 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17256 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17257 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17259 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17260 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17262 // i64 SRA needs to be performed as partial shifts.
17263 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17264 Op.getOpcode() == ISD::SRA)
17265 return ArithmeticShiftRight64(ShiftAmt);
17267 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17268 unsigned NumElts = VT.getVectorNumElements();
17269 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17271 if (Op.getOpcode() == ISD::SHL) {
17272 // Simple i8 add case
17274 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17276 // Make a large shift.
17277 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17279 SHL = DAG.getBitcast(VT, SHL);
17280 // Zero out the rightmost bits.
17281 SmallVector<SDValue, 32> V(
17282 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17283 return DAG.getNode(ISD::AND, dl, VT, SHL,
17284 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17286 if (Op.getOpcode() == ISD::SRL) {
17287 // Make a large shift.
17288 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17290 SRL = DAG.getBitcast(VT, SRL);
17291 // Zero out the leftmost bits.
17292 SmallVector<SDValue, 32> V(
17293 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17294 return DAG.getNode(ISD::AND, dl, VT, SRL,
17295 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17297 if (Op.getOpcode() == ISD::SRA) {
17298 if (ShiftAmt == 7) {
17299 // ashr(R, 7) === cmp_slt(R, 0)
17300 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17301 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17304 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17305 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17306 SmallVector<SDValue, 32> V(NumElts,
17307 DAG.getConstant(128 >> ShiftAmt, dl,
17309 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17310 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17311 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17314 llvm_unreachable("Unknown shift opcode.");
17319 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17320 if (!Subtarget->is64Bit() &&
17321 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17323 // Peek through any splat that was introduced for i64 shift vectorization.
17324 int SplatIndex = -1;
17325 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17326 if (SVN->isSplat()) {
17327 SplatIndex = SVN->getSplatIndex();
17328 Amt = Amt.getOperand(0);
17329 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17330 "Splat shuffle referencing second operand");
17333 if (Amt.getOpcode() != ISD::BITCAST ||
17334 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17337 Amt = Amt.getOperand(0);
17338 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17339 VT.getVectorNumElements();
17340 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17341 uint64_t ShiftAmt = 0;
17342 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17343 for (unsigned i = 0; i != Ratio; ++i) {
17344 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17348 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17351 // Check remaining shift amounts (if not a splat).
17352 if (SplatIndex < 0) {
17353 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17354 uint64_t ShAmt = 0;
17355 for (unsigned j = 0; j != Ratio; ++j) {
17356 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17360 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17362 if (ShAmt != ShiftAmt)
17367 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17368 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17370 if (Op.getOpcode() == ISD::SRA)
17371 return ArithmeticShiftRight64(ShiftAmt);
17377 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17378 const X86Subtarget* Subtarget) {
17379 MVT VT = Op.getSimpleValueType();
17381 SDValue R = Op.getOperand(0);
17382 SDValue Amt = Op.getOperand(1);
17384 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17385 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17387 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17388 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17390 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17392 EVT EltVT = VT.getVectorElementType();
17394 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17395 // Check if this build_vector node is doing a splat.
17396 // If so, then set BaseShAmt equal to the splat value.
17397 BaseShAmt = BV->getSplatValue();
17398 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17399 BaseShAmt = SDValue();
17401 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17402 Amt = Amt.getOperand(0);
17404 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17405 if (SVN && SVN->isSplat()) {
17406 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17407 SDValue InVec = Amt.getOperand(0);
17408 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17409 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17410 "Unexpected shuffle index found!");
17411 BaseShAmt = InVec.getOperand(SplatIdx);
17412 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17413 if (ConstantSDNode *C =
17414 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17415 if (C->getZExtValue() == SplatIdx)
17416 BaseShAmt = InVec.getOperand(1);
17421 // Avoid introducing an extract element from a shuffle.
17422 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17423 DAG.getIntPtrConstant(SplatIdx, dl));
17427 if (BaseShAmt.getNode()) {
17428 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17429 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17430 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17431 else if (EltVT.bitsLT(MVT::i32))
17432 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17434 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17438 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17439 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17440 Amt.getOpcode() == ISD::BITCAST &&
17441 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17442 Amt = Amt.getOperand(0);
17443 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17444 VT.getVectorNumElements();
17445 std::vector<SDValue> Vals(Ratio);
17446 for (unsigned i = 0; i != Ratio; ++i)
17447 Vals[i] = Amt.getOperand(i);
17448 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17449 for (unsigned j = 0; j != Ratio; ++j)
17450 if (Vals[j] != Amt.getOperand(i + j))
17454 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17455 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17460 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17461 SelectionDAG &DAG) {
17462 MVT VT = Op.getSimpleValueType();
17464 SDValue R = Op.getOperand(0);
17465 SDValue Amt = Op.getOperand(1);
17467 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17468 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17470 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17473 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17476 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17479 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17480 // shifts per-lane and then shuffle the partial results back together.
17481 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17482 // Splat the shift amounts so the scalar shifts above will catch it.
17483 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17484 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17485 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17486 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17487 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17490 // i64 vector arithmetic shift can be emulated with the transform:
17491 // M = lshr(SIGN_BIT, Amt)
17492 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17493 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17494 Op.getOpcode() == ISD::SRA) {
17495 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17496 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17497 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17498 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17499 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17503 // If possible, lower this packed shift into a vector multiply instead of
17504 // expanding it into a sequence of scalar shifts.
17505 // Do this only if the vector shift count is a constant build_vector.
17506 if (Op.getOpcode() == ISD::SHL &&
17507 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17508 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17509 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17510 SmallVector<SDValue, 8> Elts;
17511 EVT SVT = VT.getScalarType();
17512 unsigned SVTBits = SVT.getSizeInBits();
17513 const APInt &One = APInt(SVTBits, 1);
17514 unsigned NumElems = VT.getVectorNumElements();
17516 for (unsigned i=0; i !=NumElems; ++i) {
17517 SDValue Op = Amt->getOperand(i);
17518 if (Op->getOpcode() == ISD::UNDEF) {
17519 Elts.push_back(Op);
17523 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17524 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17525 uint64_t ShAmt = C.getZExtValue();
17526 if (ShAmt >= SVTBits) {
17527 Elts.push_back(DAG.getUNDEF(SVT));
17530 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17532 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17533 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17536 // Lower SHL with variable shift amount.
17537 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17538 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17540 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17541 DAG.getConstant(0x3f800000U, dl, VT));
17542 Op = DAG.getBitcast(MVT::v4f32, Op);
17543 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17544 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17547 // If possible, lower this shift as a sequence of two shifts by
17548 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17550 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17552 // Could be rewritten as:
17553 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17555 // The advantage is that the two shifts from the example would be
17556 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17557 // the vector shift into four scalar shifts plus four pairs of vector
17559 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17560 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17561 unsigned TargetOpcode = X86ISD::MOVSS;
17562 bool CanBeSimplified;
17563 // The splat value for the first packed shift (the 'X' from the example).
17564 SDValue Amt1 = Amt->getOperand(0);
17565 // The splat value for the second packed shift (the 'Y' from the example).
17566 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17567 Amt->getOperand(2);
17569 // See if it is possible to replace this node with a sequence of
17570 // two shifts followed by a MOVSS/MOVSD
17571 if (VT == MVT::v4i32) {
17572 // Check if it is legal to use a MOVSS.
17573 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17574 Amt2 == Amt->getOperand(3);
17575 if (!CanBeSimplified) {
17576 // Otherwise, check if we can still simplify this node using a MOVSD.
17577 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17578 Amt->getOperand(2) == Amt->getOperand(3);
17579 TargetOpcode = X86ISD::MOVSD;
17580 Amt2 = Amt->getOperand(2);
17583 // Do similar checks for the case where the machine value type
17585 CanBeSimplified = Amt1 == Amt->getOperand(1);
17586 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17587 CanBeSimplified = Amt2 == Amt->getOperand(i);
17589 if (!CanBeSimplified) {
17590 TargetOpcode = X86ISD::MOVSD;
17591 CanBeSimplified = true;
17592 Amt2 = Amt->getOperand(4);
17593 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17594 CanBeSimplified = Amt1 == Amt->getOperand(i);
17595 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17596 CanBeSimplified = Amt2 == Amt->getOperand(j);
17600 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17601 isa<ConstantSDNode>(Amt2)) {
17602 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17603 EVT CastVT = MVT::v4i32;
17605 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17606 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17608 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17609 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17610 if (TargetOpcode == X86ISD::MOVSD)
17611 CastVT = MVT::v2i64;
17612 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17613 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17614 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17616 return DAG.getBitcast(VT, Result);
17620 // v4i32 Non Uniform Shifts.
17621 // If the shift amount is constant we can shift each lane using the SSE2
17622 // immediate shifts, else we need to zero-extend each lane to the lower i64
17623 // and shift using the SSE2 variable shifts.
17624 // The separate results can then be blended together.
17625 if (VT == MVT::v4i32) {
17626 unsigned Opc = Op.getOpcode();
17627 SDValue Amt0, Amt1, Amt2, Amt3;
17628 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17629 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17630 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17631 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17632 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17634 // ISD::SHL is handled above but we include it here for completeness.
17637 llvm_unreachable("Unknown target vector shift node");
17639 Opc = X86ISD::VSHL;
17642 Opc = X86ISD::VSRL;
17645 Opc = X86ISD::VSRA;
17648 // The SSE2 shifts use the lower i64 as the same shift amount for
17649 // all lanes and the upper i64 is ignored. These shuffle masks
17650 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17651 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17652 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17653 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17654 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17655 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17658 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17659 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17660 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17661 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17662 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17663 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17664 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17667 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17668 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17669 unsigned ShiftOpcode = Op->getOpcode();
17671 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17672 // On SSE41 targets we make use of the fact that VSELECT lowers
17673 // to PBLENDVB which selects bytes based just on the sign bit.
17674 if (Subtarget->hasSSE41()) {
17675 V0 = DAG.getBitcast(VT, V0);
17676 V1 = DAG.getBitcast(VT, V1);
17677 Sel = DAG.getBitcast(VT, Sel);
17678 return DAG.getBitcast(SelVT,
17679 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17681 // On pre-SSE41 targets we test for the sign bit by comparing to
17682 // zero - a negative value will set all bits of the lanes to true
17683 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17684 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17685 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17686 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17689 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17690 // We can safely do this using i16 shifts as we're only interested in
17691 // the 3 lower bits of each byte.
17692 Amt = DAG.getBitcast(ExtVT, Amt);
17693 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17694 Amt = DAG.getBitcast(VT, Amt);
17696 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17697 // r = VSELECT(r, shift(r, 4), a);
17699 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17700 R = SignBitSelect(VT, Amt, M, R);
17703 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17705 // r = VSELECT(r, shift(r, 2), a);
17706 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17707 R = SignBitSelect(VT, Amt, M, R);
17710 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17712 // return VSELECT(r, shift(r, 1), a);
17713 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17714 R = SignBitSelect(VT, Amt, M, R);
17718 if (Op->getOpcode() == ISD::SRA) {
17719 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17720 // so we can correctly sign extend. We don't care what happens to the
17722 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17723 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17724 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17725 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17726 ALo = DAG.getBitcast(ExtVT, ALo);
17727 AHi = DAG.getBitcast(ExtVT, AHi);
17728 RLo = DAG.getBitcast(ExtVT, RLo);
17729 RHi = DAG.getBitcast(ExtVT, RHi);
17731 // r = VSELECT(r, shift(r, 4), a);
17732 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17733 DAG.getConstant(4, dl, ExtVT));
17734 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17735 DAG.getConstant(4, dl, ExtVT));
17736 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17737 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17740 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17741 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17743 // r = VSELECT(r, shift(r, 2), a);
17744 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17745 DAG.getConstant(2, dl, ExtVT));
17746 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17747 DAG.getConstant(2, dl, ExtVT));
17748 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17749 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17752 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17753 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17755 // r = VSELECT(r, shift(r, 1), a);
17756 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17757 DAG.getConstant(1, dl, ExtVT));
17758 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17759 DAG.getConstant(1, dl, ExtVT));
17760 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17761 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17763 // Logical shift the result back to the lower byte, leaving a zero upper
17765 // meaning that we can safely pack with PACKUSWB.
17767 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17769 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17770 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17774 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17775 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17776 // solution better.
17777 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17778 MVT ExtVT = MVT::v8i32;
17780 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17781 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17782 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17783 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17784 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17787 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17788 MVT ExtVT = MVT::v8i32;
17789 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17790 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17791 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17792 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17793 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17794 ALo = DAG.getBitcast(ExtVT, ALo);
17795 AHi = DAG.getBitcast(ExtVT, AHi);
17796 RLo = DAG.getBitcast(ExtVT, RLo);
17797 RHi = DAG.getBitcast(ExtVT, RHi);
17798 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17799 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17800 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17801 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17802 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17805 if (VT == MVT::v8i16) {
17806 unsigned ShiftOpcode = Op->getOpcode();
17808 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17809 // On SSE41 targets we make use of the fact that VSELECT lowers
17810 // to PBLENDVB which selects bytes based just on the sign bit.
17811 if (Subtarget->hasSSE41()) {
17812 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17813 V0 = DAG.getBitcast(ExtVT, V0);
17814 V1 = DAG.getBitcast(ExtVT, V1);
17815 Sel = DAG.getBitcast(ExtVT, Sel);
17816 return DAG.getBitcast(
17817 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17819 // On pre-SSE41 targets we splat the sign bit - a negative value will
17820 // set all bits of the lanes to true and VSELECT uses that in
17821 // its OR(AND(V0,C),AND(V1,~C)) lowering.
17823 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17824 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17827 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17828 if (Subtarget->hasSSE41()) {
17829 // On SSE41 targets we need to replicate the shift mask in both
17830 // bytes for PBLENDVB.
17833 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17834 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17836 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17839 // r = VSELECT(r, shift(r, 8), a);
17840 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17841 R = SignBitSelect(Amt, M, R);
17844 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17846 // r = VSELECT(r, shift(r, 4), a);
17847 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17848 R = SignBitSelect(Amt, M, R);
17851 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17853 // r = VSELECT(r, shift(r, 2), a);
17854 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17855 R = SignBitSelect(Amt, M, R);
17858 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17860 // return VSELECT(r, shift(r, 1), a);
17861 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17862 R = SignBitSelect(Amt, M, R);
17866 // Decompose 256-bit shifts into smaller 128-bit shifts.
17867 if (VT.is256BitVector()) {
17868 unsigned NumElems = VT.getVectorNumElements();
17869 MVT EltVT = VT.getVectorElementType();
17870 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17872 // Extract the two vectors
17873 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17874 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17876 // Recreate the shift amount vectors
17877 SDValue Amt1, Amt2;
17878 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17879 // Constant shift amount
17880 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17881 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17882 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17884 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17885 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17887 // Variable shift amount
17888 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17889 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17892 // Issue new vector shifts for the smaller types
17893 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17894 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17896 // Concatenate the result back
17897 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17903 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17904 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17905 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17906 // looks for this combo and may remove the "setcc" instruction if the "setcc"
17907 // has only one use.
17908 SDNode *N = Op.getNode();
17909 SDValue LHS = N->getOperand(0);
17910 SDValue RHS = N->getOperand(1);
17911 unsigned BaseOp = 0;
17914 switch (Op.getOpcode()) {
17915 default: llvm_unreachable("Unknown ovf instruction!");
17917 // A subtract of one will be selected as a INC. Note that INC doesn't
17918 // set CF, so we can't do this for UADDO.
17919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17921 BaseOp = X86ISD::INC;
17922 Cond = X86::COND_O;
17925 BaseOp = X86ISD::ADD;
17926 Cond = X86::COND_O;
17929 BaseOp = X86ISD::ADD;
17930 Cond = X86::COND_B;
17933 // A subtract of one will be selected as a DEC. Note that DEC doesn't
17934 // set CF, so we can't do this for USUBO.
17935 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17937 BaseOp = X86ISD::DEC;
17938 Cond = X86::COND_O;
17941 BaseOp = X86ISD::SUB;
17942 Cond = X86::COND_O;
17945 BaseOp = X86ISD::SUB;
17946 Cond = X86::COND_B;
17949 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17950 Cond = X86::COND_O;
17952 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17953 if (N->getValueType(0) == MVT::i8) {
17954 BaseOp = X86ISD::UMUL8;
17955 Cond = X86::COND_O;
17958 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17960 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17963 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17964 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17965 SDValue(Sum.getNode(), 2));
17967 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17971 // Also sets EFLAGS.
17972 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17973 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17976 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17977 DAG.getConstant(Cond, DL, MVT::i32),
17978 SDValue(Sum.getNode(), 1));
17980 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17983 /// Returns true if the operand type is exactly twice the native width, and
17984 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17985 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17986 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17987 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
17988 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17991 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17992 else if (OpWidth == 128)
17993 return Subtarget->hasCmpxchg16b();
17998 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17999 return needsCmpXchgNb(SI->getValueOperand()->getType());
18002 // Note: this turns large loads into lock cmpxchg8b/16b.
18003 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18004 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18005 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18006 return needsCmpXchgNb(PTy->getElementType());
18009 TargetLoweringBase::AtomicRMWExpansionKind
18010 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18011 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18012 Type *MemType = AI->getType();
18014 // If the operand is too big, we must see if cmpxchg8/16b is available
18015 // and default to library calls otherwise.
18016 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18017 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18018 : AtomicRMWExpansionKind::None;
18021 AtomicRMWInst::BinOp Op = AI->getOperation();
18024 llvm_unreachable("Unknown atomic operation");
18025 case AtomicRMWInst::Xchg:
18026 case AtomicRMWInst::Add:
18027 case AtomicRMWInst::Sub:
18028 // It's better to use xadd, xsub or xchg for these in all cases.
18029 return AtomicRMWExpansionKind::None;
18030 case AtomicRMWInst::Or:
18031 case AtomicRMWInst::And:
18032 case AtomicRMWInst::Xor:
18033 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18034 // prefix to a normal instruction for these operations.
18035 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18036 : AtomicRMWExpansionKind::None;
18037 case AtomicRMWInst::Nand:
18038 case AtomicRMWInst::Max:
18039 case AtomicRMWInst::Min:
18040 case AtomicRMWInst::UMax:
18041 case AtomicRMWInst::UMin:
18042 // These always require a non-trivial set of data operations on x86. We must
18043 // use a cmpxchg loop.
18044 return AtomicRMWExpansionKind::CmpXChg;
18048 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18049 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18050 // no-sse2). There isn't any reason to disable it if the target processor
18052 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18056 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18057 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18058 Type *MemType = AI->getType();
18059 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18060 // there is no benefit in turning such RMWs into loads, and it is actually
18061 // harmful as it introduces a mfence.
18062 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18065 auto Builder = IRBuilder<>(AI);
18066 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18067 auto SynchScope = AI->getSynchScope();
18068 // We must restrict the ordering to avoid generating loads with Release or
18069 // ReleaseAcquire orderings.
18070 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18071 auto Ptr = AI->getPointerOperand();
18073 // Before the load we need a fence. Here is an example lifted from
18074 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18077 // x.store(1, relaxed);
18078 // r1 = y.fetch_add(0, release);
18080 // y.fetch_add(42, acquire);
18081 // r2 = x.load(relaxed);
18082 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18083 // lowered to just a load without a fence. A mfence flushes the store buffer,
18084 // making the optimization clearly correct.
18085 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18086 // otherwise, we might be able to be more aggressive on relaxed idempotent
18087 // rmw. In practice, they do not look useful, so we don't try to be
18088 // especially clever.
18089 if (SynchScope == SingleThread)
18090 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18091 // the IR level, so we must wrap it in an intrinsic.
18094 if (!hasMFENCE(*Subtarget))
18095 // FIXME: it might make sense to use a locked operation here but on a
18096 // different cache-line to prevent cache-line bouncing. In practice it
18097 // is probably a small win, and x86 processors without mfence are rare
18098 // enough that we do not bother.
18102 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18103 Builder.CreateCall(MFence, {});
18105 // Finally we can emit the atomic load.
18106 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18107 AI->getType()->getPrimitiveSizeInBits());
18108 Loaded->setAtomic(Order, SynchScope);
18109 AI->replaceAllUsesWith(Loaded);
18110 AI->eraseFromParent();
18114 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18115 SelectionDAG &DAG) {
18117 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18118 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18119 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18120 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18122 // The only fence that needs an instruction is a sequentially-consistent
18123 // cross-thread fence.
18124 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18125 if (hasMFENCE(*Subtarget))
18126 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18128 SDValue Chain = Op.getOperand(0);
18129 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18131 DAG.getRegister(X86::ESP, MVT::i32), // Base
18132 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18133 DAG.getRegister(0, MVT::i32), // Index
18134 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18135 DAG.getRegister(0, MVT::i32), // Segment.
18139 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18140 return SDValue(Res, 0);
18143 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18144 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18147 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18148 SelectionDAG &DAG) {
18149 MVT T = Op.getSimpleValueType();
18153 switch(T.SimpleTy) {
18154 default: llvm_unreachable("Invalid value type!");
18155 case MVT::i8: Reg = X86::AL; size = 1; break;
18156 case MVT::i16: Reg = X86::AX; size = 2; break;
18157 case MVT::i32: Reg = X86::EAX; size = 4; break;
18159 assert(Subtarget->is64Bit() && "Node not type legal!");
18160 Reg = X86::RAX; size = 8;
18163 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18164 Op.getOperand(2), SDValue());
18165 SDValue Ops[] = { cpIn.getValue(0),
18168 DAG.getTargetConstant(size, DL, MVT::i8),
18169 cpIn.getValue(1) };
18170 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18171 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18172 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18176 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18177 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18178 MVT::i32, cpOut.getValue(2));
18179 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18180 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18183 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18184 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18185 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18189 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18190 SelectionDAG &DAG) {
18191 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18192 MVT DstVT = Op.getSimpleValueType();
18194 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18195 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18196 if (DstVT != MVT::f64)
18197 // This conversion needs to be expanded.
18200 SDValue InVec = Op->getOperand(0);
18202 unsigned NumElts = SrcVT.getVectorNumElements();
18203 EVT SVT = SrcVT.getVectorElementType();
18205 // Widen the vector in input in the case of MVT::v2i32.
18206 // Example: from MVT::v2i32 to MVT::v4i32.
18207 SmallVector<SDValue, 16> Elts;
18208 for (unsigned i = 0, e = NumElts; i != e; ++i)
18209 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18210 DAG.getIntPtrConstant(i, dl)));
18212 // Explicitly mark the extra elements as Undef.
18213 Elts.append(NumElts, DAG.getUNDEF(SVT));
18215 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18216 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18217 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18218 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18219 DAG.getIntPtrConstant(0, dl));
18222 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18223 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18224 assert((DstVT == MVT::i64 ||
18225 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18226 "Unexpected custom BITCAST");
18227 // i64 <=> MMX conversions are Legal.
18228 if (SrcVT==MVT::i64 && DstVT.isVector())
18230 if (DstVT==MVT::i64 && SrcVT.isVector())
18232 // MMX <=> MMX conversions are Legal.
18233 if (SrcVT.isVector() && DstVT.isVector())
18235 // All other conversions need to be expanded.
18239 /// Compute the horizontal sum of bytes in V for the elements of VT.
18241 /// Requires V to be a byte vector and VT to be an integer vector type with
18242 /// wider elements than V's type. The width of the elements of VT determines
18243 /// how many bytes of V are summed horizontally to produce each element of the
18245 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18246 const X86Subtarget *Subtarget,
18247 SelectionDAG &DAG) {
18249 MVT ByteVecVT = V.getSimpleValueType();
18250 MVT EltVT = VT.getVectorElementType();
18251 int NumElts = VT.getVectorNumElements();
18252 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18253 "Expected value to have byte element type.");
18254 assert(EltVT != MVT::i8 &&
18255 "Horizontal byte sum only makes sense for wider elements!");
18256 unsigned VecSize = VT.getSizeInBits();
18257 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18259 // PSADBW instruction horizontally add all bytes and leave the result in i64
18260 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18261 if (EltVT == MVT::i64) {
18262 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18263 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18264 return DAG.getBitcast(VT, V);
18267 if (EltVT == MVT::i32) {
18268 // We unpack the low half and high half into i32s interleaved with zeros so
18269 // that we can use PSADBW to horizontally sum them. The most useful part of
18270 // this is that it lines up the results of two PSADBW instructions to be
18271 // two v2i64 vectors which concatenated are the 4 population counts. We can
18272 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18273 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18274 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18275 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18277 // Do the horizontal sums into two v2i64s.
18278 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18279 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18280 DAG.getBitcast(ByteVecVT, Low), Zeros);
18281 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18282 DAG.getBitcast(ByteVecVT, High), Zeros);
18284 // Merge them together.
18285 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18286 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18287 DAG.getBitcast(ShortVecVT, Low),
18288 DAG.getBitcast(ShortVecVT, High));
18290 return DAG.getBitcast(VT, V);
18293 // The only element type left is i16.
18294 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18296 // To obtain pop count for each i16 element starting from the pop count for
18297 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18298 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18299 // directly supported.
18300 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18301 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18302 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18303 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18304 DAG.getBitcast(ByteVecVT, V));
18305 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18308 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18309 const X86Subtarget *Subtarget,
18310 SelectionDAG &DAG) {
18311 MVT VT = Op.getSimpleValueType();
18312 MVT EltVT = VT.getVectorElementType();
18313 unsigned VecSize = VT.getSizeInBits();
18315 // Implement a lookup table in register by using an algorithm based on:
18316 // http://wm.ite.pl/articles/sse-popcount.html
18318 // The general idea is that every lower byte nibble in the input vector is an
18319 // index into a in-register pre-computed pop count table. We then split up the
18320 // input vector in two new ones: (1) a vector with only the shifted-right
18321 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18322 // masked out higher ones) for each byte. PSHUB is used separately with both
18323 // to index the in-register table. Next, both are added and the result is a
18324 // i8 vector where each element contains the pop count for input byte.
18326 // To obtain the pop count for elements != i8, we follow up with the same
18327 // approach and use additional tricks as described below.
18329 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18330 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18331 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18332 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18334 int NumByteElts = VecSize / 8;
18335 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18336 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18337 SmallVector<SDValue, 16> LUTVec;
18338 for (int i = 0; i < NumByteElts; ++i)
18339 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18340 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18341 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18342 DAG.getConstant(0x0F, DL, MVT::i8));
18343 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18346 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18347 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18348 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18351 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18353 // The input vector is used as the shuffle mask that index elements into the
18354 // LUT. After counting low and high nibbles, add the vector to obtain the
18355 // final pop count per i8 element.
18356 SDValue HighPopCnt =
18357 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18358 SDValue LowPopCnt =
18359 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18360 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18362 if (EltVT == MVT::i8)
18365 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18368 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18369 const X86Subtarget *Subtarget,
18370 SelectionDAG &DAG) {
18371 MVT VT = Op.getSimpleValueType();
18372 assert(VT.is128BitVector() &&
18373 "Only 128-bit vector bitmath lowering supported.");
18375 int VecSize = VT.getSizeInBits();
18376 MVT EltVT = VT.getVectorElementType();
18377 int Len = EltVT.getSizeInBits();
18379 // This is the vectorized version of the "best" algorithm from
18380 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18381 // with a minor tweak to use a series of adds + shifts instead of vector
18382 // multiplications. Implemented for all integer vector types. We only use
18383 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18384 // much faster, even faster than using native popcnt instructions.
18386 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18387 MVT VT = V.getSimpleValueType();
18388 SmallVector<SDValue, 32> Shifters(
18389 VT.getVectorNumElements(),
18390 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18391 return DAG.getNode(OpCode, DL, VT, V,
18392 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18394 auto GetMask = [&](SDValue V, APInt Mask) {
18395 MVT VT = V.getSimpleValueType();
18396 SmallVector<SDValue, 32> Masks(
18397 VT.getVectorNumElements(),
18398 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18399 return DAG.getNode(ISD::AND, DL, VT, V,
18400 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18403 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18404 // x86, so set the SRL type to have elements at least i16 wide. This is
18405 // correct because all of our SRLs are followed immediately by a mask anyways
18406 // that handles any bits that sneak into the high bits of the byte elements.
18407 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18411 // v = v - ((v >> 1) & 0x55555555...)
18413 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18414 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18415 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18417 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18418 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18419 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18420 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18421 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18423 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18424 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18425 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18426 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18428 // At this point, V contains the byte-wise population count, and we are
18429 // merely doing a horizontal sum if necessary to get the wider element
18431 if (EltVT == MVT::i8)
18434 return LowerHorizontalByteSum(
18435 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18439 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18440 SelectionDAG &DAG) {
18441 MVT VT = Op.getSimpleValueType();
18442 // FIXME: Need to add AVX-512 support here!
18443 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18444 "Unknown CTPOP type to handle");
18445 SDLoc DL(Op.getNode());
18446 SDValue Op0 = Op.getOperand(0);
18448 if (!Subtarget->hasSSSE3()) {
18449 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18450 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18451 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18454 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18455 unsigned NumElems = VT.getVectorNumElements();
18457 // Extract each 128-bit vector, compute pop count and concat the result.
18458 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18459 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18461 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18462 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18463 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18466 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18469 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18470 SelectionDAG &DAG) {
18471 assert(Op.getValueType().isVector() &&
18472 "We only do custom lowering for vector population count.");
18473 return LowerVectorCTPOP(Op, Subtarget, DAG);
18476 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18477 SDNode *Node = Op.getNode();
18479 EVT T = Node->getValueType(0);
18480 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18481 DAG.getConstant(0, dl, T), Node->getOperand(2));
18482 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18483 cast<AtomicSDNode>(Node)->getMemoryVT(),
18484 Node->getOperand(0),
18485 Node->getOperand(1), negOp,
18486 cast<AtomicSDNode>(Node)->getMemOperand(),
18487 cast<AtomicSDNode>(Node)->getOrdering(),
18488 cast<AtomicSDNode>(Node)->getSynchScope());
18491 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18492 SDNode *Node = Op.getNode();
18494 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18496 // Convert seq_cst store -> xchg
18497 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18498 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18499 // (The only way to get a 16-byte store is cmpxchg16b)
18500 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18501 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18502 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18503 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18504 cast<AtomicSDNode>(Node)->getMemoryVT(),
18505 Node->getOperand(0),
18506 Node->getOperand(1), Node->getOperand(2),
18507 cast<AtomicSDNode>(Node)->getMemOperand(),
18508 cast<AtomicSDNode>(Node)->getOrdering(),
18509 cast<AtomicSDNode>(Node)->getSynchScope());
18510 return Swap.getValue(1);
18512 // Other atomic stores have a simple pattern.
18516 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18517 EVT VT = Op.getNode()->getSimpleValueType(0);
18519 // Let legalize expand this if it isn't a legal type yet.
18520 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18523 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18526 bool ExtraOp = false;
18527 switch (Op.getOpcode()) {
18528 default: llvm_unreachable("Invalid code");
18529 case ISD::ADDC: Opc = X86ISD::ADD; break;
18530 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18531 case ISD::SUBC: Opc = X86ISD::SUB; break;
18532 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18536 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18538 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18539 Op.getOperand(1), Op.getOperand(2));
18542 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18543 SelectionDAG &DAG) {
18544 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18546 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18547 // which returns the values as { float, float } (in XMM0) or
18548 // { double, double } (which is returned in XMM0, XMM1).
18550 SDValue Arg = Op.getOperand(0);
18551 EVT ArgVT = Arg.getValueType();
18552 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18554 TargetLowering::ArgListTy Args;
18555 TargetLowering::ArgListEntry Entry;
18559 Entry.isSExt = false;
18560 Entry.isZExt = false;
18561 Args.push_back(Entry);
18563 bool isF64 = ArgVT == MVT::f64;
18564 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18565 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18566 // the results are returned via SRet in memory.
18567 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18570 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18572 Type *RetTy = isF64
18573 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18574 : (Type*)VectorType::get(ArgTy, 4);
18576 TargetLowering::CallLoweringInfo CLI(DAG);
18577 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18578 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18580 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18583 // Returned in xmm0 and xmm1.
18584 return CallResult.first;
18586 // Returned in bits 0:31 and 32:64 xmm0.
18587 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18588 CallResult.first, DAG.getIntPtrConstant(0, dl));
18589 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18590 CallResult.first, DAG.getIntPtrConstant(1, dl));
18591 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18592 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18595 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18596 SelectionDAG &DAG) {
18597 assert(Subtarget->hasAVX512() &&
18598 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18600 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18601 EVT VT = N->getValue().getValueType();
18602 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18605 // X86 scatter kills mask register, so its type should be added to
18606 // the list of return values
18607 if (N->getNumValues() == 1) {
18608 SDValue Index = N->getIndex();
18609 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18610 !Index.getValueType().is512BitVector())
18611 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18613 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18614 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18615 N->getOperand(3), Index };
18617 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18618 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18619 return SDValue(NewScatter.getNode(), 0);
18624 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18625 SelectionDAG &DAG) {
18626 assert(Subtarget->hasAVX512() &&
18627 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18629 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18630 EVT VT = Op.getValueType();
18631 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18634 SDValue Index = N->getIndex();
18635 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18636 !Index.getValueType().is512BitVector()) {
18637 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18638 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18639 N->getOperand(3), Index };
18640 DAG.UpdateNodeOperands(N, Ops);
18645 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18646 SelectionDAG &DAG) const {
18647 // TODO: Eventually, the lowering of these nodes should be informed by or
18648 // deferred to the GC strategy for the function in which they appear. For
18649 // now, however, they must be lowered to something. Since they are logically
18650 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18651 // require special handling for these nodes), lower them as literal NOOPs for
18653 SmallVector<SDValue, 2> Ops;
18655 Ops.push_back(Op.getOperand(0));
18656 if (Op->getGluedNode())
18657 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18660 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18661 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18666 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18667 SelectionDAG &DAG) const {
18668 // TODO: Eventually, the lowering of these nodes should be informed by or
18669 // deferred to the GC strategy for the function in which they appear. For
18670 // now, however, they must be lowered to something. Since they are logically
18671 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18672 // require special handling for these nodes), lower them as literal NOOPs for
18674 SmallVector<SDValue, 2> Ops;
18676 Ops.push_back(Op.getOperand(0));
18677 if (Op->getGluedNode())
18678 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18681 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18682 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18687 /// LowerOperation - Provide custom lowering hooks for some operations.
18689 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18690 switch (Op.getOpcode()) {
18691 default: llvm_unreachable("Should not custom lower this!");
18692 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18693 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18694 return LowerCMP_SWAP(Op, Subtarget, DAG);
18695 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18696 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18697 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18698 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18699 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18700 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18701 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18702 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18703 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18704 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18705 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18706 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18707 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18708 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18709 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18710 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18711 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18712 case ISD::SHL_PARTS:
18713 case ISD::SRA_PARTS:
18714 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18715 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18716 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18717 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18718 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18719 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18720 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18721 case ISD::SIGN_EXTEND_VECTOR_INREG:
18722 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18723 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18724 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18725 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18726 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18728 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18729 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18730 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18731 case ISD::SETCC: return LowerSETCC(Op, DAG);
18732 case ISD::SELECT: return LowerSELECT(Op, DAG);
18733 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18734 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18735 case ISD::VASTART: return LowerVASTART(Op, DAG);
18736 case ISD::VAARG: return LowerVAARG(Op, DAG);
18737 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18738 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18739 case ISD::INTRINSIC_VOID:
18740 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18741 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18742 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18743 case ISD::FRAME_TO_ARGS_OFFSET:
18744 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18745 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18746 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18747 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18748 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18749 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18750 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18751 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18752 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18753 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18754 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18755 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18756 case ISD::UMUL_LOHI:
18757 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18760 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18766 case ISD::UMULO: return LowerXALUO(Op, DAG);
18767 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18768 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18772 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18773 case ISD::ADD: return LowerADD(Op, DAG);
18774 case ISD::SUB: return LowerSUB(Op, DAG);
18775 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18776 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18777 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18778 case ISD::GC_TRANSITION_START:
18779 return LowerGC_TRANSITION_START(Op, DAG);
18780 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18784 /// ReplaceNodeResults - Replace a node with an illegal result type
18785 /// with a new node built out of custom code.
18786 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18787 SmallVectorImpl<SDValue>&Results,
18788 SelectionDAG &DAG) const {
18790 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18791 switch (N->getOpcode()) {
18793 llvm_unreachable("Do not know how to custom type legalize this operation!");
18794 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18795 case X86ISD::FMINC:
18797 case X86ISD::FMAXC:
18798 case X86ISD::FMAX: {
18799 EVT VT = N->getValueType(0);
18800 if (VT != MVT::v2f32)
18801 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18802 SDValue UNDEF = DAG.getUNDEF(VT);
18803 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18804 N->getOperand(0), UNDEF);
18805 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18806 N->getOperand(1), UNDEF);
18807 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18810 case ISD::SIGN_EXTEND_INREG:
18815 // We don't want to expand or promote these.
18822 case ISD::UDIVREM: {
18823 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18824 Results.push_back(V);
18827 case ISD::FP_TO_SINT:
18828 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
18829 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18830 if (N->getOperand(0).getValueType() == MVT::f16)
18833 case ISD::FP_TO_UINT: {
18834 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18836 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18839 std::pair<SDValue,SDValue> Vals =
18840 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18841 SDValue FIST = Vals.first, StackSlot = Vals.second;
18842 if (FIST.getNode()) {
18843 EVT VT = N->getValueType(0);
18844 // Return a load from the stack slot.
18845 if (StackSlot.getNode())
18846 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18847 MachinePointerInfo(),
18848 false, false, false, 0));
18850 Results.push_back(FIST);
18854 case ISD::UINT_TO_FP: {
18855 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18856 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18857 N->getValueType(0) != MVT::v2f32)
18859 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18861 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18863 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18864 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18865 DAG.getBitcast(MVT::v2i64, VBias));
18866 Or = DAG.getBitcast(MVT::v2f64, Or);
18867 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18868 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18871 case ISD::FP_ROUND: {
18872 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18874 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18875 Results.push_back(V);
18878 case ISD::FP_EXTEND: {
18879 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18880 // No other ValueType for FP_EXTEND should reach this point.
18881 assert(N->getValueType(0) == MVT::v2f32 &&
18882 "Do not know how to legalize this Node");
18885 case ISD::INTRINSIC_W_CHAIN: {
18886 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18888 default : llvm_unreachable("Do not know how to custom type "
18889 "legalize this intrinsic operation!");
18890 case Intrinsic::x86_rdtsc:
18891 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18893 case Intrinsic::x86_rdtscp:
18894 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18896 case Intrinsic::x86_rdpmc:
18897 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18900 case ISD::READCYCLECOUNTER: {
18901 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18904 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18905 EVT T = N->getValueType(0);
18906 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18907 bool Regs64bit = T == MVT::i128;
18908 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18909 SDValue cpInL, cpInH;
18910 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18911 DAG.getConstant(0, dl, HalfT));
18912 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18913 DAG.getConstant(1, dl, HalfT));
18914 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18915 Regs64bit ? X86::RAX : X86::EAX,
18917 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18918 Regs64bit ? X86::RDX : X86::EDX,
18919 cpInH, cpInL.getValue(1));
18920 SDValue swapInL, swapInH;
18921 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18922 DAG.getConstant(0, dl, HalfT));
18923 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18924 DAG.getConstant(1, dl, HalfT));
18925 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18926 Regs64bit ? X86::RBX : X86::EBX,
18927 swapInL, cpInH.getValue(1));
18928 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18929 Regs64bit ? X86::RCX : X86::ECX,
18930 swapInH, swapInL.getValue(1));
18931 SDValue Ops[] = { swapInH.getValue(0),
18933 swapInH.getValue(1) };
18934 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18935 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18936 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18937 X86ISD::LCMPXCHG8_DAG;
18938 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18939 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18940 Regs64bit ? X86::RAX : X86::EAX,
18941 HalfT, Result.getValue(1));
18942 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18943 Regs64bit ? X86::RDX : X86::EDX,
18944 HalfT, cpOutL.getValue(2));
18945 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18947 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18948 MVT::i32, cpOutH.getValue(2));
18950 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18951 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18952 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18954 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18955 Results.push_back(Success);
18956 Results.push_back(EFLAGS.getValue(1));
18959 case ISD::ATOMIC_SWAP:
18960 case ISD::ATOMIC_LOAD_ADD:
18961 case ISD::ATOMIC_LOAD_SUB:
18962 case ISD::ATOMIC_LOAD_AND:
18963 case ISD::ATOMIC_LOAD_OR:
18964 case ISD::ATOMIC_LOAD_XOR:
18965 case ISD::ATOMIC_LOAD_NAND:
18966 case ISD::ATOMIC_LOAD_MIN:
18967 case ISD::ATOMIC_LOAD_MAX:
18968 case ISD::ATOMIC_LOAD_UMIN:
18969 case ISD::ATOMIC_LOAD_UMAX:
18970 case ISD::ATOMIC_LOAD: {
18971 // Delegate to generic TypeLegalization. Situations we can really handle
18972 // should have already been dealt with by AtomicExpandPass.cpp.
18975 case ISD::BITCAST: {
18976 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18977 EVT DstVT = N->getValueType(0);
18978 EVT SrcVT = N->getOperand(0)->getValueType(0);
18980 if (SrcVT != MVT::f64 ||
18981 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18984 unsigned NumElts = DstVT.getVectorNumElements();
18985 EVT SVT = DstVT.getVectorElementType();
18986 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18987 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18988 MVT::v2f64, N->getOperand(0));
18989 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18991 if (ExperimentalVectorWideningLegalization) {
18992 // If we are legalizing vectors by widening, we already have the desired
18993 // legal vector type, just return it.
18994 Results.push_back(ToVecInt);
18998 SmallVector<SDValue, 8> Elts;
18999 for (unsigned i = 0, e = NumElts; i != e; ++i)
19000 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19001 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19003 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19008 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19009 switch ((X86ISD::NodeType)Opcode) {
19010 case X86ISD::FIRST_NUMBER: break;
19011 case X86ISD::BSF: return "X86ISD::BSF";
19012 case X86ISD::BSR: return "X86ISD::BSR";
19013 case X86ISD::SHLD: return "X86ISD::SHLD";
19014 case X86ISD::SHRD: return "X86ISD::SHRD";
19015 case X86ISD::FAND: return "X86ISD::FAND";
19016 case X86ISD::FANDN: return "X86ISD::FANDN";
19017 case X86ISD::FOR: return "X86ISD::FOR";
19018 case X86ISD::FXOR: return "X86ISD::FXOR";
19019 case X86ISD::FILD: return "X86ISD::FILD";
19020 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19021 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19022 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19023 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19024 case X86ISD::FLD: return "X86ISD::FLD";
19025 case X86ISD::FST: return "X86ISD::FST";
19026 case X86ISD::CALL: return "X86ISD::CALL";
19027 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19028 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19029 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19030 case X86ISD::BT: return "X86ISD::BT";
19031 case X86ISD::CMP: return "X86ISD::CMP";
19032 case X86ISD::COMI: return "X86ISD::COMI";
19033 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19034 case X86ISD::CMPM: return "X86ISD::CMPM";
19035 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19036 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19037 case X86ISD::SETCC: return "X86ISD::SETCC";
19038 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19039 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19040 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19041 case X86ISD::CMOV: return "X86ISD::CMOV";
19042 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19043 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19044 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19045 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19046 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19047 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19048 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19049 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19050 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19051 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19052 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19053 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19054 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19055 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19056 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19057 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19058 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19059 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19060 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19061 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19062 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19063 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19064 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19065 case X86ISD::HADD: return "X86ISD::HADD";
19066 case X86ISD::HSUB: return "X86ISD::HSUB";
19067 case X86ISD::FHADD: return "X86ISD::FHADD";
19068 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19069 case X86ISD::ABS: return "X86ISD::ABS";
19070 case X86ISD::FMAX: return "X86ISD::FMAX";
19071 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19072 case X86ISD::FMIN: return "X86ISD::FMIN";
19073 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19074 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19075 case X86ISD::FMINC: return "X86ISD::FMINC";
19076 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19077 case X86ISD::FRCP: return "X86ISD::FRCP";
19078 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19079 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19080 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19081 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19082 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19083 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19084 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19085 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19086 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19087 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19088 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19089 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19090 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19091 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19092 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19093 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19094 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19095 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19096 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19097 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19098 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19099 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19100 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19101 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19102 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19103 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19104 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19105 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19106 case X86ISD::VSHL: return "X86ISD::VSHL";
19107 case X86ISD::VSRL: return "X86ISD::VSRL";
19108 case X86ISD::VSRA: return "X86ISD::VSRA";
19109 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19110 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19111 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19112 case X86ISD::CMPP: return "X86ISD::CMPP";
19113 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19114 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19115 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19116 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19117 case X86ISD::ADD: return "X86ISD::ADD";
19118 case X86ISD::SUB: return "X86ISD::SUB";
19119 case X86ISD::ADC: return "X86ISD::ADC";
19120 case X86ISD::SBB: return "X86ISD::SBB";
19121 case X86ISD::SMUL: return "X86ISD::SMUL";
19122 case X86ISD::UMUL: return "X86ISD::UMUL";
19123 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19124 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19125 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19126 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19127 case X86ISD::INC: return "X86ISD::INC";
19128 case X86ISD::DEC: return "X86ISD::DEC";
19129 case X86ISD::OR: return "X86ISD::OR";
19130 case X86ISD::XOR: return "X86ISD::XOR";
19131 case X86ISD::AND: return "X86ISD::AND";
19132 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19133 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19134 case X86ISD::PTEST: return "X86ISD::PTEST";
19135 case X86ISD::TESTP: return "X86ISD::TESTP";
19136 case X86ISD::TESTM: return "X86ISD::TESTM";
19137 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19138 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19139 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19140 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19141 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19142 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19143 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19144 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19145 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19146 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19147 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19148 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19149 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19150 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19151 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19152 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19153 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19154 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19155 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19156 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19157 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19158 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19159 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19160 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19161 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19162 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19163 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19164 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19165 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19166 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19167 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19168 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19169 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19170 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19171 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19172 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19173 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19174 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19175 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19176 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19177 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19178 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19179 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19180 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19181 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19182 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19183 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
19184 case X86ISD::SAHF: return "X86ISD::SAHF";
19185 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19186 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19187 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19188 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19189 case X86ISD::FMADD: return "X86ISD::FMADD";
19190 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19191 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19192 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19193 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19194 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19195 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19196 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19197 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19198 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19199 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19200 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19201 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19202 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19203 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19204 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19205 case X86ISD::XTEST: return "X86ISD::XTEST";
19206 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19207 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19208 case X86ISD::SELECT: return "X86ISD::SELECT";
19209 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19210 case X86ISD::RCP28: return "X86ISD::RCP28";
19211 case X86ISD::EXP2: return "X86ISD::EXP2";
19212 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19213 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19214 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19215 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19216 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19217 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19218 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19219 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19220 case X86ISD::ADDS: return "X86ISD::ADDS";
19221 case X86ISD::SUBS: return "X86ISD::SUBS";
19222 case X86ISD::AVG: return "X86ISD::AVG";
19223 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19224 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19225 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19226 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19227 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19232 // isLegalAddressingMode - Return true if the addressing mode represented
19233 // by AM is legal for this target, for a load/store of the specified type.
19234 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19235 const AddrMode &AM, Type *Ty,
19236 unsigned AS) const {
19237 // X86 supports extremely general addressing modes.
19238 CodeModel::Model M = getTargetMachine().getCodeModel();
19239 Reloc::Model R = getTargetMachine().getRelocationModel();
19241 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19242 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19247 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19249 // If a reference to this global requires an extra load, we can't fold it.
19250 if (isGlobalStubReference(GVFlags))
19253 // If BaseGV requires a register for the PIC base, we cannot also have a
19254 // BaseReg specified.
19255 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19258 // If lower 4G is not available, then we must use rip-relative addressing.
19259 if ((M != CodeModel::Small || R != Reloc::Static) &&
19260 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19264 switch (AM.Scale) {
19270 // These scales always work.
19275 // These scales are formed with basereg+scalereg. Only accept if there is
19280 default: // Other stuff never works.
19287 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19288 unsigned Bits = Ty->getScalarSizeInBits();
19290 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19291 // particularly cheaper than those without.
19295 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19296 // variable shifts just as cheap as scalar ones.
19297 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19300 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19301 // fully general vector.
19305 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19306 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19308 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19309 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19310 return NumBits1 > NumBits2;
19313 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19314 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19317 if (!isTypeLegal(EVT::getEVT(Ty1)))
19320 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19322 // Assuming the caller doesn't have a zeroext or signext return parameter,
19323 // truncation all the way down to i1 is valid.
19327 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19328 return isInt<32>(Imm);
19331 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19332 // Can also use sub to handle negated immediates.
19333 return isInt<32>(Imm);
19336 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19337 if (!VT1.isInteger() || !VT2.isInteger())
19339 unsigned NumBits1 = VT1.getSizeInBits();
19340 unsigned NumBits2 = VT2.getSizeInBits();
19341 return NumBits1 > NumBits2;
19344 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19345 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19346 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19349 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19350 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19351 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19354 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19355 EVT VT1 = Val.getValueType();
19356 if (isZExtFree(VT1, VT2))
19359 if (Val.getOpcode() != ISD::LOAD)
19362 if (!VT1.isSimple() || !VT1.isInteger() ||
19363 !VT2.isSimple() || !VT2.isInteger())
19366 switch (VT1.getSimpleVT().SimpleTy) {
19371 // X86 has 8, 16, and 32-bit zero-extending loads.
19378 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19381 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19382 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19385 VT = VT.getScalarType();
19387 if (!VT.isSimple())
19390 switch (VT.getSimpleVT().SimpleTy) {
19401 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19402 // i16 instructions are longer (0x66 prefix) and potentially slower.
19403 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19406 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19407 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19408 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19409 /// are assumed to be legal.
19411 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19413 if (!VT.isSimple())
19416 // Not for i1 vectors
19417 if (VT.getScalarType() == MVT::i1)
19420 // Very little shuffling can be done for 64-bit vectors right now.
19421 if (VT.getSizeInBits() == 64)
19424 // We only care that the types being shuffled are legal. The lowering can
19425 // handle any possible shuffle mask that results.
19426 return isTypeLegal(VT.getSimpleVT());
19430 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19432 // Just delegate to the generic legality, clear masks aren't special.
19433 return isShuffleMaskLegal(Mask, VT);
19436 //===----------------------------------------------------------------------===//
19437 // X86 Scheduler Hooks
19438 //===----------------------------------------------------------------------===//
19440 /// Utility function to emit xbegin specifying the start of an RTM region.
19441 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19442 const TargetInstrInfo *TII) {
19443 DebugLoc DL = MI->getDebugLoc();
19445 const BasicBlock *BB = MBB->getBasicBlock();
19446 MachineFunction::iterator I = MBB;
19449 // For the v = xbegin(), we generate
19460 MachineBasicBlock *thisMBB = MBB;
19461 MachineFunction *MF = MBB->getParent();
19462 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19463 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19464 MF->insert(I, mainMBB);
19465 MF->insert(I, sinkMBB);
19467 // Transfer the remainder of BB and its successor edges to sinkMBB.
19468 sinkMBB->splice(sinkMBB->begin(), MBB,
19469 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19470 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19474 // # fallthrough to mainMBB
19475 // # abortion to sinkMBB
19476 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19477 thisMBB->addSuccessor(mainMBB);
19478 thisMBB->addSuccessor(sinkMBB);
19482 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19483 mainMBB->addSuccessor(sinkMBB);
19486 // EAX is live into the sinkMBB
19487 sinkMBB->addLiveIn(X86::EAX);
19488 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19489 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19492 MI->eraseFromParent();
19496 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19497 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19498 // in the .td file.
19499 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19500 const TargetInstrInfo *TII) {
19502 switch (MI->getOpcode()) {
19503 default: llvm_unreachable("illegal opcode!");
19504 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19505 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19506 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19507 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19508 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19509 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19510 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19511 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19514 DebugLoc dl = MI->getDebugLoc();
19515 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19517 unsigned NumArgs = MI->getNumOperands();
19518 for (unsigned i = 1; i < NumArgs; ++i) {
19519 MachineOperand &Op = MI->getOperand(i);
19520 if (!(Op.isReg() && Op.isImplicit()))
19521 MIB.addOperand(Op);
19523 if (MI->hasOneMemOperand())
19524 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19526 BuildMI(*BB, MI, dl,
19527 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19528 .addReg(X86::XMM0);
19530 MI->eraseFromParent();
19534 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19535 // defs in an instruction pattern
19536 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19537 const TargetInstrInfo *TII) {
19539 switch (MI->getOpcode()) {
19540 default: llvm_unreachable("illegal opcode!");
19541 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19542 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19543 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19544 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19545 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19546 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19547 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19548 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19551 DebugLoc dl = MI->getDebugLoc();
19552 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19554 unsigned NumArgs = MI->getNumOperands(); // remove the results
19555 for (unsigned i = 1; i < NumArgs; ++i) {
19556 MachineOperand &Op = MI->getOperand(i);
19557 if (!(Op.isReg() && Op.isImplicit()))
19558 MIB.addOperand(Op);
19560 if (MI->hasOneMemOperand())
19561 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19563 BuildMI(*BB, MI, dl,
19564 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19567 MI->eraseFromParent();
19571 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19572 const X86Subtarget *Subtarget) {
19573 DebugLoc dl = MI->getDebugLoc();
19574 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19575 // Address into RAX/EAX, other two args into ECX, EDX.
19576 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19577 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19578 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19579 for (int i = 0; i < X86::AddrNumOperands; ++i)
19580 MIB.addOperand(MI->getOperand(i));
19582 unsigned ValOps = X86::AddrNumOperands;
19583 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19584 .addReg(MI->getOperand(ValOps).getReg());
19585 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19586 .addReg(MI->getOperand(ValOps+1).getReg());
19588 // The instruction doesn't actually take any operands though.
19589 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19591 MI->eraseFromParent(); // The pseudo is gone now.
19595 MachineBasicBlock *
19596 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19597 MachineBasicBlock *MBB) const {
19598 // Emit va_arg instruction on X86-64.
19600 // Operands to this pseudo-instruction:
19601 // 0 ) Output : destination address (reg)
19602 // 1-5) Input : va_list address (addr, i64mem)
19603 // 6 ) ArgSize : Size (in bytes) of vararg type
19604 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19605 // 8 ) Align : Alignment of type
19606 // 9 ) EFLAGS (implicit-def)
19608 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19609 static_assert(X86::AddrNumOperands == 5,
19610 "VAARG_64 assumes 5 address operands");
19612 unsigned DestReg = MI->getOperand(0).getReg();
19613 MachineOperand &Base = MI->getOperand(1);
19614 MachineOperand &Scale = MI->getOperand(2);
19615 MachineOperand &Index = MI->getOperand(3);
19616 MachineOperand &Disp = MI->getOperand(4);
19617 MachineOperand &Segment = MI->getOperand(5);
19618 unsigned ArgSize = MI->getOperand(6).getImm();
19619 unsigned ArgMode = MI->getOperand(7).getImm();
19620 unsigned Align = MI->getOperand(8).getImm();
19622 // Memory Reference
19623 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19624 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19625 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19627 // Machine Information
19628 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19629 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19630 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19631 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19632 DebugLoc DL = MI->getDebugLoc();
19634 // struct va_list {
19637 // i64 overflow_area (address)
19638 // i64 reg_save_area (address)
19640 // sizeof(va_list) = 24
19641 // alignment(va_list) = 8
19643 unsigned TotalNumIntRegs = 6;
19644 unsigned TotalNumXMMRegs = 8;
19645 bool UseGPOffset = (ArgMode == 1);
19646 bool UseFPOffset = (ArgMode == 2);
19647 unsigned MaxOffset = TotalNumIntRegs * 8 +
19648 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19650 /* Align ArgSize to a multiple of 8 */
19651 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19652 bool NeedsAlign = (Align > 8);
19654 MachineBasicBlock *thisMBB = MBB;
19655 MachineBasicBlock *overflowMBB;
19656 MachineBasicBlock *offsetMBB;
19657 MachineBasicBlock *endMBB;
19659 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19660 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19661 unsigned OffsetReg = 0;
19663 if (!UseGPOffset && !UseFPOffset) {
19664 // If we only pull from the overflow region, we don't create a branch.
19665 // We don't need to alter control flow.
19666 OffsetDestReg = 0; // unused
19667 OverflowDestReg = DestReg;
19669 offsetMBB = nullptr;
19670 overflowMBB = thisMBB;
19673 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19674 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19675 // If not, pull from overflow_area. (branch to overflowMBB)
19680 // offsetMBB overflowMBB
19685 // Registers for the PHI in endMBB
19686 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19687 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19689 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19690 MachineFunction *MF = MBB->getParent();
19691 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19692 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19693 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19695 MachineFunction::iterator MBBIter = MBB;
19698 // Insert the new basic blocks
19699 MF->insert(MBBIter, offsetMBB);
19700 MF->insert(MBBIter, overflowMBB);
19701 MF->insert(MBBIter, endMBB);
19703 // Transfer the remainder of MBB and its successor edges to endMBB.
19704 endMBB->splice(endMBB->begin(), thisMBB,
19705 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19706 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19708 // Make offsetMBB and overflowMBB successors of thisMBB
19709 thisMBB->addSuccessor(offsetMBB);
19710 thisMBB->addSuccessor(overflowMBB);
19712 // endMBB is a successor of both offsetMBB and overflowMBB
19713 offsetMBB->addSuccessor(endMBB);
19714 overflowMBB->addSuccessor(endMBB);
19716 // Load the offset value into a register
19717 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19718 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19722 .addDisp(Disp, UseFPOffset ? 4 : 0)
19723 .addOperand(Segment)
19724 .setMemRefs(MMOBegin, MMOEnd);
19726 // Check if there is enough room left to pull this argument.
19727 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19729 .addImm(MaxOffset + 8 - ArgSizeA8);
19731 // Branch to "overflowMBB" if offset >= max
19732 // Fall through to "offsetMBB" otherwise
19733 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19734 .addMBB(overflowMBB);
19737 // In offsetMBB, emit code to use the reg_save_area.
19739 assert(OffsetReg != 0);
19741 // Read the reg_save_area address.
19742 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19743 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19748 .addOperand(Segment)
19749 .setMemRefs(MMOBegin, MMOEnd);
19751 // Zero-extend the offset
19752 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19753 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19756 .addImm(X86::sub_32bit);
19758 // Add the offset to the reg_save_area to get the final address.
19759 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19760 .addReg(OffsetReg64)
19761 .addReg(RegSaveReg);
19763 // Compute the offset for the next argument
19764 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19765 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19767 .addImm(UseFPOffset ? 16 : 8);
19769 // Store it back into the va_list.
19770 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19774 .addDisp(Disp, UseFPOffset ? 4 : 0)
19775 .addOperand(Segment)
19776 .addReg(NextOffsetReg)
19777 .setMemRefs(MMOBegin, MMOEnd);
19780 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19785 // Emit code to use overflow area
19788 // Load the overflow_area address into a register.
19789 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19790 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19795 .addOperand(Segment)
19796 .setMemRefs(MMOBegin, MMOEnd);
19798 // If we need to align it, do so. Otherwise, just copy the address
19799 // to OverflowDestReg.
19801 // Align the overflow address
19802 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19803 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19805 // aligned_addr = (addr + (align-1)) & ~(align-1)
19806 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19807 .addReg(OverflowAddrReg)
19810 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19812 .addImm(~(uint64_t)(Align-1));
19814 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19815 .addReg(OverflowAddrReg);
19818 // Compute the next overflow address after this argument.
19819 // (the overflow address should be kept 8-byte aligned)
19820 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19821 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19822 .addReg(OverflowDestReg)
19823 .addImm(ArgSizeA8);
19825 // Store the new overflow address.
19826 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19831 .addOperand(Segment)
19832 .addReg(NextAddrReg)
19833 .setMemRefs(MMOBegin, MMOEnd);
19835 // If we branched, emit the PHI to the front of endMBB.
19837 BuildMI(*endMBB, endMBB->begin(), DL,
19838 TII->get(X86::PHI), DestReg)
19839 .addReg(OffsetDestReg).addMBB(offsetMBB)
19840 .addReg(OverflowDestReg).addMBB(overflowMBB);
19843 // Erase the pseudo instruction
19844 MI->eraseFromParent();
19849 MachineBasicBlock *
19850 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19852 MachineBasicBlock *MBB) const {
19853 // Emit code to save XMM registers to the stack. The ABI says that the
19854 // number of registers to save is given in %al, so it's theoretically
19855 // possible to do an indirect jump trick to avoid saving all of them,
19856 // however this code takes a simpler approach and just executes all
19857 // of the stores if %al is non-zero. It's less code, and it's probably
19858 // easier on the hardware branch predictor, and stores aren't all that
19859 // expensive anyway.
19861 // Create the new basic blocks. One block contains all the XMM stores,
19862 // and one block is the final destination regardless of whether any
19863 // stores were performed.
19864 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19865 MachineFunction *F = MBB->getParent();
19866 MachineFunction::iterator MBBIter = MBB;
19868 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19869 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19870 F->insert(MBBIter, XMMSaveMBB);
19871 F->insert(MBBIter, EndMBB);
19873 // Transfer the remainder of MBB and its successor edges to EndMBB.
19874 EndMBB->splice(EndMBB->begin(), MBB,
19875 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19876 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19878 // The original block will now fall through to the XMM save block.
19879 MBB->addSuccessor(XMMSaveMBB);
19880 // The XMMSaveMBB will fall through to the end block.
19881 XMMSaveMBB->addSuccessor(EndMBB);
19883 // Now add the instructions.
19884 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19885 DebugLoc DL = MI->getDebugLoc();
19887 unsigned CountReg = MI->getOperand(0).getReg();
19888 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19889 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19891 if (!Subtarget->isTargetWin64()) {
19892 // If %al is 0, branch around the XMM save block.
19893 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19894 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19895 MBB->addSuccessor(EndMBB);
19898 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19899 // that was just emitted, but clearly shouldn't be "saved".
19900 assert((MI->getNumOperands() <= 3 ||
19901 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19902 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19903 && "Expected last argument to be EFLAGS");
19904 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19905 // In the XMM save block, save all the XMM argument registers.
19906 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19907 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19908 MachineMemOperand *MMO = F->getMachineMemOperand(
19909 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
19910 MachineMemOperand::MOStore,
19911 /*Size=*/16, /*Align=*/16);
19912 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19913 .addFrameIndex(RegSaveFrameIndex)
19914 .addImm(/*Scale=*/1)
19915 .addReg(/*IndexReg=*/0)
19916 .addImm(/*Disp=*/Offset)
19917 .addReg(/*Segment=*/0)
19918 .addReg(MI->getOperand(i).getReg())
19919 .addMemOperand(MMO);
19922 MI->eraseFromParent(); // The pseudo instruction is gone now.
19927 // The EFLAGS operand of SelectItr might be missing a kill marker
19928 // because there were multiple uses of EFLAGS, and ISel didn't know
19929 // which to mark. Figure out whether SelectItr should have had a
19930 // kill marker, and set it if it should. Returns the correct kill
19932 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19933 MachineBasicBlock* BB,
19934 const TargetRegisterInfo* TRI) {
19935 // Scan forward through BB for a use/def of EFLAGS.
19936 MachineBasicBlock::iterator miI(std::next(SelectItr));
19937 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19938 const MachineInstr& mi = *miI;
19939 if (mi.readsRegister(X86::EFLAGS))
19941 if (mi.definesRegister(X86::EFLAGS))
19942 break; // Should have kill-flag - update below.
19945 // If we hit the end of the block, check whether EFLAGS is live into a
19947 if (miI == BB->end()) {
19948 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19949 sEnd = BB->succ_end();
19950 sItr != sEnd; ++sItr) {
19951 MachineBasicBlock* succ = *sItr;
19952 if (succ->isLiveIn(X86::EFLAGS))
19957 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19958 // out. SelectMI should have a kill flag on EFLAGS.
19959 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19963 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
19964 // together with other CMOV pseudo-opcodes into a single basic-block with
19965 // conditional jump around it.
19966 static bool isCMOVPseudo(MachineInstr *MI) {
19967 switch (MI->getOpcode()) {
19968 case X86::CMOV_FR32:
19969 case X86::CMOV_FR64:
19970 case X86::CMOV_GR8:
19971 case X86::CMOV_GR16:
19972 case X86::CMOV_GR32:
19973 case X86::CMOV_RFP32:
19974 case X86::CMOV_RFP64:
19975 case X86::CMOV_RFP80:
19976 case X86::CMOV_V2F64:
19977 case X86::CMOV_V2I64:
19978 case X86::CMOV_V4F32:
19979 case X86::CMOV_V4F64:
19980 case X86::CMOV_V4I64:
19981 case X86::CMOV_V16F32:
19982 case X86::CMOV_V8F32:
19983 case X86::CMOV_V8F64:
19984 case X86::CMOV_V8I64:
19985 case X86::CMOV_V8I1:
19986 case X86::CMOV_V16I1:
19987 case X86::CMOV_V32I1:
19988 case X86::CMOV_V64I1:
19996 MachineBasicBlock *
19997 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19998 MachineBasicBlock *BB) const {
19999 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20000 DebugLoc DL = MI->getDebugLoc();
20002 // To "insert" a SELECT_CC instruction, we actually have to insert the
20003 // diamond control-flow pattern. The incoming instruction knows the
20004 // destination vreg to set, the condition code register to branch on, the
20005 // true/false values to select between, and a branch opcode to use.
20006 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20007 MachineFunction::iterator It = BB;
20013 // cmpTY ccX, r1, r2
20015 // fallthrough --> copy0MBB
20016 MachineBasicBlock *thisMBB = BB;
20017 MachineFunction *F = BB->getParent();
20019 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20020 // as described above, by inserting a BB, and then making a PHI at the join
20021 // point to select the true and false operands of the CMOV in the PHI.
20023 // The code also handles two different cases of multiple CMOV opcodes
20027 // In this case, there are multiple CMOVs in a row, all which are based on
20028 // the same condition setting (or the exact opposite condition setting).
20029 // In this case we can lower all the CMOVs using a single inserted BB, and
20030 // then make a number of PHIs at the join point to model the CMOVs. The only
20031 // trickiness here, is that in a case like:
20033 // t2 = CMOV cond1 t1, f1
20034 // t3 = CMOV cond1 t2, f2
20036 // when rewriting this into PHIs, we have to perform some renaming on the
20037 // temps since you cannot have a PHI operand refer to a PHI result earlier
20038 // in the same block. The "simple" but wrong lowering would be:
20040 // t2 = PHI t1(BB1), f1(BB2)
20041 // t3 = PHI t2(BB1), f2(BB2)
20043 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20044 // renaming is to note that on the path through BB1, t2 is really just a
20045 // copy of t1, and do that renaming, properly generating:
20047 // t2 = PHI t1(BB1), f1(BB2)
20048 // t3 = PHI t1(BB1), f2(BB2)
20050 // Case 2, we lower cascaded CMOVs such as
20052 // (CMOV (CMOV F, T, cc1), T, cc2)
20054 // to two successives branches. For that, we look for another CMOV as the
20055 // following instruction.
20057 // Without this, we would add a PHI between the two jumps, which ends up
20058 // creating a few copies all around. For instance, for
20060 // (sitofp (zext (fcmp une)))
20062 // we would generate:
20064 // ucomiss %xmm1, %xmm0
20065 // movss <1.0f>, %xmm0
20066 // movaps %xmm0, %xmm1
20068 // xorps %xmm1, %xmm1
20071 // movaps %xmm1, %xmm0
20075 // because this custom-inserter would have generated:
20087 // A: X = ...; Y = ...
20089 // C: Z = PHI [X, A], [Y, B]
20091 // E: PHI [X, C], [Z, D]
20093 // If we lower both CMOVs in a single step, we can instead generate:
20105 // A: X = ...; Y = ...
20107 // E: PHI [X, A], [X, C], [Y, D]
20109 // Which, in our sitofp/fcmp example, gives us something like:
20111 // ucomiss %xmm1, %xmm0
20112 // movss <1.0f>, %xmm0
20115 // xorps %xmm0, %xmm0
20119 MachineInstr *CascadedCMOV = nullptr;
20120 MachineInstr *LastCMOV = MI;
20121 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20122 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20123 MachineBasicBlock::iterator NextMIIt =
20124 std::next(MachineBasicBlock::iterator(MI));
20126 // Check for case 1, where there are multiple CMOVs with the same condition
20127 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20128 // number of jumps the most.
20130 if (isCMOVPseudo(MI)) {
20131 // See if we have a string of CMOVS with the same condition.
20132 while (NextMIIt != BB->end() &&
20133 isCMOVPseudo(NextMIIt) &&
20134 (NextMIIt->getOperand(3).getImm() == CC ||
20135 NextMIIt->getOperand(3).getImm() == OppCC)) {
20136 LastCMOV = &*NextMIIt;
20141 // This checks for case 2, but only do this if we didn't already find
20142 // case 1, as indicated by LastCMOV == MI.
20143 if (LastCMOV == MI &&
20144 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20145 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20146 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20147 CascadedCMOV = &*NextMIIt;
20150 MachineBasicBlock *jcc1MBB = nullptr;
20152 // If we have a cascaded CMOV, we lower it to two successive branches to
20153 // the same block. EFLAGS is used by both, so mark it as live in the second.
20154 if (CascadedCMOV) {
20155 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20156 F->insert(It, jcc1MBB);
20157 jcc1MBB->addLiveIn(X86::EFLAGS);
20160 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20161 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20162 F->insert(It, copy0MBB);
20163 F->insert(It, sinkMBB);
20165 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20166 // live into the sink and copy blocks.
20167 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20169 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20170 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20171 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20172 copy0MBB->addLiveIn(X86::EFLAGS);
20173 sinkMBB->addLiveIn(X86::EFLAGS);
20176 // Transfer the remainder of BB and its successor edges to sinkMBB.
20177 sinkMBB->splice(sinkMBB->begin(), BB,
20178 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20179 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20181 // Add the true and fallthrough blocks as its successors.
20182 if (CascadedCMOV) {
20183 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20184 BB->addSuccessor(jcc1MBB);
20186 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20187 // jump to the sinkMBB.
20188 jcc1MBB->addSuccessor(copy0MBB);
20189 jcc1MBB->addSuccessor(sinkMBB);
20191 BB->addSuccessor(copy0MBB);
20194 // The true block target of the first (or only) branch is always sinkMBB.
20195 BB->addSuccessor(sinkMBB);
20197 // Create the conditional branch instruction.
20198 unsigned Opc = X86::GetCondBranchFromCond(CC);
20199 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20201 if (CascadedCMOV) {
20202 unsigned Opc2 = X86::GetCondBranchFromCond(
20203 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20204 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20208 // %FalseValue = ...
20209 // # fallthrough to sinkMBB
20210 copy0MBB->addSuccessor(sinkMBB);
20213 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20215 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20216 MachineBasicBlock::iterator MIItEnd =
20217 std::next(MachineBasicBlock::iterator(LastCMOV));
20218 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20219 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20220 MachineInstrBuilder MIB;
20222 // As we are creating the PHIs, we have to be careful if there is more than
20223 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20224 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20225 // That also means that PHI construction must work forward from earlier to
20226 // later, and that the code must maintain a mapping from earlier PHI's
20227 // destination registers, and the registers that went into the PHI.
20229 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20230 unsigned DestReg = MIIt->getOperand(0).getReg();
20231 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20232 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20234 // If this CMOV we are generating is the opposite condition from
20235 // the jump we generated, then we have to swap the operands for the
20236 // PHI that is going to be generated.
20237 if (MIIt->getOperand(3).getImm() == OppCC)
20238 std::swap(Op1Reg, Op2Reg);
20240 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20241 Op1Reg = RegRewriteTable[Op1Reg].first;
20243 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20244 Op2Reg = RegRewriteTable[Op2Reg].second;
20246 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20247 TII->get(X86::PHI), DestReg)
20248 .addReg(Op1Reg).addMBB(copy0MBB)
20249 .addReg(Op2Reg).addMBB(thisMBB);
20251 // Add this PHI to the rewrite table.
20252 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20255 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20256 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20257 if (CascadedCMOV) {
20258 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20259 // Copy the PHI result to the register defined by the second CMOV.
20260 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20261 DL, TII->get(TargetOpcode::COPY),
20262 CascadedCMOV->getOperand(0).getReg())
20263 .addReg(MI->getOperand(0).getReg());
20264 CascadedCMOV->eraseFromParent();
20267 // Now remove the CMOV(s).
20268 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20269 (MIIt++)->eraseFromParent();
20274 MachineBasicBlock *
20275 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20276 MachineBasicBlock *BB) const {
20277 // Combine the following atomic floating-point modification pattern:
20278 // a.store(reg OP a.load(acquire), release)
20279 // Transform them into:
20280 // OPss (%gpr), %xmm
20281 // movss %xmm, (%gpr)
20282 // Or sd equivalent for 64-bit operations.
20284 switch (MI->getOpcode()) {
20285 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20286 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20287 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20289 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20290 DebugLoc DL = MI->getDebugLoc();
20291 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20292 unsigned MSrc = MI->getOperand(0).getReg();
20293 unsigned VSrc = MI->getOperand(5).getReg();
20294 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20295 .addReg(/*Base=*/MSrc)
20296 .addImm(/*Scale=*/1)
20297 .addReg(/*Index=*/0)
20300 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20301 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20303 .addReg(/*Base=*/MSrc)
20304 .addImm(/*Scale=*/1)
20305 .addReg(/*Index=*/0)
20306 .addImm(/*Disp=*/0)
20307 .addReg(/*Segment=*/0);
20308 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20309 MI->eraseFromParent(); // The pseudo instruction is gone now.
20313 MachineBasicBlock *
20314 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20315 MachineBasicBlock *BB) const {
20316 MachineFunction *MF = BB->getParent();
20317 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20318 DebugLoc DL = MI->getDebugLoc();
20319 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20321 assert(MF->shouldSplitStack());
20323 const bool Is64Bit = Subtarget->is64Bit();
20324 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20326 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20327 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20330 // ... [Till the alloca]
20331 // If stacklet is not large enough, jump to mallocMBB
20334 // Allocate by subtracting from RSP
20335 // Jump to continueMBB
20338 // Allocate by call to runtime
20342 // [rest of original BB]
20345 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20346 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20347 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20349 MachineRegisterInfo &MRI = MF->getRegInfo();
20350 const TargetRegisterClass *AddrRegClass =
20351 getRegClassFor(getPointerTy(MF->getDataLayout()));
20353 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20354 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20355 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20356 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20357 sizeVReg = MI->getOperand(1).getReg(),
20358 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20360 MachineFunction::iterator MBBIter = BB;
20363 MF->insert(MBBIter, bumpMBB);
20364 MF->insert(MBBIter, mallocMBB);
20365 MF->insert(MBBIter, continueMBB);
20367 continueMBB->splice(continueMBB->begin(), BB,
20368 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20369 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20371 // Add code to the main basic block to check if the stack limit has been hit,
20372 // and if so, jump to mallocMBB otherwise to bumpMBB.
20373 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20374 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20375 .addReg(tmpSPVReg).addReg(sizeVReg);
20376 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20377 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20378 .addReg(SPLimitVReg);
20379 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20381 // bumpMBB simply decreases the stack pointer, since we know the current
20382 // stacklet has enough space.
20383 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20384 .addReg(SPLimitVReg);
20385 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20386 .addReg(SPLimitVReg);
20387 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20389 // Calls into a routine in libgcc to allocate more space from the heap.
20390 const uint32_t *RegMask =
20391 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20393 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20395 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20396 .addExternalSymbol("__morestack_allocate_stack_space")
20397 .addRegMask(RegMask)
20398 .addReg(X86::RDI, RegState::Implicit)
20399 .addReg(X86::RAX, RegState::ImplicitDefine);
20400 } else if (Is64Bit) {
20401 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20403 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20404 .addExternalSymbol("__morestack_allocate_stack_space")
20405 .addRegMask(RegMask)
20406 .addReg(X86::EDI, RegState::Implicit)
20407 .addReg(X86::EAX, RegState::ImplicitDefine);
20409 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20411 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20412 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20413 .addExternalSymbol("__morestack_allocate_stack_space")
20414 .addRegMask(RegMask)
20415 .addReg(X86::EAX, RegState::ImplicitDefine);
20419 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20422 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20423 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20424 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20426 // Set up the CFG correctly.
20427 BB->addSuccessor(bumpMBB);
20428 BB->addSuccessor(mallocMBB);
20429 mallocMBB->addSuccessor(continueMBB);
20430 bumpMBB->addSuccessor(continueMBB);
20432 // Take care of the PHI nodes.
20433 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20434 MI->getOperand(0).getReg())
20435 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20436 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20438 // Delete the original pseudo instruction.
20439 MI->eraseFromParent();
20442 return continueMBB;
20445 MachineBasicBlock *
20446 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20447 MachineBasicBlock *BB) const {
20448 DebugLoc DL = MI->getDebugLoc();
20450 assert(!Subtarget->isTargetMachO());
20452 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20455 MI->eraseFromParent(); // The pseudo instruction is gone now.
20459 MachineBasicBlock *
20460 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20461 MachineBasicBlock *BB) const {
20462 // This is pretty easy. We're taking the value that we received from
20463 // our load from the relocation, sticking it in either RDI (x86-64)
20464 // or EAX and doing an indirect call. The return value will then
20465 // be in the normal return register.
20466 MachineFunction *F = BB->getParent();
20467 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20468 DebugLoc DL = MI->getDebugLoc();
20470 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20471 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20473 // Get a register mask for the lowered call.
20474 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20475 // proper register mask.
20476 const uint32_t *RegMask =
20477 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20478 if (Subtarget->is64Bit()) {
20479 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20480 TII->get(X86::MOV64rm), X86::RDI)
20482 .addImm(0).addReg(0)
20483 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20484 MI->getOperand(3).getTargetFlags())
20486 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20487 addDirectMem(MIB, X86::RDI);
20488 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20489 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20490 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20491 TII->get(X86::MOV32rm), X86::EAX)
20493 .addImm(0).addReg(0)
20494 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20495 MI->getOperand(3).getTargetFlags())
20497 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20498 addDirectMem(MIB, X86::EAX);
20499 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20501 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20502 TII->get(X86::MOV32rm), X86::EAX)
20503 .addReg(TII->getGlobalBaseReg(F))
20504 .addImm(0).addReg(0)
20505 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20506 MI->getOperand(3).getTargetFlags())
20508 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20509 addDirectMem(MIB, X86::EAX);
20510 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20513 MI->eraseFromParent(); // The pseudo instruction is gone now.
20517 MachineBasicBlock *
20518 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20519 MachineBasicBlock *MBB) const {
20520 DebugLoc DL = MI->getDebugLoc();
20521 MachineFunction *MF = MBB->getParent();
20522 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20523 MachineRegisterInfo &MRI = MF->getRegInfo();
20525 const BasicBlock *BB = MBB->getBasicBlock();
20526 MachineFunction::iterator I = MBB;
20529 // Memory Reference
20530 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20531 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20534 unsigned MemOpndSlot = 0;
20536 unsigned CurOp = 0;
20538 DstReg = MI->getOperand(CurOp++).getReg();
20539 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20540 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20541 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20542 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20544 MemOpndSlot = CurOp;
20546 MVT PVT = getPointerTy(MF->getDataLayout());
20547 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20548 "Invalid Pointer Size!");
20550 // For v = setjmp(buf), we generate
20553 // buf[LabelOffset] = restoreMBB
20554 // SjLjSetup restoreMBB
20560 // v = phi(main, restore)
20563 // if base pointer being used, load it from frame
20566 MachineBasicBlock *thisMBB = MBB;
20567 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20568 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20569 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20570 MF->insert(I, mainMBB);
20571 MF->insert(I, sinkMBB);
20572 MF->push_back(restoreMBB);
20574 MachineInstrBuilder MIB;
20576 // Transfer the remainder of BB and its successor edges to sinkMBB.
20577 sinkMBB->splice(sinkMBB->begin(), MBB,
20578 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20579 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20582 unsigned PtrStoreOpc = 0;
20583 unsigned LabelReg = 0;
20584 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20585 Reloc::Model RM = MF->getTarget().getRelocationModel();
20586 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20587 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20589 // Prepare IP either in reg or imm.
20590 if (!UseImmLabel) {
20591 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20592 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20593 LabelReg = MRI.createVirtualRegister(PtrRC);
20594 if (Subtarget->is64Bit()) {
20595 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20599 .addMBB(restoreMBB)
20602 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20603 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20604 .addReg(XII->getGlobalBaseReg(MF))
20607 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20611 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20613 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20614 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20615 if (i == X86::AddrDisp)
20616 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20618 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20621 MIB.addReg(LabelReg);
20623 MIB.addMBB(restoreMBB);
20624 MIB.setMemRefs(MMOBegin, MMOEnd);
20626 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20627 .addMBB(restoreMBB);
20629 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20630 MIB.addRegMask(RegInfo->getNoPreservedMask());
20631 thisMBB->addSuccessor(mainMBB);
20632 thisMBB->addSuccessor(restoreMBB);
20636 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20637 mainMBB->addSuccessor(sinkMBB);
20640 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20641 TII->get(X86::PHI), DstReg)
20642 .addReg(mainDstReg).addMBB(mainMBB)
20643 .addReg(restoreDstReg).addMBB(restoreMBB);
20646 if (RegInfo->hasBasePointer(*MF)) {
20647 const bool Uses64BitFramePtr =
20648 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20649 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20650 X86FI->setRestoreBasePointer(MF);
20651 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20652 unsigned BasePtr = RegInfo->getBaseRegister();
20653 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20654 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20655 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20656 .setMIFlag(MachineInstr::FrameSetup);
20658 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20659 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20660 restoreMBB->addSuccessor(sinkMBB);
20662 MI->eraseFromParent();
20666 MachineBasicBlock *
20667 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20668 MachineBasicBlock *MBB) const {
20669 DebugLoc DL = MI->getDebugLoc();
20670 MachineFunction *MF = MBB->getParent();
20671 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20672 MachineRegisterInfo &MRI = MF->getRegInfo();
20674 // Memory Reference
20675 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20676 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20678 MVT PVT = getPointerTy(MF->getDataLayout());
20679 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20680 "Invalid Pointer Size!");
20682 const TargetRegisterClass *RC =
20683 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20684 unsigned Tmp = MRI.createVirtualRegister(RC);
20685 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20686 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20687 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20688 unsigned SP = RegInfo->getStackRegister();
20690 MachineInstrBuilder MIB;
20692 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20693 const int64_t SPOffset = 2 * PVT.getStoreSize();
20695 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20696 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20699 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20700 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20701 MIB.addOperand(MI->getOperand(i));
20702 MIB.setMemRefs(MMOBegin, MMOEnd);
20704 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20705 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20706 if (i == X86::AddrDisp)
20707 MIB.addDisp(MI->getOperand(i), LabelOffset);
20709 MIB.addOperand(MI->getOperand(i));
20711 MIB.setMemRefs(MMOBegin, MMOEnd);
20713 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20714 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20715 if (i == X86::AddrDisp)
20716 MIB.addDisp(MI->getOperand(i), SPOffset);
20718 MIB.addOperand(MI->getOperand(i));
20720 MIB.setMemRefs(MMOBegin, MMOEnd);
20722 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20724 MI->eraseFromParent();
20728 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20729 // accumulator loops. Writing back to the accumulator allows the coalescer
20730 // to remove extra copies in the loop.
20731 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20732 MachineBasicBlock *
20733 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20734 MachineBasicBlock *MBB) const {
20735 MachineOperand &AddendOp = MI->getOperand(3);
20737 // Bail out early if the addend isn't a register - we can't switch these.
20738 if (!AddendOp.isReg())
20741 MachineFunction &MF = *MBB->getParent();
20742 MachineRegisterInfo &MRI = MF.getRegInfo();
20744 // Check whether the addend is defined by a PHI:
20745 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20746 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20747 if (!AddendDef.isPHI())
20750 // Look for the following pattern:
20752 // %addend = phi [%entry, 0], [%loop, %result]
20754 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20758 // %addend = phi [%entry, 0], [%loop, %result]
20760 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20762 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20763 assert(AddendDef.getOperand(i).isReg());
20764 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20765 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20766 if (&PHISrcInst == MI) {
20767 // Found a matching instruction.
20768 unsigned NewFMAOpc = 0;
20769 switch (MI->getOpcode()) {
20770 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20771 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20772 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20773 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20774 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20775 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20776 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20777 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20778 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20779 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20780 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20781 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20782 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20783 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20784 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20785 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20786 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20787 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20788 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20789 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20791 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20792 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20793 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20794 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20795 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20796 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20797 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20798 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20799 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20800 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20801 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20802 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20803 default: llvm_unreachable("Unrecognized FMA variant.");
20806 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20807 MachineInstrBuilder MIB =
20808 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20809 .addOperand(MI->getOperand(0))
20810 .addOperand(MI->getOperand(3))
20811 .addOperand(MI->getOperand(2))
20812 .addOperand(MI->getOperand(1));
20813 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20814 MI->eraseFromParent();
20821 MachineBasicBlock *
20822 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20823 MachineBasicBlock *BB) const {
20824 switch (MI->getOpcode()) {
20825 default: llvm_unreachable("Unexpected instr type to insert");
20826 case X86::TAILJMPd64:
20827 case X86::TAILJMPr64:
20828 case X86::TAILJMPm64:
20829 case X86::TAILJMPd64_REX:
20830 case X86::TAILJMPr64_REX:
20831 case X86::TAILJMPm64_REX:
20832 llvm_unreachable("TAILJMP64 would not be touched here.");
20833 case X86::TCRETURNdi64:
20834 case X86::TCRETURNri64:
20835 case X86::TCRETURNmi64:
20837 case X86::WIN_ALLOCA:
20838 return EmitLoweredWinAlloca(MI, BB);
20839 case X86::SEG_ALLOCA_32:
20840 case X86::SEG_ALLOCA_64:
20841 return EmitLoweredSegAlloca(MI, BB);
20842 case X86::TLSCall_32:
20843 case X86::TLSCall_64:
20844 return EmitLoweredTLSCall(MI, BB);
20845 case X86::CMOV_FR32:
20846 case X86::CMOV_FR64:
20847 case X86::CMOV_GR8:
20848 case X86::CMOV_GR16:
20849 case X86::CMOV_GR32:
20850 case X86::CMOV_RFP32:
20851 case X86::CMOV_RFP64:
20852 case X86::CMOV_RFP80:
20853 case X86::CMOV_V2F64:
20854 case X86::CMOV_V2I64:
20855 case X86::CMOV_V4F32:
20856 case X86::CMOV_V4F64:
20857 case X86::CMOV_V4I64:
20858 case X86::CMOV_V16F32:
20859 case X86::CMOV_V8F32:
20860 case X86::CMOV_V8F64:
20861 case X86::CMOV_V8I64:
20862 case X86::CMOV_V8I1:
20863 case X86::CMOV_V16I1:
20864 case X86::CMOV_V32I1:
20865 case X86::CMOV_V64I1:
20866 return EmitLoweredSelect(MI, BB);
20868 case X86::RELEASE_FADD32mr:
20869 case X86::RELEASE_FADD64mr:
20870 return EmitLoweredAtomicFP(MI, BB);
20872 case X86::FP32_TO_INT16_IN_MEM:
20873 case X86::FP32_TO_INT32_IN_MEM:
20874 case X86::FP32_TO_INT64_IN_MEM:
20875 case X86::FP64_TO_INT16_IN_MEM:
20876 case X86::FP64_TO_INT32_IN_MEM:
20877 case X86::FP64_TO_INT64_IN_MEM:
20878 case X86::FP80_TO_INT16_IN_MEM:
20879 case X86::FP80_TO_INT32_IN_MEM:
20880 case X86::FP80_TO_INT64_IN_MEM: {
20881 MachineFunction *F = BB->getParent();
20882 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20883 DebugLoc DL = MI->getDebugLoc();
20885 // Change the floating point control register to use "round towards zero"
20886 // mode when truncating to an integer value.
20887 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20888 addFrameReference(BuildMI(*BB, MI, DL,
20889 TII->get(X86::FNSTCW16m)), CWFrameIdx);
20891 // Load the old value of the high byte of the control word...
20893 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20894 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20897 // Set the high part to be round to zero...
20898 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20901 // Reload the modified control word now...
20902 addFrameReference(BuildMI(*BB, MI, DL,
20903 TII->get(X86::FLDCW16m)), CWFrameIdx);
20905 // Restore the memory image of control word to original value
20906 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20909 // Get the X86 opcode to use.
20911 switch (MI->getOpcode()) {
20912 default: llvm_unreachable("illegal opcode!");
20913 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20914 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20915 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20916 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20917 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20918 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20919 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20920 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20921 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20925 MachineOperand &Op = MI->getOperand(0);
20927 AM.BaseType = X86AddressMode::RegBase;
20928 AM.Base.Reg = Op.getReg();
20930 AM.BaseType = X86AddressMode::FrameIndexBase;
20931 AM.Base.FrameIndex = Op.getIndex();
20933 Op = MI->getOperand(1);
20935 AM.Scale = Op.getImm();
20936 Op = MI->getOperand(2);
20938 AM.IndexReg = Op.getImm();
20939 Op = MI->getOperand(3);
20940 if (Op.isGlobal()) {
20941 AM.GV = Op.getGlobal();
20943 AM.Disp = Op.getImm();
20945 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20946 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20948 // Reload the original control word now.
20949 addFrameReference(BuildMI(*BB, MI, DL,
20950 TII->get(X86::FLDCW16m)), CWFrameIdx);
20952 MI->eraseFromParent(); // The pseudo instruction is gone now.
20955 // String/text processing lowering.
20956 case X86::PCMPISTRM128REG:
20957 case X86::VPCMPISTRM128REG:
20958 case X86::PCMPISTRM128MEM:
20959 case X86::VPCMPISTRM128MEM:
20960 case X86::PCMPESTRM128REG:
20961 case X86::VPCMPESTRM128REG:
20962 case X86::PCMPESTRM128MEM:
20963 case X86::VPCMPESTRM128MEM:
20964 assert(Subtarget->hasSSE42() &&
20965 "Target must have SSE4.2 or AVX features enabled");
20966 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20968 // String/text processing lowering.
20969 case X86::PCMPISTRIREG:
20970 case X86::VPCMPISTRIREG:
20971 case X86::PCMPISTRIMEM:
20972 case X86::VPCMPISTRIMEM:
20973 case X86::PCMPESTRIREG:
20974 case X86::VPCMPESTRIREG:
20975 case X86::PCMPESTRIMEM:
20976 case X86::VPCMPESTRIMEM:
20977 assert(Subtarget->hasSSE42() &&
20978 "Target must have SSE4.2 or AVX features enabled");
20979 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20981 // Thread synchronization.
20983 return EmitMonitor(MI, BB, Subtarget);
20987 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20989 case X86::VASTART_SAVE_XMM_REGS:
20990 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20992 case X86::VAARG_64:
20993 return EmitVAARG64WithCustomInserter(MI, BB);
20995 case X86::EH_SjLj_SetJmp32:
20996 case X86::EH_SjLj_SetJmp64:
20997 return emitEHSjLjSetJmp(MI, BB);
20999 case X86::EH_SjLj_LongJmp32:
21000 case X86::EH_SjLj_LongJmp64:
21001 return emitEHSjLjLongJmp(MI, BB);
21003 case TargetOpcode::STATEPOINT:
21004 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21005 // this point in the process. We diverge later.
21006 return emitPatchPoint(MI, BB);
21008 case TargetOpcode::STACKMAP:
21009 case TargetOpcode::PATCHPOINT:
21010 return emitPatchPoint(MI, BB);
21012 case X86::VFMADDPDr213r:
21013 case X86::VFMADDPSr213r:
21014 case X86::VFMADDSDr213r:
21015 case X86::VFMADDSSr213r:
21016 case X86::VFMSUBPDr213r:
21017 case X86::VFMSUBPSr213r:
21018 case X86::VFMSUBSDr213r:
21019 case X86::VFMSUBSSr213r:
21020 case X86::VFNMADDPDr213r:
21021 case X86::VFNMADDPSr213r:
21022 case X86::VFNMADDSDr213r:
21023 case X86::VFNMADDSSr213r:
21024 case X86::VFNMSUBPDr213r:
21025 case X86::VFNMSUBPSr213r:
21026 case X86::VFNMSUBSDr213r:
21027 case X86::VFNMSUBSSr213r:
21028 case X86::VFMADDSUBPDr213r:
21029 case X86::VFMADDSUBPSr213r:
21030 case X86::VFMSUBADDPDr213r:
21031 case X86::VFMSUBADDPSr213r:
21032 case X86::VFMADDPDr213rY:
21033 case X86::VFMADDPSr213rY:
21034 case X86::VFMSUBPDr213rY:
21035 case X86::VFMSUBPSr213rY:
21036 case X86::VFNMADDPDr213rY:
21037 case X86::VFNMADDPSr213rY:
21038 case X86::VFNMSUBPDr213rY:
21039 case X86::VFNMSUBPSr213rY:
21040 case X86::VFMADDSUBPDr213rY:
21041 case X86::VFMADDSUBPSr213rY:
21042 case X86::VFMSUBADDPDr213rY:
21043 case X86::VFMSUBADDPSr213rY:
21044 return emitFMA3Instr(MI, BB);
21048 //===----------------------------------------------------------------------===//
21049 // X86 Optimization Hooks
21050 //===----------------------------------------------------------------------===//
21052 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21055 const SelectionDAG &DAG,
21056 unsigned Depth) const {
21057 unsigned BitWidth = KnownZero.getBitWidth();
21058 unsigned Opc = Op.getOpcode();
21059 assert((Opc >= ISD::BUILTIN_OP_END ||
21060 Opc == ISD::INTRINSIC_WO_CHAIN ||
21061 Opc == ISD::INTRINSIC_W_CHAIN ||
21062 Opc == ISD::INTRINSIC_VOID) &&
21063 "Should use MaskedValueIsZero if you don't know whether Op"
21064 " is a target node!");
21066 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21080 // These nodes' second result is a boolean.
21081 if (Op.getResNo() == 0)
21084 case X86ISD::SETCC:
21085 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21087 case ISD::INTRINSIC_WO_CHAIN: {
21088 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21089 unsigned NumLoBits = 0;
21092 case Intrinsic::x86_sse_movmsk_ps:
21093 case Intrinsic::x86_avx_movmsk_ps_256:
21094 case Intrinsic::x86_sse2_movmsk_pd:
21095 case Intrinsic::x86_avx_movmsk_pd_256:
21096 case Intrinsic::x86_mmx_pmovmskb:
21097 case Intrinsic::x86_sse2_pmovmskb_128:
21098 case Intrinsic::x86_avx2_pmovmskb: {
21099 // High bits of movmskp{s|d}, pmovmskb are known zero.
21101 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21102 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21103 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21104 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21105 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21106 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21107 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21108 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21110 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21119 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21121 const SelectionDAG &,
21122 unsigned Depth) const {
21123 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21124 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21125 return Op.getValueType().getScalarType().getSizeInBits();
21131 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21132 /// node is a GlobalAddress + offset.
21133 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21134 const GlobalValue* &GA,
21135 int64_t &Offset) const {
21136 if (N->getOpcode() == X86ISD::Wrapper) {
21137 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21138 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21139 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21143 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21146 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21147 /// same as extracting the high 128-bit part of 256-bit vector and then
21148 /// inserting the result into the low part of a new 256-bit vector
21149 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21150 EVT VT = SVOp->getValueType(0);
21151 unsigned NumElems = VT.getVectorNumElements();
21153 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21154 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21155 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21156 SVOp->getMaskElt(j) >= 0)
21162 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21163 /// same as extracting the low 128-bit part of 256-bit vector and then
21164 /// inserting the result into the high part of a new 256-bit vector
21165 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21166 EVT VT = SVOp->getValueType(0);
21167 unsigned NumElems = VT.getVectorNumElements();
21169 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21170 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21171 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21172 SVOp->getMaskElt(j) >= 0)
21178 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21179 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21180 TargetLowering::DAGCombinerInfo &DCI,
21181 const X86Subtarget* Subtarget) {
21183 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21184 SDValue V1 = SVOp->getOperand(0);
21185 SDValue V2 = SVOp->getOperand(1);
21186 EVT VT = SVOp->getValueType(0);
21187 unsigned NumElems = VT.getVectorNumElements();
21189 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21190 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21194 // V UNDEF BUILD_VECTOR UNDEF
21196 // CONCAT_VECTOR CONCAT_VECTOR
21199 // RESULT: V + zero extended
21201 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21202 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21203 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21206 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21209 // To match the shuffle mask, the first half of the mask should
21210 // be exactly the first vector, and all the rest a splat with the
21211 // first element of the second one.
21212 for (unsigned i = 0; i != NumElems/2; ++i)
21213 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21214 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21217 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21218 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21219 if (Ld->hasNUsesOfValue(1, 0)) {
21220 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21221 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21223 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21225 Ld->getPointerInfo(),
21226 Ld->getAlignment(),
21227 false/*isVolatile*/, true/*ReadMem*/,
21228 false/*WriteMem*/);
21230 // Make sure the newly-created LOAD is in the same position as Ld in
21231 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21232 // and update uses of Ld's output chain to use the TokenFactor.
21233 if (Ld->hasAnyUseOfValue(1)) {
21234 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21235 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21236 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21237 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21238 SDValue(ResNode.getNode(), 1));
21241 return DAG.getBitcast(VT, ResNode);
21245 // Emit a zeroed vector and insert the desired subvector on its
21247 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21248 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21249 return DCI.CombineTo(N, InsV);
21252 //===--------------------------------------------------------------------===//
21253 // Combine some shuffles into subvector extracts and inserts:
21256 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21257 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21258 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21259 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21260 return DCI.CombineTo(N, InsV);
21263 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21264 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21265 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21266 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21267 return DCI.CombineTo(N, InsV);
21273 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21276 /// This is the leaf of the recursive combinine below. When we have found some
21277 /// chain of single-use x86 shuffle instructions and accumulated the combined
21278 /// shuffle mask represented by them, this will try to pattern match that mask
21279 /// into either a single instruction if there is a special purpose instruction
21280 /// for this operation, or into a PSHUFB instruction which is a fully general
21281 /// instruction but should only be used to replace chains over a certain depth.
21282 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21283 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21284 TargetLowering::DAGCombinerInfo &DCI,
21285 const X86Subtarget *Subtarget) {
21286 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21288 // Find the operand that enters the chain. Note that multiple uses are OK
21289 // here, we're not going to remove the operand we find.
21290 SDValue Input = Op.getOperand(0);
21291 while (Input.getOpcode() == ISD::BITCAST)
21292 Input = Input.getOperand(0);
21294 MVT VT = Input.getSimpleValueType();
21295 MVT RootVT = Root.getSimpleValueType();
21298 // Just remove no-op shuffle masks.
21299 if (Mask.size() == 1) {
21300 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21305 // Use the float domain if the operand type is a floating point type.
21306 bool FloatDomain = VT.isFloatingPoint();
21308 // For floating point shuffles, we don't have free copies in the shuffle
21309 // instructions or the ability to load as part of the instruction, so
21310 // canonicalize their shuffles to UNPCK or MOV variants.
21312 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21313 // vectors because it can have a load folded into it that UNPCK cannot. This
21314 // doesn't preclude something switching to the shorter encoding post-RA.
21316 // FIXME: Should teach these routines about AVX vector widths.
21317 if (FloatDomain && VT.getSizeInBits() == 128) {
21318 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21319 bool Lo = Mask.equals({0, 0});
21322 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21323 // is no slower than UNPCKLPD but has the option to fold the input operand
21324 // into even an unaligned memory load.
21325 if (Lo && Subtarget->hasSSE3()) {
21326 Shuffle = X86ISD::MOVDDUP;
21327 ShuffleVT = MVT::v2f64;
21329 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21330 // than the UNPCK variants.
21331 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21332 ShuffleVT = MVT::v4f32;
21334 if (Depth == 1 && Root->getOpcode() == Shuffle)
21335 return false; // Nothing to do!
21336 Op = DAG.getBitcast(ShuffleVT, Input);
21337 DCI.AddToWorklist(Op.getNode());
21338 if (Shuffle == X86ISD::MOVDDUP)
21339 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21341 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21342 DCI.AddToWorklist(Op.getNode());
21343 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21347 if (Subtarget->hasSSE3() &&
21348 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21349 bool Lo = Mask.equals({0, 0, 2, 2});
21350 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21351 MVT ShuffleVT = MVT::v4f32;
21352 if (Depth == 1 && Root->getOpcode() == Shuffle)
21353 return false; // Nothing to do!
21354 Op = DAG.getBitcast(ShuffleVT, Input);
21355 DCI.AddToWorklist(Op.getNode());
21356 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21357 DCI.AddToWorklist(Op.getNode());
21358 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21362 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21363 bool Lo = Mask.equals({0, 0, 1, 1});
21364 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21365 MVT ShuffleVT = MVT::v4f32;
21366 if (Depth == 1 && Root->getOpcode() == Shuffle)
21367 return false; // Nothing to do!
21368 Op = DAG.getBitcast(ShuffleVT, Input);
21369 DCI.AddToWorklist(Op.getNode());
21370 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21371 DCI.AddToWorklist(Op.getNode());
21372 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21378 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21379 // variants as none of these have single-instruction variants that are
21380 // superior to the UNPCK formulation.
21381 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21382 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21383 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21384 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21386 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21387 bool Lo = Mask[0] == 0;
21388 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21389 if (Depth == 1 && Root->getOpcode() == Shuffle)
21390 return false; // Nothing to do!
21392 switch (Mask.size()) {
21394 ShuffleVT = MVT::v8i16;
21397 ShuffleVT = MVT::v16i8;
21400 llvm_unreachable("Impossible mask size!");
21402 Op = DAG.getBitcast(ShuffleVT, Input);
21403 DCI.AddToWorklist(Op.getNode());
21404 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21405 DCI.AddToWorklist(Op.getNode());
21406 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21411 // Don't try to re-form single instruction chains under any circumstances now
21412 // that we've done encoding canonicalization for them.
21416 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21417 // can replace them with a single PSHUFB instruction profitably. Intel's
21418 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21419 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21420 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21421 SmallVector<SDValue, 16> PSHUFBMask;
21422 int NumBytes = VT.getSizeInBits() / 8;
21423 int Ratio = NumBytes / Mask.size();
21424 for (int i = 0; i < NumBytes; ++i) {
21425 if (Mask[i / Ratio] == SM_SentinelUndef) {
21426 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21429 int M = Mask[i / Ratio] != SM_SentinelZero
21430 ? Ratio * Mask[i / Ratio] + i % Ratio
21432 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21434 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21435 Op = DAG.getBitcast(ByteVT, Input);
21436 DCI.AddToWorklist(Op.getNode());
21437 SDValue PSHUFBMaskOp =
21438 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21439 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21440 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21441 DCI.AddToWorklist(Op.getNode());
21442 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21447 // Failed to find any combines.
21451 /// \brief Fully generic combining of x86 shuffle instructions.
21453 /// This should be the last combine run over the x86 shuffle instructions. Once
21454 /// they have been fully optimized, this will recursively consider all chains
21455 /// of single-use shuffle instructions, build a generic model of the cumulative
21456 /// shuffle operation, and check for simpler instructions which implement this
21457 /// operation. We use this primarily for two purposes:
21459 /// 1) Collapse generic shuffles to specialized single instructions when
21460 /// equivalent. In most cases, this is just an encoding size win, but
21461 /// sometimes we will collapse multiple generic shuffles into a single
21462 /// special-purpose shuffle.
21463 /// 2) Look for sequences of shuffle instructions with 3 or more total
21464 /// instructions, and replace them with the slightly more expensive SSSE3
21465 /// PSHUFB instruction if available. We do this as the last combining step
21466 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21467 /// a suitable short sequence of other instructions. The PHUFB will either
21468 /// use a register or have to read from memory and so is slightly (but only
21469 /// slightly) more expensive than the other shuffle instructions.
21471 /// Because this is inherently a quadratic operation (for each shuffle in
21472 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21473 /// This should never be an issue in practice as the shuffle lowering doesn't
21474 /// produce sequences of more than 8 instructions.
21476 /// FIXME: We will currently miss some cases where the redundant shuffling
21477 /// would simplify under the threshold for PSHUFB formation because of
21478 /// combine-ordering. To fix this, we should do the redundant instruction
21479 /// combining in this recursive walk.
21480 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21481 ArrayRef<int> RootMask,
21482 int Depth, bool HasPSHUFB,
21484 TargetLowering::DAGCombinerInfo &DCI,
21485 const X86Subtarget *Subtarget) {
21486 // Bound the depth of our recursive combine because this is ultimately
21487 // quadratic in nature.
21491 // Directly rip through bitcasts to find the underlying operand.
21492 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21493 Op = Op.getOperand(0);
21495 MVT VT = Op.getSimpleValueType();
21496 if (!VT.isVector())
21497 return false; // Bail if we hit a non-vector.
21499 assert(Root.getSimpleValueType().isVector() &&
21500 "Shuffles operate on vector types!");
21501 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21502 "Can only combine shuffles of the same vector register size.");
21504 if (!isTargetShuffle(Op.getOpcode()))
21506 SmallVector<int, 16> OpMask;
21508 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21509 // We only can combine unary shuffles which we can decode the mask for.
21510 if (!HaveMask || !IsUnary)
21513 assert(VT.getVectorNumElements() == OpMask.size() &&
21514 "Different mask size from vector size!");
21515 assert(((RootMask.size() > OpMask.size() &&
21516 RootMask.size() % OpMask.size() == 0) ||
21517 (OpMask.size() > RootMask.size() &&
21518 OpMask.size() % RootMask.size() == 0) ||
21519 OpMask.size() == RootMask.size()) &&
21520 "The smaller number of elements must divide the larger.");
21521 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21522 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21523 assert(((RootRatio == 1 && OpRatio == 1) ||
21524 (RootRatio == 1) != (OpRatio == 1)) &&
21525 "Must not have a ratio for both incoming and op masks!");
21527 SmallVector<int, 16> Mask;
21528 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21530 // Merge this shuffle operation's mask into our accumulated mask. Note that
21531 // this shuffle's mask will be the first applied to the input, followed by the
21532 // root mask to get us all the way to the root value arrangement. The reason
21533 // for this order is that we are recursing up the operation chain.
21534 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21535 int RootIdx = i / RootRatio;
21536 if (RootMask[RootIdx] < 0) {
21537 // This is a zero or undef lane, we're done.
21538 Mask.push_back(RootMask[RootIdx]);
21542 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21543 int OpIdx = RootMaskedIdx / OpRatio;
21544 if (OpMask[OpIdx] < 0) {
21545 // The incoming lanes are zero or undef, it doesn't matter which ones we
21547 Mask.push_back(OpMask[OpIdx]);
21551 // Ok, we have non-zero lanes, map them through.
21552 Mask.push_back(OpMask[OpIdx] * OpRatio +
21553 RootMaskedIdx % OpRatio);
21556 // See if we can recurse into the operand to combine more things.
21557 switch (Op.getOpcode()) {
21558 case X86ISD::PSHUFB:
21560 case X86ISD::PSHUFD:
21561 case X86ISD::PSHUFHW:
21562 case X86ISD::PSHUFLW:
21563 if (Op.getOperand(0).hasOneUse() &&
21564 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21565 HasPSHUFB, DAG, DCI, Subtarget))
21569 case X86ISD::UNPCKL:
21570 case X86ISD::UNPCKH:
21571 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21572 // We can't check for single use, we have to check that this shuffle is the only user.
21573 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21574 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21575 HasPSHUFB, DAG, DCI, Subtarget))
21580 // Minor canonicalization of the accumulated shuffle mask to make it easier
21581 // to match below. All this does is detect masks with squential pairs of
21582 // elements, and shrink them to the half-width mask. It does this in a loop
21583 // so it will reduce the size of the mask to the minimal width mask which
21584 // performs an equivalent shuffle.
21585 SmallVector<int, 16> WidenedMask;
21586 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21587 Mask = std::move(WidenedMask);
21588 WidenedMask.clear();
21591 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21595 /// \brief Get the PSHUF-style mask from PSHUF node.
21597 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21598 /// PSHUF-style masks that can be reused with such instructions.
21599 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21600 MVT VT = N.getSimpleValueType();
21601 SmallVector<int, 4> Mask;
21603 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21607 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21608 // matter. Check that the upper masks are repeats and remove them.
21609 if (VT.getSizeInBits() > 128) {
21610 int LaneElts = 128 / VT.getScalarSizeInBits();
21612 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21613 for (int j = 0; j < LaneElts; ++j)
21614 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21615 "Mask doesn't repeat in high 128-bit lanes!");
21617 Mask.resize(LaneElts);
21620 switch (N.getOpcode()) {
21621 case X86ISD::PSHUFD:
21623 case X86ISD::PSHUFLW:
21626 case X86ISD::PSHUFHW:
21627 Mask.erase(Mask.begin(), Mask.begin() + 4);
21628 for (int &M : Mask)
21632 llvm_unreachable("No valid shuffle instruction found!");
21636 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21638 /// We walk up the chain and look for a combinable shuffle, skipping over
21639 /// shuffles that we could hoist this shuffle's transformation past without
21640 /// altering anything.
21642 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21644 TargetLowering::DAGCombinerInfo &DCI) {
21645 assert(N.getOpcode() == X86ISD::PSHUFD &&
21646 "Called with something other than an x86 128-bit half shuffle!");
21649 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21650 // of the shuffles in the chain so that we can form a fresh chain to replace
21652 SmallVector<SDValue, 8> Chain;
21653 SDValue V = N.getOperand(0);
21654 for (; V.hasOneUse(); V = V.getOperand(0)) {
21655 switch (V.getOpcode()) {
21657 return SDValue(); // Nothing combined!
21660 // Skip bitcasts as we always know the type for the target specific
21664 case X86ISD::PSHUFD:
21665 // Found another dword shuffle.
21668 case X86ISD::PSHUFLW:
21669 // Check that the low words (being shuffled) are the identity in the
21670 // dword shuffle, and the high words are self-contained.
21671 if (Mask[0] != 0 || Mask[1] != 1 ||
21672 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21675 Chain.push_back(V);
21678 case X86ISD::PSHUFHW:
21679 // Check that the high words (being shuffled) are the identity in the
21680 // dword shuffle, and the low words are self-contained.
21681 if (Mask[2] != 2 || Mask[3] != 3 ||
21682 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21685 Chain.push_back(V);
21688 case X86ISD::UNPCKL:
21689 case X86ISD::UNPCKH:
21690 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21691 // shuffle into a preceding word shuffle.
21692 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21693 V.getSimpleValueType().getScalarType() != MVT::i16)
21696 // Search for a half-shuffle which we can combine with.
21697 unsigned CombineOp =
21698 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21699 if (V.getOperand(0) != V.getOperand(1) ||
21700 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21702 Chain.push_back(V);
21703 V = V.getOperand(0);
21705 switch (V.getOpcode()) {
21707 return SDValue(); // Nothing to combine.
21709 case X86ISD::PSHUFLW:
21710 case X86ISD::PSHUFHW:
21711 if (V.getOpcode() == CombineOp)
21714 Chain.push_back(V);
21718 V = V.getOperand(0);
21722 } while (V.hasOneUse());
21725 // Break out of the loop if we break out of the switch.
21729 if (!V.hasOneUse())
21730 // We fell out of the loop without finding a viable combining instruction.
21733 // Merge this node's mask and our incoming mask.
21734 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21735 for (int &M : Mask)
21737 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21738 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21740 // Rebuild the chain around this new shuffle.
21741 while (!Chain.empty()) {
21742 SDValue W = Chain.pop_back_val();
21744 if (V.getValueType() != W.getOperand(0).getValueType())
21745 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21747 switch (W.getOpcode()) {
21749 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21751 case X86ISD::UNPCKL:
21752 case X86ISD::UNPCKH:
21753 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21756 case X86ISD::PSHUFD:
21757 case X86ISD::PSHUFLW:
21758 case X86ISD::PSHUFHW:
21759 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21763 if (V.getValueType() != N.getValueType())
21764 V = DAG.getBitcast(N.getValueType(), V);
21766 // Return the new chain to replace N.
21770 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21772 /// We walk up the chain, skipping shuffles of the other half and looking
21773 /// through shuffles which switch halves trying to find a shuffle of the same
21774 /// pair of dwords.
21775 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21777 TargetLowering::DAGCombinerInfo &DCI) {
21779 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21780 "Called with something other than an x86 128-bit half shuffle!");
21782 unsigned CombineOpcode = N.getOpcode();
21784 // Walk up a single-use chain looking for a combinable shuffle.
21785 SDValue V = N.getOperand(0);
21786 for (; V.hasOneUse(); V = V.getOperand(0)) {
21787 switch (V.getOpcode()) {
21789 return false; // Nothing combined!
21792 // Skip bitcasts as we always know the type for the target specific
21796 case X86ISD::PSHUFLW:
21797 case X86ISD::PSHUFHW:
21798 if (V.getOpcode() == CombineOpcode)
21801 // Other-half shuffles are no-ops.
21804 // Break out of the loop if we break out of the switch.
21808 if (!V.hasOneUse())
21809 // We fell out of the loop without finding a viable combining instruction.
21812 // Combine away the bottom node as its shuffle will be accumulated into
21813 // a preceding shuffle.
21814 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21816 // Record the old value.
21819 // Merge this node's mask and our incoming mask (adjusted to account for all
21820 // the pshufd instructions encountered).
21821 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21822 for (int &M : Mask)
21824 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21825 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21827 // Check that the shuffles didn't cancel each other out. If not, we need to
21828 // combine to the new one.
21830 // Replace the combinable shuffle with the combined one, updating all users
21831 // so that we re-evaluate the chain here.
21832 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21837 /// \brief Try to combine x86 target specific shuffles.
21838 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21839 TargetLowering::DAGCombinerInfo &DCI,
21840 const X86Subtarget *Subtarget) {
21842 MVT VT = N.getSimpleValueType();
21843 SmallVector<int, 4> Mask;
21845 switch (N.getOpcode()) {
21846 case X86ISD::PSHUFD:
21847 case X86ISD::PSHUFLW:
21848 case X86ISD::PSHUFHW:
21849 Mask = getPSHUFShuffleMask(N);
21850 assert(Mask.size() == 4);
21856 // Nuke no-op shuffles that show up after combining.
21857 if (isNoopShuffleMask(Mask))
21858 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21860 // Look for simplifications involving one or two shuffle instructions.
21861 SDValue V = N.getOperand(0);
21862 switch (N.getOpcode()) {
21865 case X86ISD::PSHUFLW:
21866 case X86ISD::PSHUFHW:
21867 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21869 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21870 return SDValue(); // We combined away this shuffle, so we're done.
21872 // See if this reduces to a PSHUFD which is no more expensive and can
21873 // combine with more operations. Note that it has to at least flip the
21874 // dwords as otherwise it would have been removed as a no-op.
21875 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21876 int DMask[] = {0, 1, 2, 3};
21877 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21878 DMask[DOffset + 0] = DOffset + 1;
21879 DMask[DOffset + 1] = DOffset + 0;
21880 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21881 V = DAG.getBitcast(DVT, V);
21882 DCI.AddToWorklist(V.getNode());
21883 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21884 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21885 DCI.AddToWorklist(V.getNode());
21886 return DAG.getBitcast(VT, V);
21889 // Look for shuffle patterns which can be implemented as a single unpack.
21890 // FIXME: This doesn't handle the location of the PSHUFD generically, and
21891 // only works when we have a PSHUFD followed by two half-shuffles.
21892 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21893 (V.getOpcode() == X86ISD::PSHUFLW ||
21894 V.getOpcode() == X86ISD::PSHUFHW) &&
21895 V.getOpcode() != N.getOpcode() &&
21897 SDValue D = V.getOperand(0);
21898 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21899 D = D.getOperand(0);
21900 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21901 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21902 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21903 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21904 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21906 for (int i = 0; i < 4; ++i) {
21907 WordMask[i + NOffset] = Mask[i] + NOffset;
21908 WordMask[i + VOffset] = VMask[i] + VOffset;
21910 // Map the word mask through the DWord mask.
21912 for (int i = 0; i < 8; ++i)
21913 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21914 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21915 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21916 // We can replace all three shuffles with an unpack.
21917 V = DAG.getBitcast(VT, D.getOperand(0));
21918 DCI.AddToWorklist(V.getNode());
21919 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21928 case X86ISD::PSHUFD:
21929 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21938 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21940 /// We combine this directly on the abstract vector shuffle nodes so it is
21941 /// easier to generically match. We also insert dummy vector shuffle nodes for
21942 /// the operands which explicitly discard the lanes which are unused by this
21943 /// operation to try to flow through the rest of the combiner the fact that
21944 /// they're unused.
21945 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21947 EVT VT = N->getValueType(0);
21949 // We only handle target-independent shuffles.
21950 // FIXME: It would be easy and harmless to use the target shuffle mask
21951 // extraction tool to support more.
21952 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21955 auto *SVN = cast<ShuffleVectorSDNode>(N);
21956 ArrayRef<int> Mask = SVN->getMask();
21957 SDValue V1 = N->getOperand(0);
21958 SDValue V2 = N->getOperand(1);
21960 // We require the first shuffle operand to be the SUB node, and the second to
21961 // be the ADD node.
21962 // FIXME: We should support the commuted patterns.
21963 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21966 // If there are other uses of these operations we can't fold them.
21967 if (!V1->hasOneUse() || !V2->hasOneUse())
21970 // Ensure that both operations have the same operands. Note that we can
21971 // commute the FADD operands.
21972 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21973 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21974 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21977 // We're looking for blends between FADD and FSUB nodes. We insist on these
21978 // nodes being lined up in a specific expected pattern.
21979 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21980 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21981 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21984 // Only specific types are legal at this point, assert so we notice if and
21985 // when these change.
21986 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21987 VT == MVT::v4f64) &&
21988 "Unknown vector type encountered!");
21990 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21993 /// PerformShuffleCombine - Performs several different shuffle combines.
21994 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21995 TargetLowering::DAGCombinerInfo &DCI,
21996 const X86Subtarget *Subtarget) {
21998 SDValue N0 = N->getOperand(0);
21999 SDValue N1 = N->getOperand(1);
22000 EVT VT = N->getValueType(0);
22002 // Don't create instructions with illegal types after legalize types has run.
22003 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22004 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22007 // If we have legalized the vector types, look for blends of FADD and FSUB
22008 // nodes that we can fuse into an ADDSUB node.
22009 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22010 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22013 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22014 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22015 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22016 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22018 // During Type Legalization, when promoting illegal vector types,
22019 // the backend might introduce new shuffle dag nodes and bitcasts.
22021 // This code performs the following transformation:
22022 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22023 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22025 // We do this only if both the bitcast and the BINOP dag nodes have
22026 // one use. Also, perform this transformation only if the new binary
22027 // operation is legal. This is to avoid introducing dag nodes that
22028 // potentially need to be further expanded (or custom lowered) into a
22029 // less optimal sequence of dag nodes.
22030 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22031 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22032 N0.getOpcode() == ISD::BITCAST) {
22033 SDValue BC0 = N0.getOperand(0);
22034 EVT SVT = BC0.getValueType();
22035 unsigned Opcode = BC0.getOpcode();
22036 unsigned NumElts = VT.getVectorNumElements();
22038 if (BC0.hasOneUse() && SVT.isVector() &&
22039 SVT.getVectorNumElements() * 2 == NumElts &&
22040 TLI.isOperationLegal(Opcode, VT)) {
22041 bool CanFold = false;
22053 unsigned SVTNumElts = SVT.getVectorNumElements();
22054 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22055 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22056 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22057 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22058 CanFold = SVOp->getMaskElt(i) < 0;
22061 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22062 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22063 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22064 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22069 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22070 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22071 // consecutive, non-overlapping, and in the right order.
22072 SmallVector<SDValue, 16> Elts;
22073 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22074 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22076 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22079 if (isTargetShuffle(N->getOpcode())) {
22081 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22082 if (Shuffle.getNode())
22085 // Try recursively combining arbitrary sequences of x86 shuffle
22086 // instructions into higher-order shuffles. We do this after combining
22087 // specific PSHUF instruction sequences into their minimal form so that we
22088 // can evaluate how many specialized shuffle instructions are involved in
22089 // a particular chain.
22090 SmallVector<int, 1> NonceMask; // Just a placeholder.
22091 NonceMask.push_back(0);
22092 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22093 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22095 return SDValue(); // This routine will use CombineTo to replace N.
22101 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22102 /// specific shuffle of a load can be folded into a single element load.
22103 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22104 /// shuffles have been custom lowered so we need to handle those here.
22105 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22106 TargetLowering::DAGCombinerInfo &DCI) {
22107 if (DCI.isBeforeLegalizeOps())
22110 SDValue InVec = N->getOperand(0);
22111 SDValue EltNo = N->getOperand(1);
22113 if (!isa<ConstantSDNode>(EltNo))
22116 EVT OriginalVT = InVec.getValueType();
22118 if (InVec.getOpcode() == ISD::BITCAST) {
22119 // Don't duplicate a load with other uses.
22120 if (!InVec.hasOneUse())
22122 EVT BCVT = InVec.getOperand(0).getValueType();
22123 if (!BCVT.isVector() ||
22124 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22126 InVec = InVec.getOperand(0);
22129 EVT CurrentVT = InVec.getValueType();
22131 if (!isTargetShuffle(InVec.getOpcode()))
22134 // Don't duplicate a load with other uses.
22135 if (!InVec.hasOneUse())
22138 SmallVector<int, 16> ShuffleMask;
22140 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22141 ShuffleMask, UnaryShuffle))
22144 // Select the input vector, guarding against out of range extract vector.
22145 unsigned NumElems = CurrentVT.getVectorNumElements();
22146 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22147 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22148 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22149 : InVec.getOperand(1);
22151 // If inputs to shuffle are the same for both ops, then allow 2 uses
22152 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22153 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22155 if (LdNode.getOpcode() == ISD::BITCAST) {
22156 // Don't duplicate a load with other uses.
22157 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22160 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22161 LdNode = LdNode.getOperand(0);
22164 if (!ISD::isNormalLoad(LdNode.getNode()))
22167 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22169 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22172 EVT EltVT = N->getValueType(0);
22173 // If there's a bitcast before the shuffle, check if the load type and
22174 // alignment is valid.
22175 unsigned Align = LN0->getAlignment();
22176 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22177 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22178 EltVT.getTypeForEVT(*DAG.getContext()));
22180 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22183 // All checks match so transform back to vector_shuffle so that DAG combiner
22184 // can finish the job
22187 // Create shuffle node taking into account the case that its a unary shuffle
22188 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22189 : InVec.getOperand(1);
22190 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22191 InVec.getOperand(0), Shuffle,
22193 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22194 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22198 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22199 /// special and don't usually play with other vector types, it's better to
22200 /// handle them early to be sure we emit efficient code by avoiding
22201 /// store-load conversions.
22202 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22203 if (N->getValueType(0) != MVT::x86mmx ||
22204 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22205 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22208 SDValue V = N->getOperand(0);
22209 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22210 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22211 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22212 N->getValueType(0), V.getOperand(0));
22217 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22218 /// generation and convert it from being a bunch of shuffles and extracts
22219 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22220 /// storing the value and loading scalars back, while for x64 we should
22221 /// use 64-bit extracts and shifts.
22222 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22223 TargetLowering::DAGCombinerInfo &DCI) {
22224 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22227 SDValue InputVector = N->getOperand(0);
22228 SDLoc dl(InputVector);
22229 // Detect mmx to i32 conversion through a v2i32 elt extract.
22230 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22231 N->getValueType(0) == MVT::i32 &&
22232 InputVector.getValueType() == MVT::v2i32) {
22234 // The bitcast source is a direct mmx result.
22235 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22236 if (MMXSrc.getValueType() == MVT::x86mmx)
22237 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22238 N->getValueType(0),
22239 InputVector.getNode()->getOperand(0));
22241 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22242 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22243 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22244 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22245 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22246 MMXSrcOp.getValueType() == MVT::v1i64 &&
22247 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22248 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22249 N->getValueType(0),
22250 MMXSrcOp.getOperand(0));
22253 EVT VT = N->getValueType(0);
22255 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22256 InputVector.getOpcode() == ISD::BITCAST &&
22257 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22258 uint64_t ExtractedElt =
22259 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22260 uint64_t InputValue =
22261 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22262 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22263 return DAG.getConstant(Res, dl, MVT::i1);
22265 // Only operate on vectors of 4 elements, where the alternative shuffling
22266 // gets to be more expensive.
22267 if (InputVector.getValueType() != MVT::v4i32)
22270 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22271 // single use which is a sign-extend or zero-extend, and all elements are
22273 SmallVector<SDNode *, 4> Uses;
22274 unsigned ExtractedElements = 0;
22275 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22276 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22277 if (UI.getUse().getResNo() != InputVector.getResNo())
22280 SDNode *Extract = *UI;
22281 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22284 if (Extract->getValueType(0) != MVT::i32)
22286 if (!Extract->hasOneUse())
22288 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22289 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22291 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22294 // Record which element was extracted.
22295 ExtractedElements |=
22296 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22298 Uses.push_back(Extract);
22301 // If not all the elements were used, this may not be worthwhile.
22302 if (ExtractedElements != 15)
22305 // Ok, we've now decided to do the transformation.
22306 // If 64-bit shifts are legal, use the extract-shift sequence,
22307 // otherwise bounce the vector off the cache.
22308 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22311 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22312 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22313 auto &DL = DAG.getDataLayout();
22314 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22315 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22316 DAG.getConstant(0, dl, VecIdxTy));
22317 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22318 DAG.getConstant(1, dl, VecIdxTy));
22320 SDValue ShAmt = DAG.getConstant(
22321 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22322 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22323 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22324 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22325 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22326 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22327 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22329 // Store the value to a temporary stack slot.
22330 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22331 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22332 MachinePointerInfo(), false, false, 0);
22334 EVT ElementType = InputVector.getValueType().getVectorElementType();
22335 unsigned EltSize = ElementType.getSizeInBits() / 8;
22337 // Replace each use (extract) with a load of the appropriate element.
22338 for (unsigned i = 0; i < 4; ++i) {
22339 uint64_t Offset = EltSize * i;
22340 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22341 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22343 SDValue ScalarAddr =
22344 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22346 // Load the scalar.
22347 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22348 ScalarAddr, MachinePointerInfo(),
22349 false, false, false, 0);
22354 // Replace the extracts
22355 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22356 UE = Uses.end(); UI != UE; ++UI) {
22357 SDNode *Extract = *UI;
22359 SDValue Idx = Extract->getOperand(1);
22360 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22361 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22364 // The replacement was made in place; don't return anything.
22368 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22369 static std::pair<unsigned, bool>
22370 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22371 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22372 if (!VT.isVector())
22373 return std::make_pair(0, false);
22375 bool NeedSplit = false;
22376 switch (VT.getSimpleVT().SimpleTy) {
22377 default: return std::make_pair(0, false);
22380 if (!Subtarget->hasVLX())
22381 return std::make_pair(0, false);
22385 if (!Subtarget->hasBWI())
22386 return std::make_pair(0, false);
22390 if (!Subtarget->hasAVX512())
22391 return std::make_pair(0, false);
22396 if (!Subtarget->hasAVX2())
22398 if (!Subtarget->hasAVX())
22399 return std::make_pair(0, false);
22404 if (!Subtarget->hasSSE2())
22405 return std::make_pair(0, false);
22408 // SSE2 has only a small subset of the operations.
22409 bool hasUnsigned = Subtarget->hasSSE41() ||
22410 (Subtarget->hasSSE2() && VT == MVT::v16i8);
22411 bool hasSigned = Subtarget->hasSSE41() ||
22412 (Subtarget->hasSSE2() && VT == MVT::v8i16);
22414 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22417 // Check for x CC y ? x : y.
22418 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22419 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22424 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22427 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22430 Opc = hasSigned ? ISD::SMIN : 0; break;
22433 Opc = hasSigned ? ISD::SMAX : 0; break;
22435 // Check for x CC y ? y : x -- a min/max with reversed arms.
22436 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22437 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22442 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22445 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22448 Opc = hasSigned ? ISD::SMAX : 0; break;
22451 Opc = hasSigned ? ISD::SMIN : 0; break;
22455 return std::make_pair(Opc, NeedSplit);
22459 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22460 const X86Subtarget *Subtarget) {
22462 SDValue Cond = N->getOperand(0);
22463 SDValue LHS = N->getOperand(1);
22464 SDValue RHS = N->getOperand(2);
22466 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22467 SDValue CondSrc = Cond->getOperand(0);
22468 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22469 Cond = CondSrc->getOperand(0);
22472 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22475 // A vselect where all conditions and data are constants can be optimized into
22476 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22477 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22478 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22481 unsigned MaskValue = 0;
22482 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22485 MVT VT = N->getSimpleValueType(0);
22486 unsigned NumElems = VT.getVectorNumElements();
22487 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22488 for (unsigned i = 0; i < NumElems; ++i) {
22489 // Be sure we emit undef where we can.
22490 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22491 ShuffleMask[i] = -1;
22493 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22496 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22497 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22499 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22502 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22504 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22505 TargetLowering::DAGCombinerInfo &DCI,
22506 const X86Subtarget *Subtarget) {
22508 SDValue Cond = N->getOperand(0);
22509 // Get the LHS/RHS of the select.
22510 SDValue LHS = N->getOperand(1);
22511 SDValue RHS = N->getOperand(2);
22512 EVT VT = LHS.getValueType();
22513 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22515 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22516 // instructions match the semantics of the common C idiom x<y?x:y but not
22517 // x<=y?x:y, because of how they handle negative zero (which can be
22518 // ignored in unsafe-math mode).
22519 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22520 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22521 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22522 (Subtarget->hasSSE2() ||
22523 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22524 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22526 unsigned Opcode = 0;
22527 // Check for x CC y ? x : y.
22528 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22529 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22533 // Converting this to a min would handle NaNs incorrectly, and swapping
22534 // the operands would cause it to handle comparisons between positive
22535 // and negative zero incorrectly.
22536 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22537 if (!DAG.getTarget().Options.UnsafeFPMath &&
22538 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22540 std::swap(LHS, RHS);
22542 Opcode = X86ISD::FMIN;
22545 // Converting this to a min would handle comparisons between positive
22546 // and negative zero incorrectly.
22547 if (!DAG.getTarget().Options.UnsafeFPMath &&
22548 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22550 Opcode = X86ISD::FMIN;
22553 // Converting this to a min would handle both negative zeros and NaNs
22554 // incorrectly, but we can swap the operands to fix both.
22555 std::swap(LHS, RHS);
22559 Opcode = X86ISD::FMIN;
22563 // Converting this to a max would handle comparisons between positive
22564 // and negative zero incorrectly.
22565 if (!DAG.getTarget().Options.UnsafeFPMath &&
22566 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22568 Opcode = X86ISD::FMAX;
22571 // Converting this to a max would handle NaNs incorrectly, and swapping
22572 // the operands would cause it to handle comparisons between positive
22573 // and negative zero incorrectly.
22574 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22575 if (!DAG.getTarget().Options.UnsafeFPMath &&
22576 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22578 std::swap(LHS, RHS);
22580 Opcode = X86ISD::FMAX;
22583 // Converting this to a max would handle both negative zeros and NaNs
22584 // incorrectly, but we can swap the operands to fix both.
22585 std::swap(LHS, RHS);
22589 Opcode = X86ISD::FMAX;
22592 // Check for x CC y ? y : x -- a min/max with reversed arms.
22593 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22594 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22598 // Converting this to a min would handle comparisons between positive
22599 // and negative zero incorrectly, and swapping the operands would
22600 // cause it to handle NaNs incorrectly.
22601 if (!DAG.getTarget().Options.UnsafeFPMath &&
22602 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22603 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22605 std::swap(LHS, RHS);
22607 Opcode = X86ISD::FMIN;
22610 // Converting this to a min would handle NaNs incorrectly.
22611 if (!DAG.getTarget().Options.UnsafeFPMath &&
22612 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(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 NaNs incorrectly.
22628 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22630 Opcode = X86ISD::FMAX;
22633 // Converting this to a max would handle comparisons between positive
22634 // and negative zero incorrectly, and swapping the operands would
22635 // cause it to handle NaNs incorrectly.
22636 if (!DAG.getTarget().Options.UnsafeFPMath &&
22637 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22638 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22640 std::swap(LHS, RHS);
22642 Opcode = X86ISD::FMAX;
22645 // Converting this to a max would handle both negative zeros and NaNs
22646 // incorrectly, but we can swap the operands to fix both.
22647 std::swap(LHS, RHS);
22651 Opcode = X86ISD::FMAX;
22657 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22660 EVT CondVT = Cond.getValueType();
22661 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22662 CondVT.getVectorElementType() == MVT::i1) {
22663 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22664 // lowering on KNL. In this case we convert it to
22665 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22666 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22667 // Since SKX these selects have a proper lowering.
22668 EVT OpVT = LHS.getValueType();
22669 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22670 (OpVT.getVectorElementType() == MVT::i8 ||
22671 OpVT.getVectorElementType() == MVT::i16) &&
22672 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22673 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22674 DCI.AddToWorklist(Cond.getNode());
22675 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22678 // If this is a select between two integer constants, try to do some
22680 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22681 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22682 // Don't do this for crazy integer types.
22683 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22684 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22685 // so that TrueC (the true value) is larger than FalseC.
22686 bool NeedsCondInvert = false;
22688 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22689 // Efficiently invertible.
22690 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22691 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22692 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22693 NeedsCondInvert = true;
22694 std::swap(TrueC, FalseC);
22697 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22698 if (FalseC->getAPIntValue() == 0 &&
22699 TrueC->getAPIntValue().isPowerOf2()) {
22700 if (NeedsCondInvert) // Invert the condition if needed.
22701 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22702 DAG.getConstant(1, DL, Cond.getValueType()));
22704 // Zero extend the condition if needed.
22705 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22707 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22708 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22709 DAG.getConstant(ShAmt, DL, MVT::i8));
22712 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22713 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22714 if (NeedsCondInvert) // Invert the condition if needed.
22715 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22716 DAG.getConstant(1, DL, Cond.getValueType()));
22718 // Zero extend the condition if needed.
22719 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22720 FalseC->getValueType(0), Cond);
22721 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22722 SDValue(FalseC, 0));
22725 // Optimize cases that will turn into an LEA instruction. This requires
22726 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22727 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22728 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22729 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22731 bool isFastMultiplier = false;
22733 switch ((unsigned char)Diff) {
22735 case 1: // result = add base, cond
22736 case 2: // result = lea base( , cond*2)
22737 case 3: // result = lea base(cond, cond*2)
22738 case 4: // result = lea base( , cond*4)
22739 case 5: // result = lea base(cond, cond*4)
22740 case 8: // result = lea base( , cond*8)
22741 case 9: // result = lea base(cond, cond*8)
22742 isFastMultiplier = true;
22747 if (isFastMultiplier) {
22748 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22749 if (NeedsCondInvert) // Invert the condition if needed.
22750 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22751 DAG.getConstant(1, DL, Cond.getValueType()));
22753 // Zero extend the condition if needed.
22754 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22756 // Scale the condition by the difference.
22758 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22759 DAG.getConstant(Diff, DL,
22760 Cond.getValueType()));
22762 // Add the base if non-zero.
22763 if (FalseC->getAPIntValue() != 0)
22764 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22765 SDValue(FalseC, 0));
22772 // Canonicalize max and min:
22773 // (x > y) ? x : y -> (x >= y) ? x : y
22774 // (x < y) ? x : y -> (x <= y) ? x : y
22775 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22776 // the need for an extra compare
22777 // against zero. e.g.
22778 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22780 // testl %edi, %edi
22782 // cmovgl %edi, %eax
22786 // cmovsl %eax, %edi
22787 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22788 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22789 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22790 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22795 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22796 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22797 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22798 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22803 // Early exit check
22804 if (!TLI.isTypeLegal(VT))
22807 // Match VSELECTs into subs with unsigned saturation.
22808 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22809 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22810 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22811 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22812 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22814 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22815 // left side invert the predicate to simplify logic below.
22817 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22819 CC = ISD::getSetCCInverse(CC, true);
22820 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22824 if (Other.getNode() && Other->getNumOperands() == 2 &&
22825 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22826 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22827 SDValue CondRHS = Cond->getOperand(1);
22829 // Look for a general sub with unsigned saturation first.
22830 // x >= y ? x-y : 0 --> subus x, y
22831 // x > y ? x-y : 0 --> subus x, y
22832 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22833 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22834 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22836 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22837 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22838 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22839 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22840 // If the RHS is a constant we have to reverse the const
22841 // canonicalization.
22842 // x > C-1 ? x+-C : 0 --> subus x, C
22843 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22844 CondRHSConst->getAPIntValue() ==
22845 (-OpRHSConst->getAPIntValue() - 1))
22846 return DAG.getNode(
22847 X86ISD::SUBUS, DL, VT, OpLHS,
22848 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22850 // Another special case: If C was a sign bit, the sub has been
22851 // canonicalized into a xor.
22852 // FIXME: Would it be better to use computeKnownBits to determine
22853 // whether it's safe to decanonicalize the xor?
22854 // x s< 0 ? x^C : 0 --> subus x, C
22855 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22856 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22857 OpRHSConst->getAPIntValue().isSignBit())
22858 // Note that we have to rebuild the RHS constant here to ensure we
22859 // don't rely on particular values of undef lanes.
22860 return DAG.getNode(
22861 X86ISD::SUBUS, DL, VT, OpLHS,
22862 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22867 // Try to match a min/max vector operation.
22868 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22869 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22870 unsigned Opc = ret.first;
22871 bool NeedSplit = ret.second;
22873 if (Opc && NeedSplit) {
22874 unsigned NumElems = VT.getVectorNumElements();
22875 // Extract the LHS vectors
22876 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22877 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22879 // Extract the RHS vectors
22880 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22881 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22883 // Create min/max for each subvector
22884 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22885 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22887 // Merge the result
22888 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22890 return DAG.getNode(Opc, DL, VT, LHS, RHS);
22893 // Simplify vector selection if condition value type matches vselect
22895 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22896 assert(Cond.getValueType().isVector() &&
22897 "vector select expects a vector selector!");
22899 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22900 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22902 // Try invert the condition if true value is not all 1s and false value
22904 if (!TValIsAllOnes && !FValIsAllZeros &&
22905 // Check if the selector will be produced by CMPP*/PCMP*
22906 Cond.getOpcode() == ISD::SETCC &&
22907 // Check if SETCC has already been promoted
22908 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22910 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22911 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22913 if (TValIsAllZeros || FValIsAllOnes) {
22914 SDValue CC = Cond.getOperand(2);
22915 ISD::CondCode NewCC =
22916 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22917 Cond.getOperand(0).getValueType().isInteger());
22918 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22919 std::swap(LHS, RHS);
22920 TValIsAllOnes = FValIsAllOnes;
22921 FValIsAllZeros = TValIsAllZeros;
22925 if (TValIsAllOnes || FValIsAllZeros) {
22928 if (TValIsAllOnes && FValIsAllZeros)
22930 else if (TValIsAllOnes)
22932 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22933 else if (FValIsAllZeros)
22934 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22935 DAG.getBitcast(CondVT, LHS));
22937 return DAG.getBitcast(VT, Ret);
22941 // We should generate an X86ISD::BLENDI from a vselect if its argument
22942 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22943 // constants. This specific pattern gets generated when we split a
22944 // selector for a 512 bit vector in a machine without AVX512 (but with
22945 // 256-bit vectors), during legalization:
22947 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22949 // Iff we find this pattern and the build_vectors are built from
22950 // constants, we translate the vselect into a shuffle_vector that we
22951 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22952 if ((N->getOpcode() == ISD::VSELECT ||
22953 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22954 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22955 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22956 if (Shuffle.getNode())
22960 // If this is a *dynamic* select (non-constant condition) and we can match
22961 // this node with one of the variable blend instructions, restructure the
22962 // condition so that the blends can use the high bit of each element and use
22963 // SimplifyDemandedBits to simplify the condition operand.
22964 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22965 !DCI.isBeforeLegalize() &&
22966 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22967 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22969 // Don't optimize vector selects that map to mask-registers.
22973 // We can only handle the cases where VSELECT is directly legal on the
22974 // subtarget. We custom lower VSELECT nodes with constant conditions and
22975 // this makes it hard to see whether a dynamic VSELECT will correctly
22976 // lower, so we both check the operation's status and explicitly handle the
22977 // cases where a *dynamic* blend will fail even though a constant-condition
22978 // blend could be custom lowered.
22979 // FIXME: We should find a better way to handle this class of problems.
22980 // Potentially, we should combine constant-condition vselect nodes
22981 // pre-legalization into shuffles and not mark as many types as custom
22983 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22985 // FIXME: We don't support i16-element blends currently. We could and
22986 // should support them by making *all* the bits in the condition be set
22987 // rather than just the high bit and using an i8-element blend.
22988 if (VT.getScalarType() == MVT::i16)
22990 // Dynamic blending was only available from SSE4.1 onward.
22991 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22993 // Byte blends are only available in AVX2
22994 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22995 !Subtarget->hasAVX2())
22998 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22999 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23001 APInt KnownZero, KnownOne;
23002 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23003 DCI.isBeforeLegalizeOps());
23004 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23005 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23007 // If we changed the computation somewhere in the DAG, this change
23008 // will affect all users of Cond.
23009 // Make sure it is fine and update all the nodes so that we do not
23010 // use the generic VSELECT anymore. Otherwise, we may perform
23011 // wrong optimizations as we messed up with the actual expectation
23012 // for the vector boolean values.
23013 if (Cond != TLO.Old) {
23014 // Check all uses of that condition operand to check whether it will be
23015 // consumed by non-BLEND instructions, which may depend on all bits are
23017 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23019 if (I->getOpcode() != ISD::VSELECT)
23020 // TODO: Add other opcodes eventually lowered into BLEND.
23023 // Update all the users of the condition, before committing the change,
23024 // so that the VSELECT optimizations that expect the correct vector
23025 // boolean value will not be triggered.
23026 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23028 DAG.ReplaceAllUsesOfValueWith(
23030 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23031 Cond, I->getOperand(1), I->getOperand(2)));
23032 DCI.CommitTargetLoweringOpt(TLO);
23035 // At this point, only Cond is changed. Change the condition
23036 // just for N to keep the opportunity to optimize all other
23037 // users their own way.
23038 DAG.ReplaceAllUsesOfValueWith(
23040 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23041 TLO.New, N->getOperand(1), N->getOperand(2)));
23049 // Check whether a boolean test is testing a boolean value generated by
23050 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23053 // Simplify the following patterns:
23054 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23055 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23056 // to (Op EFLAGS Cond)
23058 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23059 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23060 // to (Op EFLAGS !Cond)
23062 // where Op could be BRCOND or CMOV.
23064 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23065 // Quit if not CMP and SUB with its value result used.
23066 if (Cmp.getOpcode() != X86ISD::CMP &&
23067 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23070 // Quit if not used as a boolean value.
23071 if (CC != X86::COND_E && CC != X86::COND_NE)
23074 // Check CMP operands. One of them should be 0 or 1 and the other should be
23075 // an SetCC or extended from it.
23076 SDValue Op1 = Cmp.getOperand(0);
23077 SDValue Op2 = Cmp.getOperand(1);
23080 const ConstantSDNode* C = nullptr;
23081 bool needOppositeCond = (CC == X86::COND_E);
23082 bool checkAgainstTrue = false; // Is it a comparison against 1?
23084 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23086 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23088 else // Quit if all operands are not constants.
23091 if (C->getZExtValue() == 1) {
23092 needOppositeCond = !needOppositeCond;
23093 checkAgainstTrue = true;
23094 } else if (C->getZExtValue() != 0)
23095 // Quit if the constant is neither 0 or 1.
23098 bool truncatedToBoolWithAnd = false;
23099 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23100 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23101 SetCC.getOpcode() == ISD::TRUNCATE ||
23102 SetCC.getOpcode() == ISD::AND) {
23103 if (SetCC.getOpcode() == ISD::AND) {
23105 ConstantSDNode *CS;
23106 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23107 CS->getZExtValue() == 1)
23109 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23110 CS->getZExtValue() == 1)
23114 SetCC = SetCC.getOperand(OpIdx);
23115 truncatedToBoolWithAnd = true;
23117 SetCC = SetCC.getOperand(0);
23120 switch (SetCC.getOpcode()) {
23121 case X86ISD::SETCC_CARRY:
23122 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23123 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23124 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23125 // truncated to i1 using 'and'.
23126 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23128 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23129 "Invalid use of SETCC_CARRY!");
23131 case X86ISD::SETCC:
23132 // Set the condition code or opposite one if necessary.
23133 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23134 if (needOppositeCond)
23135 CC = X86::GetOppositeBranchCondition(CC);
23136 return SetCC.getOperand(1);
23137 case X86ISD::CMOV: {
23138 // Check whether false/true value has canonical one, i.e. 0 or 1.
23139 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23140 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23141 // Quit if true value is not a constant.
23144 // Quit if false value is not a constant.
23146 SDValue Op = SetCC.getOperand(0);
23147 // Skip 'zext' or 'trunc' node.
23148 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23149 Op.getOpcode() == ISD::TRUNCATE)
23150 Op = Op.getOperand(0);
23151 // A special case for rdrand/rdseed, where 0 is set if false cond is
23153 if ((Op.getOpcode() != X86ISD::RDRAND &&
23154 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23157 // Quit if false value is not the constant 0 or 1.
23158 bool FValIsFalse = true;
23159 if (FVal && FVal->getZExtValue() != 0) {
23160 if (FVal->getZExtValue() != 1)
23162 // If FVal is 1, opposite cond is needed.
23163 needOppositeCond = !needOppositeCond;
23164 FValIsFalse = false;
23166 // Quit if TVal is not the constant opposite of FVal.
23167 if (FValIsFalse && TVal->getZExtValue() != 1)
23169 if (!FValIsFalse && TVal->getZExtValue() != 0)
23171 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23172 if (needOppositeCond)
23173 CC = X86::GetOppositeBranchCondition(CC);
23174 return SetCC.getOperand(3);
23181 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23183 /// (X86or (X86setcc) (X86setcc))
23184 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23185 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23186 X86::CondCode &CC1, SDValue &Flags,
23188 if (Cond->getOpcode() == X86ISD::CMP) {
23189 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23190 if (!CondOp1C || !CondOp1C->isNullValue())
23193 Cond = Cond->getOperand(0);
23198 SDValue SetCC0, SetCC1;
23199 switch (Cond->getOpcode()) {
23200 default: return false;
23207 SetCC0 = Cond->getOperand(0);
23208 SetCC1 = Cond->getOperand(1);
23212 // Make sure we have SETCC nodes, using the same flags value.
23213 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23214 SetCC1.getOpcode() != X86ISD::SETCC ||
23215 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23218 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23219 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23220 Flags = SetCC0->getOperand(1);
23224 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23225 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23226 TargetLowering::DAGCombinerInfo &DCI,
23227 const X86Subtarget *Subtarget) {
23230 // If the flag operand isn't dead, don't touch this CMOV.
23231 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23234 SDValue FalseOp = N->getOperand(0);
23235 SDValue TrueOp = N->getOperand(1);
23236 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23237 SDValue Cond = N->getOperand(3);
23239 if (CC == X86::COND_E || CC == X86::COND_NE) {
23240 switch (Cond.getOpcode()) {
23244 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23245 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23246 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23252 Flags = checkBoolTestSetCCCombine(Cond, CC);
23253 if (Flags.getNode() &&
23254 // Extra check as FCMOV only supports a subset of X86 cond.
23255 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23256 SDValue Ops[] = { FalseOp, TrueOp,
23257 DAG.getConstant(CC, DL, MVT::i8), Flags };
23258 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23261 // If this is a select between two integer constants, try to do some
23262 // optimizations. Note that the operands are ordered the opposite of SELECT
23264 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23265 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23266 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23267 // larger than FalseC (the false value).
23268 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23269 CC = X86::GetOppositeBranchCondition(CC);
23270 std::swap(TrueC, FalseC);
23271 std::swap(TrueOp, FalseOp);
23274 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23275 // This is efficient for any integer data type (including i8/i16) and
23277 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23278 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23279 DAG.getConstant(CC, DL, MVT::i8), Cond);
23281 // Zero extend the condition if needed.
23282 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23284 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23285 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23286 DAG.getConstant(ShAmt, DL, MVT::i8));
23287 if (N->getNumValues() == 2) // Dead flag value?
23288 return DCI.CombineTo(N, Cond, SDValue());
23292 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23293 // for any integer data type, including i8/i16.
23294 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23295 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23296 DAG.getConstant(CC, DL, MVT::i8), Cond);
23298 // Zero extend the condition if needed.
23299 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23300 FalseC->getValueType(0), Cond);
23301 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23302 SDValue(FalseC, 0));
23304 if (N->getNumValues() == 2) // Dead flag value?
23305 return DCI.CombineTo(N, Cond, SDValue());
23309 // Optimize cases that will turn into an LEA instruction. This requires
23310 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23311 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23312 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23313 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23315 bool isFastMultiplier = false;
23317 switch ((unsigned char)Diff) {
23319 case 1: // result = add base, cond
23320 case 2: // result = lea base( , cond*2)
23321 case 3: // result = lea base(cond, cond*2)
23322 case 4: // result = lea base( , cond*4)
23323 case 5: // result = lea base(cond, cond*4)
23324 case 8: // result = lea base( , cond*8)
23325 case 9: // result = lea base(cond, cond*8)
23326 isFastMultiplier = true;
23331 if (isFastMultiplier) {
23332 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23333 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23334 DAG.getConstant(CC, DL, MVT::i8), Cond);
23335 // Zero extend the condition if needed.
23336 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23338 // Scale the condition by the difference.
23340 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23341 DAG.getConstant(Diff, DL, Cond.getValueType()));
23343 // Add the base if non-zero.
23344 if (FalseC->getAPIntValue() != 0)
23345 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23346 SDValue(FalseC, 0));
23347 if (N->getNumValues() == 2) // Dead flag value?
23348 return DCI.CombineTo(N, Cond, SDValue());
23355 // Handle these cases:
23356 // (select (x != c), e, c) -> select (x != c), e, x),
23357 // (select (x == c), c, e) -> select (x == c), x, e)
23358 // where the c is an integer constant, and the "select" is the combination
23359 // of CMOV and CMP.
23361 // The rationale for this change is that the conditional-move from a constant
23362 // needs two instructions, however, conditional-move from a register needs
23363 // only one instruction.
23365 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23366 // some instruction-combining opportunities. This opt needs to be
23367 // postponed as late as possible.
23369 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23370 // the DCI.xxxx conditions are provided to postpone the optimization as
23371 // late as possible.
23373 ConstantSDNode *CmpAgainst = nullptr;
23374 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23375 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23376 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23378 if (CC == X86::COND_NE &&
23379 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23380 CC = X86::GetOppositeBranchCondition(CC);
23381 std::swap(TrueOp, FalseOp);
23384 if (CC == X86::COND_E &&
23385 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23386 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23387 DAG.getConstant(CC, DL, MVT::i8), Cond };
23388 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23393 // Fold and/or of setcc's to double CMOV:
23394 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23395 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23397 // This combine lets us generate:
23398 // cmovcc1 (jcc1 if we don't have CMOV)
23404 // cmovne (jne if we don't have CMOV)
23405 // When we can't use the CMOV instruction, it might increase branch
23407 // When we can use CMOV, or when there is no mispredict, this improves
23408 // throughput and reduces register pressure.
23410 if (CC == X86::COND_NE) {
23412 X86::CondCode CC0, CC1;
23414 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23416 std::swap(FalseOp, TrueOp);
23417 CC0 = X86::GetOppositeBranchCondition(CC0);
23418 CC1 = X86::GetOppositeBranchCondition(CC1);
23421 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23423 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23424 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23425 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23426 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23434 /// PerformMulCombine - Optimize a single multiply with constant into two
23435 /// in order to implement it with two cheaper instructions, e.g.
23436 /// LEA + SHL, LEA + LEA.
23437 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23438 TargetLowering::DAGCombinerInfo &DCI) {
23439 // An imul is usually smaller than the alternative sequence.
23440 if (DAG.getMachineFunction().getFunction()->optForMinSize())
23443 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23446 EVT VT = N->getValueType(0);
23447 if (VT != MVT::i64 && VT != MVT::i32)
23450 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23453 uint64_t MulAmt = C->getZExtValue();
23454 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23457 uint64_t MulAmt1 = 0;
23458 uint64_t MulAmt2 = 0;
23459 if ((MulAmt % 9) == 0) {
23461 MulAmt2 = MulAmt / 9;
23462 } else if ((MulAmt % 5) == 0) {
23464 MulAmt2 = MulAmt / 5;
23465 } else if ((MulAmt % 3) == 0) {
23467 MulAmt2 = MulAmt / 3;
23470 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23473 if (isPowerOf2_64(MulAmt2) &&
23474 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23475 // If second multiplifer is pow2, issue it first. We want the multiply by
23476 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23478 std::swap(MulAmt1, MulAmt2);
23481 if (isPowerOf2_64(MulAmt1))
23482 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23483 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23485 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23486 DAG.getConstant(MulAmt1, DL, VT));
23488 if (isPowerOf2_64(MulAmt2))
23489 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23490 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23492 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23493 DAG.getConstant(MulAmt2, DL, VT));
23495 // Do not add new nodes to DAG combiner worklist.
23496 DCI.CombineTo(N, NewMul, false);
23501 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23502 SDValue N0 = N->getOperand(0);
23503 SDValue N1 = N->getOperand(1);
23504 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23505 EVT VT = N0.getValueType();
23507 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23508 // since the result of setcc_c is all zero's or all ones.
23509 if (VT.isInteger() && !VT.isVector() &&
23510 N1C && N0.getOpcode() == ISD::AND &&
23511 N0.getOperand(1).getOpcode() == ISD::Constant) {
23512 SDValue N00 = N0.getOperand(0);
23513 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23514 ((N00.getOpcode() == ISD::ANY_EXTEND ||
23515 N00.getOpcode() == ISD::ZERO_EXTEND) &&
23516 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23517 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23518 APInt ShAmt = N1C->getAPIntValue();
23519 Mask = Mask.shl(ShAmt);
23522 return DAG.getNode(ISD::AND, DL, VT,
23523 N00, DAG.getConstant(Mask, DL, VT));
23528 // Hardware support for vector shifts is sparse which makes us scalarize the
23529 // vector operations in many cases. Also, on sandybridge ADD is faster than
23531 // (shl V, 1) -> add V,V
23532 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23533 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23534 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23535 // We shift all of the values by one. In many cases we do not have
23536 // hardware support for this operation. This is better expressed as an ADD
23538 if (N1SplatC->getAPIntValue() == 1)
23539 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23545 /// \brief Returns a vector of 0s if the node in input is a vector logical
23546 /// shift by a constant amount which is known to be bigger than or equal
23547 /// to the vector element size in bits.
23548 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23549 const X86Subtarget *Subtarget) {
23550 EVT VT = N->getValueType(0);
23552 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23553 (!Subtarget->hasInt256() ||
23554 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23557 SDValue Amt = N->getOperand(1);
23559 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23560 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23561 APInt ShiftAmt = AmtSplat->getAPIntValue();
23562 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23564 // SSE2/AVX2 logical shifts always return a vector of 0s
23565 // if the shift amount is bigger than or equal to
23566 // the element size. The constant shift amount will be
23567 // encoded as a 8-bit immediate.
23568 if (ShiftAmt.trunc(8).uge(MaxAmount))
23569 return getZeroVector(VT, Subtarget, DAG, DL);
23575 /// PerformShiftCombine - Combine shifts.
23576 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23577 TargetLowering::DAGCombinerInfo &DCI,
23578 const X86Subtarget *Subtarget) {
23579 if (N->getOpcode() == ISD::SHL)
23580 if (SDValue V = PerformSHLCombine(N, DAG))
23583 // Try to fold this logical shift into a zero vector.
23584 if (N->getOpcode() != ISD::SRA)
23585 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23591 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23592 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23593 // and friends. Likewise for OR -> CMPNEQSS.
23594 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23595 TargetLowering::DAGCombinerInfo &DCI,
23596 const X86Subtarget *Subtarget) {
23599 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23600 // we're requiring SSE2 for both.
23601 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23602 SDValue N0 = N->getOperand(0);
23603 SDValue N1 = N->getOperand(1);
23604 SDValue CMP0 = N0->getOperand(1);
23605 SDValue CMP1 = N1->getOperand(1);
23608 // The SETCCs should both refer to the same CMP.
23609 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23612 SDValue CMP00 = CMP0->getOperand(0);
23613 SDValue CMP01 = CMP0->getOperand(1);
23614 EVT VT = CMP00.getValueType();
23616 if (VT == MVT::f32 || VT == MVT::f64) {
23617 bool ExpectingFlags = false;
23618 // Check for any users that want flags:
23619 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23620 !ExpectingFlags && UI != UE; ++UI)
23621 switch (UI->getOpcode()) {
23626 ExpectingFlags = true;
23628 case ISD::CopyToReg:
23629 case ISD::SIGN_EXTEND:
23630 case ISD::ZERO_EXTEND:
23631 case ISD::ANY_EXTEND:
23635 if (!ExpectingFlags) {
23636 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23637 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23639 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23640 X86::CondCode tmp = cc0;
23645 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23646 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23647 // FIXME: need symbolic constants for these magic numbers.
23648 // See X86ATTInstPrinter.cpp:printSSECC().
23649 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23650 if (Subtarget->hasAVX512()) {
23651 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23653 DAG.getConstant(x86cc, DL, MVT::i8));
23654 if (N->getValueType(0) != MVT::i1)
23655 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23659 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23660 CMP00.getValueType(), CMP00, CMP01,
23661 DAG.getConstant(x86cc, DL,
23664 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23665 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23667 if (is64BitFP && !Subtarget->is64Bit()) {
23668 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23669 // 64-bit integer, since that's not a legal type. Since
23670 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23671 // bits, but can do this little dance to extract the lowest 32 bits
23672 // and work with those going forward.
23673 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23675 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23676 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23677 Vector32, DAG.getIntPtrConstant(0, DL));
23681 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23682 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23683 DAG.getConstant(1, DL, IntVT));
23684 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23686 return OneBitOfTruth;
23694 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23695 /// so it can be folded inside ANDNP.
23696 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23697 EVT VT = N->getValueType(0);
23699 // Match direct AllOnes for 128 and 256-bit vectors
23700 if (ISD::isBuildVectorAllOnes(N))
23703 // Look through a bit convert.
23704 if (N->getOpcode() == ISD::BITCAST)
23705 N = N->getOperand(0).getNode();
23707 // Sometimes the operand may come from a insert_subvector building a 256-bit
23709 if (VT.is256BitVector() &&
23710 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23711 SDValue V1 = N->getOperand(0);
23712 SDValue V2 = N->getOperand(1);
23714 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23715 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23716 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23717 ISD::isBuildVectorAllOnes(V2.getNode()))
23724 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23725 // register. In most cases we actually compare or select YMM-sized registers
23726 // and mixing the two types creates horrible code. This method optimizes
23727 // some of the transition sequences.
23728 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23729 TargetLowering::DAGCombinerInfo &DCI,
23730 const X86Subtarget *Subtarget) {
23731 EVT VT = N->getValueType(0);
23732 if (!VT.is256BitVector())
23735 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23736 N->getOpcode() == ISD::ZERO_EXTEND ||
23737 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23739 SDValue Narrow = N->getOperand(0);
23740 EVT NarrowVT = Narrow->getValueType(0);
23741 if (!NarrowVT.is128BitVector())
23744 if (Narrow->getOpcode() != ISD::XOR &&
23745 Narrow->getOpcode() != ISD::AND &&
23746 Narrow->getOpcode() != ISD::OR)
23749 SDValue N0 = Narrow->getOperand(0);
23750 SDValue N1 = Narrow->getOperand(1);
23753 // The Left side has to be a trunc.
23754 if (N0.getOpcode() != ISD::TRUNCATE)
23757 // The type of the truncated inputs.
23758 EVT WideVT = N0->getOperand(0)->getValueType(0);
23762 // The right side has to be a 'trunc' or a constant vector.
23763 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23764 ConstantSDNode *RHSConstSplat = nullptr;
23765 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23766 RHSConstSplat = RHSBV->getConstantSplatNode();
23767 if (!RHSTrunc && !RHSConstSplat)
23770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23772 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23775 // Set N0 and N1 to hold the inputs to the new wide operation.
23776 N0 = N0->getOperand(0);
23777 if (RHSConstSplat) {
23778 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23779 SDValue(RHSConstSplat, 0));
23780 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23781 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23782 } else if (RHSTrunc) {
23783 N1 = N1->getOperand(0);
23786 // Generate the wide operation.
23787 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23788 unsigned Opcode = N->getOpcode();
23790 case ISD::ANY_EXTEND:
23792 case ISD::ZERO_EXTEND: {
23793 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23794 APInt Mask = APInt::getAllOnesValue(InBits);
23795 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23796 return DAG.getNode(ISD::AND, DL, VT,
23797 Op, DAG.getConstant(Mask, DL, VT));
23799 case ISD::SIGN_EXTEND:
23800 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23801 Op, DAG.getValueType(NarrowVT));
23803 llvm_unreachable("Unexpected opcode");
23807 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23808 TargetLowering::DAGCombinerInfo &DCI,
23809 const X86Subtarget *Subtarget) {
23810 SDValue N0 = N->getOperand(0);
23811 SDValue N1 = N->getOperand(1);
23814 // A vector zext_in_reg may be represented as a shuffle,
23815 // feeding into a bitcast (this represents anyext) feeding into
23816 // an and with a mask.
23817 // We'd like to try to combine that into a shuffle with zero
23818 // plus a bitcast, removing the and.
23819 if (N0.getOpcode() != ISD::BITCAST ||
23820 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23823 // The other side of the AND should be a splat of 2^C, where C
23824 // is the number of bits in the source type.
23825 if (N1.getOpcode() == ISD::BITCAST)
23826 N1 = N1.getOperand(0);
23827 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23829 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23831 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23832 EVT SrcType = Shuffle->getValueType(0);
23834 // We expect a single-source shuffle
23835 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23838 unsigned SrcSize = SrcType.getScalarSizeInBits();
23840 APInt SplatValue, SplatUndef;
23841 unsigned SplatBitSize;
23843 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23844 SplatBitSize, HasAnyUndefs))
23847 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23848 // Make sure the splat matches the mask we expect
23849 if (SplatBitSize > ResSize ||
23850 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23853 // Make sure the input and output size make sense
23854 if (SrcSize >= ResSize || ResSize % SrcSize)
23857 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23858 // The number of u's between each two values depends on the ratio between
23859 // the source and dest type.
23860 unsigned ZextRatio = ResSize / SrcSize;
23861 bool IsZext = true;
23862 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23863 if (i % ZextRatio) {
23864 if (Shuffle->getMaskElt(i) > 0) {
23870 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23871 // Expected element number
23881 // Ok, perform the transformation - replace the shuffle with
23882 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23883 // (instead of undef) where the k elements come from the zero vector.
23884 SmallVector<int, 8> Mask;
23885 unsigned NumElems = SrcType.getVectorNumElements();
23886 for (unsigned i = 0; i < NumElems; ++i)
23888 Mask.push_back(NumElems);
23890 Mask.push_back(i / ZextRatio);
23892 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23893 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23894 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23897 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23898 TargetLowering::DAGCombinerInfo &DCI,
23899 const X86Subtarget *Subtarget) {
23900 if (DCI.isBeforeLegalizeOps())
23903 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23906 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23909 EVT VT = N->getValueType(0);
23910 SDValue N0 = N->getOperand(0);
23911 SDValue N1 = N->getOperand(1);
23914 // Create BEXTR instructions
23915 // BEXTR is ((X >> imm) & (2**size-1))
23916 if (VT == MVT::i32 || VT == MVT::i64) {
23917 // Check for BEXTR.
23918 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23919 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23920 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23921 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23922 if (MaskNode && ShiftNode) {
23923 uint64_t Mask = MaskNode->getZExtValue();
23924 uint64_t Shift = ShiftNode->getZExtValue();
23925 if (isMask_64(Mask)) {
23926 uint64_t MaskSize = countPopulation(Mask);
23927 if (Shift + MaskSize <= VT.getSizeInBits())
23928 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23929 DAG.getConstant(Shift | (MaskSize << 8), DL,
23938 // Want to form ANDNP nodes:
23939 // 1) In the hopes of then easily combining them with OR and AND nodes
23940 // to form PBLEND/PSIGN.
23941 // 2) To match ANDN packed intrinsics
23942 if (VT != MVT::v2i64 && VT != MVT::v4i64)
23945 // Check LHS for vnot
23946 if (N0.getOpcode() == ISD::XOR &&
23947 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23948 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23949 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23951 // Check RHS for vnot
23952 if (N1.getOpcode() == ISD::XOR &&
23953 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23954 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23955 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23960 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23961 TargetLowering::DAGCombinerInfo &DCI,
23962 const X86Subtarget *Subtarget) {
23963 if (DCI.isBeforeLegalizeOps())
23966 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23969 SDValue N0 = N->getOperand(0);
23970 SDValue N1 = N->getOperand(1);
23971 EVT VT = N->getValueType(0);
23973 // look for psign/blend
23974 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23975 if (!Subtarget->hasSSSE3() ||
23976 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23979 // Canonicalize pandn to RHS
23980 if (N0.getOpcode() == X86ISD::ANDNP)
23982 // or (and (m, y), (pandn m, x))
23983 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23984 SDValue Mask = N1.getOperand(0);
23985 SDValue X = N1.getOperand(1);
23987 if (N0.getOperand(0) == Mask)
23988 Y = N0.getOperand(1);
23989 if (N0.getOperand(1) == Mask)
23990 Y = N0.getOperand(0);
23992 // Check to see if the mask appeared in both the AND and ANDNP and
23996 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23997 // Look through mask bitcast.
23998 if (Mask.getOpcode() == ISD::BITCAST)
23999 Mask = Mask.getOperand(0);
24000 if (X.getOpcode() == ISD::BITCAST)
24001 X = X.getOperand(0);
24002 if (Y.getOpcode() == ISD::BITCAST)
24003 Y = Y.getOperand(0);
24005 EVT MaskVT = Mask.getValueType();
24007 // Validate that the Mask operand is a vector sra node.
24008 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24009 // there is no psrai.b
24010 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24011 unsigned SraAmt = ~0;
24012 if (Mask.getOpcode() == ISD::SRA) {
24013 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24014 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24015 SraAmt = AmtConst->getZExtValue();
24016 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24017 SDValue SraC = Mask.getOperand(1);
24018 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24020 if ((SraAmt + 1) != EltBits)
24025 // Now we know we at least have a plendvb with the mask val. See if
24026 // we can form a psignb/w/d.
24027 // psign = x.type == y.type == mask.type && y = sub(0, x);
24028 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24029 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24030 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24031 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24032 "Unsupported VT for PSIGN");
24033 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24034 return DAG.getBitcast(VT, Mask);
24036 // PBLENDVB only available on SSE 4.1
24037 if (!Subtarget->hasSSE41())
24040 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24042 X = DAG.getBitcast(BlendVT, X);
24043 Y = DAG.getBitcast(BlendVT, Y);
24044 Mask = DAG.getBitcast(BlendVT, Mask);
24045 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24046 return DAG.getBitcast(VT, Mask);
24050 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24053 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24054 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24056 // SHLD/SHRD instructions have lower register pressure, but on some
24057 // platforms they have higher latency than the equivalent
24058 // series of shifts/or that would otherwise be generated.
24059 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24060 // have higher latencies and we are not optimizing for size.
24061 if (!OptForSize && Subtarget->isSHLDSlow())
24064 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24066 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24068 if (!N0.hasOneUse() || !N1.hasOneUse())
24071 SDValue ShAmt0 = N0.getOperand(1);
24072 if (ShAmt0.getValueType() != MVT::i8)
24074 SDValue ShAmt1 = N1.getOperand(1);
24075 if (ShAmt1.getValueType() != MVT::i8)
24077 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24078 ShAmt0 = ShAmt0.getOperand(0);
24079 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24080 ShAmt1 = ShAmt1.getOperand(0);
24083 unsigned Opc = X86ISD::SHLD;
24084 SDValue Op0 = N0.getOperand(0);
24085 SDValue Op1 = N1.getOperand(0);
24086 if (ShAmt0.getOpcode() == ISD::SUB) {
24087 Opc = X86ISD::SHRD;
24088 std::swap(Op0, Op1);
24089 std::swap(ShAmt0, ShAmt1);
24092 unsigned Bits = VT.getSizeInBits();
24093 if (ShAmt1.getOpcode() == ISD::SUB) {
24094 SDValue Sum = ShAmt1.getOperand(0);
24095 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24096 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24097 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24098 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24099 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24100 return DAG.getNode(Opc, DL, VT,
24102 DAG.getNode(ISD::TRUNCATE, DL,
24105 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24106 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24108 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24109 return DAG.getNode(Opc, DL, VT,
24110 N0.getOperand(0), N1.getOperand(0),
24111 DAG.getNode(ISD::TRUNCATE, DL,
24118 // Generate NEG and CMOV for integer abs.
24119 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24120 EVT VT = N->getValueType(0);
24122 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24123 // 8-bit integer abs to NEG and CMOV.
24124 if (VT.isInteger() && VT.getSizeInBits() == 8)
24127 SDValue N0 = N->getOperand(0);
24128 SDValue N1 = N->getOperand(1);
24131 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24132 // and change it to SUB and CMOV.
24133 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24134 N0.getOpcode() == ISD::ADD &&
24135 N0.getOperand(1) == N1 &&
24136 N1.getOpcode() == ISD::SRA &&
24137 N1.getOperand(0) == N0.getOperand(0))
24138 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24139 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24140 // Generate SUB & CMOV.
24141 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24142 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24144 SDValue Ops[] = { N0.getOperand(0), Neg,
24145 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24146 SDValue(Neg.getNode(), 1) };
24147 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24152 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24153 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24154 TargetLowering::DAGCombinerInfo &DCI,
24155 const X86Subtarget *Subtarget) {
24156 if (DCI.isBeforeLegalizeOps())
24159 if (Subtarget->hasCMov())
24160 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24166 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24167 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24168 TargetLowering::DAGCombinerInfo &DCI,
24169 const X86Subtarget *Subtarget) {
24170 LoadSDNode *Ld = cast<LoadSDNode>(N);
24171 EVT RegVT = Ld->getValueType(0);
24172 EVT MemVT = Ld->getMemoryVT();
24174 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24176 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24177 // into two 16-byte operations.
24178 ISD::LoadExtType Ext = Ld->getExtensionType();
24179 unsigned Alignment = Ld->getAlignment();
24180 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24181 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24182 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24183 unsigned NumElems = RegVT.getVectorNumElements();
24187 SDValue Ptr = Ld->getBasePtr();
24188 SDValue Increment =
24189 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24191 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24193 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24194 Ld->getPointerInfo(), Ld->isVolatile(),
24195 Ld->isNonTemporal(), Ld->isInvariant(),
24197 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24198 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24199 Ld->getPointerInfo(), Ld->isVolatile(),
24200 Ld->isNonTemporal(), Ld->isInvariant(),
24201 std::min(16U, Alignment));
24202 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24204 Load2.getValue(1));
24206 SDValue NewVec = DAG.getUNDEF(RegVT);
24207 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24208 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24209 return DCI.CombineTo(N, NewVec, TF, true);
24215 /// PerformMLOADCombine - Resolve extending loads
24216 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24217 TargetLowering::DAGCombinerInfo &DCI,
24218 const X86Subtarget *Subtarget) {
24219 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24220 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24223 EVT VT = Mld->getValueType(0);
24224 unsigned NumElems = VT.getVectorNumElements();
24225 EVT LdVT = Mld->getMemoryVT();
24228 assert(LdVT != VT && "Cannot extend to the same type");
24229 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24230 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24231 // From, To sizes and ElemCount must be pow of two
24232 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24233 "Unexpected size for extending masked load");
24235 unsigned SizeRatio = ToSz / FromSz;
24236 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24238 // Create a type on which we perform the shuffle
24239 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24240 LdVT.getScalarType(), NumElems*SizeRatio);
24241 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24243 // Convert Src0 value
24244 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24245 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24246 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24247 for (unsigned i = 0; i != NumElems; ++i)
24248 ShuffleVec[i] = i * SizeRatio;
24250 // Can't shuffle using an illegal type.
24251 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24252 && "WideVecVT should be legal");
24253 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24254 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24256 // Prepare the new mask
24258 SDValue Mask = Mld->getMask();
24259 if (Mask.getValueType() == VT) {
24260 // Mask and original value have the same type
24261 NewMask = DAG.getBitcast(WideVecVT, Mask);
24262 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24263 for (unsigned i = 0; i != NumElems; ++i)
24264 ShuffleVec[i] = i * SizeRatio;
24265 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24266 ShuffleVec[i] = NumElems*SizeRatio;
24267 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24268 DAG.getConstant(0, dl, WideVecVT),
24272 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24273 unsigned WidenNumElts = NumElems*SizeRatio;
24274 unsigned MaskNumElts = VT.getVectorNumElements();
24275 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24278 unsigned NumConcat = WidenNumElts / MaskNumElts;
24279 SmallVector<SDValue, 16> Ops(NumConcat);
24280 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24282 for (unsigned i = 1; i != NumConcat; ++i)
24285 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24288 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24289 Mld->getBasePtr(), NewMask, WideSrc0,
24290 Mld->getMemoryVT(), Mld->getMemOperand(),
24292 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24293 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24296 /// PerformMSTORECombine - Resolve truncating stores
24297 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24298 const X86Subtarget *Subtarget) {
24299 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24300 if (!Mst->isTruncatingStore())
24303 EVT VT = Mst->getValue().getValueType();
24304 unsigned NumElems = VT.getVectorNumElements();
24305 EVT StVT = Mst->getMemoryVT();
24308 assert(StVT != VT && "Cannot truncate to the same type");
24309 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24310 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24314 // The truncating store is legal in some cases. For example
24315 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24316 // are designated for truncate store.
24317 // In this case we don't need any further transformations.
24318 if (TLI.isTruncStoreLegal(VT, StVT))
24321 // From, To sizes and ElemCount must be pow of two
24322 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24323 "Unexpected size for truncating masked store");
24324 // We are going to use the original vector elt for storing.
24325 // Accumulated smaller vector elements must be a multiple of the store size.
24326 assert (((NumElems * FromSz) % ToSz) == 0 &&
24327 "Unexpected ratio for truncating masked store");
24329 unsigned SizeRatio = FromSz / ToSz;
24330 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24332 // Create a type on which we perform the shuffle
24333 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24334 StVT.getScalarType(), NumElems*SizeRatio);
24336 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24338 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24339 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24340 for (unsigned i = 0; i != NumElems; ++i)
24341 ShuffleVec[i] = i * SizeRatio;
24343 // Can't shuffle using an illegal type.
24344 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24345 && "WideVecVT should be legal");
24347 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24348 DAG.getUNDEF(WideVecVT),
24352 SDValue Mask = Mst->getMask();
24353 if (Mask.getValueType() == VT) {
24354 // Mask and original value have the same type
24355 NewMask = DAG.getBitcast(WideVecVT, Mask);
24356 for (unsigned i = 0; i != NumElems; ++i)
24357 ShuffleVec[i] = i * SizeRatio;
24358 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24359 ShuffleVec[i] = NumElems*SizeRatio;
24360 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24361 DAG.getConstant(0, dl, WideVecVT),
24365 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24366 unsigned WidenNumElts = NumElems*SizeRatio;
24367 unsigned MaskNumElts = VT.getVectorNumElements();
24368 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24371 unsigned NumConcat = WidenNumElts / MaskNumElts;
24372 SmallVector<SDValue, 16> Ops(NumConcat);
24373 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24375 for (unsigned i = 1; i != NumConcat; ++i)
24378 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24381 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24382 NewMask, StVT, Mst->getMemOperand(), false);
24384 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24385 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24386 const X86Subtarget *Subtarget) {
24387 StoreSDNode *St = cast<StoreSDNode>(N);
24388 EVT VT = St->getValue().getValueType();
24389 EVT StVT = St->getMemoryVT();
24391 SDValue StoredVal = St->getOperand(1);
24392 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24394 // If we are saving a concatenation of two XMM registers and 32-byte stores
24395 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24396 unsigned Alignment = St->getAlignment();
24397 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24398 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24399 StVT == VT && !IsAligned) {
24400 unsigned NumElems = VT.getVectorNumElements();
24404 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24405 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24408 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24409 SDValue Ptr0 = St->getBasePtr();
24410 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24412 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24413 St->getPointerInfo(), St->isVolatile(),
24414 St->isNonTemporal(), Alignment);
24415 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24416 St->getPointerInfo(), St->isVolatile(),
24417 St->isNonTemporal(),
24418 std::min(16U, Alignment));
24419 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24422 // Optimize trunc store (of multiple scalars) to shuffle and store.
24423 // First, pack all of the elements in one place. Next, store to memory
24424 // in fewer chunks.
24425 if (St->isTruncatingStore() && VT.isVector()) {
24426 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24427 unsigned NumElems = VT.getVectorNumElements();
24428 assert(StVT != VT && "Cannot truncate to the same type");
24429 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24430 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24432 // The truncating store is legal in some cases. For example
24433 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24434 // are designated for truncate store.
24435 // In this case we don't need any further transformations.
24436 if (TLI.isTruncStoreLegal(VT, StVT))
24439 // From, To sizes and ElemCount must be pow of two
24440 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24441 // We are going to use the original vector elt for storing.
24442 // Accumulated smaller vector elements must be a multiple of the store size.
24443 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24445 unsigned SizeRatio = FromSz / ToSz;
24447 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24449 // Create a type on which we perform the shuffle
24450 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24451 StVT.getScalarType(), NumElems*SizeRatio);
24453 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24455 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24456 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24457 for (unsigned i = 0; i != NumElems; ++i)
24458 ShuffleVec[i] = i * SizeRatio;
24460 // Can't shuffle using an illegal type.
24461 if (!TLI.isTypeLegal(WideVecVT))
24464 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24465 DAG.getUNDEF(WideVecVT),
24467 // At this point all of the data is stored at the bottom of the
24468 // register. We now need to save it to mem.
24470 // Find the largest store unit
24471 MVT StoreType = MVT::i8;
24472 for (MVT Tp : MVT::integer_valuetypes()) {
24473 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24477 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24478 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24479 (64 <= NumElems * ToSz))
24480 StoreType = MVT::f64;
24482 // Bitcast the original vector into a vector of store-size units
24483 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24484 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24485 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24486 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24487 SmallVector<SDValue, 8> Chains;
24488 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24489 TLI.getPointerTy(DAG.getDataLayout()));
24490 SDValue Ptr = St->getBasePtr();
24492 // Perform one or more big stores into memory.
24493 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24494 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24495 StoreType, ShuffWide,
24496 DAG.getIntPtrConstant(i, dl));
24497 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24498 St->getPointerInfo(), St->isVolatile(),
24499 St->isNonTemporal(), St->getAlignment());
24500 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24501 Chains.push_back(Ch);
24504 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24507 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24508 // the FP state in cases where an emms may be missing.
24509 // A preferable solution to the general problem is to figure out the right
24510 // places to insert EMMS. This qualifies as a quick hack.
24512 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24513 if (VT.getSizeInBits() != 64)
24516 const Function *F = DAG.getMachineFunction().getFunction();
24517 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24519 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24520 if ((VT.isVector() ||
24521 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24522 isa<LoadSDNode>(St->getValue()) &&
24523 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24524 St->getChain().hasOneUse() && !St->isVolatile()) {
24525 SDNode* LdVal = St->getValue().getNode();
24526 LoadSDNode *Ld = nullptr;
24527 int TokenFactorIndex = -1;
24528 SmallVector<SDValue, 8> Ops;
24529 SDNode* ChainVal = St->getChain().getNode();
24530 // Must be a store of a load. We currently handle two cases: the load
24531 // is a direct child, and it's under an intervening TokenFactor. It is
24532 // possible to dig deeper under nested TokenFactors.
24533 if (ChainVal == LdVal)
24534 Ld = cast<LoadSDNode>(St->getChain());
24535 else if (St->getValue().hasOneUse() &&
24536 ChainVal->getOpcode() == ISD::TokenFactor) {
24537 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24538 if (ChainVal->getOperand(i).getNode() == LdVal) {
24539 TokenFactorIndex = i;
24540 Ld = cast<LoadSDNode>(St->getValue());
24542 Ops.push_back(ChainVal->getOperand(i));
24546 if (!Ld || !ISD::isNormalLoad(Ld))
24549 // If this is not the MMX case, i.e. we are just turning i64 load/store
24550 // into f64 load/store, avoid the transformation if there are multiple
24551 // uses of the loaded value.
24552 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24557 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24558 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24560 if (Subtarget->is64Bit() || F64IsLegal) {
24561 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24562 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24563 Ld->getPointerInfo(), Ld->isVolatile(),
24564 Ld->isNonTemporal(), Ld->isInvariant(),
24565 Ld->getAlignment());
24566 SDValue NewChain = NewLd.getValue(1);
24567 if (TokenFactorIndex != -1) {
24568 Ops.push_back(NewChain);
24569 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24571 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24572 St->getPointerInfo(),
24573 St->isVolatile(), St->isNonTemporal(),
24574 St->getAlignment());
24577 // Otherwise, lower to two pairs of 32-bit loads / stores.
24578 SDValue LoAddr = Ld->getBasePtr();
24579 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24580 DAG.getConstant(4, LdDL, MVT::i32));
24582 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24583 Ld->getPointerInfo(),
24584 Ld->isVolatile(), Ld->isNonTemporal(),
24585 Ld->isInvariant(), Ld->getAlignment());
24586 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24587 Ld->getPointerInfo().getWithOffset(4),
24588 Ld->isVolatile(), Ld->isNonTemporal(),
24590 MinAlign(Ld->getAlignment(), 4));
24592 SDValue NewChain = LoLd.getValue(1);
24593 if (TokenFactorIndex != -1) {
24594 Ops.push_back(LoLd);
24595 Ops.push_back(HiLd);
24596 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24599 LoAddr = St->getBasePtr();
24600 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24601 DAG.getConstant(4, StDL, MVT::i32));
24603 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24604 St->getPointerInfo(),
24605 St->isVolatile(), St->isNonTemporal(),
24606 St->getAlignment());
24607 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24608 St->getPointerInfo().getWithOffset(4),
24610 St->isNonTemporal(),
24611 MinAlign(St->getAlignment(), 4));
24612 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24615 // This is similar to the above case, but here we handle a scalar 64-bit
24616 // integer store that is extracted from a vector on a 32-bit target.
24617 // If we have SSE2, then we can treat it like a floating-point double
24618 // to get past legalization. The execution dependencies fixup pass will
24619 // choose the optimal machine instruction for the store if this really is
24620 // an integer or v2f32 rather than an f64.
24621 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24622 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24623 SDValue OldExtract = St->getOperand(1);
24624 SDValue ExtOp0 = OldExtract.getOperand(0);
24625 unsigned VecSize = ExtOp0.getValueSizeInBits();
24626 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24627 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24628 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24629 BitCast, OldExtract.getOperand(1));
24630 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24631 St->getPointerInfo(), St->isVolatile(),
24632 St->isNonTemporal(), St->getAlignment());
24638 /// Return 'true' if this vector operation is "horizontal"
24639 /// and return the operands for the horizontal operation in LHS and RHS. A
24640 /// horizontal operation performs the binary operation on successive elements
24641 /// of its first operand, then on successive elements of its second operand,
24642 /// returning the resulting values in a vector. For example, if
24643 /// A = < float a0, float a1, float a2, float a3 >
24645 /// B = < float b0, float b1, float b2, float b3 >
24646 /// then the result of doing a horizontal operation on A and B is
24647 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24648 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24649 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24650 /// set to A, RHS to B, and the routine returns 'true'.
24651 /// Note that the binary operation should have the property that if one of the
24652 /// operands is UNDEF then the result is UNDEF.
24653 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24654 // Look for the following pattern: if
24655 // A = < float a0, float a1, float a2, float a3 >
24656 // B = < float b0, float b1, float b2, float b3 >
24658 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24659 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24660 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24661 // which is A horizontal-op B.
24663 // At least one of the operands should be a vector shuffle.
24664 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24665 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24668 MVT VT = LHS.getSimpleValueType();
24670 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24671 "Unsupported vector type for horizontal add/sub");
24673 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24674 // operate independently on 128-bit lanes.
24675 unsigned NumElts = VT.getVectorNumElements();
24676 unsigned NumLanes = VT.getSizeInBits()/128;
24677 unsigned NumLaneElts = NumElts / NumLanes;
24678 assert((NumLaneElts % 2 == 0) &&
24679 "Vector type should have an even number of elements in each lane");
24680 unsigned HalfLaneElts = NumLaneElts/2;
24682 // View LHS in the form
24683 // LHS = VECTOR_SHUFFLE A, B, LMask
24684 // If LHS is not a shuffle then pretend it is the shuffle
24685 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24686 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24689 SmallVector<int, 16> LMask(NumElts);
24690 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24691 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24692 A = LHS.getOperand(0);
24693 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24694 B = LHS.getOperand(1);
24695 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24696 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24698 if (LHS.getOpcode() != ISD::UNDEF)
24700 for (unsigned i = 0; i != NumElts; ++i)
24704 // Likewise, view RHS in the form
24705 // RHS = VECTOR_SHUFFLE C, D, RMask
24707 SmallVector<int, 16> RMask(NumElts);
24708 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24709 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24710 C = RHS.getOperand(0);
24711 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24712 D = RHS.getOperand(1);
24713 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24714 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24716 if (RHS.getOpcode() != ISD::UNDEF)
24718 for (unsigned i = 0; i != NumElts; ++i)
24722 // Check that the shuffles are both shuffling the same vectors.
24723 if (!(A == C && B == D) && !(A == D && B == C))
24726 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24727 if (!A.getNode() && !B.getNode())
24730 // If A and B occur in reverse order in RHS, then "swap" them (which means
24731 // rewriting the mask).
24733 ShuffleVectorSDNode::commuteMask(RMask);
24735 // At this point LHS and RHS are equivalent to
24736 // LHS = VECTOR_SHUFFLE A, B, LMask
24737 // RHS = VECTOR_SHUFFLE A, B, RMask
24738 // Check that the masks correspond to performing a horizontal operation.
24739 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24740 for (unsigned i = 0; i != NumLaneElts; ++i) {
24741 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24743 // Ignore any UNDEF components.
24744 if (LIdx < 0 || RIdx < 0 ||
24745 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24746 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24749 // Check that successive elements are being operated on. If not, this is
24750 // not a horizontal operation.
24751 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24752 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24753 if (!(LIdx == Index && RIdx == Index + 1) &&
24754 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24759 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24760 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24764 /// Do target-specific dag combines on floating point adds.
24765 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24766 const X86Subtarget *Subtarget) {
24767 EVT VT = N->getValueType(0);
24768 SDValue LHS = N->getOperand(0);
24769 SDValue RHS = N->getOperand(1);
24771 // Try to synthesize horizontal adds from adds of shuffles.
24772 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24773 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24774 isHorizontalBinOp(LHS, RHS, true))
24775 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24779 /// Do target-specific dag combines on floating point subs.
24780 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24781 const X86Subtarget *Subtarget) {
24782 EVT VT = N->getValueType(0);
24783 SDValue LHS = N->getOperand(0);
24784 SDValue RHS = N->getOperand(1);
24786 // Try to synthesize horizontal subs from subs of shuffles.
24787 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24788 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24789 isHorizontalBinOp(LHS, RHS, false))
24790 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24794 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24795 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24796 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24798 // F[X]OR(0.0, x) -> x
24799 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24800 if (C->getValueAPF().isPosZero())
24801 return N->getOperand(1);
24803 // F[X]OR(x, 0.0) -> x
24804 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24805 if (C->getValueAPF().isPosZero())
24806 return N->getOperand(0);
24810 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24811 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24812 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24814 // Only perform optimizations if UnsafeMath is used.
24815 if (!DAG.getTarget().Options.UnsafeFPMath)
24818 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24819 // into FMINC and FMAXC, which are Commutative operations.
24820 unsigned NewOp = 0;
24821 switch (N->getOpcode()) {
24822 default: llvm_unreachable("unknown opcode");
24823 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24824 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24827 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24828 N->getOperand(0), N->getOperand(1));
24831 /// Do target-specific dag combines on X86ISD::FAND nodes.
24832 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24833 // FAND(0.0, x) -> 0.0
24834 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24835 if (C->getValueAPF().isPosZero())
24836 return N->getOperand(0);
24838 // FAND(x, 0.0) -> 0.0
24839 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24840 if (C->getValueAPF().isPosZero())
24841 return N->getOperand(1);
24846 /// Do target-specific dag combines on X86ISD::FANDN nodes
24847 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24848 // FANDN(0.0, x) -> x
24849 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24850 if (C->getValueAPF().isPosZero())
24851 return N->getOperand(1);
24853 // FANDN(x, 0.0) -> 0.0
24854 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24855 if (C->getValueAPF().isPosZero())
24856 return N->getOperand(1);
24861 static SDValue PerformBTCombine(SDNode *N,
24863 TargetLowering::DAGCombinerInfo &DCI) {
24864 // BT ignores high bits in the bit index operand.
24865 SDValue Op1 = N->getOperand(1);
24866 if (Op1.hasOneUse()) {
24867 unsigned BitWidth = Op1.getValueSizeInBits();
24868 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24869 APInt KnownZero, KnownOne;
24870 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24871 !DCI.isBeforeLegalizeOps());
24872 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24873 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24874 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24875 DCI.CommitTargetLoweringOpt(TLO);
24880 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24881 SDValue Op = N->getOperand(0);
24882 if (Op.getOpcode() == ISD::BITCAST)
24883 Op = Op.getOperand(0);
24884 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24885 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24886 VT.getVectorElementType().getSizeInBits() ==
24887 OpVT.getVectorElementType().getSizeInBits()) {
24888 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24893 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24894 const X86Subtarget *Subtarget) {
24895 EVT VT = N->getValueType(0);
24896 if (!VT.isVector())
24899 SDValue N0 = N->getOperand(0);
24900 SDValue N1 = N->getOperand(1);
24901 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24904 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24905 // both SSE and AVX2 since there is no sign-extended shift right
24906 // operation on a vector with 64-bit elements.
24907 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24908 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24909 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24910 N0.getOpcode() == ISD::SIGN_EXTEND)) {
24911 SDValue N00 = N0.getOperand(0);
24913 // EXTLOAD has a better solution on AVX2,
24914 // it may be replaced with X86ISD::VSEXT node.
24915 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24916 if (!ISD::isNormalLoad(N00.getNode()))
24919 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24920 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24922 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24928 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24929 TargetLowering::DAGCombinerInfo &DCI,
24930 const X86Subtarget *Subtarget) {
24931 SDValue N0 = N->getOperand(0);
24932 EVT VT = N->getValueType(0);
24933 EVT SVT = VT.getScalarType();
24934 EVT InVT = N0.getValueType();
24935 EVT InSVT = InVT.getScalarType();
24938 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24939 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24940 // This exposes the sext to the sdivrem lowering, so that it directly extends
24941 // from AH (which we otherwise need to do contortions to access).
24942 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24943 InVT == MVT::i8 && VT == MVT::i32) {
24944 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24945 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24946 N0.getOperand(0), N0.getOperand(1));
24947 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24948 return R.getValue(1);
24951 if (!DCI.isBeforeLegalizeOps()) {
24952 if (InVT == MVT::i1) {
24953 SDValue Zero = DAG.getConstant(0, DL, VT);
24955 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24956 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24961 if (VT.isVector() && Subtarget->hasSSE2()) {
24962 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24963 EVT InVT = N.getValueType();
24964 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24965 Size / InVT.getScalarSizeInBits());
24966 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24967 DAG.getUNDEF(InVT));
24969 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24972 // If target-size is less than 128-bits, extend to a type that would extend
24973 // to 128 bits, extend that and extract the original target vector.
24974 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24975 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24976 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24977 unsigned Scale = 128 / VT.getSizeInBits();
24979 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24980 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24981 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24982 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24983 DAG.getIntPtrConstant(0, DL));
24986 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24987 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24988 if (VT.getSizeInBits() == 128 &&
24989 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24990 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24991 SDValue ExOp = ExtendVecSize(DL, N0, 128);
24992 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24995 // On pre-AVX2 targets, split into 128-bit nodes of
24996 // ISD::SIGN_EXTEND_VECTOR_INREG.
24997 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24998 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24999 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25000 unsigned NumVecs = VT.getSizeInBits() / 128;
25001 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25002 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25003 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25005 SmallVector<SDValue, 8> Opnds;
25006 for (unsigned i = 0, Offset = 0; i != NumVecs;
25007 ++i, Offset += NumSubElts) {
25008 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25009 DAG.getIntPtrConstant(Offset, DL));
25010 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25011 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25012 Opnds.push_back(SrcVec);
25014 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25018 if (!Subtarget->hasFp256())
25021 if (VT.isVector() && VT.getSizeInBits() == 256)
25022 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25028 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25029 const X86Subtarget* Subtarget) {
25031 EVT VT = N->getValueType(0);
25033 // Let legalize expand this if it isn't a legal type yet.
25034 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25037 EVT ScalarVT = VT.getScalarType();
25038 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25039 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25040 !Subtarget->hasAVX512()))
25043 SDValue A = N->getOperand(0);
25044 SDValue B = N->getOperand(1);
25045 SDValue C = N->getOperand(2);
25047 bool NegA = (A.getOpcode() == ISD::FNEG);
25048 bool NegB = (B.getOpcode() == ISD::FNEG);
25049 bool NegC = (C.getOpcode() == ISD::FNEG);
25051 // Negative multiplication when NegA xor NegB
25052 bool NegMul = (NegA != NegB);
25054 A = A.getOperand(0);
25056 B = B.getOperand(0);
25058 C = C.getOperand(0);
25062 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25064 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25066 return DAG.getNode(Opcode, dl, VT, A, B, C);
25069 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25070 TargetLowering::DAGCombinerInfo &DCI,
25071 const X86Subtarget *Subtarget) {
25072 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25073 // (and (i32 x86isd::setcc_carry), 1)
25074 // This eliminates the zext. This transformation is necessary because
25075 // ISD::SETCC is always legalized to i8.
25077 SDValue N0 = N->getOperand(0);
25078 EVT VT = N->getValueType(0);
25080 if (N0.getOpcode() == ISD::AND &&
25082 N0.getOperand(0).hasOneUse()) {
25083 SDValue N00 = N0.getOperand(0);
25084 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25085 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25086 if (!C || C->getZExtValue() != 1)
25088 return DAG.getNode(ISD::AND, dl, VT,
25089 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25090 N00.getOperand(0), N00.getOperand(1)),
25091 DAG.getConstant(1, dl, VT));
25095 if (N0.getOpcode() == ISD::TRUNCATE &&
25097 N0.getOperand(0).hasOneUse()) {
25098 SDValue N00 = N0.getOperand(0);
25099 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25100 return DAG.getNode(ISD::AND, dl, VT,
25101 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25102 N00.getOperand(0), N00.getOperand(1)),
25103 DAG.getConstant(1, dl, VT));
25107 if (VT.is256BitVector())
25108 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25111 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25112 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25113 // This exposes the zext to the udivrem lowering, so that it directly extends
25114 // from AH (which we otherwise need to do contortions to access).
25115 if (N0.getOpcode() == ISD::UDIVREM &&
25116 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25117 (VT == MVT::i32 || VT == MVT::i64)) {
25118 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25119 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25120 N0.getOperand(0), N0.getOperand(1));
25121 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25122 return R.getValue(1);
25128 // Optimize x == -y --> x+y == 0
25129 // x != -y --> x+y != 0
25130 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25131 const X86Subtarget* Subtarget) {
25132 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25133 SDValue LHS = N->getOperand(0);
25134 SDValue RHS = N->getOperand(1);
25135 EVT VT = N->getValueType(0);
25138 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25139 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25140 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25141 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25142 LHS.getOperand(1));
25143 return DAG.getSetCC(DL, N->getValueType(0), addV,
25144 DAG.getConstant(0, DL, addV.getValueType()), CC);
25146 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25147 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25148 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25149 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25150 RHS.getOperand(1));
25151 return DAG.getSetCC(DL, N->getValueType(0), addV,
25152 DAG.getConstant(0, DL, addV.getValueType()), CC);
25155 if (VT.getScalarType() == MVT::i1 &&
25156 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25158 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25159 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25160 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25162 if (!IsSEXT0 || !IsVZero1) {
25163 // Swap the operands and update the condition code.
25164 std::swap(LHS, RHS);
25165 CC = ISD::getSetCCSwappedOperands(CC);
25167 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25168 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25169 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25172 if (IsSEXT0 && IsVZero1) {
25173 assert(VT == LHS.getOperand(0).getValueType() &&
25174 "Uexpected operand type");
25175 if (CC == ISD::SETGT)
25176 return DAG.getConstant(0, DL, VT);
25177 if (CC == ISD::SETLE)
25178 return DAG.getConstant(1, DL, VT);
25179 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25180 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25182 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25183 "Unexpected condition code!");
25184 return LHS.getOperand(0);
25191 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25192 SelectionDAG &DAG) {
25194 MVT VT = Load->getSimpleValueType(0);
25195 MVT EVT = VT.getVectorElementType();
25196 SDValue Addr = Load->getOperand(1);
25197 SDValue NewAddr = DAG.getNode(
25198 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25199 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25200 Addr.getSimpleValueType()));
25203 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25204 DAG.getMachineFunction().getMachineMemOperand(
25205 Load->getMemOperand(), 0, EVT.getStoreSize()));
25209 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25210 const X86Subtarget *Subtarget) {
25212 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25213 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25214 "X86insertps is only defined for v4x32");
25216 SDValue Ld = N->getOperand(1);
25217 if (MayFoldLoad(Ld)) {
25218 // Extract the countS bits from the immediate so we can get the proper
25219 // address when narrowing the vector load to a specific element.
25220 // When the second source op is a memory address, insertps doesn't use
25221 // countS and just gets an f32 from that address.
25222 unsigned DestIndex =
25223 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25225 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25227 // Create this as a scalar to vector to match the instruction pattern.
25228 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25229 // countS bits are ignored when loading from memory on insertps, which
25230 // means we don't need to explicitly set them to 0.
25231 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25232 LoadScalarToVector, N->getOperand(2));
25237 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25238 SDValue V0 = N->getOperand(0);
25239 SDValue V1 = N->getOperand(1);
25241 EVT VT = N->getValueType(0);
25243 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25244 // operands and changing the mask to 1. This saves us a bunch of
25245 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25246 // x86InstrInfo knows how to commute this back after instruction selection
25247 // if it would help register allocation.
25249 // TODO: If optimizing for size or a processor that doesn't suffer from
25250 // partial register update stalls, this should be transformed into a MOVSD
25251 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25253 if (VT == MVT::v2f64)
25254 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25255 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25256 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25257 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25263 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25264 // as "sbb reg,reg", since it can be extended without zext and produces
25265 // an all-ones bit which is more useful than 0/1 in some cases.
25266 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25269 return DAG.getNode(ISD::AND, DL, VT,
25270 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25271 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25273 DAG.getConstant(1, DL, VT));
25274 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25275 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25276 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25277 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25281 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25282 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25283 TargetLowering::DAGCombinerInfo &DCI,
25284 const X86Subtarget *Subtarget) {
25286 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25287 SDValue EFLAGS = N->getOperand(1);
25289 if (CC == X86::COND_A) {
25290 // Try to convert COND_A into COND_B in an attempt to facilitate
25291 // materializing "setb reg".
25293 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25294 // cannot take an immediate as its first operand.
25296 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25297 EFLAGS.getValueType().isInteger() &&
25298 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25299 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25300 EFLAGS.getNode()->getVTList(),
25301 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25302 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25303 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25307 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25308 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25310 if (CC == X86::COND_B)
25311 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25313 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25314 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25315 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25321 // Optimize branch condition evaluation.
25323 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25324 TargetLowering::DAGCombinerInfo &DCI,
25325 const X86Subtarget *Subtarget) {
25327 SDValue Chain = N->getOperand(0);
25328 SDValue Dest = N->getOperand(1);
25329 SDValue EFLAGS = N->getOperand(3);
25330 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25332 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25333 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25334 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25341 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25342 SelectionDAG &DAG) {
25343 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25344 // optimize away operation when it's from a constant.
25346 // The general transformation is:
25347 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25348 // AND(VECTOR_CMP(x,y), constant2)
25349 // constant2 = UNARYOP(constant)
25351 // Early exit if this isn't a vector operation, the operand of the
25352 // unary operation isn't a bitwise AND, or if the sizes of the operations
25353 // aren't the same.
25354 EVT VT = N->getValueType(0);
25355 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25356 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25357 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25360 // Now check that the other operand of the AND is a constant. We could
25361 // make the transformation for non-constant splats as well, but it's unclear
25362 // that would be a benefit as it would not eliminate any operations, just
25363 // perform one more step in scalar code before moving to the vector unit.
25364 if (BuildVectorSDNode *BV =
25365 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25366 // Bail out if the vector isn't a constant.
25367 if (!BV->isConstant())
25370 // Everything checks out. Build up the new and improved node.
25372 EVT IntVT = BV->getValueType(0);
25373 // Create a new constant of the appropriate type for the transformed
25375 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25376 // The AND node needs bitcasts to/from an integer vector type around it.
25377 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25378 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25379 N->getOperand(0)->getOperand(0), MaskConst);
25380 SDValue Res = DAG.getBitcast(VT, NewAnd);
25387 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25388 const X86Subtarget *Subtarget) {
25389 SDValue Op0 = N->getOperand(0);
25390 EVT VT = N->getValueType(0);
25391 EVT InVT = Op0.getValueType();
25392 EVT InSVT = InVT.getScalarType();
25393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25395 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25396 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25397 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25399 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25400 InVT.getVectorNumElements());
25401 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25403 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25404 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25406 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25412 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25413 const X86Subtarget *Subtarget) {
25414 // First try to optimize away the conversion entirely when it's
25415 // conditionally from a constant. Vectors only.
25416 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25419 // Now move on to more general possibilities.
25420 SDValue Op0 = N->getOperand(0);
25421 EVT VT = N->getValueType(0);
25422 EVT InVT = Op0.getValueType();
25423 EVT InSVT = InVT.getScalarType();
25425 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25426 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25427 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25429 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25430 InVT.getVectorNumElements());
25431 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25432 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25435 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25436 // a 32-bit target where SSE doesn't support i64->FP operations.
25437 if (Op0.getOpcode() == ISD::LOAD) {
25438 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25439 EVT LdVT = Ld->getValueType(0);
25441 // This transformation is not supported if the result type is f16
25442 if (VT == MVT::f16)
25445 if (!Ld->isVolatile() && !VT.isVector() &&
25446 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25447 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25448 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25449 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25450 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25457 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25458 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25459 X86TargetLowering::DAGCombinerInfo &DCI) {
25460 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25461 // the result is either zero or one (depending on the input carry bit).
25462 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25463 if (X86::isZeroNode(N->getOperand(0)) &&
25464 X86::isZeroNode(N->getOperand(1)) &&
25465 // We don't have a good way to replace an EFLAGS use, so only do this when
25467 SDValue(N, 1).use_empty()) {
25469 EVT VT = N->getValueType(0);
25470 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25471 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25472 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25473 DAG.getConstant(X86::COND_B, DL,
25476 DAG.getConstant(1, DL, VT));
25477 return DCI.CombineTo(N, Res1, CarryOut);
25483 // fold (add Y, (sete X, 0)) -> adc 0, Y
25484 // (add Y, (setne X, 0)) -> sbb -1, Y
25485 // (sub (sete X, 0), Y) -> sbb 0, Y
25486 // (sub (setne X, 0), Y) -> adc -1, Y
25487 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25490 // Look through ZExts.
25491 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25492 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25495 SDValue SetCC = Ext.getOperand(0);
25496 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25499 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25500 if (CC != X86::COND_E && CC != X86::COND_NE)
25503 SDValue Cmp = SetCC.getOperand(1);
25504 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25505 !X86::isZeroNode(Cmp.getOperand(1)) ||
25506 !Cmp.getOperand(0).getValueType().isInteger())
25509 SDValue CmpOp0 = Cmp.getOperand(0);
25510 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25511 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25513 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25514 if (CC == X86::COND_NE)
25515 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25516 DL, OtherVal.getValueType(), OtherVal,
25517 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25519 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25520 DL, OtherVal.getValueType(), OtherVal,
25521 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25524 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25525 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25526 const X86Subtarget *Subtarget) {
25527 EVT VT = N->getValueType(0);
25528 SDValue Op0 = N->getOperand(0);
25529 SDValue Op1 = N->getOperand(1);
25531 // Try to synthesize horizontal adds from adds of shuffles.
25532 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25533 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25534 isHorizontalBinOp(Op0, Op1, true))
25535 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25537 return OptimizeConditionalInDecrement(N, DAG);
25540 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25541 const X86Subtarget *Subtarget) {
25542 SDValue Op0 = N->getOperand(0);
25543 SDValue Op1 = N->getOperand(1);
25545 // X86 can't encode an immediate LHS of a sub. See if we can push the
25546 // negation into a preceding instruction.
25547 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25548 // If the RHS of the sub is a XOR with one use and a constant, invert the
25549 // immediate. Then add one to the LHS of the sub so we can turn
25550 // X-Y -> X+~Y+1, saving one register.
25551 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25552 isa<ConstantSDNode>(Op1.getOperand(1))) {
25553 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25554 EVT VT = Op0.getValueType();
25555 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25557 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25558 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25559 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25563 // Try to synthesize horizontal adds from adds of shuffles.
25564 EVT VT = N->getValueType(0);
25565 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25566 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25567 isHorizontalBinOp(Op0, Op1, true))
25568 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25570 return OptimizeConditionalInDecrement(N, DAG);
25573 /// performVZEXTCombine - Performs build vector combines
25574 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25575 TargetLowering::DAGCombinerInfo &DCI,
25576 const X86Subtarget *Subtarget) {
25578 MVT VT = N->getSimpleValueType(0);
25579 SDValue Op = N->getOperand(0);
25580 MVT OpVT = Op.getSimpleValueType();
25581 MVT OpEltVT = OpVT.getVectorElementType();
25582 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25584 // (vzext (bitcast (vzext (x)) -> (vzext x)
25586 while (V.getOpcode() == ISD::BITCAST)
25587 V = V.getOperand(0);
25589 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25590 MVT InnerVT = V.getSimpleValueType();
25591 MVT InnerEltVT = InnerVT.getVectorElementType();
25593 // If the element sizes match exactly, we can just do one larger vzext. This
25594 // is always an exact type match as vzext operates on integer types.
25595 if (OpEltVT == InnerEltVT) {
25596 assert(OpVT == InnerVT && "Types must match for vzext!");
25597 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25600 // The only other way we can combine them is if only a single element of the
25601 // inner vzext is used in the input to the outer vzext.
25602 if (InnerEltVT.getSizeInBits() < InputBits)
25605 // In this case, the inner vzext is completely dead because we're going to
25606 // only look at bits inside of the low element. Just do the outer vzext on
25607 // a bitcast of the input to the inner.
25608 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25611 // Check if we can bypass extracting and re-inserting an element of an input
25612 // vector. Essentially:
25613 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25614 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25615 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25616 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25617 SDValue ExtractedV = V.getOperand(0);
25618 SDValue OrigV = ExtractedV.getOperand(0);
25619 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25620 if (ExtractIdx->getZExtValue() == 0) {
25621 MVT OrigVT = OrigV.getSimpleValueType();
25622 // Extract a subvector if necessary...
25623 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25624 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25625 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25626 OrigVT.getVectorNumElements() / Ratio);
25627 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25628 DAG.getIntPtrConstant(0, DL));
25630 Op = DAG.getBitcast(OpVT, OrigV);
25631 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25638 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25639 DAGCombinerInfo &DCI) const {
25640 SelectionDAG &DAG = DCI.DAG;
25641 switch (N->getOpcode()) {
25643 case ISD::EXTRACT_VECTOR_ELT:
25644 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25647 case X86ISD::SHRUNKBLEND:
25648 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25649 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25650 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25651 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25652 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25653 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25654 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25657 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25658 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25659 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25660 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25661 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25662 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25663 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25664 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25665 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25666 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25667 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25668 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25670 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25672 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25673 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25674 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25675 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25676 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25677 case ISD::ANY_EXTEND:
25678 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25679 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25680 case ISD::SIGN_EXTEND_INREG:
25681 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25682 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25683 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25684 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25685 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25686 case X86ISD::SHUFP: // Handle all target specific shuffles
25687 case X86ISD::PALIGNR:
25688 case X86ISD::UNPCKH:
25689 case X86ISD::UNPCKL:
25690 case X86ISD::MOVHLPS:
25691 case X86ISD::MOVLHPS:
25692 case X86ISD::PSHUFB:
25693 case X86ISD::PSHUFD:
25694 case X86ISD::PSHUFHW:
25695 case X86ISD::PSHUFLW:
25696 case X86ISD::MOVSS:
25697 case X86ISD::MOVSD:
25698 case X86ISD::VPERMILPI:
25699 case X86ISD::VPERM2X128:
25700 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25701 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25702 case X86ISD::INSERTPS: {
25703 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25704 return PerformINSERTPSCombine(N, DAG, Subtarget);
25707 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25713 /// isTypeDesirableForOp - Return true if the target has native support for
25714 /// the specified value type and it is 'desirable' to use the type for the
25715 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25716 /// instruction encodings are longer and some i16 instructions are slow.
25717 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25718 if (!isTypeLegal(VT))
25720 if (VT != MVT::i16)
25727 case ISD::SIGN_EXTEND:
25728 case ISD::ZERO_EXTEND:
25729 case ISD::ANY_EXTEND:
25742 /// IsDesirableToPromoteOp - This method query the target whether it is
25743 /// beneficial for dag combiner to promote the specified node. If true, it
25744 /// should return the desired promotion type by reference.
25745 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25746 EVT VT = Op.getValueType();
25747 if (VT != MVT::i16)
25750 bool Promote = false;
25751 bool Commute = false;
25752 switch (Op.getOpcode()) {
25755 LoadSDNode *LD = cast<LoadSDNode>(Op);
25756 // If the non-extending load has a single use and it's not live out, then it
25757 // might be folded.
25758 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25759 Op.hasOneUse()*/) {
25760 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25761 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25762 // The only case where we'd want to promote LOAD (rather then it being
25763 // promoted as an operand is when it's only use is liveout.
25764 if (UI->getOpcode() != ISD::CopyToReg)
25771 case ISD::SIGN_EXTEND:
25772 case ISD::ZERO_EXTEND:
25773 case ISD::ANY_EXTEND:
25778 SDValue N0 = Op.getOperand(0);
25779 // Look out for (store (shl (load), x)).
25780 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25793 SDValue N0 = Op.getOperand(0);
25794 SDValue N1 = Op.getOperand(1);
25795 if (!Commute && MayFoldLoad(N1))
25797 // Avoid disabling potential load folding opportunities.
25798 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25800 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25810 //===----------------------------------------------------------------------===//
25811 // X86 Inline Assembly Support
25812 //===----------------------------------------------------------------------===//
25814 // Helper to match a string separated by whitespace.
25815 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25816 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25818 for (StringRef Piece : Pieces) {
25819 if (!S.startswith(Piece)) // Check if the piece matches.
25822 S = S.substr(Piece.size());
25823 StringRef::size_type Pos = S.find_first_not_of(" \t");
25824 if (Pos == 0) // We matched a prefix.
25833 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25835 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25836 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25837 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25838 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25840 if (AsmPieces.size() == 3)
25842 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25849 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25850 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25852 std::string AsmStr = IA->getAsmString();
25854 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25855 if (!Ty || Ty->getBitWidth() % 16 != 0)
25858 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25859 SmallVector<StringRef, 4> AsmPieces;
25860 SplitString(AsmStr, AsmPieces, ";\n");
25862 switch (AsmPieces.size()) {
25863 default: return false;
25865 // FIXME: this should verify that we are targeting a 486 or better. If not,
25866 // we will turn this bswap into something that will be lowered to logical
25867 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25868 // lower so don't worry about this.
25870 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25871 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25872 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25873 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25874 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25875 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25876 // No need to check constraints, nothing other than the equivalent of
25877 // "=r,0" would be valid here.
25878 return IntrinsicLowering::LowerToByteSwap(CI);
25881 // rorw $$8, ${0:w} --> llvm.bswap.i16
25882 if (CI->getType()->isIntegerTy(16) &&
25883 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25884 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25885 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25887 StringRef ConstraintsStr = IA->getConstraintString();
25888 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25889 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25890 if (clobbersFlagRegisters(AsmPieces))
25891 return IntrinsicLowering::LowerToByteSwap(CI);
25895 if (CI->getType()->isIntegerTy(32) &&
25896 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25897 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25898 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25899 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25901 StringRef ConstraintsStr = IA->getConstraintString();
25902 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25903 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25904 if (clobbersFlagRegisters(AsmPieces))
25905 return IntrinsicLowering::LowerToByteSwap(CI);
25908 if (CI->getType()->isIntegerTy(64)) {
25909 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25910 if (Constraints.size() >= 2 &&
25911 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25912 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25913 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
25914 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25915 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25916 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25917 return IntrinsicLowering::LowerToByteSwap(CI);
25925 /// getConstraintType - Given a constraint letter, return the type of
25926 /// constraint it is for this target.
25927 X86TargetLowering::ConstraintType
25928 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25929 if (Constraint.size() == 1) {
25930 switch (Constraint[0]) {
25941 return C_RegisterClass;
25965 return TargetLowering::getConstraintType(Constraint);
25968 /// Examine constraint type and operand type and determine a weight value.
25969 /// This object must already have been set up with the operand type
25970 /// and the current alternative constraint selected.
25971 TargetLowering::ConstraintWeight
25972 X86TargetLowering::getSingleConstraintMatchWeight(
25973 AsmOperandInfo &info, const char *constraint) const {
25974 ConstraintWeight weight = CW_Invalid;
25975 Value *CallOperandVal = info.CallOperandVal;
25976 // If we don't have a value, we can't do a match,
25977 // but allow it at the lowest weight.
25978 if (!CallOperandVal)
25980 Type *type = CallOperandVal->getType();
25981 // Look at the constraint type.
25982 switch (*constraint) {
25984 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25995 if (CallOperandVal->getType()->isIntegerTy())
25996 weight = CW_SpecificReg;
26001 if (type->isFloatingPointTy())
26002 weight = CW_SpecificReg;
26005 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26006 weight = CW_SpecificReg;
26010 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26011 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26012 weight = CW_Register;
26015 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26016 if (C->getZExtValue() <= 31)
26017 weight = CW_Constant;
26021 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26022 if (C->getZExtValue() <= 63)
26023 weight = CW_Constant;
26027 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26028 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26029 weight = CW_Constant;
26033 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26034 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26035 weight = CW_Constant;
26039 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26040 if (C->getZExtValue() <= 3)
26041 weight = CW_Constant;
26045 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26046 if (C->getZExtValue() <= 0xff)
26047 weight = CW_Constant;
26052 if (isa<ConstantFP>(CallOperandVal)) {
26053 weight = CW_Constant;
26057 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26058 if ((C->getSExtValue() >= -0x80000000LL) &&
26059 (C->getSExtValue() <= 0x7fffffffLL))
26060 weight = CW_Constant;
26064 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26065 if (C->getZExtValue() <= 0xffffffff)
26066 weight = CW_Constant;
26073 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26074 /// with another that has more specific requirements based on the type of the
26075 /// corresponding operand.
26076 const char *X86TargetLowering::
26077 LowerXConstraint(EVT ConstraintVT) const {
26078 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26079 // 'f' like normal targets.
26080 if (ConstraintVT.isFloatingPoint()) {
26081 if (Subtarget->hasSSE2())
26083 if (Subtarget->hasSSE1())
26087 return TargetLowering::LowerXConstraint(ConstraintVT);
26090 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26091 /// vector. If it is invalid, don't add anything to Ops.
26092 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26093 std::string &Constraint,
26094 std::vector<SDValue>&Ops,
26095 SelectionDAG &DAG) const {
26098 // Only support length 1 constraints for now.
26099 if (Constraint.length() > 1) return;
26101 char ConstraintLetter = Constraint[0];
26102 switch (ConstraintLetter) {
26105 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26106 if (C->getZExtValue() <= 31) {
26107 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26108 Op.getValueType());
26114 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26115 if (C->getZExtValue() <= 63) {
26116 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26117 Op.getValueType());
26123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26124 if (isInt<8>(C->getSExtValue())) {
26125 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26126 Op.getValueType());
26132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26133 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26134 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26135 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26136 Op.getValueType());
26142 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26143 if (C->getZExtValue() <= 3) {
26144 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26145 Op.getValueType());
26151 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26152 if (C->getZExtValue() <= 255) {
26153 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26154 Op.getValueType());
26160 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26161 if (C->getZExtValue() <= 127) {
26162 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26163 Op.getValueType());
26169 // 32-bit signed value
26170 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26171 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26172 C->getSExtValue())) {
26173 // Widen to 64 bits here to get it sign extended.
26174 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26177 // FIXME gcc accepts some relocatable values here too, but only in certain
26178 // memory models; it's complicated.
26183 // 32-bit unsigned value
26184 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26185 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26186 C->getZExtValue())) {
26187 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26188 Op.getValueType());
26192 // FIXME gcc accepts some relocatable values here too, but only in certain
26193 // memory models; it's complicated.
26197 // Literal immediates are always ok.
26198 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26199 // Widen to 64 bits here to get it sign extended.
26200 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26204 // In any sort of PIC mode addresses need to be computed at runtime by
26205 // adding in a register or some sort of table lookup. These can't
26206 // be used as immediates.
26207 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26210 // If we are in non-pic codegen mode, we allow the address of a global (with
26211 // an optional displacement) to be used with 'i'.
26212 GlobalAddressSDNode *GA = nullptr;
26213 int64_t Offset = 0;
26215 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26217 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26218 Offset += GA->getOffset();
26220 } else if (Op.getOpcode() == ISD::ADD) {
26221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26222 Offset += C->getZExtValue();
26223 Op = Op.getOperand(0);
26226 } else if (Op.getOpcode() == ISD::SUB) {
26227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26228 Offset += -C->getZExtValue();
26229 Op = Op.getOperand(0);
26234 // Otherwise, this isn't something we can handle, reject it.
26238 const GlobalValue *GV = GA->getGlobal();
26239 // If we require an extra load to get this address, as in PIC mode, we
26240 // can't accept it.
26241 if (isGlobalStubReference(
26242 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26245 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26246 GA->getValueType(0), Offset);
26251 if (Result.getNode()) {
26252 Ops.push_back(Result);
26255 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26258 std::pair<unsigned, const TargetRegisterClass *>
26259 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26260 StringRef Constraint,
26262 // First, see if this is a constraint that directly corresponds to an LLVM
26264 if (Constraint.size() == 1) {
26265 // GCC Constraint Letters
26266 switch (Constraint[0]) {
26268 // TODO: Slight differences here in allocation order and leaving
26269 // RIP in the class. Do they matter any more here than they do
26270 // in the normal allocation?
26271 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26272 if (Subtarget->is64Bit()) {
26273 if (VT == MVT::i32 || VT == MVT::f32)
26274 return std::make_pair(0U, &X86::GR32RegClass);
26275 if (VT == MVT::i16)
26276 return std::make_pair(0U, &X86::GR16RegClass);
26277 if (VT == MVT::i8 || VT == MVT::i1)
26278 return std::make_pair(0U, &X86::GR8RegClass);
26279 if (VT == MVT::i64 || VT == MVT::f64)
26280 return std::make_pair(0U, &X86::GR64RegClass);
26283 // 32-bit fallthrough
26284 case 'Q': // Q_REGS
26285 if (VT == MVT::i32 || VT == MVT::f32)
26286 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26287 if (VT == MVT::i16)
26288 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26289 if (VT == MVT::i8 || VT == MVT::i1)
26290 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26291 if (VT == MVT::i64)
26292 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26294 case 'r': // GENERAL_REGS
26295 case 'l': // INDEX_REGS
26296 if (VT == MVT::i8 || VT == MVT::i1)
26297 return std::make_pair(0U, &X86::GR8RegClass);
26298 if (VT == MVT::i16)
26299 return std::make_pair(0U, &X86::GR16RegClass);
26300 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26301 return std::make_pair(0U, &X86::GR32RegClass);
26302 return std::make_pair(0U, &X86::GR64RegClass);
26303 case 'R': // LEGACY_REGS
26304 if (VT == MVT::i8 || VT == MVT::i1)
26305 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26306 if (VT == MVT::i16)
26307 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26308 if (VT == MVT::i32 || !Subtarget->is64Bit())
26309 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26310 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26311 case 'f': // FP Stack registers.
26312 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26313 // value to the correct fpstack register class.
26314 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26315 return std::make_pair(0U, &X86::RFP32RegClass);
26316 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26317 return std::make_pair(0U, &X86::RFP64RegClass);
26318 return std::make_pair(0U, &X86::RFP80RegClass);
26319 case 'y': // MMX_REGS if MMX allowed.
26320 if (!Subtarget->hasMMX()) break;
26321 return std::make_pair(0U, &X86::VR64RegClass);
26322 case 'Y': // SSE_REGS if SSE2 allowed
26323 if (!Subtarget->hasSSE2()) break;
26325 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26326 if (!Subtarget->hasSSE1()) break;
26328 switch (VT.SimpleTy) {
26330 // Scalar SSE types.
26333 return std::make_pair(0U, &X86::FR32RegClass);
26336 return std::make_pair(0U, &X86::FR64RegClass);
26344 return std::make_pair(0U, &X86::VR128RegClass);
26352 return std::make_pair(0U, &X86::VR256RegClass);
26357 return std::make_pair(0U, &X86::VR512RegClass);
26363 // Use the default implementation in TargetLowering to convert the register
26364 // constraint into a member of a register class.
26365 std::pair<unsigned, const TargetRegisterClass*> Res;
26366 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26368 // Not found as a standard register?
26370 // Map st(0) -> st(7) -> ST0
26371 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26372 tolower(Constraint[1]) == 's' &&
26373 tolower(Constraint[2]) == 't' &&
26374 Constraint[3] == '(' &&
26375 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26376 Constraint[5] == ')' &&
26377 Constraint[6] == '}') {
26379 Res.first = X86::FP0+Constraint[4]-'0';
26380 Res.second = &X86::RFP80RegClass;
26384 // GCC allows "st(0)" to be called just plain "st".
26385 if (StringRef("{st}").equals_lower(Constraint)) {
26386 Res.first = X86::FP0;
26387 Res.second = &X86::RFP80RegClass;
26392 if (StringRef("{flags}").equals_lower(Constraint)) {
26393 Res.first = X86::EFLAGS;
26394 Res.second = &X86::CCRRegClass;
26398 // 'A' means EAX + EDX.
26399 if (Constraint == "A") {
26400 Res.first = X86::EAX;
26401 Res.second = &X86::GR32_ADRegClass;
26407 // Otherwise, check to see if this is a register class of the wrong value
26408 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26409 // turn into {ax},{dx}.
26410 // MVT::Other is used to specify clobber names.
26411 if (Res.second->hasType(VT) || VT == MVT::Other)
26412 return Res; // Correct type already, nothing to do.
26414 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26415 // return "eax". This should even work for things like getting 64bit integer
26416 // registers when given an f64 type.
26417 const TargetRegisterClass *Class = Res.second;
26418 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26419 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26420 unsigned Size = VT.getSizeInBits();
26421 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26422 : Size == 16 ? MVT::i16
26423 : Size == 32 ? MVT::i32
26424 : Size == 64 ? MVT::i64
26426 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26428 Res.first = DestReg;
26429 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26430 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26431 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26432 : &X86::GR64RegClass;
26433 assert(Res.second->contains(Res.first) && "Register in register class");
26435 // No register found/type mismatch.
26437 Res.second = nullptr;
26439 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26440 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26441 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26442 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26443 Class == &X86::VR512RegClass) {
26444 // Handle references to XMM physical registers that got mapped into the
26445 // wrong class. This can happen with constraints like {xmm0} where the
26446 // target independent register mapper will just pick the first match it can
26447 // find, ignoring the required type.
26449 if (VT == MVT::f32 || VT == MVT::i32)
26450 Res.second = &X86::FR32RegClass;
26451 else if (VT == MVT::f64 || VT == MVT::i64)
26452 Res.second = &X86::FR64RegClass;
26453 else if (X86::VR128RegClass.hasType(VT))
26454 Res.second = &X86::VR128RegClass;
26455 else if (X86::VR256RegClass.hasType(VT))
26456 Res.second = &X86::VR256RegClass;
26457 else if (X86::VR512RegClass.hasType(VT))
26458 Res.second = &X86::VR512RegClass;
26460 // Type mismatch and not a clobber: Return an error;
26462 Res.second = nullptr;
26469 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26470 const AddrMode &AM, Type *Ty,
26471 unsigned AS) const {
26472 // Scaling factors are not free at all.
26473 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26474 // will take 2 allocations in the out of order engine instead of 1
26475 // for plain addressing mode, i.e. inst (reg1).
26477 // vaddps (%rsi,%drx), %ymm0, %ymm1
26478 // Requires two allocations (one for the load, one for the computation)
26480 // vaddps (%rsi), %ymm0, %ymm1
26481 // Requires just 1 allocation, i.e., freeing allocations for other operations
26482 // and having less micro operations to execute.
26484 // For some X86 architectures, this is even worse because for instance for
26485 // stores, the complex addressing mode forces the instruction to use the
26486 // "load" ports instead of the dedicated "store" port.
26487 // E.g., on Haswell:
26488 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26489 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26490 if (isLegalAddressingMode(DL, AM, Ty, AS))
26491 // Scale represents reg2 * scale, thus account for 1
26492 // as soon as we use a second register.
26493 return AM.Scale != 0;
26497 bool X86TargetLowering::isTargetFTOL() const {
26498 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();