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 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75 const X86Subtarget &STI)
76 : TargetLowering(TM), Subtarget(&STI) {
77 X86ScalarSSEf64 = Subtarget->hasSSE2();
78 X86ScalarSSEf32 = Subtarget->hasSSE1();
81 // Set up the TargetLowering object.
82 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
84 // X86 is weird. It always uses i8 for shift amounts and setcc results.
85 setBooleanContents(ZeroOrOneBooleanContent);
86 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
89 // For 64-bit, since we have so many registers, use the ILP scheduler.
90 // For 32-bit, use the register pressure specific scheduling.
91 // For Atom, always use ILP scheduling.
92 if (Subtarget->isAtom())
93 setSchedulingPreference(Sched::ILP);
94 else if (Subtarget->is64Bit())
95 setSchedulingPreference(Sched::ILP);
97 setSchedulingPreference(Sched::RegPressure);
98 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
101 // Bypass expensive divides on Atom when compiling with O2.
102 if (TM.getOptLevel() >= CodeGenOpt::Default) {
103 if (Subtarget->hasSlowDivide32())
104 addBypassSlowDiv(32, 8);
105 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106 addBypassSlowDiv(64, 16);
109 if (Subtarget->isTargetKnownWindowsMSVC()) {
110 // Setup Windows compiler runtime calls.
111 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113 setLibcallName(RTLIB::SREM_I64, "_allrem");
114 setLibcallName(RTLIB::UREM_I64, "_aullrem");
115 setLibcallName(RTLIB::MUL_I64, "_allmul");
116 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
122 // The _ftol2 runtime function has an unusual calling conv, which
123 // is modeled by a special pseudo-instruction.
124 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
130 if (Subtarget->isTargetDarwin()) {
131 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132 setUseUnderscoreSetJmp(false);
133 setUseUnderscoreLongJmp(false);
134 } else if (Subtarget->isTargetWindowsGNU()) {
135 // MS runtime is weird: it exports _setjmp, but longjmp!
136 setUseUnderscoreSetJmp(true);
137 setUseUnderscoreLongJmp(false);
139 setUseUnderscoreSetJmp(true);
140 setUseUnderscoreLongJmp(true);
143 // Set up the register classes.
144 addRegisterClass(MVT::i8, &X86::GR8RegClass);
145 addRegisterClass(MVT::i16, &X86::GR16RegClass);
146 addRegisterClass(MVT::i32, &X86::GR32RegClass);
147 if (Subtarget->is64Bit())
148 addRegisterClass(MVT::i64, &X86::GR64RegClass);
150 for (MVT VT : MVT::integer_valuetypes())
151 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
153 // We don't accept any truncstore of integer registers.
154 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
161 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
163 // SETOEQ and SETUNE require checking two conditions.
164 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
171 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
173 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
174 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
175 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
177 if (Subtarget->is64Bit()) {
178 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
179 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
180 } else if (!Subtarget->useSoftFloat()) {
181 // We have an algorithm for SSE2->double, and we turn this into a
182 // 64-bit FILD followed by conditional FADD for other targets.
183 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
184 // We have an algorithm for SSE2, and we turn this into a 64-bit
185 // FILD for other targets.
186 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
189 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
191 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
192 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
194 if (!Subtarget->useSoftFloat()) {
195 // SSE has no i16 to fp conversion, only i32
196 if (X86ScalarSSEf32) {
197 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
198 // f32 and f64 cases are Legal, f80 case is not
199 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
202 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
205 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
206 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
209 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
210 // are Legal, f80 is custom lowered.
211 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
214 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
216 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
217 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
219 if (X86ScalarSSEf32) {
220 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
221 // f32 and f64 cases are Legal, f80 case is not
222 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
225 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
228 // Handle FP_TO_UINT by promoting the destination to a larger signed
230 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
234 if (Subtarget->is64Bit()) {
235 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
236 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
237 } else if (!Subtarget->useSoftFloat()) {
238 // Since AVX is a superset of SSE3, only check for SSE here.
239 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240 // Expand FP_TO_UINT into a select.
241 // FIXME: We would like to use a Custom expander here eventually to do
242 // the optimal thing for SSE vs. the default expansion in the legalizer.
243 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
245 // With SSE3 we can use fisttpll to convert to a signed i64; without
246 // SSE, we're stuck with a fistpll.
247 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
250 if (isTargetFTOL()) {
251 // Use the _ftol2 runtime function, which has a pseudo-instruction
252 // to handle its weird calling convention.
253 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
256 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257 if (!X86ScalarSSEf64) {
258 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
259 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
260 if (Subtarget->is64Bit()) {
261 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
262 // Without SSE, i64->f64 goes through memory.
263 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
267 // Scalar integer divide and remainder are lowered to use operations that
268 // produce two results, to match the available instructions. This exposes
269 // the two-result form to trivial CSE, which is able to combine x/y and x%y
270 // into a single instruction.
272 // Scalar integer multiply-high is also lowered to use two-result
273 // operations, to match the available instructions. However, plain multiply
274 // (low) operations are left as Legal, as there are single-result
275 // instructions for this in x86. Using the two-result multiply instructions
276 // when both high and low results are needed must be arranged by dagcombine.
277 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
279 setOperationAction(ISD::MULHS, VT, Expand);
280 setOperationAction(ISD::MULHU, VT, Expand);
281 setOperationAction(ISD::SDIV, VT, Expand);
282 setOperationAction(ISD::UDIV, VT, Expand);
283 setOperationAction(ISD::SREM, VT, Expand);
284 setOperationAction(ISD::UREM, VT, Expand);
286 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287 setOperationAction(ISD::ADDC, VT, Custom);
288 setOperationAction(ISD::ADDE, VT, Custom);
289 setOperationAction(ISD::SUBC, VT, Custom);
290 setOperationAction(ISD::SUBE, VT, Custom);
293 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
294 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
295 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
296 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
297 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
298 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
299 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
300 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
301 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
302 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
303 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
305 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
306 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
307 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
309 if (Subtarget->is64Bit())
310 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
312 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
313 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
314 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
315 setOperationAction(ISD::FREM , MVT::f32 , Expand);
316 setOperationAction(ISD::FREM , MVT::f64 , Expand);
317 setOperationAction(ISD::FREM , MVT::f80 , Expand);
318 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
320 // Promote the i8 variants and force them on up to i32 which has a shorter
322 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
323 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
324 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
325 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
326 if (Subtarget->hasBMI()) {
327 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
328 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
329 if (Subtarget->is64Bit())
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
332 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
333 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
334 if (Subtarget->is64Bit())
335 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
338 if (Subtarget->hasLZCNT()) {
339 // When promoting the i8 variants, force them to i32 for a shorter
341 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
342 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
343 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
344 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
346 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
347 if (Subtarget->is64Bit())
348 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
350 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
351 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
352 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
353 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
355 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
356 if (Subtarget->is64Bit()) {
357 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
358 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
362 // Special handling for half-precision floating point conversions.
363 // If we don't have F16C support, then lower half float conversions
364 // into library calls.
365 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
370 // There's never any support for operations beyond MVT::f32.
371 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
376 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
383 if (Subtarget->hasPOPCNT()) {
384 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
386 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
387 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
388 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
389 if (Subtarget->is64Bit())
390 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
393 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
395 if (!Subtarget->hasMOVBE())
396 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
398 // These should be promoted to a larger select which is supported.
399 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
400 // X86 wants to expand cmov itself.
401 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
402 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
403 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
404 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
405 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
406 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
407 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
408 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
409 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
410 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
411 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
412 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
413 if (Subtarget->is64Bit()) {
414 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
417 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
418 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420 // support continuation, user-level threading, and etc.. As a result, no
421 // other SjLj exception interfaces are implemented and please don't build
422 // your own exception handling based on them.
423 // LLVM/Clang supports zero-cost DWARF exception handling.
424 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
428 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
429 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
430 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
431 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
435 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
436 if (Subtarget->is64Bit()) {
437 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
438 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
439 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
440 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
443 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
445 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
446 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
447 if (Subtarget->is64Bit()) {
448 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
449 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
450 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
453 if (Subtarget->hasSSE1())
454 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
456 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
458 // Expand certain atomics
459 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
461 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
466 if (Subtarget->hasCmpxchg16b()) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
470 // FIXME - use subtarget debug flags
471 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
476 if (Subtarget->is64Bit()) {
477 setExceptionPointerRegister(X86::RAX);
478 setExceptionSelectorRegister(X86::RDX);
480 setExceptionPointerRegister(X86::EAX);
481 setExceptionSelectorRegister(X86::EDX);
483 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
486 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
489 setOperationAction(ISD::TRAP, MVT::Other, Legal);
490 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
492 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493 setOperationAction(ISD::VASTART , MVT::Other, Custom);
494 setOperationAction(ISD::VAEND , MVT::Other, Expand);
495 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496 // TargetInfo::X86_64ABIBuiltinVaList
497 setOperationAction(ISD::VAARG , MVT::Other, Custom);
498 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
500 // TargetInfo::CharPtrBuiltinVaList
501 setOperationAction(ISD::VAARG , MVT::Other, Expand);
502 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
505 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
506 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
508 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
510 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
514 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515 // f32 and f64 use SSE.
516 // Set up the FP register classes.
517 addRegisterClass(MVT::f32, &X86::FR32RegClass);
518 addRegisterClass(MVT::f64, &X86::FR64RegClass);
520 // Use ANDPD to simulate FABS.
521 setOperationAction(ISD::FABS , MVT::f64, Custom);
522 setOperationAction(ISD::FABS , MVT::f32, Custom);
524 // Use XORP to simulate FNEG.
525 setOperationAction(ISD::FNEG , MVT::f64, Custom);
526 setOperationAction(ISD::FNEG , MVT::f32, Custom);
528 // Use ANDPD and ORPD to simulate FCOPYSIGN.
529 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
532 // Lower this to FGETSIGNx86 plus an AND.
533 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
536 // We don't support sin/cos/fmod
537 setOperationAction(ISD::FSIN , MVT::f64, Expand);
538 setOperationAction(ISD::FCOS , MVT::f64, Expand);
539 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540 setOperationAction(ISD::FSIN , MVT::f32, Expand);
541 setOperationAction(ISD::FCOS , MVT::f32, Expand);
542 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
544 // Expand FP immediates into loads from the stack, except for the special
546 addLegalFPImmediate(APFloat(+0.0)); // xorpd
547 addLegalFPImmediate(APFloat(+0.0f)); // xorps
548 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549 // Use SSE for f32, x87 for f64.
550 // Set up the FP register classes.
551 addRegisterClass(MVT::f32, &X86::FR32RegClass);
552 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
554 // Use ANDPS to simulate FABS.
555 setOperationAction(ISD::FABS , MVT::f32, Custom);
557 // Use XORP to simulate FNEG.
558 setOperationAction(ISD::FNEG , MVT::f32, Custom);
560 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
562 // Use ANDPS and ORPS to simulate FCOPYSIGN.
563 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
566 // We don't support sin/cos/fmod
567 setOperationAction(ISD::FSIN , MVT::f32, Expand);
568 setOperationAction(ISD::FCOS , MVT::f32, Expand);
569 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
571 // Special cases we handle for FP constants.
572 addLegalFPImmediate(APFloat(+0.0f)); // xorps
573 addLegalFPImmediate(APFloat(+0.0)); // FLD0
574 addLegalFPImmediate(APFloat(+1.0)); // FLD1
575 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
578 if (!TM.Options.UnsafeFPMath) {
579 setOperationAction(ISD::FSIN , MVT::f64, Expand);
580 setOperationAction(ISD::FCOS , MVT::f64, Expand);
581 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
583 } else if (!Subtarget->useSoftFloat()) {
584 // f32 and f64 in x87.
585 // Set up the FP register classes.
586 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
589 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
590 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
591 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
594 if (!TM.Options.UnsafeFPMath) {
595 setOperationAction(ISD::FSIN , MVT::f64, Expand);
596 setOperationAction(ISD::FSIN , MVT::f32, Expand);
597 setOperationAction(ISD::FCOS , MVT::f64, Expand);
598 setOperationAction(ISD::FCOS , MVT::f32, Expand);
599 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
602 addLegalFPImmediate(APFloat(+0.0)); // FLD0
603 addLegalFPImmediate(APFloat(+1.0)); // FLD1
604 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612 // We don't support FMA.
613 setOperationAction(ISD::FMA, MVT::f64, Expand);
614 setOperationAction(ISD::FMA, MVT::f32, Expand);
616 // Long double always uses X87.
617 if (!Subtarget->useSoftFloat()) {
618 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
620 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
622 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623 addLegalFPImmediate(TmpFlt); // FLD0
625 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
628 APFloat TmpFlt2(+1.0);
629 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
631 addLegalFPImmediate(TmpFlt2); // FLD1
632 TmpFlt2.changeSign();
633 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
636 if (!TM.Options.UnsafeFPMath) {
637 setOperationAction(ISD::FSIN , MVT::f80, Expand);
638 setOperationAction(ISD::FCOS , MVT::f80, Expand);
639 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
644 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645 setOperationAction(ISD::FRINT, MVT::f80, Expand);
646 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647 setOperationAction(ISD::FMA, MVT::f80, Expand);
650 // Always use a library call for pow.
651 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
652 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
653 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
655 setOperationAction(ISD::FLOG, MVT::f80, Expand);
656 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658 setOperationAction(ISD::FEXP, MVT::f80, Expand);
659 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
663 // First set operation action for all vector types to either promote
664 // (for widening) or expand (for scalarization). Then we will selectively
665 // turn on ones that can be effectively codegen'd.
666 for (MVT VT : MVT::vector_valuetypes()) {
667 setOperationAction(ISD::ADD , VT, Expand);
668 setOperationAction(ISD::SUB , VT, Expand);
669 setOperationAction(ISD::FADD, VT, Expand);
670 setOperationAction(ISD::FNEG, VT, Expand);
671 setOperationAction(ISD::FSUB, VT, Expand);
672 setOperationAction(ISD::MUL , VT, Expand);
673 setOperationAction(ISD::FMUL, VT, Expand);
674 setOperationAction(ISD::SDIV, VT, Expand);
675 setOperationAction(ISD::UDIV, VT, Expand);
676 setOperationAction(ISD::FDIV, VT, Expand);
677 setOperationAction(ISD::SREM, VT, Expand);
678 setOperationAction(ISD::UREM, VT, Expand);
679 setOperationAction(ISD::LOAD, VT, Expand);
680 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685 setOperationAction(ISD::FABS, VT, Expand);
686 setOperationAction(ISD::FSIN, VT, Expand);
687 setOperationAction(ISD::FSINCOS, VT, Expand);
688 setOperationAction(ISD::FCOS, VT, Expand);
689 setOperationAction(ISD::FSINCOS, VT, Expand);
690 setOperationAction(ISD::FREM, VT, Expand);
691 setOperationAction(ISD::FMA, VT, Expand);
692 setOperationAction(ISD::FPOWI, VT, Expand);
693 setOperationAction(ISD::FSQRT, VT, Expand);
694 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695 setOperationAction(ISD::FFLOOR, VT, Expand);
696 setOperationAction(ISD::FCEIL, VT, Expand);
697 setOperationAction(ISD::FTRUNC, VT, Expand);
698 setOperationAction(ISD::FRINT, VT, Expand);
699 setOperationAction(ISD::FNEARBYINT, VT, Expand);
700 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701 setOperationAction(ISD::MULHS, VT, Expand);
702 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703 setOperationAction(ISD::MULHU, VT, Expand);
704 setOperationAction(ISD::SDIVREM, VT, Expand);
705 setOperationAction(ISD::UDIVREM, VT, Expand);
706 setOperationAction(ISD::FPOW, VT, Expand);
707 setOperationAction(ISD::CTPOP, VT, Expand);
708 setOperationAction(ISD::CTTZ, VT, Expand);
709 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710 setOperationAction(ISD::CTLZ, VT, Expand);
711 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712 setOperationAction(ISD::SHL, VT, Expand);
713 setOperationAction(ISD::SRA, VT, Expand);
714 setOperationAction(ISD::SRL, VT, Expand);
715 setOperationAction(ISD::ROTL, VT, Expand);
716 setOperationAction(ISD::ROTR, VT, Expand);
717 setOperationAction(ISD::BSWAP, VT, Expand);
718 setOperationAction(ISD::SETCC, VT, Expand);
719 setOperationAction(ISD::FLOG, VT, Expand);
720 setOperationAction(ISD::FLOG2, VT, Expand);
721 setOperationAction(ISD::FLOG10, VT, Expand);
722 setOperationAction(ISD::FEXP, VT, Expand);
723 setOperationAction(ISD::FEXP2, VT, Expand);
724 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729 setOperationAction(ISD::TRUNCATE, VT, Expand);
730 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733 setOperationAction(ISD::VSELECT, VT, Expand);
734 setOperationAction(ISD::SELECT_CC, VT, Expand);
735 for (MVT InnerVT : MVT::vector_valuetypes()) {
736 setTruncStoreAction(InnerVT, VT, Expand);
738 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
741 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742 // types, we have to deal with them whether we ask for Expansion or not.
743 // Setting Expand causes its own optimisation problems though, so leave
745 if (VT.getVectorElementType() == MVT::i1)
746 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749 // split/scalarized right now.
750 if (VT.getVectorElementType() == MVT::f16)
751 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
755 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756 // with -msoft-float, disable use of MMX as well.
757 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759 // No operations on x86mmx supported, everything uses intrinsics.
762 // MMX-sized vectors (other than x86mmx) are expected to be expanded
763 // into smaller operations.
764 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765 setOperationAction(ISD::MULHS, MMXTy, Expand);
766 setOperationAction(ISD::AND, MMXTy, Expand);
767 setOperationAction(ISD::OR, MMXTy, Expand);
768 setOperationAction(ISD::XOR, MMXTy, Expand);
769 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
770 setOperationAction(ISD::SELECT, MMXTy, Expand);
771 setOperationAction(ISD::BITCAST, MMXTy, Expand);
773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
775 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
778 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
779 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
780 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
781 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
782 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
783 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
784 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
785 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
786 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
787 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
788 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
791 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
794 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
797 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798 // registers cannot be used even for integer operations.
799 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
804 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
805 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
806 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
807 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
808 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
809 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
810 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
811 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
812 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
813 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
814 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
815 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
816 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
817 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
818 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
819 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
820 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
821 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
822 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
823 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
824 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
825 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
826 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
828 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
829 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
830 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
831 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
833 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
834 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
835 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
836 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
844 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
845 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
846 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851 MVT VT = (MVT::SimpleValueType)i;
852 // Do not attempt to custom lower non-power-of-2 vectors
853 if (!isPowerOf2_32(VT.getVectorNumElements()))
855 // Do not attempt to custom lower non-128-bit vectors
856 if (!VT.is128BitVector())
858 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
859 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
860 setOperationAction(ISD::VSELECT, VT, Custom);
861 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
864 // We support custom legalizing of sext and anyext loads for specific
865 // memory vector types which we can load as a scalar (or sequence of
866 // scalars) and extend in-register to a legal 128-bit vector type. For sext
867 // loads these must work with a single scalar load.
868 for (MVT VT : MVT::integer_vector_valuetypes()) {
869 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
880 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
881 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
882 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
883 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
884 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
885 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
889 if (Subtarget->is64Bit()) {
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
894 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896 MVT VT = (MVT::SimpleValueType)i;
898 // Do not attempt to promote non-128-bit vectors
899 if (!VT.is128BitVector())
902 setOperationAction(ISD::AND, VT, Promote);
903 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
904 setOperationAction(ISD::OR, VT, Promote);
905 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
906 setOperationAction(ISD::XOR, VT, Promote);
907 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
908 setOperationAction(ISD::LOAD, VT, Promote);
909 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
910 setOperationAction(ISD::SELECT, VT, Promote);
911 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
914 // Custom lower v2i64 and v2f64 selects.
915 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
916 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
917 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
918 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
920 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
921 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
923 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
925 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
926 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
927 // As there is no 64-bit GPR available, we need build a special custom
928 // sequence to convert from v2i32 to v2f32.
929 if (!Subtarget->is64Bit())
930 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
932 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
933 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
935 for (MVT VT : MVT::fp_vector_valuetypes())
936 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
938 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
939 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
940 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
943 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
946 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
947 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
948 setOperationAction(ISD::FRINT, RoundedTy, Legal);
949 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
952 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
953 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
954 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
955 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
956 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
957 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
958 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
959 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
961 // FIXME: Do we need to handle scalar-to-vector here?
962 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
964 // We directly match byte blends in the backend as they match the VSELECT
966 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
968 // SSE41 brings specific instructions for doing vector sign extend even in
969 // cases where we don't have SRA.
970 for (MVT VT : MVT::integer_vector_valuetypes()) {
971 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
976 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
978 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
979 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
980 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
984 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
985 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
986 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
987 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
991 // i8 and i16 vectors are custom because the source register and source
992 // source memory operand types are not the same width. f32 vectors are
993 // custom since the immediate controlling the insert encodes additional
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1005 // FIXME: these should be Legal, but that's only for the case where
1006 // the index is constant. For now custom expand to deal with that.
1007 if (Subtarget->is64Bit()) {
1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1009 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1013 if (Subtarget->hasSSE2()) {
1014 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1018 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1019 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1021 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1022 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1024 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1027 // In the customized shift lowering, the legal cases in AVX2 will be
1029 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1030 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1032 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1033 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1035 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1036 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1039 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1041 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1043 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1044 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1045 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1047 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1048 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1049 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1051 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1054 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1058 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1059 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1060 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1061 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1062 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1064 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1067 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1068 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1069 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1070 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1071 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1072 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1073 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1074 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1075 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1077 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078 // even though v8i16 is a legal type.
1079 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1080 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1081 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1083 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1084 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1085 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1087 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1088 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1090 for (MVT VT : MVT::fp_vector_valuetypes())
1091 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1093 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1094 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1096 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1097 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1099 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1100 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1102 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1103 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1104 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1105 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1107 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1108 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1109 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1111 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1112 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1113 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1114 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1115 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1116 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1117 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1118 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1119 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1120 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1121 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1122 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1124 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1125 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1126 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1127 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1129 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1132 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1133 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1134 setOperationAction(ISD::FMA, MVT::f32, Legal);
1135 setOperationAction(ISD::FMA, MVT::f64, Legal);
1138 if (Subtarget->hasInt256()) {
1139 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1140 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1141 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1142 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1144 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1145 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1146 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1147 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1149 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1150 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1151 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1152 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1154 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1155 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1156 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1157 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1159 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1160 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1161 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1162 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1163 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1164 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1165 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1166 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1167 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1168 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1169 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1170 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1172 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173 // when we have a 256bit-wide blend with immediate.
1174 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1176 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1179 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1180 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1181 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1182 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1184 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1186 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1187 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1188 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1189 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1191 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1192 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1193 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1194 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1196 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1198 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1199 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1201 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1202 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1203 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1204 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1207 // In the customized shift lowering, the legal cases in AVX2 will be
1209 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1210 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1212 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1213 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1215 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1216 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1218 // Custom lower several nodes for 256-bit types.
1219 for (MVT VT : MVT::vector_valuetypes()) {
1220 if (VT.getScalarSizeInBits() >= 32) {
1221 setOperationAction(ISD::MLOAD, VT, Legal);
1222 setOperationAction(ISD::MSTORE, VT, Legal);
1224 // Extract subvector is special because the value type
1225 // (result) is 128-bit but the source is 256-bit wide.
1226 if (VT.is128BitVector()) {
1227 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1229 // Do not attempt to custom lower other non-256-bit vectors
1230 if (!VT.is256BitVector())
1233 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1234 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1235 setOperationAction(ISD::VSELECT, VT, Custom);
1236 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1237 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1239 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1240 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1243 if (Subtarget->hasInt256())
1244 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1247 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249 MVT VT = (MVT::SimpleValueType)i;
1251 // Do not attempt to promote non-256-bit vectors
1252 if (!VT.is256BitVector())
1255 setOperationAction(ISD::AND, VT, Promote);
1256 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1257 setOperationAction(ISD::OR, VT, Promote);
1258 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1259 setOperationAction(ISD::XOR, VT, Promote);
1260 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1261 setOperationAction(ISD::LOAD, VT, Promote);
1262 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1263 setOperationAction(ISD::SELECT, VT, Promote);
1264 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1268 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1272 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1274 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1275 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1276 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1278 for (MVT VT : MVT::fp_vector_valuetypes())
1279 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1281 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1288 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1289 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1290 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1291 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1292 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1294 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1295 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1296 setOperationAction(ISD::XOR, MVT::i1, Legal);
1297 setOperationAction(ISD::OR, MVT::i1, Legal);
1298 setOperationAction(ISD::AND, MVT::i1, Legal);
1299 setOperationAction(ISD::SUB, MVT::i1, Custom);
1300 setOperationAction(ISD::ADD, MVT::i1, Custom);
1301 setOperationAction(ISD::MUL, MVT::i1, Custom);
1302 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1303 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1304 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1305 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1306 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1308 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1309 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1310 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1311 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1312 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1313 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1315 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1316 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1317 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1318 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1319 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1320 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1321 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1322 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1324 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1325 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1326 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1327 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1328 if (Subtarget->is64Bit()) {
1329 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1330 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1331 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1332 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1334 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1335 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1336 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1337 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1338 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1339 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1340 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1341 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1342 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1343 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1344 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1346 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1347 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1348 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1349 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1351 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1352 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1353 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1354 if (Subtarget->hasDQI()) {
1355 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1356 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1358 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1359 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1360 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1361 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1362 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1363 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1364 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1365 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1366 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1367 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1368 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1369 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1370 if (Subtarget->hasDQI()) {
1371 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1372 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1374 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1375 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1376 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1377 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1378 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1379 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1380 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1381 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1382 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1383 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1389 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1391 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1392 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1394 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1400 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1401 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1402 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1403 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1404 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1405 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1406 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1408 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1409 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1410 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1411 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1412 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1413 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1414 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1415 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1417 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1418 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1420 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1421 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1423 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1425 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1426 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1428 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1429 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1431 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1432 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1434 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1435 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1436 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1437 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1438 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1439 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1441 if (Subtarget->hasCDI()) {
1442 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1443 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1445 if (Subtarget->hasDQI()) {
1446 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1447 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1448 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1450 // Custom lower several nodes.
1451 for (MVT VT : MVT::vector_valuetypes()) {
1452 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1454 setOperationAction(ISD::AND, VT, Legal);
1455 setOperationAction(ISD::OR, VT, Legal);
1456 setOperationAction(ISD::XOR, VT, Legal);
1458 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1459 setOperationAction(ISD::MGATHER, VT, Custom);
1460 setOperationAction(ISD::MSCATTER, VT, Custom);
1462 // Extract subvector is special because the value type
1463 // (result) is 256/128-bit but the source is 512-bit wide.
1464 if (VT.is128BitVector() || VT.is256BitVector()) {
1465 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1467 if (VT.getVectorElementType() == MVT::i1)
1468 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1470 // Do not attempt to custom lower other non-512-bit vectors
1471 if (!VT.is512BitVector())
1474 if (EltSize >= 32) {
1475 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1476 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1477 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1478 setOperationAction(ISD::VSELECT, VT, Legal);
1479 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1480 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1481 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1482 setOperationAction(ISD::MLOAD, VT, Legal);
1483 setOperationAction(ISD::MSTORE, VT, Legal);
1486 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1487 MVT VT = (MVT::SimpleValueType)i;
1489 // Do not attempt to promote non-512-bit vectors.
1490 if (!VT.is512BitVector())
1493 setOperationAction(ISD::SELECT, VT, Promote);
1494 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1498 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1499 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1500 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1502 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1503 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1505 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1506 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1507 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1508 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1509 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1510 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1511 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1512 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1513 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1514 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1515 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1516 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1517 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1518 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1519 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1520 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1521 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1522 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1523 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1524 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1525 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1526 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1527 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1528 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1529 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1530 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1531 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1532 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1533 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1535 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1536 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1537 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1538 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1539 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1540 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1541 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1542 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1544 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1545 const MVT VT = (MVT::SimpleValueType)i;
1547 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1549 // Do not attempt to promote non-512-bit vectors.
1550 if (!VT.is512BitVector())
1554 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1555 setOperationAction(ISD::VSELECT, VT, Legal);
1560 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1561 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1562 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1564 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1565 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1566 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1567 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1568 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1569 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1570 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1571 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1572 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1573 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1575 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1576 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1577 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1578 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1579 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1580 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1581 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1582 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1584 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1585 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1586 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1587 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1588 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1589 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1590 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1591 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1594 // We want to custom lower some of our intrinsics.
1595 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1596 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1597 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1598 if (!Subtarget->is64Bit())
1599 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1601 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1602 // handle type legalization for these operations here.
1604 // FIXME: We really should do custom legalization for addition and
1605 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1606 // than generic legalization for 64-bit multiplication-with-overflow, though.
1607 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1608 // Add/Sub/Mul with overflow operations are custom lowered.
1610 setOperationAction(ISD::SADDO, VT, Custom);
1611 setOperationAction(ISD::UADDO, VT, Custom);
1612 setOperationAction(ISD::SSUBO, VT, Custom);
1613 setOperationAction(ISD::USUBO, VT, Custom);
1614 setOperationAction(ISD::SMULO, VT, Custom);
1615 setOperationAction(ISD::UMULO, VT, Custom);
1619 if (!Subtarget->is64Bit()) {
1620 // These libcalls are not available in 32-bit.
1621 setLibcallName(RTLIB::SHL_I128, nullptr);
1622 setLibcallName(RTLIB::SRL_I128, nullptr);
1623 setLibcallName(RTLIB::SRA_I128, nullptr);
1626 // Combine sin / cos into one node or libcall if possible.
1627 if (Subtarget->hasSinCos()) {
1628 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1629 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1630 if (Subtarget->isTargetDarwin()) {
1631 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1632 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1633 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1634 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1638 if (Subtarget->isTargetWin64()) {
1639 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1640 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1641 setOperationAction(ISD::SREM, MVT::i128, Custom);
1642 setOperationAction(ISD::UREM, MVT::i128, Custom);
1643 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1644 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1647 // We have target-specific dag combine patterns for the following nodes:
1648 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1649 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1650 setTargetDAGCombine(ISD::BITCAST);
1651 setTargetDAGCombine(ISD::VSELECT);
1652 setTargetDAGCombine(ISD::SELECT);
1653 setTargetDAGCombine(ISD::SHL);
1654 setTargetDAGCombine(ISD::SRA);
1655 setTargetDAGCombine(ISD::SRL);
1656 setTargetDAGCombine(ISD::OR);
1657 setTargetDAGCombine(ISD::AND);
1658 setTargetDAGCombine(ISD::ADD);
1659 setTargetDAGCombine(ISD::FADD);
1660 setTargetDAGCombine(ISD::FSUB);
1661 setTargetDAGCombine(ISD::FMA);
1662 setTargetDAGCombine(ISD::SUB);
1663 setTargetDAGCombine(ISD::LOAD);
1664 setTargetDAGCombine(ISD::MLOAD);
1665 setTargetDAGCombine(ISD::STORE);
1666 setTargetDAGCombine(ISD::MSTORE);
1667 setTargetDAGCombine(ISD::ZERO_EXTEND);
1668 setTargetDAGCombine(ISD::ANY_EXTEND);
1669 setTargetDAGCombine(ISD::SIGN_EXTEND);
1670 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1671 setTargetDAGCombine(ISD::SINT_TO_FP);
1672 setTargetDAGCombine(ISD::UINT_TO_FP);
1673 setTargetDAGCombine(ISD::SETCC);
1674 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1675 setTargetDAGCombine(ISD::BUILD_VECTOR);
1676 setTargetDAGCombine(ISD::MUL);
1677 setTargetDAGCombine(ISD::XOR);
1679 computeRegisterProperties(Subtarget->getRegisterInfo());
1681 // On Darwin, -Os means optimize for size without hurting performance,
1682 // do not reduce the limit.
1683 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1684 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1685 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1686 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1687 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1688 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1689 setPrefLoopAlignment(4); // 2^4 bytes.
1691 // Predictable cmov don't hurt on atom because it's in-order.
1692 PredictableSelectIsExpensive = !Subtarget->isAtom();
1693 EnableExtLdPromotion = true;
1694 setPrefFunctionAlignment(4); // 2^4 bytes.
1696 verifyIntrinsicTables();
1699 // This has so far only been implemented for 64-bit MachO.
1700 bool X86TargetLowering::useLoadStackGuardNode() const {
1701 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1704 TargetLoweringBase::LegalizeTypeAction
1705 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1706 if (ExperimentalVectorWideningLegalization &&
1707 VT.getVectorNumElements() != 1 &&
1708 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1709 return TypeWidenVector;
1711 return TargetLoweringBase::getPreferredVectorAction(VT);
1714 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1716 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1718 const unsigned NumElts = VT.getVectorNumElements();
1719 const EVT EltVT = VT.getVectorElementType();
1720 if (VT.is512BitVector()) {
1721 if (Subtarget->hasAVX512())
1722 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1723 EltVT == MVT::f32 || EltVT == MVT::f64)
1725 case 8: return MVT::v8i1;
1726 case 16: return MVT::v16i1;
1728 if (Subtarget->hasBWI())
1729 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1731 case 32: return MVT::v32i1;
1732 case 64: return MVT::v64i1;
1736 if (VT.is256BitVector() || VT.is128BitVector()) {
1737 if (Subtarget->hasVLX())
1738 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1739 EltVT == MVT::f32 || EltVT == MVT::f64)
1741 case 2: return MVT::v2i1;
1742 case 4: return MVT::v4i1;
1743 case 8: return MVT::v8i1;
1745 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1746 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1748 case 8: return MVT::v8i1;
1749 case 16: return MVT::v16i1;
1750 case 32: return MVT::v32i1;
1754 return VT.changeVectorElementTypeToInteger();
1757 /// Helper for getByValTypeAlignment to determine
1758 /// the desired ByVal argument alignment.
1759 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1762 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1763 if (VTy->getBitWidth() == 128)
1765 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1766 unsigned EltAlign = 0;
1767 getMaxByValAlign(ATy->getElementType(), EltAlign);
1768 if (EltAlign > MaxAlign)
1769 MaxAlign = EltAlign;
1770 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1771 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1772 unsigned EltAlign = 0;
1773 getMaxByValAlign(STy->getElementType(i), EltAlign);
1774 if (EltAlign > MaxAlign)
1775 MaxAlign = EltAlign;
1782 /// Return the desired alignment for ByVal aggregate
1783 /// function arguments in the caller parameter area. For X86, aggregates
1784 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1785 /// are at 4-byte boundaries.
1786 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1787 if (Subtarget->is64Bit()) {
1788 // Max of 8 and alignment of type.
1789 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1796 if (Subtarget->hasSSE1())
1797 getMaxByValAlign(Ty, Align);
1801 /// Returns the target specific optimal type for load
1802 /// and store operations as a result of memset, memcpy, and memmove
1803 /// lowering. If DstAlign is zero that means it's safe to destination
1804 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1805 /// means there isn't a need to check it against alignment requirement,
1806 /// probably because the source does not need to be loaded. If 'IsMemset' is
1807 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1808 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1809 /// source is constant so it does not need to be loaded.
1810 /// It returns EVT::Other if the type should be determined using generic
1811 /// target-independent logic.
1813 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1814 unsigned DstAlign, unsigned SrcAlign,
1815 bool IsMemset, bool ZeroMemset,
1817 MachineFunction &MF) const {
1818 const Function *F = MF.getFunction();
1819 if ((!IsMemset || ZeroMemset) &&
1820 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1822 (Subtarget->isUnalignedMemAccessFast() ||
1823 ((DstAlign == 0 || DstAlign >= 16) &&
1824 (SrcAlign == 0 || SrcAlign >= 16)))) {
1826 if (Subtarget->hasInt256())
1828 if (Subtarget->hasFp256())
1831 if (Subtarget->hasSSE2())
1833 if (Subtarget->hasSSE1())
1835 } else if (!MemcpyStrSrc && Size >= 8 &&
1836 !Subtarget->is64Bit() &&
1837 Subtarget->hasSSE2()) {
1838 // Do not use f64 to lower memcpy if source is string constant. It's
1839 // better to use i32 to avoid the loads.
1843 if (Subtarget->is64Bit() && Size >= 8)
1848 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1850 return X86ScalarSSEf32;
1851 else if (VT == MVT::f64)
1852 return X86ScalarSSEf64;
1857 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1862 *Fast = Subtarget->isUnalignedMemAccessFast();
1866 /// Return the entry encoding for a jump table in the
1867 /// current function. The returned value is a member of the
1868 /// MachineJumpTableInfo::JTEntryKind enum.
1869 unsigned X86TargetLowering::getJumpTableEncoding() const {
1870 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1872 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1873 Subtarget->isPICStyleGOT())
1874 return MachineJumpTableInfo::EK_Custom32;
1876 // Otherwise, use the normal jump table encoding heuristics.
1877 return TargetLowering::getJumpTableEncoding();
1880 bool X86TargetLowering::useSoftFloat() const {
1881 return Subtarget->useSoftFloat();
1885 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1886 const MachineBasicBlock *MBB,
1887 unsigned uid,MCContext &Ctx) const{
1888 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1889 Subtarget->isPICStyleGOT());
1890 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1892 return MCSymbolRefExpr::create(MBB->getSymbol(),
1893 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1896 /// Returns relocation base for the given PIC jumptable.
1897 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1898 SelectionDAG &DAG) const {
1899 if (!Subtarget->is64Bit())
1900 // This doesn't have SDLoc associated with it, but is not really the
1901 // same as a Register.
1902 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1906 /// This returns the relocation base for the given PIC jumptable,
1907 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1908 const MCExpr *X86TargetLowering::
1909 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1910 MCContext &Ctx) const {
1911 // X86-64 uses RIP relative addressing based on the jump table label.
1912 if (Subtarget->isPICStyleRIPRel())
1913 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1915 // Otherwise, the reference is relative to the PIC base.
1916 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1919 std::pair<const TargetRegisterClass *, uint8_t>
1920 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1922 const TargetRegisterClass *RRC = nullptr;
1924 switch (VT.SimpleTy) {
1926 return TargetLowering::findRepresentativeClass(TRI, VT);
1927 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1928 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1931 RRC = &X86::VR64RegClass;
1933 case MVT::f32: case MVT::f64:
1934 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1935 case MVT::v4f32: case MVT::v2f64:
1936 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1938 RRC = &X86::VR128RegClass;
1941 return std::make_pair(RRC, Cost);
1944 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1945 unsigned &Offset) const {
1946 if (!Subtarget->isTargetLinux())
1949 if (Subtarget->is64Bit()) {
1950 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1952 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1964 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1965 unsigned DestAS) const {
1966 assert(SrcAS != DestAS && "Expected different address spaces!");
1968 return SrcAS < 256 && DestAS < 256;
1971 //===----------------------------------------------------------------------===//
1972 // Return Value Calling Convention Implementation
1973 //===----------------------------------------------------------------------===//
1975 #include "X86GenCallingConv.inc"
1978 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1979 MachineFunction &MF, bool isVarArg,
1980 const SmallVectorImpl<ISD::OutputArg> &Outs,
1981 LLVMContext &Context) const {
1982 SmallVector<CCValAssign, 16> RVLocs;
1983 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1984 return CCInfo.CheckReturn(Outs, RetCC_X86);
1987 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1988 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1993 X86TargetLowering::LowerReturn(SDValue Chain,
1994 CallingConv::ID CallConv, bool isVarArg,
1995 const SmallVectorImpl<ISD::OutputArg> &Outs,
1996 const SmallVectorImpl<SDValue> &OutVals,
1997 SDLoc dl, SelectionDAG &DAG) const {
1998 MachineFunction &MF = DAG.getMachineFunction();
1999 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2001 SmallVector<CCValAssign, 16> RVLocs;
2002 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2003 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2006 SmallVector<SDValue, 6> RetOps;
2007 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2008 // Operand #1 = Bytes To Pop
2009 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2012 // Copy the result values into the output registers.
2013 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2014 CCValAssign &VA = RVLocs[i];
2015 assert(VA.isRegLoc() && "Can only return in registers!");
2016 SDValue ValToCopy = OutVals[i];
2017 EVT ValVT = ValToCopy.getValueType();
2019 // Promote values to the appropriate types.
2020 if (VA.getLocInfo() == CCValAssign::SExt)
2021 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2022 else if (VA.getLocInfo() == CCValAssign::ZExt)
2023 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2024 else if (VA.getLocInfo() == CCValAssign::AExt) {
2025 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2026 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2028 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2030 else if (VA.getLocInfo() == CCValAssign::BCvt)
2031 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2033 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2034 "Unexpected FP-extend for return value.");
2036 // If this is x86-64, and we disabled SSE, we can't return FP values,
2037 // or SSE or MMX vectors.
2038 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2039 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2040 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2041 report_fatal_error("SSE register return with SSE disabled");
2043 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2044 // llvm-gcc has never done it right and no one has noticed, so this
2045 // should be OK for now.
2046 if (ValVT == MVT::f64 &&
2047 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2048 report_fatal_error("SSE2 register return with SSE2 disabled");
2050 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2051 // the RET instruction and handled by the FP Stackifier.
2052 if (VA.getLocReg() == X86::FP0 ||
2053 VA.getLocReg() == X86::FP1) {
2054 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2055 // change the value to the FP stack register class.
2056 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2057 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2058 RetOps.push_back(ValToCopy);
2059 // Don't emit a copytoreg.
2063 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2064 // which is returned in RAX / RDX.
2065 if (Subtarget->is64Bit()) {
2066 if (ValVT == MVT::x86mmx) {
2067 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2068 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2069 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2071 // If we don't have SSE2 available, convert to v4f32 so the generated
2072 // register is legal.
2073 if (!Subtarget->hasSSE2())
2074 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2079 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2080 Flag = Chain.getValue(1);
2081 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2084 // All x86 ABIs require that for returning structs by value we copy
2085 // the sret argument into %rax/%eax (depending on ABI) for the return.
2086 // We saved the argument into a virtual register in the entry block,
2087 // so now we copy the value out and into %rax/%eax.
2089 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2090 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2091 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2092 // either case FuncInfo->setSRetReturnReg() will have been called.
2093 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2094 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2097 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2098 X86::RAX : X86::EAX;
2099 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2100 Flag = Chain.getValue(1);
2102 // RAX/EAX now acts like a return value.
2103 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2106 RetOps[0] = Chain; // Update chain.
2108 // Add the flag if we have it.
2110 RetOps.push_back(Flag);
2112 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2115 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2116 if (N->getNumValues() != 1)
2118 if (!N->hasNUsesOfValue(1, 0))
2121 SDValue TCChain = Chain;
2122 SDNode *Copy = *N->use_begin();
2123 if (Copy->getOpcode() == ISD::CopyToReg) {
2124 // If the copy has a glue operand, we conservatively assume it isn't safe to
2125 // perform a tail call.
2126 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2128 TCChain = Copy->getOperand(0);
2129 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2132 bool HasRet = false;
2133 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2135 if (UI->getOpcode() != X86ISD::RET_FLAG)
2137 // If we are returning more than one value, we can definitely
2138 // not make a tail call see PR19530
2139 if (UI->getNumOperands() > 4)
2141 if (UI->getNumOperands() == 4 &&
2142 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2155 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2156 ISD::NodeType ExtendKind) const {
2158 // TODO: Is this also valid on 32-bit?
2159 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2160 ReturnMVT = MVT::i8;
2162 ReturnMVT = MVT::i32;
2164 EVT MinVT = getRegisterType(Context, ReturnMVT);
2165 return VT.bitsLT(MinVT) ? MinVT : VT;
2168 /// Lower the result values of a call into the
2169 /// appropriate copies out of appropriate physical registers.
2172 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2173 CallingConv::ID CallConv, bool isVarArg,
2174 const SmallVectorImpl<ISD::InputArg> &Ins,
2175 SDLoc dl, SelectionDAG &DAG,
2176 SmallVectorImpl<SDValue> &InVals) const {
2178 // Assign locations to each value returned by this call.
2179 SmallVector<CCValAssign, 16> RVLocs;
2180 bool Is64Bit = Subtarget->is64Bit();
2181 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2183 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2185 // Copy all of the result registers out of their specified physreg.
2186 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2187 CCValAssign &VA = RVLocs[i];
2188 EVT CopyVT = VA.getLocVT();
2190 // If this is x86-64, and we disabled SSE, we can't return FP values
2191 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2192 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2193 report_fatal_error("SSE register return with SSE disabled");
2196 // If we prefer to use the value in xmm registers, copy it out as f80 and
2197 // use a truncate to move it from fp stack reg to xmm reg.
2198 bool RoundAfterCopy = false;
2199 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2200 isScalarFPTypeInSSEReg(VA.getValVT())) {
2202 RoundAfterCopy = (CopyVT != VA.getLocVT());
2205 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2206 CopyVT, InFlag).getValue(1);
2207 SDValue Val = Chain.getValue(0);
2210 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2211 // This truncation won't change the value.
2212 DAG.getIntPtrConstant(1, dl));
2214 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2215 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2217 InFlag = Chain.getValue(2);
2218 InVals.push_back(Val);
2224 //===----------------------------------------------------------------------===//
2225 // C & StdCall & Fast Calling Convention implementation
2226 //===----------------------------------------------------------------------===//
2227 // StdCall calling convention seems to be standard for many Windows' API
2228 // routines and around. It differs from C calling convention just a little:
2229 // callee should clean up the stack, not caller. Symbols should be also
2230 // decorated in some fancy way :) It doesn't support any vector arguments.
2231 // For info on fast calling convention see Fast Calling Convention (tail call)
2232 // implementation LowerX86_32FastCCCallTo.
2234 /// CallIsStructReturn - Determines whether a call uses struct return
2236 enum StructReturnType {
2241 static StructReturnType
2242 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2244 return NotStructReturn;
2246 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2247 if (!Flags.isSRet())
2248 return NotStructReturn;
2249 if (Flags.isInReg())
2250 return RegStructReturn;
2251 return StackStructReturn;
2254 /// Determines whether a function uses struct return semantics.
2255 static StructReturnType
2256 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2258 return NotStructReturn;
2260 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2261 if (!Flags.isSRet())
2262 return NotStructReturn;
2263 if (Flags.isInReg())
2264 return RegStructReturn;
2265 return StackStructReturn;
2268 /// Make a copy of an aggregate at address specified by "Src" to address
2269 /// "Dst" with size and alignment information specified by the specific
2270 /// parameter attribute. The copy will be passed as a byval function parameter.
2272 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2273 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2275 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2277 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2278 /*isVolatile*/false, /*AlwaysInline=*/true,
2279 /*isTailCall*/false,
2280 MachinePointerInfo(), MachinePointerInfo());
2283 /// Return true if the calling convention is one that
2284 /// supports tail call optimization.
2285 static bool IsTailCallConvention(CallingConv::ID CC) {
2286 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2287 CC == CallingConv::HiPE);
2290 /// \brief Return true if the calling convention is a C calling convention.
2291 static bool IsCCallConvention(CallingConv::ID CC) {
2292 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2293 CC == CallingConv::X86_64_SysV);
2296 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2298 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2299 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2303 CallingConv::ID CalleeCC = CS.getCallingConv();
2304 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2310 /// Return true if the function is being made into
2311 /// a tailcall target by changing its ABI.
2312 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2313 bool GuaranteedTailCallOpt) {
2314 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2318 X86TargetLowering::LowerMemArgument(SDValue Chain,
2319 CallingConv::ID CallConv,
2320 const SmallVectorImpl<ISD::InputArg> &Ins,
2321 SDLoc dl, SelectionDAG &DAG,
2322 const CCValAssign &VA,
2323 MachineFrameInfo *MFI,
2325 // Create the nodes corresponding to a load from this parameter slot.
2326 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2327 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2328 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2329 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2332 // If value is passed by pointer we have address passed instead of the value
2334 bool ExtendedInMem = VA.isExtInLoc() &&
2335 VA.getValVT().getScalarType() == MVT::i1;
2337 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2338 ValVT = VA.getLocVT();
2340 ValVT = VA.getValVT();
2342 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2343 // changed with more analysis.
2344 // In case of tail call optimization mark all arguments mutable. Since they
2345 // could be overwritten by lowering of arguments in case of a tail call.
2346 if (Flags.isByVal()) {
2347 unsigned Bytes = Flags.getByValSize();
2348 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2349 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2350 return DAG.getFrameIndex(FI, getPointerTy());
2352 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2353 VA.getLocMemOffset(), isImmutable);
2354 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2355 SDValue Val = DAG.getLoad(ValVT, dl, Chain, FIN,
2356 MachinePointerInfo::getFixedStack(FI),
2357 false, false, false, 0);
2358 return ExtendedInMem ?
2359 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2363 // FIXME: Get this from tablegen.
2364 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2365 const X86Subtarget *Subtarget) {
2366 assert(Subtarget->is64Bit());
2368 if (Subtarget->isCallingConvWin64(CallConv)) {
2369 static const MCPhysReg GPR64ArgRegsWin64[] = {
2370 X86::RCX, X86::RDX, X86::R8, X86::R9
2372 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2375 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2376 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2378 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2381 // FIXME: Get this from tablegen.
2382 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2383 CallingConv::ID CallConv,
2384 const X86Subtarget *Subtarget) {
2385 assert(Subtarget->is64Bit());
2386 if (Subtarget->isCallingConvWin64(CallConv)) {
2387 // The XMM registers which might contain var arg parameters are shadowed
2388 // in their paired GPR. So we only need to save the GPR to their home
2390 // TODO: __vectorcall will change this.
2394 const Function *Fn = MF.getFunction();
2395 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2396 bool isSoftFloat = Subtarget->useSoftFloat();
2397 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2398 "SSE register cannot be used when SSE is disabled!");
2399 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2400 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2404 static const MCPhysReg XMMArgRegs64Bit[] = {
2405 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2406 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2408 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2412 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2413 CallingConv::ID CallConv,
2415 const SmallVectorImpl<ISD::InputArg> &Ins,
2418 SmallVectorImpl<SDValue> &InVals)
2420 MachineFunction &MF = DAG.getMachineFunction();
2421 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2422 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2424 const Function* Fn = MF.getFunction();
2425 if (Fn->hasExternalLinkage() &&
2426 Subtarget->isTargetCygMing() &&
2427 Fn->getName() == "main")
2428 FuncInfo->setForceFramePointer(true);
2430 MachineFrameInfo *MFI = MF.getFrameInfo();
2431 bool Is64Bit = Subtarget->is64Bit();
2432 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2434 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2435 "Var args not supported with calling convention fastcc, ghc or hipe");
2437 // Assign locations to all of the incoming arguments.
2438 SmallVector<CCValAssign, 16> ArgLocs;
2439 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2441 // Allocate shadow area for Win64
2443 CCInfo.AllocateStack(32, 8);
2445 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2447 unsigned LastVal = ~0U;
2449 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2450 CCValAssign &VA = ArgLocs[i];
2451 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2453 assert(VA.getValNo() != LastVal &&
2454 "Don't support value assigned to multiple locs yet");
2456 LastVal = VA.getValNo();
2458 if (VA.isRegLoc()) {
2459 EVT RegVT = VA.getLocVT();
2460 const TargetRegisterClass *RC;
2461 if (RegVT == MVT::i32)
2462 RC = &X86::GR32RegClass;
2463 else if (Is64Bit && RegVT == MVT::i64)
2464 RC = &X86::GR64RegClass;
2465 else if (RegVT == MVT::f32)
2466 RC = &X86::FR32RegClass;
2467 else if (RegVT == MVT::f64)
2468 RC = &X86::FR64RegClass;
2469 else if (RegVT.is512BitVector())
2470 RC = &X86::VR512RegClass;
2471 else if (RegVT.is256BitVector())
2472 RC = &X86::VR256RegClass;
2473 else if (RegVT.is128BitVector())
2474 RC = &X86::VR128RegClass;
2475 else if (RegVT == MVT::x86mmx)
2476 RC = &X86::VR64RegClass;
2477 else if (RegVT == MVT::i1)
2478 RC = &X86::VK1RegClass;
2479 else if (RegVT == MVT::v8i1)
2480 RC = &X86::VK8RegClass;
2481 else if (RegVT == MVT::v16i1)
2482 RC = &X86::VK16RegClass;
2483 else if (RegVT == MVT::v32i1)
2484 RC = &X86::VK32RegClass;
2485 else if (RegVT == MVT::v64i1)
2486 RC = &X86::VK64RegClass;
2488 llvm_unreachable("Unknown argument type!");
2490 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2491 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2493 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2494 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2496 if (VA.getLocInfo() == CCValAssign::SExt)
2497 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2498 DAG.getValueType(VA.getValVT()));
2499 else if (VA.getLocInfo() == CCValAssign::ZExt)
2500 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2501 DAG.getValueType(VA.getValVT()));
2502 else if (VA.getLocInfo() == CCValAssign::BCvt)
2503 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2505 if (VA.isExtInLoc()) {
2506 // Handle MMX values passed in XMM regs.
2507 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2508 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2510 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2513 assert(VA.isMemLoc());
2514 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2517 // If value is passed via pointer - do a load.
2518 if (VA.getLocInfo() == CCValAssign::Indirect)
2519 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2520 MachinePointerInfo(), false, false, false, 0);
2522 InVals.push_back(ArgValue);
2525 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2526 // All x86 ABIs require that for returning structs by value we copy the
2527 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2528 // the argument into a virtual register so that we can access it from the
2530 if (Ins[i].Flags.isSRet()) {
2531 unsigned Reg = FuncInfo->getSRetReturnReg();
2533 MVT PtrTy = getPointerTy();
2534 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2535 FuncInfo->setSRetReturnReg(Reg);
2537 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2538 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2543 unsigned StackSize = CCInfo.getNextStackOffset();
2544 // Align stack specially for tail calls.
2545 if (FuncIsMadeTailCallSafe(CallConv,
2546 MF.getTarget().Options.GuaranteedTailCallOpt))
2547 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2549 // If the function takes variable number of arguments, make a frame index for
2550 // the start of the first vararg value... for expansion of llvm.va_start. We
2551 // can skip this if there are no va_start calls.
2552 if (MFI->hasVAStart() &&
2553 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2554 CallConv != CallingConv::X86_ThisCall))) {
2555 FuncInfo->setVarArgsFrameIndex(
2556 MFI->CreateFixedObject(1, StackSize, true));
2559 MachineModuleInfo &MMI = MF.getMMI();
2560 const Function *WinEHParent = nullptr;
2561 if (MMI.hasWinEHFuncInfo(Fn))
2562 WinEHParent = MMI.getWinEHParent(Fn);
2563 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2564 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2566 // Figure out if XMM registers are in use.
2567 assert(!(Subtarget->useSoftFloat() &&
2568 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2569 "SSE register cannot be used when SSE is disabled!");
2571 // 64-bit calling conventions support varargs and register parameters, so we
2572 // have to do extra work to spill them in the prologue.
2573 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2574 // Find the first unallocated argument registers.
2575 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2576 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2577 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2578 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2579 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2580 "SSE register cannot be used when SSE is disabled!");
2582 // Gather all the live in physical registers.
2583 SmallVector<SDValue, 6> LiveGPRs;
2584 SmallVector<SDValue, 8> LiveXMMRegs;
2586 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2587 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2589 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2591 if (!ArgXMMs.empty()) {
2592 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2593 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2594 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2595 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2596 LiveXMMRegs.push_back(
2597 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2602 // Get to the caller-allocated home save location. Add 8 to account
2603 // for the return address.
2604 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2605 FuncInfo->setRegSaveFrameIndex(
2606 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2607 // Fixup to set vararg frame on shadow area (4 x i64).
2609 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2611 // For X86-64, if there are vararg parameters that are passed via
2612 // registers, then we must store them to their spots on the stack so
2613 // they may be loaded by deferencing the result of va_next.
2614 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2615 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2616 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2617 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2620 // Store the integer parameter registers.
2621 SmallVector<SDValue, 8> MemOps;
2622 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2624 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2625 for (SDValue Val : LiveGPRs) {
2626 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2627 DAG.getIntPtrConstant(Offset, dl));
2629 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2630 MachinePointerInfo::getFixedStack(
2631 FuncInfo->getRegSaveFrameIndex(), Offset),
2633 MemOps.push_back(Store);
2637 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2638 // Now store the XMM (fp + vector) parameter registers.
2639 SmallVector<SDValue, 12> SaveXMMOps;
2640 SaveXMMOps.push_back(Chain);
2641 SaveXMMOps.push_back(ALVal);
2642 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2643 FuncInfo->getRegSaveFrameIndex(), dl));
2644 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2645 FuncInfo->getVarArgsFPOffset(), dl));
2646 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2648 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2649 MVT::Other, SaveXMMOps));
2652 if (!MemOps.empty())
2653 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2654 } else if (IsWin64 && IsWinEHOutlined) {
2655 // Get to the caller-allocated home save location. Add 8 to account
2656 // for the return address.
2657 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2658 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2659 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2661 MMI.getWinEHFuncInfo(Fn)
2662 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2663 FuncInfo->getRegSaveFrameIndex();
2665 // Store the second integer parameter (rdx) into rsp+16 relative to the
2666 // stack pointer at the entry of the function.
2668 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2669 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2670 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2671 Chain = DAG.getStore(
2672 Val.getValue(1), dl, Val, RSFIN,
2673 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2674 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2677 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2678 // Find the largest legal vector type.
2679 MVT VecVT = MVT::Other;
2680 // FIXME: Only some x86_32 calling conventions support AVX512.
2681 if (Subtarget->hasAVX512() &&
2682 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2683 CallConv == CallingConv::Intel_OCL_BI)))
2684 VecVT = MVT::v16f32;
2685 else if (Subtarget->hasAVX())
2687 else if (Subtarget->hasSSE2())
2690 // We forward some GPRs and some vector types.
2691 SmallVector<MVT, 2> RegParmTypes;
2692 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2693 RegParmTypes.push_back(IntVT);
2694 if (VecVT != MVT::Other)
2695 RegParmTypes.push_back(VecVT);
2697 // Compute the set of forwarded registers. The rest are scratch.
2698 SmallVectorImpl<ForwardedRegister> &Forwards =
2699 FuncInfo->getForwardedMustTailRegParms();
2700 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2702 // Conservatively forward AL on x86_64, since it might be used for varargs.
2703 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2704 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2705 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2708 // Copy all forwards from physical to virtual registers.
2709 for (ForwardedRegister &F : Forwards) {
2710 // FIXME: Can we use a less constrained schedule?
2711 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2712 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2713 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2717 // Some CCs need callee pop.
2718 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2719 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2720 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2722 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2723 // If this is an sret function, the return should pop the hidden pointer.
2724 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2725 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2726 argsAreStructReturn(Ins) == StackStructReturn)
2727 FuncInfo->setBytesToPopOnReturn(4);
2731 // RegSaveFrameIndex is X86-64 only.
2732 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2733 if (CallConv == CallingConv::X86_FastCall ||
2734 CallConv == CallingConv::X86_ThisCall)
2735 // fastcc functions can't have varargs.
2736 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2739 FuncInfo->setArgumentStackSize(StackSize);
2741 if (IsWinEHParent) {
2743 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2744 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2745 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2746 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2747 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2748 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2749 /*isVolatile=*/true,
2750 /*isNonTemporal=*/false, /*Alignment=*/0);
2752 // Functions using Win32 EH are considered to have opaque SP adjustments
2753 // to force local variables to be addressed from the frame or base
2755 MFI->setHasOpaqueSPAdjustment(true);
2763 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2764 SDValue StackPtr, SDValue Arg,
2765 SDLoc dl, SelectionDAG &DAG,
2766 const CCValAssign &VA,
2767 ISD::ArgFlagsTy Flags) const {
2768 unsigned LocMemOffset = VA.getLocMemOffset();
2769 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2770 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2771 if (Flags.isByVal())
2772 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2774 return DAG.getStore(Chain, dl, Arg, PtrOff,
2775 MachinePointerInfo::getStack(LocMemOffset),
2779 /// Emit a load of return address if tail call
2780 /// optimization is performed and it is required.
2782 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2783 SDValue &OutRetAddr, SDValue Chain,
2784 bool IsTailCall, bool Is64Bit,
2785 int FPDiff, SDLoc dl) const {
2786 // Adjust the Return address stack slot.
2787 EVT VT = getPointerTy();
2788 OutRetAddr = getReturnAddressFrameIndex(DAG);
2790 // Load the "old" Return address.
2791 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2792 false, false, false, 0);
2793 return SDValue(OutRetAddr.getNode(), 1);
2796 /// Emit a store of the return address if tail call
2797 /// optimization is performed and it is required (FPDiff!=0).
2798 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2799 SDValue Chain, SDValue RetAddrFrIdx,
2800 EVT PtrVT, unsigned SlotSize,
2801 int FPDiff, SDLoc dl) {
2802 // Store the return address to the appropriate stack slot.
2803 if (!FPDiff) return Chain;
2804 // Calculate the new stack slot for the return address.
2805 int NewReturnAddrFI =
2806 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2808 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2809 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2810 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2816 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2817 SmallVectorImpl<SDValue> &InVals) const {
2818 SelectionDAG &DAG = CLI.DAG;
2820 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2821 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2822 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2823 SDValue Chain = CLI.Chain;
2824 SDValue Callee = CLI.Callee;
2825 CallingConv::ID CallConv = CLI.CallConv;
2826 bool &isTailCall = CLI.IsTailCall;
2827 bool isVarArg = CLI.IsVarArg;
2829 MachineFunction &MF = DAG.getMachineFunction();
2830 bool Is64Bit = Subtarget->is64Bit();
2831 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2832 StructReturnType SR = callIsStructReturn(Outs);
2833 bool IsSibcall = false;
2834 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2835 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2837 if (Attr.getValueAsString() == "true")
2840 if (Subtarget->isPICStyleGOT() &&
2841 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2842 // If we are using a GOT, disable tail calls to external symbols with
2843 // default visibility. Tail calling such a symbol requires using a GOT
2844 // relocation, which forces early binding of the symbol. This breaks code
2845 // that require lazy function symbol resolution. Using musttail or
2846 // GuaranteedTailCallOpt will override this.
2847 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2848 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2849 G->getGlobal()->hasDefaultVisibility()))
2853 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2855 // Force this to be a tail call. The verifier rules are enough to ensure
2856 // that we can lower this successfully without moving the return address
2859 } else if (isTailCall) {
2860 // Check if it's really possible to do a tail call.
2861 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2862 isVarArg, SR != NotStructReturn,
2863 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2864 Outs, OutVals, Ins, DAG);
2866 // Sibcalls are automatically detected tailcalls which do not require
2868 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2875 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2876 "Var args not supported with calling convention fastcc, ghc or hipe");
2878 // Analyze operands of the call, assigning locations to each operand.
2879 SmallVector<CCValAssign, 16> ArgLocs;
2880 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2882 // Allocate shadow area for Win64
2884 CCInfo.AllocateStack(32, 8);
2886 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2888 // Get a count of how many bytes are to be pushed on the stack.
2889 unsigned NumBytes = CCInfo.getNextStackOffset();
2891 // This is a sibcall. The memory operands are available in caller's
2892 // own caller's stack.
2894 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2895 IsTailCallConvention(CallConv))
2896 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2899 if (isTailCall && !IsSibcall && !IsMustTail) {
2900 // Lower arguments at fp - stackoffset + fpdiff.
2901 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2903 FPDiff = NumBytesCallerPushed - NumBytes;
2905 // Set the delta of movement of the returnaddr stackslot.
2906 // But only set if delta is greater than previous delta.
2907 if (FPDiff < X86Info->getTCReturnAddrDelta())
2908 X86Info->setTCReturnAddrDelta(FPDiff);
2911 unsigned NumBytesToPush = NumBytes;
2912 unsigned NumBytesToPop = NumBytes;
2914 // If we have an inalloca argument, all stack space has already been allocated
2915 // for us and be right at the top of the stack. We don't support multiple
2916 // arguments passed in memory when using inalloca.
2917 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2919 if (!ArgLocs.back().isMemLoc())
2920 report_fatal_error("cannot use inalloca attribute on a register "
2922 if (ArgLocs.back().getLocMemOffset() != 0)
2923 report_fatal_error("any parameter with the inalloca attribute must be "
2924 "the only memory argument");
2928 Chain = DAG.getCALLSEQ_START(
2929 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2931 SDValue RetAddrFrIdx;
2932 // Load return address for tail calls.
2933 if (isTailCall && FPDiff)
2934 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2935 Is64Bit, FPDiff, dl);
2937 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2938 SmallVector<SDValue, 8> MemOpChains;
2941 // Walk the register/memloc assignments, inserting copies/loads. In the case
2942 // of tail call optimization arguments are handle later.
2943 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2944 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2945 // Skip inalloca arguments, they have already been written.
2946 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2947 if (Flags.isInAlloca())
2950 CCValAssign &VA = ArgLocs[i];
2951 EVT RegVT = VA.getLocVT();
2952 SDValue Arg = OutVals[i];
2953 bool isByVal = Flags.isByVal();
2955 // Promote the value if needed.
2956 switch (VA.getLocInfo()) {
2957 default: llvm_unreachable("Unknown loc info!");
2958 case CCValAssign::Full: break;
2959 case CCValAssign::SExt:
2960 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2962 case CCValAssign::ZExt:
2963 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2965 case CCValAssign::AExt:
2966 if (Arg.getValueType().isVector() &&
2967 Arg.getValueType().getScalarType() == MVT::i1)
2968 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2969 else if (RegVT.is128BitVector()) {
2970 // Special case: passing MMX values in XMM registers.
2971 Arg = DAG.getBitcast(MVT::i64, Arg);
2972 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2973 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2975 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2977 case CCValAssign::BCvt:
2978 Arg = DAG.getBitcast(RegVT, Arg);
2980 case CCValAssign::Indirect: {
2981 // Store the argument.
2982 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2983 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2984 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2985 MachinePointerInfo::getFixedStack(FI),
2992 if (VA.isRegLoc()) {
2993 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2994 if (isVarArg && IsWin64) {
2995 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2996 // shadow reg if callee is a varargs function.
2997 unsigned ShadowReg = 0;
2998 switch (VA.getLocReg()) {
2999 case X86::XMM0: ShadowReg = X86::RCX; break;
3000 case X86::XMM1: ShadowReg = X86::RDX; break;
3001 case X86::XMM2: ShadowReg = X86::R8; break;
3002 case X86::XMM3: ShadowReg = X86::R9; break;
3005 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3007 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3008 assert(VA.isMemLoc());
3009 if (!StackPtr.getNode())
3010 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3012 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3013 dl, DAG, VA, Flags));
3017 if (!MemOpChains.empty())
3018 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3020 if (Subtarget->isPICStyleGOT()) {
3021 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3024 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
3025 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
3027 // If we are tail calling and generating PIC/GOT style code load the
3028 // address of the callee into ECX. The value in ecx is used as target of
3029 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3030 // for tail calls on PIC/GOT architectures. Normally we would just put the
3031 // address of GOT into ebx and then call target@PLT. But for tail calls
3032 // ebx would be restored (since ebx is callee saved) before jumping to the
3035 // Note: The actual moving to ECX is done further down.
3036 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3037 if (G && !G->getGlobal()->hasLocalLinkage() &&
3038 G->getGlobal()->hasDefaultVisibility())
3039 Callee = LowerGlobalAddress(Callee, DAG);
3040 else if (isa<ExternalSymbolSDNode>(Callee))
3041 Callee = LowerExternalSymbol(Callee, DAG);
3045 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3046 // From AMD64 ABI document:
3047 // For calls that may call functions that use varargs or stdargs
3048 // (prototype-less calls or calls to functions containing ellipsis (...) in
3049 // the declaration) %al is used as hidden argument to specify the number
3050 // of SSE registers used. The contents of %al do not need to match exactly
3051 // the number of registers, but must be an ubound on the number of SSE
3052 // registers used and is in the range 0 - 8 inclusive.
3054 // Count the number of XMM registers allocated.
3055 static const MCPhysReg XMMArgRegs[] = {
3056 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3057 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3059 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3060 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3061 && "SSE registers cannot be used when SSE is disabled");
3063 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3064 DAG.getConstant(NumXMMRegs, dl,
3068 if (isVarArg && IsMustTail) {
3069 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3070 for (const auto &F : Forwards) {
3071 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3072 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3076 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3077 // don't need this because the eligibility check rejects calls that require
3078 // shuffling arguments passed in memory.
3079 if (!IsSibcall && isTailCall) {
3080 // Force all the incoming stack arguments to be loaded from the stack
3081 // before any new outgoing arguments are stored to the stack, because the
3082 // outgoing stack slots may alias the incoming argument stack slots, and
3083 // the alias isn't otherwise explicit. This is slightly more conservative
3084 // than necessary, because it means that each store effectively depends
3085 // on every argument instead of just those arguments it would clobber.
3086 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3088 SmallVector<SDValue, 8> MemOpChains2;
3091 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3092 CCValAssign &VA = ArgLocs[i];
3095 assert(VA.isMemLoc());
3096 SDValue Arg = OutVals[i];
3097 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3098 // Skip inalloca arguments. They don't require any work.
3099 if (Flags.isInAlloca())
3101 // Create frame index.
3102 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3103 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3104 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3105 FIN = DAG.getFrameIndex(FI, getPointerTy());
3107 if (Flags.isByVal()) {
3108 // Copy relative to framepointer.
3109 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3110 if (!StackPtr.getNode())
3111 StackPtr = DAG.getCopyFromReg(Chain, dl,
3112 RegInfo->getStackRegister(),
3114 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3116 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3120 // Store relative to framepointer.
3121 MemOpChains2.push_back(
3122 DAG.getStore(ArgChain, dl, Arg, FIN,
3123 MachinePointerInfo::getFixedStack(FI),
3128 if (!MemOpChains2.empty())
3129 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3131 // Store the return address to the appropriate stack slot.
3132 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3133 getPointerTy(), RegInfo->getSlotSize(),
3137 // Build a sequence of copy-to-reg nodes chained together with token chain
3138 // and flag operands which copy the outgoing args into registers.
3140 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3141 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3142 RegsToPass[i].second, InFlag);
3143 InFlag = Chain.getValue(1);
3146 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3147 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3148 // In the 64-bit large code model, we have to make all calls
3149 // through a register, since the call instruction's 32-bit
3150 // pc-relative offset may not be large enough to hold the whole
3152 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3153 // If the callee is a GlobalAddress node (quite common, every direct call
3154 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3156 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3158 // We should use extra load for direct calls to dllimported functions in
3160 const GlobalValue *GV = G->getGlobal();
3161 if (!GV->hasDLLImportStorageClass()) {
3162 unsigned char OpFlags = 0;
3163 bool ExtraLoad = false;
3164 unsigned WrapperKind = ISD::DELETED_NODE;
3166 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3167 // external symbols most go through the PLT in PIC mode. If the symbol
3168 // has hidden or protected visibility, or if it is static or local, then
3169 // we don't need to use the PLT - we can directly call it.
3170 if (Subtarget->isTargetELF() &&
3171 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3172 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3173 OpFlags = X86II::MO_PLT;
3174 } else if (Subtarget->isPICStyleStubAny() &&
3175 !GV->isStrongDefinitionForLinker() &&
3176 (!Subtarget->getTargetTriple().isMacOSX() ||
3177 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3178 // PC-relative references to external symbols should go through $stub,
3179 // unless we're building with the leopard linker or later, which
3180 // automatically synthesizes these stubs.
3181 OpFlags = X86II::MO_DARWIN_STUB;
3182 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3183 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3184 // If the function is marked as non-lazy, generate an indirect call
3185 // which loads from the GOT directly. This avoids runtime overhead
3186 // at the cost of eager binding (and one extra byte of encoding).
3187 OpFlags = X86II::MO_GOTPCREL;
3188 WrapperKind = X86ISD::WrapperRIP;
3192 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3193 G->getOffset(), OpFlags);
3195 // Add a wrapper if needed.
3196 if (WrapperKind != ISD::DELETED_NODE)
3197 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3198 // Add extra indirection if needed.
3200 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3201 MachinePointerInfo::getGOT(),
3202 false, false, false, 0);
3204 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3205 unsigned char OpFlags = 0;
3207 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3208 // external symbols should go through the PLT.
3209 if (Subtarget->isTargetELF() &&
3210 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3211 OpFlags = X86II::MO_PLT;
3212 } else if (Subtarget->isPICStyleStubAny() &&
3213 (!Subtarget->getTargetTriple().isMacOSX() ||
3214 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3215 // PC-relative references to external symbols should go through $stub,
3216 // unless we're building with the leopard linker or later, which
3217 // automatically synthesizes these stubs.
3218 OpFlags = X86II::MO_DARWIN_STUB;
3221 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3223 } else if (Subtarget->isTarget64BitILP32() &&
3224 Callee->getValueType(0) == MVT::i32) {
3225 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3226 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3229 // Returns a chain & a flag for retval copy to use.
3230 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3231 SmallVector<SDValue, 8> Ops;
3233 if (!IsSibcall && isTailCall) {
3234 Chain = DAG.getCALLSEQ_END(Chain,
3235 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3236 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3237 InFlag = Chain.getValue(1);
3240 Ops.push_back(Chain);
3241 Ops.push_back(Callee);
3244 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3246 // Add argument registers to the end of the list so that they are known live
3248 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3249 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3250 RegsToPass[i].second.getValueType()));
3252 // Add a register mask operand representing the call-preserved registers.
3253 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3254 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3255 assert(Mask && "Missing call preserved mask for calling convention");
3256 Ops.push_back(DAG.getRegisterMask(Mask));
3258 if (InFlag.getNode())
3259 Ops.push_back(InFlag);
3263 //// If this is the first return lowered for this function, add the regs
3264 //// to the liveout set for the function.
3265 // This isn't right, although it's probably harmless on x86; liveouts
3266 // should be computed from returns not tail calls. Consider a void
3267 // function making a tail call to a function returning int.
3268 MF.getFrameInfo()->setHasTailCall();
3269 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3272 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3273 InFlag = Chain.getValue(1);
3275 // Create the CALLSEQ_END node.
3276 unsigned NumBytesForCalleeToPop;
3277 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3278 DAG.getTarget().Options.GuaranteedTailCallOpt))
3279 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3280 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3281 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3282 SR == StackStructReturn)
3283 // If this is a call to a struct-return function, the callee
3284 // pops the hidden struct pointer, so we have to push it back.
3285 // This is common for Darwin/X86, Linux & Mingw32 targets.
3286 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3287 NumBytesForCalleeToPop = 4;
3289 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3291 // Returns a flag for retval copy to use.
3293 Chain = DAG.getCALLSEQ_END(Chain,
3294 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3295 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3298 InFlag = Chain.getValue(1);
3301 // Handle result values, copying them out of physregs into vregs that we
3303 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3304 Ins, dl, DAG, InVals);
3307 //===----------------------------------------------------------------------===//
3308 // Fast Calling Convention (tail call) implementation
3309 //===----------------------------------------------------------------------===//
3311 // Like std call, callee cleans arguments, convention except that ECX is
3312 // reserved for storing the tail called function address. Only 2 registers are
3313 // free for argument passing (inreg). Tail call optimization is performed
3315 // * tailcallopt is enabled
3316 // * caller/callee are fastcc
3317 // On X86_64 architecture with GOT-style position independent code only local
3318 // (within module) calls are supported at the moment.
3319 // To keep the stack aligned according to platform abi the function
3320 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3321 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3322 // If a tail called function callee has more arguments than the caller the
3323 // caller needs to make sure that there is room to move the RETADDR to. This is
3324 // achieved by reserving an area the size of the argument delta right after the
3325 // original RETADDR, but before the saved framepointer or the spilled registers
3326 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3338 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3339 /// for a 16 byte align requirement.
3341 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3342 SelectionDAG& DAG) const {
3343 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3344 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3345 unsigned StackAlignment = TFI.getStackAlignment();
3346 uint64_t AlignMask = StackAlignment - 1;
3347 int64_t Offset = StackSize;
3348 unsigned SlotSize = RegInfo->getSlotSize();
3349 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3350 // Number smaller than 12 so just add the difference.
3351 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3353 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3354 Offset = ((~AlignMask) & Offset) + StackAlignment +
3355 (StackAlignment-SlotSize);
3360 /// MatchingStackOffset - Return true if the given stack call argument is
3361 /// already available in the same position (relatively) of the caller's
3362 /// incoming argument stack.
3364 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3365 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3366 const X86InstrInfo *TII) {
3367 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3369 if (Arg.getOpcode() == ISD::CopyFromReg) {
3370 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3371 if (!TargetRegisterInfo::isVirtualRegister(VR))
3373 MachineInstr *Def = MRI->getVRegDef(VR);
3376 if (!Flags.isByVal()) {
3377 if (!TII->isLoadFromStackSlot(Def, FI))
3380 unsigned Opcode = Def->getOpcode();
3381 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3382 Opcode == X86::LEA64_32r) &&
3383 Def->getOperand(1).isFI()) {
3384 FI = Def->getOperand(1).getIndex();
3385 Bytes = Flags.getByValSize();
3389 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3390 if (Flags.isByVal())
3391 // ByVal argument is passed in as a pointer but it's now being
3392 // dereferenced. e.g.
3393 // define @foo(%struct.X* %A) {
3394 // tail call @bar(%struct.X* byval %A)
3397 SDValue Ptr = Ld->getBasePtr();
3398 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3401 FI = FINode->getIndex();
3402 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3403 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3404 FI = FINode->getIndex();
3405 Bytes = Flags.getByValSize();
3409 assert(FI != INT_MAX);
3410 if (!MFI->isFixedObjectIndex(FI))
3412 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3415 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3416 /// for tail call optimization. Targets which want to do tail call
3417 /// optimization should implement this function.
3419 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3420 CallingConv::ID CalleeCC,
3422 bool isCalleeStructRet,
3423 bool isCallerStructRet,
3425 const SmallVectorImpl<ISD::OutputArg> &Outs,
3426 const SmallVectorImpl<SDValue> &OutVals,
3427 const SmallVectorImpl<ISD::InputArg> &Ins,
3428 SelectionDAG &DAG) const {
3429 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3432 // If -tailcallopt is specified, make fastcc functions tail-callable.
3433 const MachineFunction &MF = DAG.getMachineFunction();
3434 const Function *CallerF = MF.getFunction();
3436 // If the function return type is x86_fp80 and the callee return type is not,
3437 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3438 // perform a tailcall optimization here.
3439 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3442 CallingConv::ID CallerCC = CallerF->getCallingConv();
3443 bool CCMatch = CallerCC == CalleeCC;
3444 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3445 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3447 // Win64 functions have extra shadow space for argument homing. Don't do the
3448 // sibcall if the caller and callee have mismatched expectations for this
3450 if (IsCalleeWin64 != IsCallerWin64)
3453 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3454 if (IsTailCallConvention(CalleeCC) && CCMatch)
3459 // Look for obvious safe cases to perform tail call optimization that do not
3460 // require ABI changes. This is what gcc calls sibcall.
3462 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3463 // emit a special epilogue.
3464 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3465 if (RegInfo->needsStackRealignment(MF))
3468 // Also avoid sibcall optimization if either caller or callee uses struct
3469 // return semantics.
3470 if (isCalleeStructRet || isCallerStructRet)
3473 // An stdcall/thiscall caller is expected to clean up its arguments; the
3474 // callee isn't going to do that.
3475 // FIXME: this is more restrictive than needed. We could produce a tailcall
3476 // when the stack adjustment matches. For example, with a thiscall that takes
3477 // only one argument.
3478 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3479 CallerCC == CallingConv::X86_ThisCall))
3482 // Do not sibcall optimize vararg calls unless all arguments are passed via
3484 if (isVarArg && !Outs.empty()) {
3486 // Optimizing for varargs on Win64 is unlikely to be safe without
3487 // additional testing.
3488 if (IsCalleeWin64 || IsCallerWin64)
3491 SmallVector<CCValAssign, 16> ArgLocs;
3492 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3495 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3497 if (!ArgLocs[i].isRegLoc())
3501 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3502 // stack. Therefore, if it's not used by the call it is not safe to optimize
3503 // this into a sibcall.
3504 bool Unused = false;
3505 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3512 SmallVector<CCValAssign, 16> RVLocs;
3513 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3515 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3516 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3517 CCValAssign &VA = RVLocs[i];
3518 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3523 // If the calling conventions do not match, then we'd better make sure the
3524 // results are returned in the same way as what the caller expects.
3526 SmallVector<CCValAssign, 16> RVLocs1;
3527 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3529 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3531 SmallVector<CCValAssign, 16> RVLocs2;
3532 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3534 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3536 if (RVLocs1.size() != RVLocs2.size())
3538 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3539 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3541 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3543 if (RVLocs1[i].isRegLoc()) {
3544 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3547 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3553 // If the callee takes no arguments then go on to check the results of the
3555 if (!Outs.empty()) {
3556 // Check if stack adjustment is needed. For now, do not do this if any
3557 // argument is passed on the stack.
3558 SmallVector<CCValAssign, 16> ArgLocs;
3559 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3562 // Allocate shadow area for Win64
3564 CCInfo.AllocateStack(32, 8);
3566 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3567 if (CCInfo.getNextStackOffset()) {
3568 MachineFunction &MF = DAG.getMachineFunction();
3569 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3572 // Check if the arguments are already laid out in the right way as
3573 // the caller's fixed stack objects.
3574 MachineFrameInfo *MFI = MF.getFrameInfo();
3575 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3576 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3577 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3578 CCValAssign &VA = ArgLocs[i];
3579 SDValue Arg = OutVals[i];
3580 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3581 if (VA.getLocInfo() == CCValAssign::Indirect)
3583 if (!VA.isRegLoc()) {
3584 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3591 // If the tailcall address may be in a register, then make sure it's
3592 // possible to register allocate for it. In 32-bit, the call address can
3593 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3594 // callee-saved registers are restored. These happen to be the same
3595 // registers used to pass 'inreg' arguments so watch out for those.
3596 if (!Subtarget->is64Bit() &&
3597 ((!isa<GlobalAddressSDNode>(Callee) &&
3598 !isa<ExternalSymbolSDNode>(Callee)) ||
3599 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3600 unsigned NumInRegs = 0;
3601 // In PIC we need an extra register to formulate the address computation
3603 unsigned MaxInRegs =
3604 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3607 CCValAssign &VA = ArgLocs[i];
3610 unsigned Reg = VA.getLocReg();
3613 case X86::EAX: case X86::EDX: case X86::ECX:
3614 if (++NumInRegs == MaxInRegs)
3626 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3627 const TargetLibraryInfo *libInfo) const {
3628 return X86::createFastISel(funcInfo, libInfo);
3631 //===----------------------------------------------------------------------===//
3632 // Other Lowering Hooks
3633 //===----------------------------------------------------------------------===//
3635 static bool MayFoldLoad(SDValue Op) {
3636 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3639 static bool MayFoldIntoStore(SDValue Op) {
3640 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3643 static bool isTargetShuffle(unsigned Opcode) {
3645 default: return false;
3646 case X86ISD::BLENDI:
3647 case X86ISD::PSHUFB:
3648 case X86ISD::PSHUFD:
3649 case X86ISD::PSHUFHW:
3650 case X86ISD::PSHUFLW:
3652 case X86ISD::PALIGNR:
3653 case X86ISD::MOVLHPS:
3654 case X86ISD::MOVLHPD:
3655 case X86ISD::MOVHLPS:
3656 case X86ISD::MOVLPS:
3657 case X86ISD::MOVLPD:
3658 case X86ISD::MOVSHDUP:
3659 case X86ISD::MOVSLDUP:
3660 case X86ISD::MOVDDUP:
3663 case X86ISD::UNPCKL:
3664 case X86ISD::UNPCKH:
3665 case X86ISD::VPERMILPI:
3666 case X86ISD::VPERM2X128:
3667 case X86ISD::VPERMI:
3672 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3673 SDValue V1, unsigned TargetMask,
3674 SelectionDAG &DAG) {
3676 default: llvm_unreachable("Unknown x86 shuffle node");
3677 case X86ISD::PSHUFD:
3678 case X86ISD::PSHUFHW:
3679 case X86ISD::PSHUFLW:
3680 case X86ISD::VPERMILPI:
3681 case X86ISD::VPERMI:
3682 return DAG.getNode(Opc, dl, VT, V1,
3683 DAG.getConstant(TargetMask, dl, MVT::i8));
3687 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3688 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3690 default: llvm_unreachable("Unknown x86 shuffle node");
3691 case X86ISD::MOVLHPS:
3692 case X86ISD::MOVLHPD:
3693 case X86ISD::MOVHLPS:
3694 case X86ISD::MOVLPS:
3695 case X86ISD::MOVLPD:
3698 case X86ISD::UNPCKL:
3699 case X86ISD::UNPCKH:
3700 return DAG.getNode(Opc, dl, VT, V1, V2);
3704 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3705 MachineFunction &MF = DAG.getMachineFunction();
3706 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3707 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3708 int ReturnAddrIndex = FuncInfo->getRAIndex();
3710 if (ReturnAddrIndex == 0) {
3711 // Set up a frame object for the return address.
3712 unsigned SlotSize = RegInfo->getSlotSize();
3713 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3716 FuncInfo->setRAIndex(ReturnAddrIndex);
3719 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3722 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3723 bool hasSymbolicDisplacement) {
3724 // Offset should fit into 32 bit immediate field.
3725 if (!isInt<32>(Offset))
3728 // If we don't have a symbolic displacement - we don't have any extra
3730 if (!hasSymbolicDisplacement)
3733 // FIXME: Some tweaks might be needed for medium code model.
3734 if (M != CodeModel::Small && M != CodeModel::Kernel)
3737 // For small code model we assume that latest object is 16MB before end of 31
3738 // bits boundary. We may also accept pretty large negative constants knowing
3739 // that all objects are in the positive half of address space.
3740 if (M == CodeModel::Small && Offset < 16*1024*1024)
3743 // For kernel code model we know that all object resist in the negative half
3744 // of 32bits address space. We may not accept negative offsets, since they may
3745 // be just off and we may accept pretty large positive ones.
3746 if (M == CodeModel::Kernel && Offset >= 0)
3752 /// isCalleePop - Determines whether the callee is required to pop its
3753 /// own arguments. Callee pop is necessary to support tail calls.
3754 bool X86::isCalleePop(CallingConv::ID CallingConv,
3755 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3756 switch (CallingConv) {
3759 case CallingConv::X86_StdCall:
3760 case CallingConv::X86_FastCall:
3761 case CallingConv::X86_ThisCall:
3763 case CallingConv::Fast:
3764 case CallingConv::GHC:
3765 case CallingConv::HiPE:
3772 /// \brief Return true if the condition is an unsigned comparison operation.
3773 static bool isX86CCUnsigned(unsigned X86CC) {
3775 default: llvm_unreachable("Invalid integer condition!");
3776 case X86::COND_E: return true;
3777 case X86::COND_G: return false;
3778 case X86::COND_GE: return false;
3779 case X86::COND_L: return false;
3780 case X86::COND_LE: return false;
3781 case X86::COND_NE: return true;
3782 case X86::COND_B: return true;
3783 case X86::COND_A: return true;
3784 case X86::COND_BE: return true;
3785 case X86::COND_AE: return true;
3787 llvm_unreachable("covered switch fell through?!");
3790 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3791 /// specific condition code, returning the condition code and the LHS/RHS of the
3792 /// comparison to make.
3793 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3794 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3796 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3797 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3798 // X > -1 -> X == 0, jump !sign.
3799 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3800 return X86::COND_NS;
3802 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3803 // X < 0 -> X == 0, jump on sign.
3806 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3808 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3809 return X86::COND_LE;
3813 switch (SetCCOpcode) {
3814 default: llvm_unreachable("Invalid integer condition!");
3815 case ISD::SETEQ: return X86::COND_E;
3816 case ISD::SETGT: return X86::COND_G;
3817 case ISD::SETGE: return X86::COND_GE;
3818 case ISD::SETLT: return X86::COND_L;
3819 case ISD::SETLE: return X86::COND_LE;
3820 case ISD::SETNE: return X86::COND_NE;
3821 case ISD::SETULT: return X86::COND_B;
3822 case ISD::SETUGT: return X86::COND_A;
3823 case ISD::SETULE: return X86::COND_BE;
3824 case ISD::SETUGE: return X86::COND_AE;
3828 // First determine if it is required or is profitable to flip the operands.
3830 // If LHS is a foldable load, but RHS is not, flip the condition.
3831 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3832 !ISD::isNON_EXTLoad(RHS.getNode())) {
3833 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3834 std::swap(LHS, RHS);
3837 switch (SetCCOpcode) {
3843 std::swap(LHS, RHS);
3847 // On a floating point condition, the flags are set as follows:
3849 // 0 | 0 | 0 | X > Y
3850 // 0 | 0 | 1 | X < Y
3851 // 1 | 0 | 0 | X == Y
3852 // 1 | 1 | 1 | unordered
3853 switch (SetCCOpcode) {
3854 default: llvm_unreachable("Condcode should be pre-legalized away");
3856 case ISD::SETEQ: return X86::COND_E;
3857 case ISD::SETOLT: // flipped
3859 case ISD::SETGT: return X86::COND_A;
3860 case ISD::SETOLE: // flipped
3862 case ISD::SETGE: return X86::COND_AE;
3863 case ISD::SETUGT: // flipped
3865 case ISD::SETLT: return X86::COND_B;
3866 case ISD::SETUGE: // flipped
3868 case ISD::SETLE: return X86::COND_BE;
3870 case ISD::SETNE: return X86::COND_NE;
3871 case ISD::SETUO: return X86::COND_P;
3872 case ISD::SETO: return X86::COND_NP;
3874 case ISD::SETUNE: return X86::COND_INVALID;
3878 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3879 /// code. Current x86 isa includes the following FP cmov instructions:
3880 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3881 static bool hasFPCMov(unsigned X86CC) {
3897 /// isFPImmLegal - Returns true if the target can instruction select the
3898 /// specified FP immediate natively. If false, the legalizer will
3899 /// materialize the FP immediate as a load from a constant pool.
3900 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3901 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3902 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3908 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3909 ISD::LoadExtType ExtTy,
3911 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3912 // relocation target a movq or addq instruction: don't let the load shrink.
3913 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3914 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3915 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3916 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3920 /// \brief Returns true if it is beneficial to convert a load of a constant
3921 /// to just the constant itself.
3922 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3924 assert(Ty->isIntegerTy());
3926 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3927 if (BitSize == 0 || BitSize > 64)
3932 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3933 unsigned Index) const {
3934 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3937 return (Index == 0 || Index == ResVT.getVectorNumElements());
3940 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3941 // Speculate cttz only if we can directly use TZCNT.
3942 return Subtarget->hasBMI();
3945 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3946 // Speculate ctlz only if we can directly use LZCNT.
3947 return Subtarget->hasLZCNT();
3950 /// isUndefInRange - Return true if every element in Mask, beginning
3951 /// from position Pos and ending in Pos+Size is undef.
3952 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3953 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
3959 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3960 /// the specified range (L, H].
3961 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3962 return (Val < 0) || (Val >= Low && Val < Hi);
3965 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3966 /// specified value.
3967 static bool isUndefOrEqual(int Val, int CmpVal) {
3968 return (Val < 0 || Val == CmpVal);
3971 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3972 /// from position Pos and ending in Pos+Size, falls within the specified
3973 /// sequential range (Low, Low+Size]. or is undef.
3974 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3975 unsigned Pos, unsigned Size, int Low) {
3976 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3977 if (!isUndefOrEqual(Mask[i], Low))
3982 /// isVEXTRACTIndex - Return true if the specified
3983 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3984 /// suitable for instruction that extract 128 or 256 bit vectors
3985 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3986 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3987 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3990 // The index should be aligned on a vecWidth-bit boundary.
3992 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3994 MVT VT = N->getSimpleValueType(0);
3995 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3996 bool Result = (Index * ElSize) % vecWidth == 0;
4001 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4002 /// operand specifies a subvector insert that is suitable for input to
4003 /// insertion of 128 or 256-bit subvectors
4004 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4005 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4006 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4008 // The index should be aligned on a vecWidth-bit boundary.
4010 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4012 MVT VT = N->getSimpleValueType(0);
4013 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4014 bool Result = (Index * ElSize) % vecWidth == 0;
4019 bool X86::isVINSERT128Index(SDNode *N) {
4020 return isVINSERTIndex(N, 128);
4023 bool X86::isVINSERT256Index(SDNode *N) {
4024 return isVINSERTIndex(N, 256);
4027 bool X86::isVEXTRACT128Index(SDNode *N) {
4028 return isVEXTRACTIndex(N, 128);
4031 bool X86::isVEXTRACT256Index(SDNode *N) {
4032 return isVEXTRACTIndex(N, 256);
4035 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4036 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4037 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4038 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4041 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4043 MVT VecVT = N->getOperand(0).getSimpleValueType();
4044 MVT ElVT = VecVT.getVectorElementType();
4046 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4047 return Index / NumElemsPerChunk;
4050 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4051 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4052 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4053 llvm_unreachable("Illegal insert subvector for VINSERT");
4056 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4058 MVT VecVT = N->getSimpleValueType(0);
4059 MVT ElVT = VecVT.getVectorElementType();
4061 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4062 return Index / NumElemsPerChunk;
4065 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4066 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4067 /// and VINSERTI128 instructions.
4068 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4069 return getExtractVEXTRACTImmediate(N, 128);
4072 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4073 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4074 /// and VINSERTI64x4 instructions.
4075 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4076 return getExtractVEXTRACTImmediate(N, 256);
4079 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4080 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4081 /// and VINSERTI128 instructions.
4082 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4083 return getInsertVINSERTImmediate(N, 128);
4086 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4087 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4088 /// and VINSERTI64x4 instructions.
4089 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4090 return getInsertVINSERTImmediate(N, 256);
4093 /// isZero - Returns true if Elt is a constant integer zero
4094 static bool isZero(SDValue V) {
4095 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4096 return C && C->isNullValue();
4099 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4101 bool X86::isZeroNode(SDValue Elt) {
4104 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4105 return CFP->getValueAPF().isPosZero();
4109 /// getZeroVector - Returns a vector of specified type with all zero elements.
4111 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4112 SelectionDAG &DAG, SDLoc dl) {
4113 assert(VT.isVector() && "Expected a vector type");
4115 // Always build SSE zero vectors as <4 x i32> bitcasted
4116 // to their dest type. This ensures they get CSE'd.
4118 if (VT.is128BitVector()) { // SSE
4119 if (Subtarget->hasSSE2()) { // SSE2
4120 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4121 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4123 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4124 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4126 } else if (VT.is256BitVector()) { // AVX
4127 if (Subtarget->hasInt256()) { // AVX2
4128 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4129 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4130 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4132 // 256-bit logic and arithmetic instructions in AVX are all
4133 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4134 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4135 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4136 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4138 } else if (VT.is512BitVector()) { // AVX-512
4139 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4140 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4141 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4142 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4143 } else if (VT.getScalarType() == MVT::i1) {
4145 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4146 && "Unexpected vector type");
4147 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4148 && "Unexpected vector type");
4149 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4150 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4151 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4153 llvm_unreachable("Unexpected vector type");
4155 return DAG.getBitcast(VT, Vec);
4158 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4159 SelectionDAG &DAG, SDLoc dl,
4160 unsigned vectorWidth) {
4161 assert((vectorWidth == 128 || vectorWidth == 256) &&
4162 "Unsupported vector width");
4163 EVT VT = Vec.getValueType();
4164 EVT ElVT = VT.getVectorElementType();
4165 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4166 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4167 VT.getVectorNumElements()/Factor);
4169 // Extract from UNDEF is UNDEF.
4170 if (Vec.getOpcode() == ISD::UNDEF)
4171 return DAG.getUNDEF(ResultVT);
4173 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4174 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4176 // This is the index of the first element of the vectorWidth-bit chunk
4178 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4181 // If the input is a buildvector just emit a smaller one.
4182 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4183 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4184 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4187 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4188 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4191 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4192 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4193 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4194 /// instructions or a simple subregister reference. Idx is an index in the
4195 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4196 /// lowering EXTRACT_VECTOR_ELT operations easier.
4197 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4198 SelectionDAG &DAG, SDLoc dl) {
4199 assert((Vec.getValueType().is256BitVector() ||
4200 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4201 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4204 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4205 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4206 SelectionDAG &DAG, SDLoc dl) {
4207 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4208 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4211 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4212 unsigned IdxVal, SelectionDAG &DAG,
4213 SDLoc dl, unsigned vectorWidth) {
4214 assert((vectorWidth == 128 || vectorWidth == 256) &&
4215 "Unsupported vector width");
4216 // Inserting UNDEF is Result
4217 if (Vec.getOpcode() == ISD::UNDEF)
4219 EVT VT = Vec.getValueType();
4220 EVT ElVT = VT.getVectorElementType();
4221 EVT ResultVT = Result.getValueType();
4223 // Insert the relevant vectorWidth bits.
4224 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4226 // This is the index of the first element of the vectorWidth-bit chunk
4228 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4231 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4232 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4235 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4236 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4237 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4238 /// simple superregister reference. Idx is an index in the 128 bits
4239 /// we want. It need not be aligned to a 128-bit boundary. That makes
4240 /// lowering INSERT_VECTOR_ELT operations easier.
4241 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4242 SelectionDAG &DAG, SDLoc dl) {
4243 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4245 // For insertion into the zero index (low half) of a 256-bit vector, it is
4246 // more efficient to generate a blend with immediate instead of an insert*128.
4247 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4248 // extend the subvector to the size of the result vector. Make sure that
4249 // we are not recursing on that node by checking for undef here.
4250 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4251 Result.getOpcode() != ISD::UNDEF) {
4252 EVT ResultVT = Result.getValueType();
4253 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4254 SDValue Undef = DAG.getUNDEF(ResultVT);
4255 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4258 // The blend instruction, and therefore its mask, depend on the data type.
4259 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4260 if (ScalarType.isFloatingPoint()) {
4261 // Choose either vblendps (float) or vblendpd (double).
4262 unsigned ScalarSize = ScalarType.getSizeInBits();
4263 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4264 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4265 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4266 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4269 const X86Subtarget &Subtarget =
4270 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4272 // AVX2 is needed for 256-bit integer blend support.
4273 // Integers must be cast to 32-bit because there is only vpblendd;
4274 // vpblendw can't be used for this because it has a handicapped mask.
4276 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4277 // is still more efficient than using the wrong domain vinsertf128 that
4278 // will be created by InsertSubVector().
4279 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4281 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4282 Vec256 = DAG.getBitcast(CastVT, Vec256);
4283 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4284 return DAG.getBitcast(ResultVT, Vec256);
4287 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4290 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4291 SelectionDAG &DAG, SDLoc dl) {
4292 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4293 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4296 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4297 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4298 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4299 /// large BUILD_VECTORS.
4300 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4301 unsigned NumElems, SelectionDAG &DAG,
4303 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4304 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4307 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4308 unsigned NumElems, SelectionDAG &DAG,
4310 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4311 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4314 /// getOnesVector - Returns a vector of specified type with all bits set.
4315 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4316 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4317 /// Then bitcast to their original type, ensuring they get CSE'd.
4318 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4320 assert(VT.isVector() && "Expected a vector type");
4322 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4324 if (VT.is256BitVector()) {
4325 if (HasInt256) { // AVX2
4326 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4327 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4329 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4330 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4332 } else if (VT.is128BitVector()) {
4333 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4335 llvm_unreachable("Unexpected vector type");
4337 return DAG.getBitcast(VT, Vec);
4340 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4341 /// operation of specified width.
4342 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4344 unsigned NumElems = VT.getVectorNumElements();
4345 SmallVector<int, 8> Mask;
4346 Mask.push_back(NumElems);
4347 for (unsigned i = 1; i != NumElems; ++i)
4349 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4352 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4353 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4355 unsigned NumElems = VT.getVectorNumElements();
4356 SmallVector<int, 8> Mask;
4357 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4359 Mask.push_back(i + NumElems);
4361 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4364 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4365 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4367 unsigned NumElems = VT.getVectorNumElements();
4368 SmallVector<int, 8> Mask;
4369 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4370 Mask.push_back(i + Half);
4371 Mask.push_back(i + NumElems + Half);
4373 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4376 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4377 /// vector of zero or undef vector. This produces a shuffle where the low
4378 /// element of V2 is swizzled into the zero/undef vector, landing at element
4379 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4380 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4382 const X86Subtarget *Subtarget,
4383 SelectionDAG &DAG) {
4384 MVT VT = V2.getSimpleValueType();
4386 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4387 unsigned NumElems = VT.getVectorNumElements();
4388 SmallVector<int, 16> MaskVec;
4389 for (unsigned i = 0; i != NumElems; ++i)
4390 // If this is the insertion idx, put the low elt of V2 here.
4391 MaskVec.push_back(i == Idx ? NumElems : i);
4392 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4395 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4396 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4397 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4398 /// shuffles which use a single input multiple times, and in those cases it will
4399 /// adjust the mask to only have indices within that single input.
4400 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4401 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4402 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4403 unsigned NumElems = VT.getVectorNumElements();
4407 bool IsFakeUnary = false;
4408 switch(N->getOpcode()) {
4409 case X86ISD::BLENDI:
4410 ImmN = N->getOperand(N->getNumOperands()-1);
4411 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4414 ImmN = N->getOperand(N->getNumOperands()-1);
4415 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4416 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4418 case X86ISD::UNPCKH:
4419 DecodeUNPCKHMask(VT, Mask);
4420 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4422 case X86ISD::UNPCKL:
4423 DecodeUNPCKLMask(VT, Mask);
4424 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4426 case X86ISD::MOVHLPS:
4427 DecodeMOVHLPSMask(NumElems, Mask);
4428 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4430 case X86ISD::MOVLHPS:
4431 DecodeMOVLHPSMask(NumElems, Mask);
4432 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4434 case X86ISD::PALIGNR:
4435 ImmN = N->getOperand(N->getNumOperands()-1);
4436 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4438 case X86ISD::PSHUFD:
4439 case X86ISD::VPERMILPI:
4440 ImmN = N->getOperand(N->getNumOperands()-1);
4441 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4444 case X86ISD::PSHUFHW:
4445 ImmN = N->getOperand(N->getNumOperands()-1);
4446 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4449 case X86ISD::PSHUFLW:
4450 ImmN = N->getOperand(N->getNumOperands()-1);
4451 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4454 case X86ISD::PSHUFB: {
4456 SDValue MaskNode = N->getOperand(1);
4457 while (MaskNode->getOpcode() == ISD::BITCAST)
4458 MaskNode = MaskNode->getOperand(0);
4460 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4461 // If we have a build-vector, then things are easy.
4462 EVT VT = MaskNode.getValueType();
4463 assert(VT.isVector() &&
4464 "Can't produce a non-vector with a build_vector!");
4465 if (!VT.isInteger())
4468 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4470 SmallVector<uint64_t, 32> RawMask;
4471 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4472 SDValue Op = MaskNode->getOperand(i);
4473 if (Op->getOpcode() == ISD::UNDEF) {
4474 RawMask.push_back((uint64_t)SM_SentinelUndef);
4477 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4480 APInt MaskElement = CN->getAPIntValue();
4482 // We now have to decode the element which could be any integer size and
4483 // extract each byte of it.
4484 for (int j = 0; j < NumBytesPerElement; ++j) {
4485 // Note that this is x86 and so always little endian: the low byte is
4486 // the first byte of the mask.
4487 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4488 MaskElement = MaskElement.lshr(8);
4491 DecodePSHUFBMask(RawMask, Mask);
4495 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4499 SDValue Ptr = MaskLoad->getBasePtr();
4500 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4501 Ptr->getOpcode() == X86ISD::WrapperRIP)
4502 Ptr = Ptr->getOperand(0);
4504 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4505 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4508 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4509 DecodePSHUFBMask(C, Mask);
4517 case X86ISD::VPERMI:
4518 ImmN = N->getOperand(N->getNumOperands()-1);
4519 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4526 case X86ISD::VPERM2X128:
4527 ImmN = N->getOperand(N->getNumOperands()-1);
4528 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529 if (Mask.empty()) return false;
4530 // Mask only contains negative index if an element is zero.
4531 if (std::any_of(Mask.begin(), Mask.end(),
4532 [](int M){ return M == SM_SentinelZero; }))
4535 case X86ISD::MOVSLDUP:
4536 DecodeMOVSLDUPMask(VT, Mask);
4539 case X86ISD::MOVSHDUP:
4540 DecodeMOVSHDUPMask(VT, Mask);
4543 case X86ISD::MOVDDUP:
4544 DecodeMOVDDUPMask(VT, Mask);
4547 case X86ISD::MOVLHPD:
4548 case X86ISD::MOVLPD:
4549 case X86ISD::MOVLPS:
4550 // Not yet implemented
4552 default: llvm_unreachable("unknown target shuffle node");
4555 // If we have a fake unary shuffle, the shuffle mask is spread across two
4556 // inputs that are actually the same node. Re-map the mask to always point
4557 // into the first input.
4560 if (M >= (int)Mask.size())
4566 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4567 /// element of the result of the vector shuffle.
4568 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4571 return SDValue(); // Limit search depth.
4573 SDValue V = SDValue(N, 0);
4574 EVT VT = V.getValueType();
4575 unsigned Opcode = V.getOpcode();
4577 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4578 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4579 int Elt = SV->getMaskElt(Index);
4582 return DAG.getUNDEF(VT.getVectorElementType());
4584 unsigned NumElems = VT.getVectorNumElements();
4585 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4586 : SV->getOperand(1);
4587 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4590 // Recurse into target specific vector shuffles to find scalars.
4591 if (isTargetShuffle(Opcode)) {
4592 MVT ShufVT = V.getSimpleValueType();
4593 unsigned NumElems = ShufVT.getVectorNumElements();
4594 SmallVector<int, 16> ShuffleMask;
4597 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4600 int Elt = ShuffleMask[Index];
4602 return DAG.getUNDEF(ShufVT.getVectorElementType());
4604 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4606 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4610 // Actual nodes that may contain scalar elements
4611 if (Opcode == ISD::BITCAST) {
4612 V = V.getOperand(0);
4613 EVT SrcVT = V.getValueType();
4614 unsigned NumElems = VT.getVectorNumElements();
4616 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4620 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4621 return (Index == 0) ? V.getOperand(0)
4622 : DAG.getUNDEF(VT.getVectorElementType());
4624 if (V.getOpcode() == ISD::BUILD_VECTOR)
4625 return V.getOperand(Index);
4630 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4632 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4633 unsigned NumNonZero, unsigned NumZero,
4635 const X86Subtarget* Subtarget,
4636 const TargetLowering &TLI) {
4644 // SSE4.1 - use PINSRB to insert each byte directly.
4645 if (Subtarget->hasSSE41()) {
4646 for (unsigned i = 0; i < 16; ++i) {
4647 bool isNonZero = (NonZeros & (1 << i)) != 0;
4651 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4653 V = DAG.getUNDEF(MVT::v16i8);
4656 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4657 MVT::v16i8, V, Op.getOperand(i),
4658 DAG.getIntPtrConstant(i, dl));
4665 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4666 for (unsigned i = 0; i < 16; ++i) {
4667 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4668 if (ThisIsNonZero && First) {
4670 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4672 V = DAG.getUNDEF(MVT::v8i16);
4677 SDValue ThisElt, LastElt;
4678 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4679 if (LastIsNonZero) {
4680 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4681 MVT::i16, Op.getOperand(i-1));
4683 if (ThisIsNonZero) {
4684 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4685 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4686 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4688 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4692 if (ThisElt.getNode())
4693 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4694 DAG.getIntPtrConstant(i/2, dl));
4698 return DAG.getBitcast(MVT::v16i8, V);
4701 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4703 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4704 unsigned NumNonZero, unsigned NumZero,
4706 const X86Subtarget* Subtarget,
4707 const TargetLowering &TLI) {
4714 for (unsigned i = 0; i < 8; ++i) {
4715 bool isNonZero = (NonZeros & (1 << i)) != 0;
4719 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4721 V = DAG.getUNDEF(MVT::v8i16);
4724 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4725 MVT::v8i16, V, Op.getOperand(i),
4726 DAG.getIntPtrConstant(i, dl));
4733 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4734 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4735 const X86Subtarget *Subtarget,
4736 const TargetLowering &TLI) {
4737 // Find all zeroable elements.
4738 std::bitset<4> Zeroable;
4739 for (int i=0; i < 4; ++i) {
4740 SDValue Elt = Op->getOperand(i);
4741 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4743 assert(Zeroable.size() - Zeroable.count() > 1 &&
4744 "We expect at least two non-zero elements!");
4746 // We only know how to deal with build_vector nodes where elements are either
4747 // zeroable or extract_vector_elt with constant index.
4748 SDValue FirstNonZero;
4749 unsigned FirstNonZeroIdx;
4750 for (unsigned i=0; i < 4; ++i) {
4753 SDValue Elt = Op->getOperand(i);
4754 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4755 !isa<ConstantSDNode>(Elt.getOperand(1)))
4757 // Make sure that this node is extracting from a 128-bit vector.
4758 MVT VT = Elt.getOperand(0).getSimpleValueType();
4759 if (!VT.is128BitVector())
4761 if (!FirstNonZero.getNode()) {
4763 FirstNonZeroIdx = i;
4767 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4768 SDValue V1 = FirstNonZero.getOperand(0);
4769 MVT VT = V1.getSimpleValueType();
4771 // See if this build_vector can be lowered as a blend with zero.
4773 unsigned EltMaskIdx, EltIdx;
4775 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4776 if (Zeroable[EltIdx]) {
4777 // The zero vector will be on the right hand side.
4778 Mask[EltIdx] = EltIdx+4;
4782 Elt = Op->getOperand(EltIdx);
4783 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4784 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4785 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4787 Mask[EltIdx] = EltIdx;
4791 // Let the shuffle legalizer deal with blend operations.
4792 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4793 if (V1.getSimpleValueType() != VT)
4794 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4795 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4798 // See if we can lower this build_vector to a INSERTPS.
4799 if (!Subtarget->hasSSE41())
4802 SDValue V2 = Elt.getOperand(0);
4803 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4806 bool CanFold = true;
4807 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4811 SDValue Current = Op->getOperand(i);
4812 SDValue SrcVector = Current->getOperand(0);
4815 CanFold = SrcVector == V1 &&
4816 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4822 assert(V1.getNode() && "Expected at least two non-zero elements!");
4823 if (V1.getSimpleValueType() != MVT::v4f32)
4824 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4825 if (V2.getSimpleValueType() != MVT::v4f32)
4826 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4828 // Ok, we can emit an INSERTPS instruction.
4829 unsigned ZMask = Zeroable.to_ulong();
4831 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4832 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4834 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4835 DAG.getIntPtrConstant(InsertPSMask, DL));
4836 return DAG.getBitcast(VT, Result);
4839 /// Return a vector logical shift node.
4840 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4841 unsigned NumBits, SelectionDAG &DAG,
4842 const TargetLowering &TLI, SDLoc dl) {
4843 assert(VT.is128BitVector() && "Unknown type for VShift");
4844 MVT ShVT = MVT::v2i64;
4845 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4846 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4847 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4848 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4849 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4850 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4854 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4856 // Check if the scalar load can be widened into a vector load. And if
4857 // the address is "base + cst" see if the cst can be "absorbed" into
4858 // the shuffle mask.
4859 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4860 SDValue Ptr = LD->getBasePtr();
4861 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4863 EVT PVT = LD->getValueType(0);
4864 if (PVT != MVT::i32 && PVT != MVT::f32)
4869 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4870 FI = FINode->getIndex();
4872 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4873 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4874 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4875 Offset = Ptr.getConstantOperandVal(1);
4876 Ptr = Ptr.getOperand(0);
4881 // FIXME: 256-bit vector instructions don't require a strict alignment,
4882 // improve this code to support it better.
4883 unsigned RequiredAlign = VT.getSizeInBits()/8;
4884 SDValue Chain = LD->getChain();
4885 // Make sure the stack object alignment is at least 16 or 32.
4886 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4887 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4888 if (MFI->isFixedObjectIndex(FI)) {
4889 // Can't change the alignment. FIXME: It's possible to compute
4890 // the exact stack offset and reference FI + adjust offset instead.
4891 // If someone *really* cares about this. That's the way to implement it.
4894 MFI->setObjectAlignment(FI, RequiredAlign);
4898 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4899 // Ptr + (Offset & ~15).
4902 if ((Offset % RequiredAlign) & 3)
4904 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4907 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4908 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4911 int EltNo = (Offset - StartOffset) >> 2;
4912 unsigned NumElems = VT.getVectorNumElements();
4914 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4915 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4916 LD->getPointerInfo().getWithOffset(StartOffset),
4917 false, false, false, 0);
4919 SmallVector<int, 8> Mask(NumElems, EltNo);
4921 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4927 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4928 /// elements can be replaced by a single large load which has the same value as
4929 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4931 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4933 /// FIXME: we'd also like to handle the case where the last elements are zero
4934 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4935 /// There's even a handy isZeroNode for that purpose.
4936 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4937 SDLoc &DL, SelectionDAG &DAG,
4938 bool isAfterLegalize) {
4939 unsigned NumElems = Elts.size();
4941 LoadSDNode *LDBase = nullptr;
4942 unsigned LastLoadedElt = -1U;
4944 // For each element in the initializer, see if we've found a load or an undef.
4945 // If we don't find an initial load element, or later load elements are
4946 // non-consecutive, bail out.
4947 for (unsigned i = 0; i < NumElems; ++i) {
4948 SDValue Elt = Elts[i];
4949 // Look through a bitcast.
4950 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4951 Elt = Elt.getOperand(0);
4952 if (!Elt.getNode() ||
4953 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4956 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4958 LDBase = cast<LoadSDNode>(Elt.getNode());
4962 if (Elt.getOpcode() == ISD::UNDEF)
4965 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4966 EVT LdVT = Elt.getValueType();
4967 // Each loaded element must be the correct fractional portion of the
4968 // requested vector load.
4969 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4971 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4976 // If we have found an entire vector of loads and undefs, then return a large
4977 // load of the entire vector width starting at the base pointer. If we found
4978 // consecutive loads for the low half, generate a vzext_load node.
4979 if (LastLoadedElt == NumElems - 1) {
4980 assert(LDBase && "Did not find base load for merging consecutive loads");
4981 EVT EltVT = LDBase->getValueType(0);
4982 // Ensure that the input vector size for the merged loads matches the
4983 // cumulative size of the input elements.
4984 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4987 if (isAfterLegalize &&
4988 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4991 SDValue NewLd = SDValue();
4993 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4994 LDBase->getPointerInfo(), LDBase->isVolatile(),
4995 LDBase->isNonTemporal(), LDBase->isInvariant(),
4996 LDBase->getAlignment());
4998 if (LDBase->hasAnyUseOfValue(1)) {
4999 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5001 SDValue(NewLd.getNode(), 1));
5002 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5003 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5004 SDValue(NewLd.getNode(), 1));
5010 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5011 //of a v4i32 / v4f32. It's probably worth generalizing.
5012 EVT EltVT = VT.getVectorElementType();
5013 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5014 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5015 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5016 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5018 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5019 LDBase->getPointerInfo(),
5020 LDBase->getAlignment(),
5021 false/*isVolatile*/, true/*ReadMem*/,
5024 // Make sure the newly-created LOAD is in the same position as LDBase in
5025 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5026 // update uses of LDBase's output chain to use the TokenFactor.
5027 if (LDBase->hasAnyUseOfValue(1)) {
5028 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5029 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5030 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5031 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5032 SDValue(ResNode.getNode(), 1));
5035 return DAG.getBitcast(VT, ResNode);
5040 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5041 /// to generate a splat value for the following cases:
5042 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5043 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5044 /// a scalar load, or a constant.
5045 /// The VBROADCAST node is returned when a pattern is found,
5046 /// or SDValue() otherwise.
5047 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5048 SelectionDAG &DAG) {
5049 // VBROADCAST requires AVX.
5050 // TODO: Splats could be generated for non-AVX CPUs using SSE
5051 // instructions, but there's less potential gain for only 128-bit vectors.
5052 if (!Subtarget->hasAVX())
5055 MVT VT = Op.getSimpleValueType();
5058 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5059 "Unsupported vector type for broadcast.");
5064 switch (Op.getOpcode()) {
5066 // Unknown pattern found.
5069 case ISD::BUILD_VECTOR: {
5070 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5071 BitVector UndefElements;
5072 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5074 // We need a splat of a single value to use broadcast, and it doesn't
5075 // make any sense if the value is only in one element of the vector.
5076 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5080 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5081 Ld.getOpcode() == ISD::ConstantFP);
5083 // Make sure that all of the users of a non-constant load are from the
5084 // BUILD_VECTOR node.
5085 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5090 case ISD::VECTOR_SHUFFLE: {
5091 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5093 // Shuffles must have a splat mask where the first element is
5095 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5098 SDValue Sc = Op.getOperand(0);
5099 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5100 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5102 if (!Subtarget->hasInt256())
5105 // Use the register form of the broadcast instruction available on AVX2.
5106 if (VT.getSizeInBits() >= 256)
5107 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5108 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5111 Ld = Sc.getOperand(0);
5112 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5113 Ld.getOpcode() == ISD::ConstantFP);
5115 // The scalar_to_vector node and the suspected
5116 // load node must have exactly one user.
5117 // Constants may have multiple users.
5119 // AVX-512 has register version of the broadcast
5120 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5121 Ld.getValueType().getSizeInBits() >= 32;
5122 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5129 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5130 bool IsGE256 = (VT.getSizeInBits() >= 256);
5132 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5133 // instruction to save 8 or more bytes of constant pool data.
5134 // TODO: If multiple splats are generated to load the same constant,
5135 // it may be detrimental to overall size. There needs to be a way to detect
5136 // that condition to know if this is truly a size win.
5137 const Function *F = DAG.getMachineFunction().getFunction();
5138 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5140 // Handle broadcasting a single constant scalar from the constant pool
5142 // On Sandybridge (no AVX2), it is still better to load a constant vector
5143 // from the constant pool and not to broadcast it from a scalar.
5144 // But override that restriction when optimizing for size.
5145 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5146 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5147 EVT CVT = Ld.getValueType();
5148 assert(!CVT.isVector() && "Must not broadcast a vector type");
5150 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5151 // For size optimization, also splat v2f64 and v2i64, and for size opt
5152 // with AVX2, also splat i8 and i16.
5153 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5154 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5155 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5156 const Constant *C = nullptr;
5157 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5158 C = CI->getConstantIntValue();
5159 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5160 C = CF->getConstantFPValue();
5162 assert(C && "Invalid constant type");
5164 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5165 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5166 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5167 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5168 MachinePointerInfo::getConstantPool(),
5169 false, false, false, Alignment);
5171 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5175 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5177 // Handle AVX2 in-register broadcasts.
5178 if (!IsLoad && Subtarget->hasInt256() &&
5179 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5180 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5182 // The scalar source must be a normal load.
5186 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5187 (Subtarget->hasVLX() && ScalarSize == 64))
5188 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5190 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5191 // double since there is no vbroadcastsd xmm
5192 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5193 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5194 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5197 // Unsupported broadcast.
5201 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5202 /// underlying vector and index.
5204 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5206 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5208 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5209 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5212 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5214 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5216 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5217 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5220 // In this case the vector is the extract_subvector expression and the index
5221 // is 2, as specified by the shuffle.
5222 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5223 SDValue ShuffleVec = SVOp->getOperand(0);
5224 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5225 assert(ShuffleVecVT.getVectorElementType() ==
5226 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5228 int ShuffleIdx = SVOp->getMaskElt(Idx);
5229 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5230 ExtractedFromVec = ShuffleVec;
5236 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5237 MVT VT = Op.getSimpleValueType();
5239 // Skip if insert_vec_elt is not supported.
5240 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5241 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5245 unsigned NumElems = Op.getNumOperands();
5249 SmallVector<unsigned, 4> InsertIndices;
5250 SmallVector<int, 8> Mask(NumElems, -1);
5252 for (unsigned i = 0; i != NumElems; ++i) {
5253 unsigned Opc = Op.getOperand(i).getOpcode();
5255 if (Opc == ISD::UNDEF)
5258 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5259 // Quit if more than 1 elements need inserting.
5260 if (InsertIndices.size() > 1)
5263 InsertIndices.push_back(i);
5267 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5268 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5269 // Quit if non-constant index.
5270 if (!isa<ConstantSDNode>(ExtIdx))
5272 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5274 // Quit if extracted from vector of different type.
5275 if (ExtractedFromVec.getValueType() != VT)
5278 if (!VecIn1.getNode())
5279 VecIn1 = ExtractedFromVec;
5280 else if (VecIn1 != ExtractedFromVec) {
5281 if (!VecIn2.getNode())
5282 VecIn2 = ExtractedFromVec;
5283 else if (VecIn2 != ExtractedFromVec)
5284 // Quit if more than 2 vectors to shuffle
5288 if (ExtractedFromVec == VecIn1)
5290 else if (ExtractedFromVec == VecIn2)
5291 Mask[i] = Idx + NumElems;
5294 if (!VecIn1.getNode())
5297 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5298 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5299 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5300 unsigned Idx = InsertIndices[i];
5301 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5302 DAG.getIntPtrConstant(Idx, DL));
5308 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5309 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5310 Op.getScalarValueSizeInBits() == 1 &&
5311 "Can not convert non-constant vector");
5312 uint64_t Immediate = 0;
5313 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5314 SDValue In = Op.getOperand(idx);
5315 if (In.getOpcode() != ISD::UNDEF)
5316 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5320 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5321 return DAG.getConstant(Immediate, dl, VT);
5323 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5325 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5327 MVT VT = Op.getSimpleValueType();
5328 assert((VT.getVectorElementType() == MVT::i1) &&
5329 "Unexpected type in LowerBUILD_VECTORvXi1!");
5332 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5333 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5334 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5335 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5338 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5339 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5340 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5341 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5344 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5345 SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5346 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5347 return DAG.getBitcast(VT, Imm);
5348 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5349 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5350 DAG.getIntPtrConstant(0, dl));
5353 // Vector has one or more non-const elements
5354 uint64_t Immediate = 0;
5355 SmallVector<unsigned, 16> NonConstIdx;
5356 bool IsSplat = true;
5357 bool HasConstElts = false;
5359 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5360 SDValue In = Op.getOperand(idx);
5361 if (In.getOpcode() == ISD::UNDEF)
5363 if (!isa<ConstantSDNode>(In))
5364 NonConstIdx.push_back(idx);
5366 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5367 HasConstElts = true;
5371 else if (In != Op.getOperand(SplatIdx))
5375 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5377 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5378 DAG.getConstant(1, dl, VT),
5379 DAG.getConstant(0, dl, VT));
5381 // insert elements one by one
5385 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5386 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5388 else if (HasConstElts)
5389 Imm = DAG.getConstant(0, dl, VT);
5391 Imm = DAG.getUNDEF(VT);
5392 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5393 DstVec = DAG.getBitcast(VT, Imm);
5395 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5396 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5397 DAG.getIntPtrConstant(0, dl));
5400 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5401 unsigned InsertIdx = NonConstIdx[i];
5402 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5403 Op.getOperand(InsertIdx),
5404 DAG.getIntPtrConstant(InsertIdx, dl));
5409 /// \brief Return true if \p N implements a horizontal binop and return the
5410 /// operands for the horizontal binop into V0 and V1.
5412 /// This is a helper function of LowerToHorizontalOp().
5413 /// This function checks that the build_vector \p N in input implements a
5414 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5415 /// operation to match.
5416 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5417 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5418 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5421 /// This function only analyzes elements of \p N whose indices are
5422 /// in range [BaseIdx, LastIdx).
5423 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5425 unsigned BaseIdx, unsigned LastIdx,
5426 SDValue &V0, SDValue &V1) {
5427 EVT VT = N->getValueType(0);
5429 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5430 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5431 "Invalid Vector in input!");
5433 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5434 bool CanFold = true;
5435 unsigned ExpectedVExtractIdx = BaseIdx;
5436 unsigned NumElts = LastIdx - BaseIdx;
5437 V0 = DAG.getUNDEF(VT);
5438 V1 = DAG.getUNDEF(VT);
5440 // Check if N implements a horizontal binop.
5441 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5442 SDValue Op = N->getOperand(i + BaseIdx);
5445 if (Op->getOpcode() == ISD::UNDEF) {
5446 // Update the expected vector extract index.
5447 if (i * 2 == NumElts)
5448 ExpectedVExtractIdx = BaseIdx;
5449 ExpectedVExtractIdx += 2;
5453 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5458 SDValue Op0 = Op.getOperand(0);
5459 SDValue Op1 = Op.getOperand(1);
5461 // Try to match the following pattern:
5462 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5463 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5464 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5465 Op0.getOperand(0) == Op1.getOperand(0) &&
5466 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5467 isa<ConstantSDNode>(Op1.getOperand(1)));
5471 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5472 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5474 if (i * 2 < NumElts) {
5475 if (V0.getOpcode() == ISD::UNDEF) {
5476 V0 = Op0.getOperand(0);
5477 if (V0.getValueType() != VT)
5481 if (V1.getOpcode() == ISD::UNDEF) {
5482 V1 = Op0.getOperand(0);
5483 if (V1.getValueType() != VT)
5486 if (i * 2 == NumElts)
5487 ExpectedVExtractIdx = BaseIdx;
5490 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5491 if (I0 == ExpectedVExtractIdx)
5492 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5493 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5494 // Try to match the following dag sequence:
5495 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5496 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5500 ExpectedVExtractIdx += 2;
5506 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5507 /// a concat_vector.
5509 /// This is a helper function of LowerToHorizontalOp().
5510 /// This function expects two 256-bit vectors called V0 and V1.
5511 /// At first, each vector is split into two separate 128-bit vectors.
5512 /// Then, the resulting 128-bit vectors are used to implement two
5513 /// horizontal binary operations.
5515 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5517 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5518 /// the two new horizontal binop.
5519 /// When Mode is set, the first horizontal binop dag node would take as input
5520 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5521 /// horizontal binop dag node would take as input the lower 128-bit of V1
5522 /// and the upper 128-bit of V1.
5524 /// HADD V0_LO, V0_HI
5525 /// HADD V1_LO, V1_HI
5527 /// Otherwise, the first horizontal binop dag node takes as input the lower
5528 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5529 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5531 /// HADD V0_LO, V1_LO
5532 /// HADD V0_HI, V1_HI
5534 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5535 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5536 /// the upper 128-bits of the result.
5537 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5538 SDLoc DL, SelectionDAG &DAG,
5539 unsigned X86Opcode, bool Mode,
5540 bool isUndefLO, bool isUndefHI) {
5541 EVT VT = V0.getValueType();
5542 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5543 "Invalid nodes in input!");
5545 unsigned NumElts = VT.getVectorNumElements();
5546 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5547 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5548 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5549 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5550 EVT NewVT = V0_LO.getValueType();
5552 SDValue LO = DAG.getUNDEF(NewVT);
5553 SDValue HI = DAG.getUNDEF(NewVT);
5556 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5557 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5558 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5559 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5560 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5562 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5563 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5564 V1_LO->getOpcode() != ISD::UNDEF))
5565 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5567 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5568 V1_HI->getOpcode() != ISD::UNDEF))
5569 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5572 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5575 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5577 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5578 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5579 EVT VT = BV->getValueType(0);
5580 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5581 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5585 unsigned NumElts = VT.getVectorNumElements();
5586 SDValue InVec0 = DAG.getUNDEF(VT);
5587 SDValue InVec1 = DAG.getUNDEF(VT);
5589 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5590 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5592 // Odd-numbered elements in the input build vector are obtained from
5593 // adding two integer/float elements.
5594 // Even-numbered elements in the input build vector are obtained from
5595 // subtracting two integer/float elements.
5596 unsigned ExpectedOpcode = ISD::FSUB;
5597 unsigned NextExpectedOpcode = ISD::FADD;
5598 bool AddFound = false;
5599 bool SubFound = false;
5601 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5602 SDValue Op = BV->getOperand(i);
5604 // Skip 'undef' values.
5605 unsigned Opcode = Op.getOpcode();
5606 if (Opcode == ISD::UNDEF) {
5607 std::swap(ExpectedOpcode, NextExpectedOpcode);
5611 // Early exit if we found an unexpected opcode.
5612 if (Opcode != ExpectedOpcode)
5615 SDValue Op0 = Op.getOperand(0);
5616 SDValue Op1 = Op.getOperand(1);
5618 // Try to match the following pattern:
5619 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5620 // Early exit if we cannot match that sequence.
5621 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5622 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5623 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5624 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5625 Op0.getOperand(1) != Op1.getOperand(1))
5628 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5632 // We found a valid add/sub node. Update the information accordingly.
5638 // Update InVec0 and InVec1.
5639 if (InVec0.getOpcode() == ISD::UNDEF) {
5640 InVec0 = Op0.getOperand(0);
5641 if (InVec0.getValueType() != VT)
5644 if (InVec1.getOpcode() == ISD::UNDEF) {
5645 InVec1 = Op1.getOperand(0);
5646 if (InVec1.getValueType() != VT)
5650 // Make sure that operands in input to each add/sub node always
5651 // come from a same pair of vectors.
5652 if (InVec0 != Op0.getOperand(0)) {
5653 if (ExpectedOpcode == ISD::FSUB)
5656 // FADD is commutable. Try to commute the operands
5657 // and then test again.
5658 std::swap(Op0, Op1);
5659 if (InVec0 != Op0.getOperand(0))
5663 if (InVec1 != Op1.getOperand(0))
5666 // Update the pair of expected opcodes.
5667 std::swap(ExpectedOpcode, NextExpectedOpcode);
5670 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5671 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5672 InVec1.getOpcode() != ISD::UNDEF)
5673 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5678 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5679 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5680 const X86Subtarget *Subtarget,
5681 SelectionDAG &DAG) {
5682 EVT VT = BV->getValueType(0);
5683 unsigned NumElts = VT.getVectorNumElements();
5684 unsigned NumUndefsLO = 0;
5685 unsigned NumUndefsHI = 0;
5686 unsigned Half = NumElts/2;
5688 // Count the number of UNDEF operands in the build_vector in input.
5689 for (unsigned i = 0, e = Half; i != e; ++i)
5690 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5693 for (unsigned i = Half, e = NumElts; i != e; ++i)
5694 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5697 // Early exit if this is either a build_vector of all UNDEFs or all the
5698 // operands but one are UNDEF.
5699 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5703 SDValue InVec0, InVec1;
5704 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5705 // Try to match an SSE3 float HADD/HSUB.
5706 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5707 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5709 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5710 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5711 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5712 // Try to match an SSSE3 integer HADD/HSUB.
5713 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5714 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5716 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5717 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5720 if (!Subtarget->hasAVX())
5723 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5724 // Try to match an AVX horizontal add/sub of packed single/double
5725 // precision floating point values from 256-bit vectors.
5726 SDValue InVec2, InVec3;
5727 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5728 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5729 ((InVec0.getOpcode() == ISD::UNDEF ||
5730 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5731 ((InVec1.getOpcode() == ISD::UNDEF ||
5732 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5733 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5735 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5736 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5737 ((InVec0.getOpcode() == ISD::UNDEF ||
5738 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5739 ((InVec1.getOpcode() == ISD::UNDEF ||
5740 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5741 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5742 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5743 // Try to match an AVX2 horizontal add/sub of signed integers.
5744 SDValue InVec2, InVec3;
5746 bool CanFold = true;
5748 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5749 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5750 ((InVec0.getOpcode() == ISD::UNDEF ||
5751 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5752 ((InVec1.getOpcode() == ISD::UNDEF ||
5753 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5754 X86Opcode = X86ISD::HADD;
5755 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5756 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5757 ((InVec0.getOpcode() == ISD::UNDEF ||
5758 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5759 ((InVec1.getOpcode() == ISD::UNDEF ||
5760 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5761 X86Opcode = X86ISD::HSUB;
5766 // Fold this build_vector into a single horizontal add/sub.
5767 // Do this only if the target has AVX2.
5768 if (Subtarget->hasAVX2())
5769 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5771 // Do not try to expand this build_vector into a pair of horizontal
5772 // add/sub if we can emit a pair of scalar add/sub.
5773 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5776 // Convert this build_vector into a pair of horizontal binop followed by
5778 bool isUndefLO = NumUndefsLO == Half;
5779 bool isUndefHI = NumUndefsHI == Half;
5780 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5781 isUndefLO, isUndefHI);
5785 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5786 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5788 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5789 X86Opcode = X86ISD::HADD;
5790 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5791 X86Opcode = X86ISD::HSUB;
5792 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5793 X86Opcode = X86ISD::FHADD;
5794 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5795 X86Opcode = X86ISD::FHSUB;
5799 // Don't try to expand this build_vector into a pair of horizontal add/sub
5800 // if we can simply emit a pair of scalar add/sub.
5801 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5804 // Convert this build_vector into two horizontal add/sub followed by
5806 bool isUndefLO = NumUndefsLO == Half;
5807 bool isUndefHI = NumUndefsHI == Half;
5808 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5809 isUndefLO, isUndefHI);
5816 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5819 MVT VT = Op.getSimpleValueType();
5820 MVT ExtVT = VT.getVectorElementType();
5821 unsigned NumElems = Op.getNumOperands();
5823 // Generate vectors for predicate vectors.
5824 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5825 return LowerBUILD_VECTORvXi1(Op, DAG);
5827 // Vectors containing all zeros can be matched by pxor and xorps later
5828 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5829 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5830 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5831 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5834 return getZeroVector(VT, Subtarget, DAG, dl);
5837 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5838 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5839 // vpcmpeqd on 256-bit vectors.
5840 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5841 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5844 if (!VT.is512BitVector())
5845 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5848 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5849 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5851 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5852 return HorizontalOp;
5853 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5856 unsigned EVTBits = ExtVT.getSizeInBits();
5858 unsigned NumZero = 0;
5859 unsigned NumNonZero = 0;
5860 unsigned NonZeros = 0;
5861 bool IsAllConstants = true;
5862 SmallSet<SDValue, 8> Values;
5863 for (unsigned i = 0; i < NumElems; ++i) {
5864 SDValue Elt = Op.getOperand(i);
5865 if (Elt.getOpcode() == ISD::UNDEF)
5868 if (Elt.getOpcode() != ISD::Constant &&
5869 Elt.getOpcode() != ISD::ConstantFP)
5870 IsAllConstants = false;
5871 if (X86::isZeroNode(Elt))
5874 NonZeros |= (1 << i);
5879 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5880 if (NumNonZero == 0)
5881 return DAG.getUNDEF(VT);
5883 // Special case for single non-zero, non-undef, element.
5884 if (NumNonZero == 1) {
5885 unsigned Idx = countTrailingZeros(NonZeros);
5886 SDValue Item = Op.getOperand(Idx);
5888 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5889 // the value are obviously zero, truncate the value to i32 and do the
5890 // insertion that way. Only do this if the value is non-constant or if the
5891 // value is a constant being inserted into element 0. It is cheaper to do
5892 // a constant pool load than it is to do a movd + shuffle.
5893 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5894 (!IsAllConstants || Idx == 0)) {
5895 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5897 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5898 EVT VecVT = MVT::v4i32;
5900 // Truncate the value (which may itself be a constant) to i32, and
5901 // convert it to a vector with movd (S2V+shuffle to zero extend).
5902 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5903 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5904 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5905 Item, Idx * 2, true, Subtarget, DAG));
5909 // If we have a constant or non-constant insertion into the low element of
5910 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5911 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5912 // depending on what the source datatype is.
5915 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5917 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5918 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5919 if (VT.is512BitVector()) {
5920 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5921 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5922 Item, DAG.getIntPtrConstant(0, dl));
5924 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5925 "Expected an SSE value type!");
5926 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5927 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5928 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5931 // We can't directly insert an i8 or i16 into a vector, so zero extend
5933 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5934 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5935 if (VT.is256BitVector()) {
5936 if (Subtarget->hasAVX()) {
5937 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5938 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5940 // Without AVX, we need to extend to a 128-bit vector and then
5941 // insert into the 256-bit vector.
5942 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5943 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5944 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5947 assert(VT.is128BitVector() && "Expected an SSE value type!");
5948 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5949 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5951 return DAG.getBitcast(VT, Item);
5955 // Is it a vector logical left shift?
5956 if (NumElems == 2 && Idx == 1 &&
5957 X86::isZeroNode(Op.getOperand(0)) &&
5958 !X86::isZeroNode(Op.getOperand(1))) {
5959 unsigned NumBits = VT.getSizeInBits();
5960 return getVShift(true, VT,
5961 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5962 VT, Op.getOperand(1)),
5963 NumBits/2, DAG, *this, dl);
5966 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5969 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5970 // is a non-constant being inserted into an element other than the low one,
5971 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5972 // movd/movss) to move this into the low element, then shuffle it into
5974 if (EVTBits == 32) {
5975 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5976 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5980 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5981 if (Values.size() == 1) {
5982 if (EVTBits == 32) {
5983 // Instead of a shuffle like this:
5984 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5985 // Check if it's possible to issue this instead.
5986 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5987 unsigned Idx = countTrailingZeros(NonZeros);
5988 SDValue Item = Op.getOperand(Idx);
5989 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5990 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5995 // A vector full of immediates; various special cases are already
5996 // handled, so this is best done with a single constant-pool load.
6000 // For AVX-length vectors, see if we can use a vector load to get all of the
6001 // elements, otherwise build the individual 128-bit pieces and use
6002 // shuffles to put them in place.
6003 if (VT.is256BitVector() || VT.is512BitVector()) {
6004 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6006 // Check for a build vector of consecutive loads.
6007 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6010 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6012 // Build both the lower and upper subvector.
6013 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6014 makeArrayRef(&V[0], NumElems/2));
6015 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6016 makeArrayRef(&V[NumElems / 2], NumElems/2));
6018 // Recreate the wider vector with the lower and upper part.
6019 if (VT.is256BitVector())
6020 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6021 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6024 // Let legalizer expand 2-wide build_vectors.
6025 if (EVTBits == 64) {
6026 if (NumNonZero == 1) {
6027 // One half is zero or undef.
6028 unsigned Idx = countTrailingZeros(NonZeros);
6029 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6030 Op.getOperand(Idx));
6031 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6036 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6037 if (EVTBits == 8 && NumElems == 16)
6038 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6042 if (EVTBits == 16 && NumElems == 8)
6043 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6047 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6048 if (EVTBits == 32 && NumElems == 4)
6049 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6052 // If element VT is == 32 bits, turn it into a number of shuffles.
6053 SmallVector<SDValue, 8> V(NumElems);
6054 if (NumElems == 4 && NumZero > 0) {
6055 for (unsigned i = 0; i < 4; ++i) {
6056 bool isZero = !(NonZeros & (1 << i));
6058 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6060 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6063 for (unsigned i = 0; i < 2; ++i) {
6064 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6067 V[i] = V[i*2]; // Must be a zero vector.
6070 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6073 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6076 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6081 bool Reverse1 = (NonZeros & 0x3) == 2;
6082 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6086 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6087 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6089 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6092 if (Values.size() > 1 && VT.is128BitVector()) {
6093 // Check for a build vector of consecutive loads.
6094 for (unsigned i = 0; i < NumElems; ++i)
6095 V[i] = Op.getOperand(i);
6097 // Check for elements which are consecutive loads.
6098 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6101 // Check for a build vector from mostly shuffle plus few inserting.
6102 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6105 // For SSE 4.1, use insertps to put the high elements into the low element.
6106 if (Subtarget->hasSSE41()) {
6108 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6109 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6111 Result = DAG.getUNDEF(VT);
6113 for (unsigned i = 1; i < NumElems; ++i) {
6114 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6115 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6116 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6121 // Otherwise, expand into a number of unpckl*, start by extending each of
6122 // our (non-undef) elements to the full vector width with the element in the
6123 // bottom slot of the vector (which generates no code for SSE).
6124 for (unsigned i = 0; i < NumElems; ++i) {
6125 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6126 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6128 V[i] = DAG.getUNDEF(VT);
6131 // Next, we iteratively mix elements, e.g. for v4f32:
6132 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6133 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6134 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6135 unsigned EltStride = NumElems >> 1;
6136 while (EltStride != 0) {
6137 for (unsigned i = 0; i < EltStride; ++i) {
6138 // If V[i+EltStride] is undef and this is the first round of mixing,
6139 // then it is safe to just drop this shuffle: V[i] is already in the
6140 // right place, the one element (since it's the first round) being
6141 // inserted as undef can be dropped. This isn't safe for successive
6142 // rounds because they will permute elements within both vectors.
6143 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6144 EltStride == NumElems/2)
6147 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6156 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6157 // to create 256-bit vectors from two other 128-bit ones.
6158 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6160 MVT ResVT = Op.getSimpleValueType();
6162 assert((ResVT.is256BitVector() ||
6163 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6165 SDValue V1 = Op.getOperand(0);
6166 SDValue V2 = Op.getOperand(1);
6167 unsigned NumElems = ResVT.getVectorNumElements();
6168 if (ResVT.is256BitVector())
6169 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6171 if (Op.getNumOperands() == 4) {
6172 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6173 ResVT.getVectorNumElements()/2);
6174 SDValue V3 = Op.getOperand(2);
6175 SDValue V4 = Op.getOperand(3);
6176 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6177 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6179 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6182 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6183 const X86Subtarget *Subtarget,
6184 SelectionDAG & DAG) {
6186 MVT ResVT = Op.getSimpleValueType();
6187 unsigned NumOfOperands = Op.getNumOperands();
6189 assert(isPowerOf2_32(NumOfOperands) &&
6190 "Unexpected number of operands in CONCAT_VECTORS");
6192 if (NumOfOperands > 2) {
6193 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6194 ResVT.getVectorNumElements()/2);
6195 SmallVector<SDValue, 2> Ops;
6196 for (unsigned i = 0; i < NumOfOperands/2; i++)
6197 Ops.push_back(Op.getOperand(i));
6198 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6200 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6201 Ops.push_back(Op.getOperand(i));
6202 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6203 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6206 SDValue V1 = Op.getOperand(0);
6207 SDValue V2 = Op.getOperand(1);
6208 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6209 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6211 if (IsZeroV1 && IsZeroV2)
6212 return getZeroVector(ResVT, Subtarget, DAG, dl);
6214 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6215 SDValue Undef = DAG.getUNDEF(ResVT);
6216 unsigned NumElems = ResVT.getVectorNumElements();
6217 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6219 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6220 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6224 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6225 // Zero the upper bits of V1
6226 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6227 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6230 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6233 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6234 const X86Subtarget *Subtarget,
6235 SelectionDAG &DAG) {
6236 MVT VT = Op.getSimpleValueType();
6237 if (VT.getVectorElementType() == MVT::i1)
6238 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6240 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6241 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6242 Op.getNumOperands() == 4)));
6244 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6245 // from two other 128-bit ones.
6247 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6248 return LowerAVXCONCAT_VECTORS(Op, DAG);
6252 //===----------------------------------------------------------------------===//
6253 // Vector shuffle lowering
6255 // This is an experimental code path for lowering vector shuffles on x86. It is
6256 // designed to handle arbitrary vector shuffles and blends, gracefully
6257 // degrading performance as necessary. It works hard to recognize idiomatic
6258 // shuffles and lower them to optimal instruction patterns without leaving
6259 // a framework that allows reasonably efficient handling of all vector shuffle
6261 //===----------------------------------------------------------------------===//
6263 /// \brief Tiny helper function to identify a no-op mask.
6265 /// This is a somewhat boring predicate function. It checks whether the mask
6266 /// array input, which is assumed to be a single-input shuffle mask of the kind
6267 /// used by the X86 shuffle instructions (not a fully general
6268 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6269 /// in-place shuffle are 'no-op's.
6270 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6271 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6272 if (Mask[i] != -1 && Mask[i] != i)
6277 /// \brief Helper function to classify a mask as a single-input mask.
6279 /// This isn't a generic single-input test because in the vector shuffle
6280 /// lowering we canonicalize single inputs to be the first input operand. This
6281 /// means we can more quickly test for a single input by only checking whether
6282 /// an input from the second operand exists. We also assume that the size of
6283 /// mask corresponds to the size of the input vectors which isn't true in the
6284 /// fully general case.
6285 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6287 if (M >= (int)Mask.size())
6292 /// \brief Test whether there are elements crossing 128-bit lanes in this
6295 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6296 /// and we routinely test for these.
6297 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6298 int LaneSize = 128 / VT.getScalarSizeInBits();
6299 int Size = Mask.size();
6300 for (int i = 0; i < Size; ++i)
6301 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6306 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6308 /// This checks a shuffle mask to see if it is performing the same
6309 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6310 /// that it is also not lane-crossing. It may however involve a blend from the
6311 /// same lane of a second vector.
6313 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6314 /// non-trivial to compute in the face of undef lanes. The representation is
6315 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6316 /// entries from both V1 and V2 inputs to the wider mask.
6318 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6319 SmallVectorImpl<int> &RepeatedMask) {
6320 int LaneSize = 128 / VT.getScalarSizeInBits();
6321 RepeatedMask.resize(LaneSize, -1);
6322 int Size = Mask.size();
6323 for (int i = 0; i < Size; ++i) {
6326 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6327 // This entry crosses lanes, so there is no way to model this shuffle.
6330 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6331 if (RepeatedMask[i % LaneSize] == -1)
6332 // This is the first non-undef entry in this slot of a 128-bit lane.
6333 RepeatedMask[i % LaneSize] =
6334 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6335 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6336 // Found a mismatch with the repeated mask.
6342 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6345 /// This is a fast way to test a shuffle mask against a fixed pattern:
6347 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6349 /// It returns true if the mask is exactly as wide as the argument list, and
6350 /// each element of the mask is either -1 (signifying undef) or the value given
6351 /// in the argument.
6352 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6353 ArrayRef<int> ExpectedMask) {
6354 if (Mask.size() != ExpectedMask.size())
6357 int Size = Mask.size();
6359 // If the values are build vectors, we can look through them to find
6360 // equivalent inputs that make the shuffles equivalent.
6361 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6362 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6364 for (int i = 0; i < Size; ++i)
6365 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6366 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6367 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6368 if (!MaskBV || !ExpectedBV ||
6369 MaskBV->getOperand(Mask[i] % Size) !=
6370 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6377 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6379 /// This helper function produces an 8-bit shuffle immediate corresponding to
6380 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6381 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6384 /// NB: We rely heavily on "undef" masks preserving the input lane.
6385 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6386 SelectionDAG &DAG) {
6387 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6388 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6389 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6390 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6391 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6394 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6395 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6396 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6397 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6398 return DAG.getConstant(Imm, DL, MVT::i8);
6401 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6403 /// This is used as a fallback approach when first class blend instructions are
6404 /// unavailable. Currently it is only suitable for integer vectors, but could
6405 /// be generalized for floating point vectors if desirable.
6406 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6407 SDValue V2, ArrayRef<int> Mask,
6408 SelectionDAG &DAG) {
6409 assert(VT.isInteger() && "Only supports integer vector types!");
6410 MVT EltVT = VT.getScalarType();
6411 int NumEltBits = EltVT.getSizeInBits();
6412 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6413 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6415 SmallVector<SDValue, 16> MaskOps;
6416 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6417 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6418 return SDValue(); // Shuffled input!
6419 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6422 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6423 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6424 // We have to cast V2 around.
6425 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6426 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6427 DAG.getBitcast(MaskVT, V1Mask),
6428 DAG.getBitcast(MaskVT, V2)));
6429 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6432 /// \brief Try to emit a blend instruction for a shuffle.
6434 /// This doesn't do any checks for the availability of instructions for blending
6435 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6436 /// be matched in the backend with the type given. What it does check for is
6437 /// that the shuffle mask is in fact a blend.
6438 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6439 SDValue V2, ArrayRef<int> Mask,
6440 const X86Subtarget *Subtarget,
6441 SelectionDAG &DAG) {
6442 unsigned BlendMask = 0;
6443 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6444 if (Mask[i] >= Size) {
6445 if (Mask[i] != i + Size)
6446 return SDValue(); // Shuffled V2 input!
6447 BlendMask |= 1u << i;
6450 if (Mask[i] >= 0 && Mask[i] != i)
6451 return SDValue(); // Shuffled V1 input!
6453 switch (VT.SimpleTy) {
6458 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6459 DAG.getConstant(BlendMask, DL, MVT::i8));
6463 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6467 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6468 // that instruction.
6469 if (Subtarget->hasAVX2()) {
6470 // Scale the blend by the number of 32-bit dwords per element.
6471 int Scale = VT.getScalarSizeInBits() / 32;
6473 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6474 if (Mask[i] >= Size)
6475 for (int j = 0; j < Scale; ++j)
6476 BlendMask |= 1u << (i * Scale + j);
6478 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6479 V1 = DAG.getBitcast(BlendVT, V1);
6480 V2 = DAG.getBitcast(BlendVT, V2);
6481 return DAG.getBitcast(
6482 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6483 DAG.getConstant(BlendMask, DL, MVT::i8)));
6487 // For integer shuffles we need to expand the mask and cast the inputs to
6488 // v8i16s prior to blending.
6489 int Scale = 8 / VT.getVectorNumElements();
6491 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6492 if (Mask[i] >= Size)
6493 for (int j = 0; j < Scale; ++j)
6494 BlendMask |= 1u << (i * Scale + j);
6496 V1 = DAG.getBitcast(MVT::v8i16, V1);
6497 V2 = DAG.getBitcast(MVT::v8i16, V2);
6498 return DAG.getBitcast(VT,
6499 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6500 DAG.getConstant(BlendMask, DL, MVT::i8)));
6504 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6505 SmallVector<int, 8> RepeatedMask;
6506 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6507 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6508 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6510 for (int i = 0; i < 8; ++i)
6511 if (RepeatedMask[i] >= 16)
6512 BlendMask |= 1u << i;
6513 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6514 DAG.getConstant(BlendMask, DL, MVT::i8));
6520 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6521 "256-bit byte-blends require AVX2 support!");
6523 // Scale the blend by the number of bytes per element.
6524 int Scale = VT.getScalarSizeInBits() / 8;
6526 // This form of blend is always done on bytes. Compute the byte vector
6528 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6530 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6531 // mix of LLVM's code generator and the x86 backend. We tell the code
6532 // generator that boolean values in the elements of an x86 vector register
6533 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6534 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6535 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6536 // of the element (the remaining are ignored) and 0 in that high bit would
6537 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6538 // the LLVM model for boolean values in vector elements gets the relevant
6539 // bit set, it is set backwards and over constrained relative to x86's
6541 SmallVector<SDValue, 32> VSELECTMask;
6542 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6543 for (int j = 0; j < Scale; ++j)
6544 VSELECTMask.push_back(
6545 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6546 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6549 V1 = DAG.getBitcast(BlendVT, V1);
6550 V2 = DAG.getBitcast(BlendVT, V2);
6551 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6552 DAG.getNode(ISD::BUILD_VECTOR, DL,
6553 BlendVT, VSELECTMask),
6558 llvm_unreachable("Not a supported integer vector type!");
6562 /// \brief Try to lower as a blend of elements from two inputs followed by
6563 /// a single-input permutation.
6565 /// This matches the pattern where we can blend elements from two inputs and
6566 /// then reduce the shuffle to a single-input permutation.
6567 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6570 SelectionDAG &DAG) {
6571 // We build up the blend mask while checking whether a blend is a viable way
6572 // to reduce the shuffle.
6573 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6574 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6576 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6580 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6582 if (BlendMask[Mask[i] % Size] == -1)
6583 BlendMask[Mask[i] % Size] = Mask[i];
6584 else if (BlendMask[Mask[i] % Size] != Mask[i])
6585 return SDValue(); // Can't blend in the needed input!
6587 PermuteMask[i] = Mask[i] % Size;
6590 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6591 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6594 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6595 /// blends and permutes.
6597 /// This matches the extremely common pattern for handling combined
6598 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6599 /// operations. It will try to pick the best arrangement of shuffles and
6601 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6605 SelectionDAG &DAG) {
6606 // Shuffle the input elements into the desired positions in V1 and V2 and
6607 // blend them together.
6608 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6609 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6610 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6611 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6612 if (Mask[i] >= 0 && Mask[i] < Size) {
6613 V1Mask[i] = Mask[i];
6615 } else if (Mask[i] >= Size) {
6616 V2Mask[i] = Mask[i] - Size;
6617 BlendMask[i] = i + Size;
6620 // Try to lower with the simpler initial blend strategy unless one of the
6621 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6622 // shuffle may be able to fold with a load or other benefit. However, when
6623 // we'll have to do 2x as many shuffles in order to achieve this, blending
6624 // first is a better strategy.
6625 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6626 if (SDValue BlendPerm =
6627 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6630 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6631 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6632 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6635 /// \brief Try to lower a vector shuffle as a byte rotation.
6637 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6638 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6639 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6640 /// try to generically lower a vector shuffle through such an pattern. It
6641 /// does not check for the profitability of lowering either as PALIGNR or
6642 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6643 /// This matches shuffle vectors that look like:
6645 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6647 /// Essentially it concatenates V1 and V2, shifts right by some number of
6648 /// elements, and takes the low elements as the result. Note that while this is
6649 /// specified as a *right shift* because x86 is little-endian, it is a *left
6650 /// rotate* of the vector lanes.
6651 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6654 const X86Subtarget *Subtarget,
6655 SelectionDAG &DAG) {
6656 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6658 int NumElts = Mask.size();
6659 int NumLanes = VT.getSizeInBits() / 128;
6660 int NumLaneElts = NumElts / NumLanes;
6662 // We need to detect various ways of spelling a rotation:
6663 // [11, 12, 13, 14, 15, 0, 1, 2]
6664 // [-1, 12, 13, 14, -1, -1, 1, -1]
6665 // [-1, -1, -1, -1, -1, -1, 1, 2]
6666 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6667 // [-1, 4, 5, 6, -1, -1, 9, -1]
6668 // [-1, 4, 5, 6, -1, -1, -1, -1]
6671 for (int l = 0; l < NumElts; l += NumLaneElts) {
6672 for (int i = 0; i < NumLaneElts; ++i) {
6673 if (Mask[l + i] == -1)
6675 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6677 // Get the mod-Size index and lane correct it.
6678 int LaneIdx = (Mask[l + i] % NumElts) - l;
6679 // Make sure it was in this lane.
6680 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6683 // Determine where a rotated vector would have started.
6684 int StartIdx = i - LaneIdx;
6686 // The identity rotation isn't interesting, stop.
6689 // If we found the tail of a vector the rotation must be the missing
6690 // front. If we found the head of a vector, it must be how much of the
6692 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6695 Rotation = CandidateRotation;
6696 else if (Rotation != CandidateRotation)
6697 // The rotations don't match, so we can't match this mask.
6700 // Compute which value this mask is pointing at.
6701 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6703 // Compute which of the two target values this index should be assigned
6704 // to. This reflects whether the high elements are remaining or the low
6705 // elements are remaining.
6706 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6708 // Either set up this value if we've not encountered it before, or check
6709 // that it remains consistent.
6712 else if (TargetV != MaskV)
6713 // This may be a rotation, but it pulls from the inputs in some
6714 // unsupported interleaving.
6719 // Check that we successfully analyzed the mask, and normalize the results.
6720 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6721 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6727 // The actual rotate instruction rotates bytes, so we need to scale the
6728 // rotation based on how many bytes are in the vector lane.
6729 int Scale = 16 / NumLaneElts;
6731 // SSSE3 targets can use the palignr instruction.
6732 if (Subtarget->hasSSSE3()) {
6733 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6734 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6735 Lo = DAG.getBitcast(AlignVT, Lo);
6736 Hi = DAG.getBitcast(AlignVT, Hi);
6738 return DAG.getBitcast(
6739 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6740 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6743 assert(VT.getSizeInBits() == 128 &&
6744 "Rotate-based lowering only supports 128-bit lowering!");
6745 assert(Mask.size() <= 16 &&
6746 "Can shuffle at most 16 bytes in a 128-bit vector!");
6748 // Default SSE2 implementation
6749 int LoByteShift = 16 - Rotation * Scale;
6750 int HiByteShift = Rotation * Scale;
6752 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6753 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6754 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6756 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6757 DAG.getConstant(LoByteShift, DL, MVT::i8));
6758 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6759 DAG.getConstant(HiByteShift, DL, MVT::i8));
6760 return DAG.getBitcast(VT,
6761 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6764 /// \brief Compute whether each element of a shuffle is zeroable.
6766 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6767 /// Either it is an undef element in the shuffle mask, the element of the input
6768 /// referenced is undef, or the element of the input referenced is known to be
6769 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6770 /// as many lanes with this technique as possible to simplify the remaining
6772 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6773 SDValue V1, SDValue V2) {
6774 SmallBitVector Zeroable(Mask.size(), false);
6776 while (V1.getOpcode() == ISD::BITCAST)
6777 V1 = V1->getOperand(0);
6778 while (V2.getOpcode() == ISD::BITCAST)
6779 V2 = V2->getOperand(0);
6781 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6782 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6784 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6786 // Handle the easy cases.
6787 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6792 // If this is an index into a build_vector node (which has the same number
6793 // of elements), dig out the input value and use it.
6794 SDValue V = M < Size ? V1 : V2;
6795 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6798 SDValue Input = V.getOperand(M % Size);
6799 // The UNDEF opcode check really should be dead code here, but not quite
6800 // worth asserting on (it isn't invalid, just unexpected).
6801 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6808 /// \brief Try to emit a bitmask instruction for a shuffle.
6810 /// This handles cases where we can model a blend exactly as a bitmask due to
6811 /// one of the inputs being zeroable.
6812 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6813 SDValue V2, ArrayRef<int> Mask,
6814 SelectionDAG &DAG) {
6815 MVT EltVT = VT.getScalarType();
6816 int NumEltBits = EltVT.getSizeInBits();
6817 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6818 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6819 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6821 if (EltVT.isFloatingPoint()) {
6822 Zero = DAG.getBitcast(EltVT, Zero);
6823 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6825 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6826 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6828 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6831 if (Mask[i] % Size != i)
6832 return SDValue(); // Not a blend.
6834 V = Mask[i] < Size ? V1 : V2;
6835 else if (V != (Mask[i] < Size ? V1 : V2))
6836 return SDValue(); // Can only let one input through the mask.
6838 VMaskOps[i] = AllOnes;
6841 return SDValue(); // No non-zeroable elements!
6843 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6844 V = DAG.getNode(VT.isFloatingPoint()
6845 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6850 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6852 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6853 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6854 /// matches elements from one of the input vectors shuffled to the left or
6855 /// right with zeroable elements 'shifted in'. It handles both the strictly
6856 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6859 /// PSHL : (little-endian) left bit shift.
6860 /// [ zz, 0, zz, 2 ]
6861 /// [ -1, 4, zz, -1 ]
6862 /// PSRL : (little-endian) right bit shift.
6864 /// [ -1, -1, 7, zz]
6865 /// PSLLDQ : (little-endian) left byte shift
6866 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6867 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6868 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6869 /// PSRLDQ : (little-endian) right byte shift
6870 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6871 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6872 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6873 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6874 SDValue V2, ArrayRef<int> Mask,
6875 SelectionDAG &DAG) {
6876 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6878 int Size = Mask.size();
6879 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6881 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6882 for (int i = 0; i < Size; i += Scale)
6883 for (int j = 0; j < Shift; ++j)
6884 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6890 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6891 for (int i = 0; i != Size; i += Scale) {
6892 unsigned Pos = Left ? i + Shift : i;
6893 unsigned Low = Left ? i : i + Shift;
6894 unsigned Len = Scale - Shift;
6895 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6896 Low + (V == V1 ? 0 : Size)))
6900 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6901 bool ByteShift = ShiftEltBits > 64;
6902 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6903 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6904 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6906 // Normalize the scale for byte shifts to still produce an i64 element
6908 Scale = ByteShift ? Scale / 2 : Scale;
6910 // We need to round trip through the appropriate type for the shift.
6911 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6912 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6913 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6914 "Illegal integer vector type");
6915 V = DAG.getBitcast(ShiftVT, V);
6917 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6918 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6919 return DAG.getBitcast(VT, V);
6922 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6923 // keep doubling the size of the integer elements up to that. We can
6924 // then shift the elements of the integer vector by whole multiples of
6925 // their width within the elements of the larger integer vector. Test each
6926 // multiple to see if we can find a match with the moved element indices
6927 // and that the shifted in elements are all zeroable.
6928 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6929 for (int Shift = 1; Shift != Scale; ++Shift)
6930 for (bool Left : {true, false})
6931 if (CheckZeros(Shift, Scale, Left))
6932 for (SDValue V : {V1, V2})
6933 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6940 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6941 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6942 SDValue V2, ArrayRef<int> Mask,
6943 SelectionDAG &DAG) {
6944 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6945 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6947 int Size = Mask.size();
6948 int HalfSize = Size / 2;
6949 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6951 // Upper half must be undefined.
6952 if (!isUndefInRange(Mask, HalfSize, HalfSize))
6955 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
6956 // Remainder of lower half result is zero and upper half is all undef.
6957 auto LowerAsEXTRQ = [&]() {
6958 // Determine the extraction length from the part of the
6959 // lower half that isn't zeroable.
6961 for (; Len >= 0; --Len)
6962 if (!Zeroable[Len - 1])
6964 assert(Len > 0 && "Zeroable shuffle mask");
6966 // Attempt to match first Len sequential elements from the lower half.
6969 for (int i = 0; i != Len; ++i) {
6973 SDValue &V = (M < Size ? V1 : V2);
6976 // All mask elements must be in the lower half.
6980 if (Idx < 0 || (Src == V && Idx == (M - i))) {
6991 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
6992 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
6993 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
6994 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
6995 DAG.getConstant(BitLen, DL, MVT::i8),
6996 DAG.getConstant(BitIdx, DL, MVT::i8));
6999 if (SDValue ExtrQ = LowerAsEXTRQ())
7002 // INSERTQ: Extract lowest Len elements from lower half of second source and
7003 // insert over first source, starting at Idx.
7004 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7005 auto LowerAsInsertQ = [&]() {
7006 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7009 // Attempt to match first source from mask before insertion point.
7010 if (isUndefInRange(Mask, 0, Idx)) {
7012 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7014 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7020 // Extend the extraction length looking to match both the insertion of
7021 // the second source and the remaining elements of the first.
7022 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7027 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7029 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7035 // Match the remaining elements of the lower half.
7036 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7038 } else if ((!Base || (Base == V1)) &&
7039 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7041 } else if ((!Base || (Base == V2)) &&
7042 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7049 // We may not have a base (first source) - this can safely be undefined.
7051 Base = DAG.getUNDEF(VT);
7053 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7054 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7055 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7056 DAG.getConstant(BitLen, DL, MVT::i8),
7057 DAG.getConstant(BitIdx, DL, MVT::i8));
7064 if (SDValue InsertQ = LowerAsInsertQ())
7070 /// \brief Lower a vector shuffle as a zero or any extension.
7072 /// Given a specific number of elements, element bit width, and extension
7073 /// stride, produce either a zero or any extension based on the available
7074 /// features of the subtarget.
7075 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7076 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7077 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7078 assert(Scale > 1 && "Need a scale to extend.");
7079 int NumElements = VT.getVectorNumElements();
7080 int EltBits = VT.getScalarSizeInBits();
7081 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7082 "Only 8, 16, and 32 bit elements can be extended.");
7083 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7085 // Found a valid zext mask! Try various lowering strategies based on the
7086 // input type and available ISA extensions.
7087 if (Subtarget->hasSSE41()) {
7088 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7089 NumElements / Scale);
7090 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7093 // For any extends we can cheat for larger element sizes and use shuffle
7094 // instructions that can fold with a load and/or copy.
7095 if (AnyExt && EltBits == 32) {
7096 int PSHUFDMask[4] = {0, -1, 1, -1};
7097 return DAG.getBitcast(
7098 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7099 DAG.getBitcast(MVT::v4i32, InputV),
7100 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7102 if (AnyExt && EltBits == 16 && Scale > 2) {
7103 int PSHUFDMask[4] = {0, -1, 0, -1};
7104 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7105 DAG.getBitcast(MVT::v4i32, InputV),
7106 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7107 int PSHUFHWMask[4] = {1, -1, -1, -1};
7108 return DAG.getBitcast(
7109 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7110 DAG.getBitcast(MVT::v8i16, InputV),
7111 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7114 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7116 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7117 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7118 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7120 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7121 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7122 DAG.getConstant(EltBits, DL, MVT::i8),
7123 DAG.getConstant(0, DL, MVT::i8)));
7124 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7125 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7128 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7129 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7130 DAG.getConstant(EltBits, DL, MVT::i8),
7131 DAG.getConstant(EltBits, DL, MVT::i8)));
7132 return DAG.getNode(ISD::BITCAST, DL, VT,
7133 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7136 // If this would require more than 2 unpack instructions to expand, use
7137 // pshufb when available. We can only use more than 2 unpack instructions
7138 // when zero extending i8 elements which also makes it easier to use pshufb.
7139 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7140 assert(NumElements == 16 && "Unexpected byte vector width!");
7141 SDValue PSHUFBMask[16];
7142 for (int i = 0; i < 16; ++i)
7144 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7145 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7146 return DAG.getBitcast(VT,
7147 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7148 DAG.getNode(ISD::BUILD_VECTOR, DL,
7149 MVT::v16i8, PSHUFBMask)));
7152 // Otherwise emit a sequence of unpacks.
7154 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7155 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7156 : getZeroVector(InputVT, Subtarget, DAG, DL);
7157 InputV = DAG.getBitcast(InputVT, InputV);
7158 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7162 } while (Scale > 1);
7163 return DAG.getBitcast(VT, InputV);
7166 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7168 /// This routine will try to do everything in its power to cleverly lower
7169 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7170 /// check for the profitability of this lowering, it tries to aggressively
7171 /// match this pattern. It will use all of the micro-architectural details it
7172 /// can to emit an efficient lowering. It handles both blends with all-zero
7173 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7174 /// masking out later).
7176 /// The reason we have dedicated lowering for zext-style shuffles is that they
7177 /// are both incredibly common and often quite performance sensitive.
7178 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7179 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7180 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7181 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7183 int Bits = VT.getSizeInBits();
7184 int NumElements = VT.getVectorNumElements();
7185 assert(VT.getScalarSizeInBits() <= 32 &&
7186 "Exceeds 32-bit integer zero extension limit");
7187 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7189 // Define a helper function to check a particular ext-scale and lower to it if
7191 auto Lower = [&](int Scale) -> SDValue {
7194 for (int i = 0; i < NumElements; ++i) {
7196 continue; // Valid anywhere but doesn't tell us anything.
7197 if (i % Scale != 0) {
7198 // Each of the extended elements need to be zeroable.
7202 // We no longer are in the anyext case.
7207 // Each of the base elements needs to be consecutive indices into the
7208 // same input vector.
7209 SDValue V = Mask[i] < NumElements ? V1 : V2;
7212 else if (InputV != V)
7213 return SDValue(); // Flip-flopping inputs.
7215 if (Mask[i] % NumElements != i / Scale)
7216 return SDValue(); // Non-consecutive strided elements.
7219 // If we fail to find an input, we have a zero-shuffle which should always
7220 // have already been handled.
7221 // FIXME: Maybe handle this here in case during blending we end up with one?
7225 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7226 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7229 // The widest scale possible for extending is to a 64-bit integer.
7230 assert(Bits % 64 == 0 &&
7231 "The number of bits in a vector must be divisible by 64 on x86!");
7232 int NumExtElements = Bits / 64;
7234 // Each iteration, try extending the elements half as much, but into twice as
7236 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7237 assert(NumElements % NumExtElements == 0 &&
7238 "The input vector size must be divisible by the extended size.");
7239 if (SDValue V = Lower(NumElements / NumExtElements))
7243 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7247 // Returns one of the source operands if the shuffle can be reduced to a
7248 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7249 auto CanZExtLowHalf = [&]() {
7250 for (int i = NumElements / 2; i != NumElements; ++i)
7253 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7255 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7260 if (SDValue V = CanZExtLowHalf()) {
7261 V = DAG.getBitcast(MVT::v2i64, V);
7262 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7263 return DAG.getBitcast(VT, V);
7266 // No viable ext lowering found.
7270 /// \brief Try to get a scalar value for a specific element of a vector.
7272 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7273 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7274 SelectionDAG &DAG) {
7275 MVT VT = V.getSimpleValueType();
7276 MVT EltVT = VT.getVectorElementType();
7277 while (V.getOpcode() == ISD::BITCAST)
7278 V = V.getOperand(0);
7279 // If the bitcasts shift the element size, we can't extract an equivalent
7281 MVT NewVT = V.getSimpleValueType();
7282 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7285 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7286 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7287 // Ensure the scalar operand is the same size as the destination.
7288 // FIXME: Add support for scalar truncation where possible.
7289 SDValue S = V.getOperand(Idx);
7290 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7291 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7297 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7299 /// This is particularly important because the set of instructions varies
7300 /// significantly based on whether the operand is a load or not.
7301 static bool isShuffleFoldableLoad(SDValue V) {
7302 while (V.getOpcode() == ISD::BITCAST)
7303 V = V.getOperand(0);
7305 return ISD::isNON_EXTLoad(V.getNode());
7308 /// \brief Try to lower insertion of a single element into a zero vector.
7310 /// This is a common pattern that we have especially efficient patterns to lower
7311 /// across all subtarget feature sets.
7312 static SDValue lowerVectorShuffleAsElementInsertion(
7313 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7314 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7315 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7317 MVT EltVT = VT.getVectorElementType();
7319 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7320 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7322 bool IsV1Zeroable = true;
7323 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7324 if (i != V2Index && !Zeroable[i]) {
7325 IsV1Zeroable = false;
7329 // Check for a single input from a SCALAR_TO_VECTOR node.
7330 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7331 // all the smarts here sunk into that routine. However, the current
7332 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7333 // vector shuffle lowering is dead.
7334 if (SDValue V2S = getScalarValueForVectorElement(
7335 V2, Mask[V2Index] - Mask.size(), DAG)) {
7336 // We need to zext the scalar if it is smaller than an i32.
7337 V2S = DAG.getBitcast(EltVT, V2S);
7338 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7339 // Using zext to expand a narrow element won't work for non-zero
7344 // Zero-extend directly to i32.
7346 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7348 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7349 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7350 EltVT == MVT::i16) {
7351 // Either not inserting from the low element of the input or the input
7352 // element size is too small to use VZEXT_MOVL to clear the high bits.
7356 if (!IsV1Zeroable) {
7357 // If V1 can't be treated as a zero vector we have fewer options to lower
7358 // this. We can't support integer vectors or non-zero targets cheaply, and
7359 // the V1 elements can't be permuted in any way.
7360 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7361 if (!VT.isFloatingPoint() || V2Index != 0)
7363 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7364 V1Mask[V2Index] = -1;
7365 if (!isNoopShuffleMask(V1Mask))
7367 // This is essentially a special case blend operation, but if we have
7368 // general purpose blend operations, they are always faster. Bail and let
7369 // the rest of the lowering handle these as blends.
7370 if (Subtarget->hasSSE41())
7373 // Otherwise, use MOVSD or MOVSS.
7374 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7375 "Only two types of floating point element types to handle!");
7376 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7380 // This lowering only works for the low element with floating point vectors.
7381 if (VT.isFloatingPoint() && V2Index != 0)
7384 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7386 V2 = DAG.getBitcast(VT, V2);
7389 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7390 // the desired position. Otherwise it is more efficient to do a vector
7391 // shift left. We know that we can do a vector shift left because all
7392 // the inputs are zero.
7393 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7394 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7395 V2Shuffle[V2Index] = 0;
7396 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7398 V2 = DAG.getBitcast(MVT::v2i64, V2);
7400 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7402 V2Index * EltVT.getSizeInBits()/8, DL,
7403 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7404 V2 = DAG.getBitcast(VT, V2);
7410 /// \brief Try to lower broadcast of a single element.
7412 /// For convenience, this code also bundles all of the subtarget feature set
7413 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7414 /// a convenient way to factor it out.
7415 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7417 const X86Subtarget *Subtarget,
7418 SelectionDAG &DAG) {
7419 if (!Subtarget->hasAVX())
7421 if (VT.isInteger() && !Subtarget->hasAVX2())
7424 // Check that the mask is a broadcast.
7425 int BroadcastIdx = -1;
7427 if (M >= 0 && BroadcastIdx == -1)
7429 else if (M >= 0 && M != BroadcastIdx)
7432 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7433 "a sorted mask where the broadcast "
7436 // Go up the chain of (vector) values to find a scalar load that we can
7437 // combine with the broadcast.
7439 switch (V.getOpcode()) {
7440 case ISD::CONCAT_VECTORS: {
7441 int OperandSize = Mask.size() / V.getNumOperands();
7442 V = V.getOperand(BroadcastIdx / OperandSize);
7443 BroadcastIdx %= OperandSize;
7447 case ISD::INSERT_SUBVECTOR: {
7448 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7449 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7453 int BeginIdx = (int)ConstantIdx->getZExtValue();
7455 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7456 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7457 BroadcastIdx -= BeginIdx;
7468 // Check if this is a broadcast of a scalar. We special case lowering
7469 // for scalars so that we can more effectively fold with loads.
7470 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7471 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7472 V = V.getOperand(BroadcastIdx);
7474 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7475 // Only AVX2 has register broadcasts.
7476 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7478 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7479 // We can't broadcast from a vector register without AVX2, and we can only
7480 // broadcast from the zero-element of a vector register.
7484 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7487 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7488 // INSERTPS when the V1 elements are already in the correct locations
7489 // because otherwise we can just always use two SHUFPS instructions which
7490 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7491 // perform INSERTPS if a single V1 element is out of place and all V2
7492 // elements are zeroable.
7493 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7495 SelectionDAG &DAG) {
7496 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7497 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7498 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7499 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7501 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7504 int V1DstIndex = -1;
7505 int V2DstIndex = -1;
7506 bool V1UsedInPlace = false;
7508 for (int i = 0; i < 4; ++i) {
7509 // Synthesize a zero mask from the zeroable elements (includes undefs).
7515 // Flag if we use any V1 inputs in place.
7517 V1UsedInPlace = true;
7521 // We can only insert a single non-zeroable element.
7522 if (V1DstIndex != -1 || V2DstIndex != -1)
7526 // V1 input out of place for insertion.
7529 // V2 input for insertion.
7534 // Don't bother if we have no (non-zeroable) element for insertion.
7535 if (V1DstIndex == -1 && V2DstIndex == -1)
7538 // Determine element insertion src/dst indices. The src index is from the
7539 // start of the inserted vector, not the start of the concatenated vector.
7540 unsigned V2SrcIndex = 0;
7541 if (V1DstIndex != -1) {
7542 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7543 // and don't use the original V2 at all.
7544 V2SrcIndex = Mask[V1DstIndex];
7545 V2DstIndex = V1DstIndex;
7548 V2SrcIndex = Mask[V2DstIndex] - 4;
7551 // If no V1 inputs are used in place, then the result is created only from
7552 // the zero mask and the V2 insertion - so remove V1 dependency.
7554 V1 = DAG.getUNDEF(MVT::v4f32);
7556 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7557 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7559 // Insert the V2 element into the desired position.
7561 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7562 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7565 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7566 /// UNPCK instruction.
7568 /// This specifically targets cases where we end up with alternating between
7569 /// the two inputs, and so can permute them into something that feeds a single
7570 /// UNPCK instruction. Note that this routine only targets integer vectors
7571 /// because for floating point vectors we have a generalized SHUFPS lowering
7572 /// strategy that handles everything that doesn't *exactly* match an unpack,
7573 /// making this clever lowering unnecessary.
7574 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7575 SDValue V2, ArrayRef<int> Mask,
7576 SelectionDAG &DAG) {
7577 assert(!VT.isFloatingPoint() &&
7578 "This routine only supports integer vectors.");
7579 assert(!isSingleInputShuffleMask(Mask) &&
7580 "This routine should only be used when blending two inputs.");
7581 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7583 int Size = Mask.size();
7585 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7586 return M >= 0 && M % Size < Size / 2;
7588 int NumHiInputs = std::count_if(
7589 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7591 bool UnpackLo = NumLoInputs >= NumHiInputs;
7593 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7594 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7595 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7597 for (int i = 0; i < Size; ++i) {
7601 // Each element of the unpack contains Scale elements from this mask.
7602 int UnpackIdx = i / Scale;
7604 // We only handle the case where V1 feeds the first slots of the unpack.
7605 // We rely on canonicalization to ensure this is the case.
7606 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7609 // Setup the mask for this input. The indexing is tricky as we have to
7610 // handle the unpack stride.
7611 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7612 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7616 // If we will have to shuffle both inputs to use the unpack, check whether
7617 // we can just unpack first and shuffle the result. If so, skip this unpack.
7618 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7619 !isNoopShuffleMask(V2Mask))
7622 // Shuffle the inputs into place.
7623 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7624 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7626 // Cast the inputs to the type we will use to unpack them.
7627 V1 = DAG.getBitcast(UnpackVT, V1);
7628 V2 = DAG.getBitcast(UnpackVT, V2);
7630 // Unpack the inputs and cast the result back to the desired type.
7631 return DAG.getBitcast(
7632 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7636 // We try each unpack from the largest to the smallest to try and find one
7637 // that fits this mask.
7638 int OrigNumElements = VT.getVectorNumElements();
7639 int OrigScalarSize = VT.getScalarSizeInBits();
7640 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7641 int Scale = ScalarSize / OrigScalarSize;
7642 int NumElements = OrigNumElements / Scale;
7643 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7644 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7648 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7650 if (NumLoInputs == 0 || NumHiInputs == 0) {
7651 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7652 "We have to have *some* inputs!");
7653 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7655 // FIXME: We could consider the total complexity of the permute of each
7656 // possible unpacking. Or at the least we should consider how many
7657 // half-crossings are created.
7658 // FIXME: We could consider commuting the unpacks.
7660 SmallVector<int, 32> PermMask;
7661 PermMask.assign(Size, -1);
7662 for (int i = 0; i < Size; ++i) {
7666 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7669 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7671 return DAG.getVectorShuffle(
7672 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7674 DAG.getUNDEF(VT), PermMask);
7680 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7682 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7683 /// support for floating point shuffles but not integer shuffles. These
7684 /// instructions will incur a domain crossing penalty on some chips though so
7685 /// it is better to avoid lowering through this for integer vectors where
7687 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7688 const X86Subtarget *Subtarget,
7689 SelectionDAG &DAG) {
7691 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7692 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7693 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7694 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7695 ArrayRef<int> Mask = SVOp->getMask();
7696 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7698 if (isSingleInputShuffleMask(Mask)) {
7699 // Use low duplicate instructions for masks that match their pattern.
7700 if (Subtarget->hasSSE3())
7701 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7702 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7704 // Straight shuffle of a single input vector. Simulate this by using the
7705 // single input as both of the "inputs" to this instruction..
7706 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7708 if (Subtarget->hasAVX()) {
7709 // If we have AVX, we can use VPERMILPS which will allow folding a load
7710 // into the shuffle.
7711 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7712 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7715 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7716 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7718 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7719 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7721 // If we have a single input, insert that into V1 if we can do so cheaply.
7722 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7723 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7724 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7726 // Try inverting the insertion since for v2 masks it is easy to do and we
7727 // can't reliably sort the mask one way or the other.
7728 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7729 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7730 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7731 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7735 // Try to use one of the special instruction patterns to handle two common
7736 // blend patterns if a zero-blend above didn't work.
7737 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7738 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7739 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7740 // We can either use a special instruction to load over the low double or
7741 // to move just the low double.
7743 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7745 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7747 if (Subtarget->hasSSE41())
7748 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7752 // Use dedicated unpack instructions for masks that match their pattern.
7753 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7754 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7755 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7756 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7758 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7759 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7760 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7763 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7765 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7766 /// the integer unit to minimize domain crossing penalties. However, for blends
7767 /// it falls back to the floating point shuffle operation with appropriate bit
7769 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7770 const X86Subtarget *Subtarget,
7771 SelectionDAG &DAG) {
7773 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7774 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7775 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7776 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7777 ArrayRef<int> Mask = SVOp->getMask();
7778 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7780 if (isSingleInputShuffleMask(Mask)) {
7781 // Check for being able to broadcast a single element.
7782 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7783 Mask, Subtarget, DAG))
7786 // Straight shuffle of a single input vector. For everything from SSE2
7787 // onward this has a single fast instruction with no scary immediates.
7788 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7789 V1 = DAG.getBitcast(MVT::v4i32, V1);
7790 int WidenedMask[4] = {
7791 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7792 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7793 return DAG.getBitcast(
7795 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7796 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7798 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7799 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7800 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7801 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7803 // If we have a blend of two PACKUS operations an the blend aligns with the
7804 // low and half halves, we can just merge the PACKUS operations. This is
7805 // particularly important as it lets us merge shuffles that this routine itself
7807 auto GetPackNode = [](SDValue V) {
7808 while (V.getOpcode() == ISD::BITCAST)
7809 V = V.getOperand(0);
7811 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7813 if (SDValue V1Pack = GetPackNode(V1))
7814 if (SDValue V2Pack = GetPackNode(V2))
7815 return DAG.getBitcast(MVT::v2i64,
7816 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7817 Mask[0] == 0 ? V1Pack.getOperand(0)
7818 : V1Pack.getOperand(1),
7819 Mask[1] == 2 ? V2Pack.getOperand(0)
7820 : V2Pack.getOperand(1)));
7822 // Try to use shift instructions.
7824 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7827 // When loading a scalar and then shuffling it into a vector we can often do
7828 // the insertion cheaply.
7829 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7830 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7832 // Try inverting the insertion since for v2 masks it is easy to do and we
7833 // can't reliably sort the mask one way or the other.
7834 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7835 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7836 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7839 // We have different paths for blend lowering, but they all must use the
7840 // *exact* same predicate.
7841 bool IsBlendSupported = Subtarget->hasSSE41();
7842 if (IsBlendSupported)
7843 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7847 // Use dedicated unpack instructions for masks that match their pattern.
7848 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7849 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7850 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7851 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7853 // Try to use byte rotation instructions.
7854 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7855 if (Subtarget->hasSSSE3())
7856 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7857 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7860 // If we have direct support for blends, we should lower by decomposing into
7861 // a permute. That will be faster than the domain cross.
7862 if (IsBlendSupported)
7863 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7866 // We implement this with SHUFPD which is pretty lame because it will likely
7867 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7868 // However, all the alternatives are still more cycles and newer chips don't
7869 // have this problem. It would be really nice if x86 had better shuffles here.
7870 V1 = DAG.getBitcast(MVT::v2f64, V1);
7871 V2 = DAG.getBitcast(MVT::v2f64, V2);
7872 return DAG.getBitcast(MVT::v2i64,
7873 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7876 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7878 /// This is used to disable more specialized lowerings when the shufps lowering
7879 /// will happen to be efficient.
7880 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7881 // This routine only handles 128-bit shufps.
7882 assert(Mask.size() == 4 && "Unsupported mask size!");
7884 // To lower with a single SHUFPS we need to have the low half and high half
7885 // each requiring a single input.
7886 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7888 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7894 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7896 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7897 /// It makes no assumptions about whether this is the *best* lowering, it simply
7899 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7900 ArrayRef<int> Mask, SDValue V1,
7901 SDValue V2, SelectionDAG &DAG) {
7902 SDValue LowV = V1, HighV = V2;
7903 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7906 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7908 if (NumV2Elements == 1) {
7910 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7913 // Compute the index adjacent to V2Index and in the same half by toggling
7915 int V2AdjIndex = V2Index ^ 1;
7917 if (Mask[V2AdjIndex] == -1) {
7918 // Handles all the cases where we have a single V2 element and an undef.
7919 // This will only ever happen in the high lanes because we commute the
7920 // vector otherwise.
7922 std::swap(LowV, HighV);
7923 NewMask[V2Index] -= 4;
7925 // Handle the case where the V2 element ends up adjacent to a V1 element.
7926 // To make this work, blend them together as the first step.
7927 int V1Index = V2AdjIndex;
7928 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7929 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7930 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7932 // Now proceed to reconstruct the final blend as we have the necessary
7933 // high or low half formed.
7940 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7941 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7943 } else if (NumV2Elements == 2) {
7944 if (Mask[0] < 4 && Mask[1] < 4) {
7945 // Handle the easy case where we have V1 in the low lanes and V2 in the
7949 } else if (Mask[2] < 4 && Mask[3] < 4) {
7950 // We also handle the reversed case because this utility may get called
7951 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7952 // arrange things in the right direction.
7958 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7959 // trying to place elements directly, just blend them and set up the final
7960 // shuffle to place them.
7962 // The first two blend mask elements are for V1, the second two are for
7964 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7965 Mask[2] < 4 ? Mask[2] : Mask[3],
7966 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7967 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7968 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7969 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7971 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7974 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7975 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7976 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7977 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7980 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7981 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7984 /// \brief Lower 4-lane 32-bit floating point shuffles.
7986 /// Uses instructions exclusively from the floating point unit to minimize
7987 /// domain crossing penalties, as these are sufficient to implement all v4f32
7989 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7990 const X86Subtarget *Subtarget,
7991 SelectionDAG &DAG) {
7993 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7994 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7995 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7996 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7997 ArrayRef<int> Mask = SVOp->getMask();
7998 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8001 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8003 if (NumV2Elements == 0) {
8004 // Check for being able to broadcast a single element.
8005 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8006 Mask, Subtarget, DAG))
8009 // Use even/odd duplicate instructions for masks that match their pattern.
8010 if (Subtarget->hasSSE3()) {
8011 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8012 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8013 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8014 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8017 if (Subtarget->hasAVX()) {
8018 // If we have AVX, we can use VPERMILPS which will allow folding a load
8019 // into the shuffle.
8020 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8021 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8024 // Otherwise, use a straight shuffle of a single input vector. We pass the
8025 // input vector to both operands to simulate this with a SHUFPS.
8026 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8027 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8030 // There are special ways we can lower some single-element blends. However, we
8031 // have custom ways we can lower more complex single-element blends below that
8032 // we defer to if both this and BLENDPS fail to match, so restrict this to
8033 // when the V2 input is targeting element 0 of the mask -- that is the fast
8035 if (NumV2Elements == 1 && Mask[0] >= 4)
8036 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8037 Mask, Subtarget, DAG))
8040 if (Subtarget->hasSSE41()) {
8041 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8045 // Use INSERTPS if we can complete the shuffle efficiently.
8046 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8049 if (!isSingleSHUFPSMask(Mask))
8050 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8051 DL, MVT::v4f32, V1, V2, Mask, DAG))
8055 // Use dedicated unpack instructions for masks that match their pattern.
8056 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8057 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8058 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8059 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8060 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8061 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8062 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8063 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8065 // Otherwise fall back to a SHUFPS lowering strategy.
8066 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8069 /// \brief Lower 4-lane i32 vector shuffles.
8071 /// We try to handle these with integer-domain shuffles where we can, but for
8072 /// blends we use the floating point domain blend instructions.
8073 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8074 const X86Subtarget *Subtarget,
8075 SelectionDAG &DAG) {
8077 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8078 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8079 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8080 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8081 ArrayRef<int> Mask = SVOp->getMask();
8082 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8084 // Whenever we can lower this as a zext, that instruction is strictly faster
8085 // than any alternative. It also allows us to fold memory operands into the
8086 // shuffle in many cases.
8087 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8088 Mask, Subtarget, DAG))
8092 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8094 if (NumV2Elements == 0) {
8095 // Check for being able to broadcast a single element.
8096 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8097 Mask, Subtarget, DAG))
8100 // Straight shuffle of a single input vector. For everything from SSE2
8101 // onward this has a single fast instruction with no scary immediates.
8102 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8103 // but we aren't actually going to use the UNPCK instruction because doing
8104 // so prevents folding a load into this instruction or making a copy.
8105 const int UnpackLoMask[] = {0, 0, 1, 1};
8106 const int UnpackHiMask[] = {2, 2, 3, 3};
8107 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8108 Mask = UnpackLoMask;
8109 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8110 Mask = UnpackHiMask;
8112 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8113 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8116 // Try to use shift instructions.
8118 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8121 // There are special ways we can lower some single-element blends.
8122 if (NumV2Elements == 1)
8123 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8124 Mask, Subtarget, DAG))
8127 // We have different paths for blend lowering, but they all must use the
8128 // *exact* same predicate.
8129 bool IsBlendSupported = Subtarget->hasSSE41();
8130 if (IsBlendSupported)
8131 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8135 if (SDValue Masked =
8136 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8139 // Use dedicated unpack instructions for masks that match their pattern.
8140 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8141 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8142 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8143 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8144 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8145 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8146 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8147 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8149 // Try to use byte rotation instructions.
8150 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8151 if (Subtarget->hasSSSE3())
8152 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8153 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8156 // If we have direct support for blends, we should lower by decomposing into
8157 // a permute. That will be faster than the domain cross.
8158 if (IsBlendSupported)
8159 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8162 // Try to lower by permuting the inputs into an unpack instruction.
8163 if (SDValue Unpack =
8164 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8167 // We implement this with SHUFPS because it can blend from two vectors.
8168 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8169 // up the inputs, bypassing domain shift penalties that we would encur if we
8170 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8172 return DAG.getBitcast(
8174 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8175 DAG.getBitcast(MVT::v4f32, V2), Mask));
8178 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8179 /// shuffle lowering, and the most complex part.
8181 /// The lowering strategy is to try to form pairs of input lanes which are
8182 /// targeted at the same half of the final vector, and then use a dword shuffle
8183 /// to place them onto the right half, and finally unpack the paired lanes into
8184 /// their final position.
8186 /// The exact breakdown of how to form these dword pairs and align them on the
8187 /// correct sides is really tricky. See the comments within the function for
8188 /// more of the details.
8190 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8191 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8192 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8193 /// vector, form the analogous 128-bit 8-element Mask.
8194 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8195 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8196 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8197 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8198 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8200 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8201 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8202 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8204 SmallVector<int, 4> LoInputs;
8205 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8206 [](int M) { return M >= 0; });
8207 std::sort(LoInputs.begin(), LoInputs.end());
8208 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8209 SmallVector<int, 4> HiInputs;
8210 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8211 [](int M) { return M >= 0; });
8212 std::sort(HiInputs.begin(), HiInputs.end());
8213 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8215 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8216 int NumHToL = LoInputs.size() - NumLToL;
8218 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8219 int NumHToH = HiInputs.size() - NumLToH;
8220 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8221 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8222 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8223 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8225 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8226 // such inputs we can swap two of the dwords across the half mark and end up
8227 // with <=2 inputs to each half in each half. Once there, we can fall through
8228 // to the generic code below. For example:
8230 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8231 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8233 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8234 // and an existing 2-into-2 on the other half. In this case we may have to
8235 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8236 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8237 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8238 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8239 // half than the one we target for fixing) will be fixed when we re-enter this
8240 // path. We will also combine away any sequence of PSHUFD instructions that
8241 // result into a single instruction. Here is an example of the tricky case:
8243 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8244 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8246 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8248 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8249 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8251 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8252 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8254 // The result is fine to be handled by the generic logic.
8255 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8256 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8257 int AOffset, int BOffset) {
8258 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8259 "Must call this with A having 3 or 1 inputs from the A half.");
8260 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8261 "Must call this with B having 1 or 3 inputs from the B half.");
8262 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8263 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8265 // Compute the index of dword with only one word among the three inputs in
8266 // a half by taking the sum of the half with three inputs and subtracting
8267 // the sum of the actual three inputs. The difference is the remaining
8270 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8271 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8272 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8273 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8274 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8275 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8276 int TripleNonInputIdx =
8277 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8278 TripleDWord = TripleNonInputIdx / 2;
8280 // We use xor with one to compute the adjacent DWord to whichever one the
8282 OneInputDWord = (OneInput / 2) ^ 1;
8284 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8285 // and BToA inputs. If there is also such a problem with the BToB and AToB
8286 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8287 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8288 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8289 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8290 // Compute how many inputs will be flipped by swapping these DWords. We
8292 // to balance this to ensure we don't form a 3-1 shuffle in the other
8294 int NumFlippedAToBInputs =
8295 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8296 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8297 int NumFlippedBToBInputs =
8298 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8299 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8300 if ((NumFlippedAToBInputs == 1 &&
8301 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8302 (NumFlippedBToBInputs == 1 &&
8303 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8304 // We choose whether to fix the A half or B half based on whether that
8305 // half has zero flipped inputs. At zero, we may not be able to fix it
8306 // with that half. We also bias towards fixing the B half because that
8307 // will more commonly be the high half, and we have to bias one way.
8308 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8309 ArrayRef<int> Inputs) {
8310 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8311 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8312 PinnedIdx ^ 1) != Inputs.end();
8313 // Determine whether the free index is in the flipped dword or the
8314 // unflipped dword based on where the pinned index is. We use this bit
8315 // in an xor to conditionally select the adjacent dword.
8316 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8317 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8318 FixFreeIdx) != Inputs.end();
8319 if (IsFixIdxInput == IsFixFreeIdxInput)
8321 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8322 FixFreeIdx) != Inputs.end();
8323 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8324 "We need to be changing the number of flipped inputs!");
8325 int PSHUFHalfMask[] = {0, 1, 2, 3};
8326 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8327 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8329 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8332 if (M != -1 && M == FixIdx)
8334 else if (M != -1 && M == FixFreeIdx)
8337 if (NumFlippedBToBInputs != 0) {
8339 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8340 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8342 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8344 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8345 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8350 int PSHUFDMask[] = {0, 1, 2, 3};
8351 PSHUFDMask[ADWord] = BDWord;
8352 PSHUFDMask[BDWord] = ADWord;
8355 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8356 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8358 // Adjust the mask to match the new locations of A and B.
8360 if (M != -1 && M/2 == ADWord)
8361 M = 2 * BDWord + M % 2;
8362 else if (M != -1 && M/2 == BDWord)
8363 M = 2 * ADWord + M % 2;
8365 // Recurse back into this routine to re-compute state now that this isn't
8366 // a 3 and 1 problem.
8367 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8370 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8371 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8372 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8373 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8375 // At this point there are at most two inputs to the low and high halves from
8376 // each half. That means the inputs can always be grouped into dwords and
8377 // those dwords can then be moved to the correct half with a dword shuffle.
8378 // We use at most one low and one high word shuffle to collect these paired
8379 // inputs into dwords, and finally a dword shuffle to place them.
8380 int PSHUFLMask[4] = {-1, -1, -1, -1};
8381 int PSHUFHMask[4] = {-1, -1, -1, -1};
8382 int PSHUFDMask[4] = {-1, -1, -1, -1};
8384 // First fix the masks for all the inputs that are staying in their
8385 // original halves. This will then dictate the targets of the cross-half
8387 auto fixInPlaceInputs =
8388 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8389 MutableArrayRef<int> SourceHalfMask,
8390 MutableArrayRef<int> HalfMask, int HalfOffset) {
8391 if (InPlaceInputs.empty())
8393 if (InPlaceInputs.size() == 1) {
8394 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8395 InPlaceInputs[0] - HalfOffset;
8396 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8399 if (IncomingInputs.empty()) {
8400 // Just fix all of the in place inputs.
8401 for (int Input : InPlaceInputs) {
8402 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8403 PSHUFDMask[Input / 2] = Input / 2;
8408 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8409 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8410 InPlaceInputs[0] - HalfOffset;
8411 // Put the second input next to the first so that they are packed into
8412 // a dword. We find the adjacent index by toggling the low bit.
8413 int AdjIndex = InPlaceInputs[0] ^ 1;
8414 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8415 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8416 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8418 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8419 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8421 // Now gather the cross-half inputs and place them into a free dword of
8422 // their target half.
8423 // FIXME: This operation could almost certainly be simplified dramatically to
8424 // look more like the 3-1 fixing operation.
8425 auto moveInputsToRightHalf = [&PSHUFDMask](
8426 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8427 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8428 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8430 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8431 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8433 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8435 int LowWord = Word & ~1;
8436 int HighWord = Word | 1;
8437 return isWordClobbered(SourceHalfMask, LowWord) ||
8438 isWordClobbered(SourceHalfMask, HighWord);
8441 if (IncomingInputs.empty())
8444 if (ExistingInputs.empty()) {
8445 // Map any dwords with inputs from them into the right half.
8446 for (int Input : IncomingInputs) {
8447 // If the source half mask maps over the inputs, turn those into
8448 // swaps and use the swapped lane.
8449 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8450 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8451 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8452 Input - SourceOffset;
8453 // We have to swap the uses in our half mask in one sweep.
8454 for (int &M : HalfMask)
8455 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8457 else if (M == Input)
8458 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8460 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8461 Input - SourceOffset &&
8462 "Previous placement doesn't match!");
8464 // Note that this correctly re-maps both when we do a swap and when
8465 // we observe the other side of the swap above. We rely on that to
8466 // avoid swapping the members of the input list directly.
8467 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8470 // Map the input's dword into the correct half.
8471 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8472 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8474 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8476 "Previous placement doesn't match!");
8479 // And just directly shift any other-half mask elements to be same-half
8480 // as we will have mirrored the dword containing the element into the
8481 // same position within that half.
8482 for (int &M : HalfMask)
8483 if (M >= SourceOffset && M < SourceOffset + 4) {
8484 M = M - SourceOffset + DestOffset;
8485 assert(M >= 0 && "This should never wrap below zero!");
8490 // Ensure we have the input in a viable dword of its current half. This
8491 // is particularly tricky because the original position may be clobbered
8492 // by inputs being moved and *staying* in that half.
8493 if (IncomingInputs.size() == 1) {
8494 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8495 int InputFixed = std::find(std::begin(SourceHalfMask),
8496 std::end(SourceHalfMask), -1) -
8497 std::begin(SourceHalfMask) + SourceOffset;
8498 SourceHalfMask[InputFixed - SourceOffset] =
8499 IncomingInputs[0] - SourceOffset;
8500 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8502 IncomingInputs[0] = InputFixed;
8504 } else if (IncomingInputs.size() == 2) {
8505 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8506 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8507 // We have two non-adjacent or clobbered inputs we need to extract from
8508 // the source half. To do this, we need to map them into some adjacent
8509 // dword slot in the source mask.
8510 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8511 IncomingInputs[1] - SourceOffset};
8513 // If there is a free slot in the source half mask adjacent to one of
8514 // the inputs, place the other input in it. We use (Index XOR 1) to
8515 // compute an adjacent index.
8516 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8517 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8518 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8519 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8520 InputsFixed[1] = InputsFixed[0] ^ 1;
8521 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8522 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8523 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8524 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8525 InputsFixed[0] = InputsFixed[1] ^ 1;
8526 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8527 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8528 // The two inputs are in the same DWord but it is clobbered and the
8529 // adjacent DWord isn't used at all. Move both inputs to the free
8531 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8532 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8533 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8534 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8536 // The only way we hit this point is if there is no clobbering
8537 // (because there are no off-half inputs to this half) and there is no
8538 // free slot adjacent to one of the inputs. In this case, we have to
8539 // swap an input with a non-input.
8540 for (int i = 0; i < 4; ++i)
8541 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8542 "We can't handle any clobbers here!");
8543 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8544 "Cannot have adjacent inputs here!");
8546 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8547 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8549 // We also have to update the final source mask in this case because
8550 // it may need to undo the above swap.
8551 for (int &M : FinalSourceHalfMask)
8552 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8553 M = InputsFixed[1] + SourceOffset;
8554 else if (M == InputsFixed[1] + SourceOffset)
8555 M = (InputsFixed[0] ^ 1) + SourceOffset;
8557 InputsFixed[1] = InputsFixed[0] ^ 1;
8560 // Point everything at the fixed inputs.
8561 for (int &M : HalfMask)
8562 if (M == IncomingInputs[0])
8563 M = InputsFixed[0] + SourceOffset;
8564 else if (M == IncomingInputs[1])
8565 M = InputsFixed[1] + SourceOffset;
8567 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8568 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8571 llvm_unreachable("Unhandled input size!");
8574 // Now hoist the DWord down to the right half.
8575 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8576 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8577 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8578 for (int &M : HalfMask)
8579 for (int Input : IncomingInputs)
8581 M = FreeDWord * 2 + Input % 2;
8583 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8584 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8585 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8586 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8588 // Now enact all the shuffles we've computed to move the inputs into their
8590 if (!isNoopShuffleMask(PSHUFLMask))
8591 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8592 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8593 if (!isNoopShuffleMask(PSHUFHMask))
8594 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8595 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8596 if (!isNoopShuffleMask(PSHUFDMask))
8599 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8600 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8602 // At this point, each half should contain all its inputs, and we can then
8603 // just shuffle them into their final position.
8604 assert(std::count_if(LoMask.begin(), LoMask.end(),
8605 [](int M) { return M >= 4; }) == 0 &&
8606 "Failed to lift all the high half inputs to the low mask!");
8607 assert(std::count_if(HiMask.begin(), HiMask.end(),
8608 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8609 "Failed to lift all the low half inputs to the high mask!");
8611 // Do a half shuffle for the low mask.
8612 if (!isNoopShuffleMask(LoMask))
8613 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8614 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8616 // Do a half shuffle with the high mask after shifting its values down.
8617 for (int &M : HiMask)
8620 if (!isNoopShuffleMask(HiMask))
8621 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8622 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8627 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8628 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8629 SDValue V2, ArrayRef<int> Mask,
8630 SelectionDAG &DAG, bool &V1InUse,
8632 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8638 int Size = Mask.size();
8639 int Scale = 16 / Size;
8640 for (int i = 0; i < 16; ++i) {
8641 if (Mask[i / Scale] == -1) {
8642 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8644 const int ZeroMask = 0x80;
8645 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8647 int V2Idx = Mask[i / Scale] < Size
8649 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8650 if (Zeroable[i / Scale])
8651 V1Idx = V2Idx = ZeroMask;
8652 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8653 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8654 V1InUse |= (ZeroMask != V1Idx);
8655 V2InUse |= (ZeroMask != V2Idx);
8660 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8661 DAG.getBitcast(MVT::v16i8, V1),
8662 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8664 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8665 DAG.getBitcast(MVT::v16i8, V2),
8666 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8668 // If we need shuffled inputs from both, blend the two.
8670 if (V1InUse && V2InUse)
8671 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8673 V = V1InUse ? V1 : V2;
8675 // Cast the result back to the correct type.
8676 return DAG.getBitcast(VT, V);
8679 /// \brief Generic lowering of 8-lane i16 shuffles.
8681 /// This handles both single-input shuffles and combined shuffle/blends with
8682 /// two inputs. The single input shuffles are immediately delegated to
8683 /// a dedicated lowering routine.
8685 /// The blends are lowered in one of three fundamental ways. If there are few
8686 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8687 /// of the input is significantly cheaper when lowered as an interleaving of
8688 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8689 /// halves of the inputs separately (making them have relatively few inputs)
8690 /// and then concatenate them.
8691 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8692 const X86Subtarget *Subtarget,
8693 SelectionDAG &DAG) {
8695 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8696 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8697 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8698 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8699 ArrayRef<int> OrigMask = SVOp->getMask();
8700 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8701 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8702 MutableArrayRef<int> Mask(MaskStorage);
8704 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8706 // Whenever we can lower this as a zext, that instruction is strictly faster
8707 // than any alternative.
8708 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8709 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8712 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8714 auto isV2 = [](int M) { return M >= 8; };
8716 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8718 if (NumV2Inputs == 0) {
8719 // Check for being able to broadcast a single element.
8720 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8721 Mask, Subtarget, DAG))
8724 // Try to use shift instructions.
8726 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8729 // Use dedicated unpack instructions for masks that match their pattern.
8730 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8731 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8732 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8733 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8735 // Try to use byte rotation instructions.
8736 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8737 Mask, Subtarget, DAG))
8740 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8744 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8745 "All single-input shuffles should be canonicalized to be V1-input "
8748 // Try to use shift instructions.
8750 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8753 // See if we can use SSE4A Extraction / Insertion.
8754 if (Subtarget->hasSSE4A())
8755 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8758 // There are special ways we can lower some single-element blends.
8759 if (NumV2Inputs == 1)
8760 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8761 Mask, Subtarget, DAG))
8764 // We have different paths for blend lowering, but they all must use the
8765 // *exact* same predicate.
8766 bool IsBlendSupported = Subtarget->hasSSE41();
8767 if (IsBlendSupported)
8768 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8772 if (SDValue Masked =
8773 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8776 // Use dedicated unpack instructions for masks that match their pattern.
8777 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8778 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8779 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8780 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8782 // Try to use byte rotation instructions.
8783 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8784 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8787 if (SDValue BitBlend =
8788 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8791 if (SDValue Unpack =
8792 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8795 // If we can't directly blend but can use PSHUFB, that will be better as it
8796 // can both shuffle and set up the inefficient blend.
8797 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8798 bool V1InUse, V2InUse;
8799 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8803 // We can always bit-blend if we have to so the fallback strategy is to
8804 // decompose into single-input permutes and blends.
8805 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8809 /// \brief Check whether a compaction lowering can be done by dropping even
8810 /// elements and compute how many times even elements must be dropped.
8812 /// This handles shuffles which take every Nth element where N is a power of
8813 /// two. Example shuffle masks:
8815 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8816 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8817 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8818 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8819 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8820 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8822 /// Any of these lanes can of course be undef.
8824 /// This routine only supports N <= 3.
8825 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8828 /// \returns N above, or the number of times even elements must be dropped if
8829 /// there is such a number. Otherwise returns zero.
8830 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8831 // Figure out whether we're looping over two inputs or just one.
8832 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8834 // The modulus for the shuffle vector entries is based on whether this is
8835 // a single input or not.
8836 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8837 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8838 "We should only be called with masks with a power-of-2 size!");
8840 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8842 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8843 // and 2^3 simultaneously. This is because we may have ambiguity with
8844 // partially undef inputs.
8845 bool ViableForN[3] = {true, true, true};
8847 for (int i = 0, e = Mask.size(); i < e; ++i) {
8848 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8853 bool IsAnyViable = false;
8854 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8855 if (ViableForN[j]) {
8858 // The shuffle mask must be equal to (i * 2^N) % M.
8859 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8862 ViableForN[j] = false;
8864 // Early exit if we exhaust the possible powers of two.
8869 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8873 // Return 0 as there is no viable power of two.
8877 /// \brief Generic lowering of v16i8 shuffles.
8879 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8880 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8881 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8882 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8884 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8885 const X86Subtarget *Subtarget,
8886 SelectionDAG &DAG) {
8888 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8889 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8890 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8891 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8892 ArrayRef<int> Mask = SVOp->getMask();
8893 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8895 // Try to use shift instructions.
8897 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8900 // Try to use byte rotation instructions.
8901 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8902 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8905 // Try to use a zext lowering.
8906 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8907 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8910 // See if we can use SSE4A Extraction / Insertion.
8911 if (Subtarget->hasSSE4A())
8912 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8916 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8918 // For single-input shuffles, there are some nicer lowering tricks we can use.
8919 if (NumV2Elements == 0) {
8920 // Check for being able to broadcast a single element.
8921 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8922 Mask, Subtarget, DAG))
8925 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8926 // Notably, this handles splat and partial-splat shuffles more efficiently.
8927 // However, it only makes sense if the pre-duplication shuffle simplifies
8928 // things significantly. Currently, this means we need to be able to
8929 // express the pre-duplication shuffle as an i16 shuffle.
8931 // FIXME: We should check for other patterns which can be widened into an
8932 // i16 shuffle as well.
8933 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8934 for (int i = 0; i < 16; i += 2)
8935 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8940 auto tryToWidenViaDuplication = [&]() -> SDValue {
8941 if (!canWidenViaDuplication(Mask))
8943 SmallVector<int, 4> LoInputs;
8944 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8945 [](int M) { return M >= 0 && M < 8; });
8946 std::sort(LoInputs.begin(), LoInputs.end());
8947 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8949 SmallVector<int, 4> HiInputs;
8950 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8951 [](int M) { return M >= 8; });
8952 std::sort(HiInputs.begin(), HiInputs.end());
8953 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8956 bool TargetLo = LoInputs.size() >= HiInputs.size();
8957 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8958 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8960 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8961 SmallDenseMap<int, int, 8> LaneMap;
8962 for (int I : InPlaceInputs) {
8963 PreDupI16Shuffle[I/2] = I/2;
8966 int j = TargetLo ? 0 : 4, je = j + 4;
8967 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8968 // Check if j is already a shuffle of this input. This happens when
8969 // there are two adjacent bytes after we move the low one.
8970 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8971 // If we haven't yet mapped the input, search for a slot into which
8973 while (j < je && PreDupI16Shuffle[j] != -1)
8977 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8980 // Map this input with the i16 shuffle.
8981 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8984 // Update the lane map based on the mapping we ended up with.
8985 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8987 V1 = DAG.getBitcast(
8989 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8990 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8992 // Unpack the bytes to form the i16s that will be shuffled into place.
8993 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8994 MVT::v16i8, V1, V1);
8996 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8997 for (int i = 0; i < 16; ++i)
8998 if (Mask[i] != -1) {
8999 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9000 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9001 if (PostDupI16Shuffle[i / 2] == -1)
9002 PostDupI16Shuffle[i / 2] = MappedMask;
9004 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9005 "Conflicting entrties in the original shuffle!");
9007 return DAG.getBitcast(
9009 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9010 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9012 if (SDValue V = tryToWidenViaDuplication())
9016 // Use dedicated unpack instructions for masks that match their pattern.
9017 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9018 0, 16, 1, 17, 2, 18, 3, 19,
9020 4, 20, 5, 21, 6, 22, 7, 23}))
9021 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9022 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9023 8, 24, 9, 25, 10, 26, 11, 27,
9025 12, 28, 13, 29, 14, 30, 15, 31}))
9026 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9028 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9029 // with PSHUFB. It is important to do this before we attempt to generate any
9030 // blends but after all of the single-input lowerings. If the single input
9031 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9032 // want to preserve that and we can DAG combine any longer sequences into
9033 // a PSHUFB in the end. But once we start blending from multiple inputs,
9034 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9035 // and there are *very* few patterns that would actually be faster than the
9036 // PSHUFB approach because of its ability to zero lanes.
9038 // FIXME: The only exceptions to the above are blends which are exact
9039 // interleavings with direct instructions supporting them. We currently don't
9040 // handle those well here.
9041 if (Subtarget->hasSSSE3()) {
9042 bool V1InUse = false;
9043 bool V2InUse = false;
9045 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9046 DAG, V1InUse, V2InUse);
9048 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9049 // do so. This avoids using them to handle blends-with-zero which is
9050 // important as a single pshufb is significantly faster for that.
9051 if (V1InUse && V2InUse) {
9052 if (Subtarget->hasSSE41())
9053 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9054 Mask, Subtarget, DAG))
9057 // We can use an unpack to do the blending rather than an or in some
9058 // cases. Even though the or may be (very minorly) more efficient, we
9059 // preference this lowering because there are common cases where part of
9060 // the complexity of the shuffles goes away when we do the final blend as
9062 // FIXME: It might be worth trying to detect if the unpack-feeding
9063 // shuffles will both be pshufb, in which case we shouldn't bother with
9065 if (SDValue Unpack =
9066 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9073 // There are special ways we can lower some single-element blends.
9074 if (NumV2Elements == 1)
9075 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9076 Mask, Subtarget, DAG))
9079 if (SDValue BitBlend =
9080 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9083 // Check whether a compaction lowering can be done. This handles shuffles
9084 // which take every Nth element for some even N. See the helper function for
9087 // We special case these as they can be particularly efficiently handled with
9088 // the PACKUSB instruction on x86 and they show up in common patterns of
9089 // rearranging bytes to truncate wide elements.
9090 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9091 // NumEvenDrops is the power of two stride of the elements. Another way of
9092 // thinking about it is that we need to drop the even elements this many
9093 // times to get the original input.
9094 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9096 // First we need to zero all the dropped bytes.
9097 assert(NumEvenDrops <= 3 &&
9098 "No support for dropping even elements more than 3 times.");
9099 // We use the mask type to pick which bytes are preserved based on how many
9100 // elements are dropped.
9101 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9102 SDValue ByteClearMask = DAG.getBitcast(
9103 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9104 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9106 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9108 // Now pack things back together.
9109 V1 = DAG.getBitcast(MVT::v8i16, V1);
9110 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9111 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9112 for (int i = 1; i < NumEvenDrops; ++i) {
9113 Result = DAG.getBitcast(MVT::v8i16, Result);
9114 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9120 // Handle multi-input cases by blending single-input shuffles.
9121 if (NumV2Elements > 0)
9122 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9125 // The fallback path for single-input shuffles widens this into two v8i16
9126 // vectors with unpacks, shuffles those, and then pulls them back together
9130 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9131 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9132 for (int i = 0; i < 16; ++i)
9134 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9136 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9138 SDValue VLoHalf, VHiHalf;
9139 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9140 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9142 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9143 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9144 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9145 [](int M) { return M >= 0 && M % 2 == 1; })) {
9146 // Use a mask to drop the high bytes.
9147 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9148 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9149 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9151 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9152 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9154 // Squash the masks to point directly into VLoHalf.
9155 for (int &M : LoBlendMask)
9158 for (int &M : HiBlendMask)
9162 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9163 // VHiHalf so that we can blend them as i16s.
9164 VLoHalf = DAG.getBitcast(
9165 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9166 VHiHalf = DAG.getBitcast(
9167 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9170 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9171 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9173 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9176 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9178 /// This routine breaks down the specific type of 128-bit shuffle and
9179 /// dispatches to the lowering routines accordingly.
9180 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9181 MVT VT, const X86Subtarget *Subtarget,
9182 SelectionDAG &DAG) {
9183 switch (VT.SimpleTy) {
9185 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9187 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9189 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9191 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9193 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9195 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9198 llvm_unreachable("Unimplemented!");
9202 /// \brief Helper function to test whether a shuffle mask could be
9203 /// simplified by widening the elements being shuffled.
9205 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9206 /// leaves it in an unspecified state.
9208 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9209 /// shuffle masks. The latter have the special property of a '-2' representing
9210 /// a zero-ed lane of a vector.
9211 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9212 SmallVectorImpl<int> &WidenedMask) {
9213 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9214 // If both elements are undef, its trivial.
9215 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9216 WidenedMask.push_back(SM_SentinelUndef);
9220 // Check for an undef mask and a mask value properly aligned to fit with
9221 // a pair of values. If we find such a case, use the non-undef mask's value.
9222 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9223 WidenedMask.push_back(Mask[i + 1] / 2);
9226 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9227 WidenedMask.push_back(Mask[i] / 2);
9231 // When zeroing, we need to spread the zeroing across both lanes to widen.
9232 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9233 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9234 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9235 WidenedMask.push_back(SM_SentinelZero);
9241 // Finally check if the two mask values are adjacent and aligned with
9243 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9244 WidenedMask.push_back(Mask[i] / 2);
9248 // Otherwise we can't safely widen the elements used in this shuffle.
9251 assert(WidenedMask.size() == Mask.size() / 2 &&
9252 "Incorrect size of mask after widening the elements!");
9257 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9259 /// This routine just extracts two subvectors, shuffles them independently, and
9260 /// then concatenates them back together. This should work effectively with all
9261 /// AVX vector shuffle types.
9262 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9263 SDValue V2, ArrayRef<int> Mask,
9264 SelectionDAG &DAG) {
9265 assert(VT.getSizeInBits() >= 256 &&
9266 "Only for 256-bit or wider vector shuffles!");
9267 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9268 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9270 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9271 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9273 int NumElements = VT.getVectorNumElements();
9274 int SplitNumElements = NumElements / 2;
9275 MVT ScalarVT = VT.getScalarType();
9276 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9278 // Rather than splitting build-vectors, just build two narrower build
9279 // vectors. This helps shuffling with splats and zeros.
9280 auto SplitVector = [&](SDValue V) {
9281 while (V.getOpcode() == ISD::BITCAST)
9282 V = V->getOperand(0);
9284 MVT OrigVT = V.getSimpleValueType();
9285 int OrigNumElements = OrigVT.getVectorNumElements();
9286 int OrigSplitNumElements = OrigNumElements / 2;
9287 MVT OrigScalarVT = OrigVT.getScalarType();
9288 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9292 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9294 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9295 DAG.getIntPtrConstant(0, DL));
9296 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9297 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9300 SmallVector<SDValue, 16> LoOps, HiOps;
9301 for (int i = 0; i < OrigSplitNumElements; ++i) {
9302 LoOps.push_back(BV->getOperand(i));
9303 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9305 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9306 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9308 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9309 DAG.getBitcast(SplitVT, HiV));
9312 SDValue LoV1, HiV1, LoV2, HiV2;
9313 std::tie(LoV1, HiV1) = SplitVector(V1);
9314 std::tie(LoV2, HiV2) = SplitVector(V2);
9316 // Now create two 4-way blends of these half-width vectors.
9317 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9318 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9319 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9320 for (int i = 0; i < SplitNumElements; ++i) {
9321 int M = HalfMask[i];
9322 if (M >= NumElements) {
9323 if (M >= NumElements + SplitNumElements)
9327 V2BlendMask.push_back(M - NumElements);
9328 V1BlendMask.push_back(-1);
9329 BlendMask.push_back(SplitNumElements + i);
9330 } else if (M >= 0) {
9331 if (M >= SplitNumElements)
9335 V2BlendMask.push_back(-1);
9336 V1BlendMask.push_back(M);
9337 BlendMask.push_back(i);
9339 V2BlendMask.push_back(-1);
9340 V1BlendMask.push_back(-1);
9341 BlendMask.push_back(-1);
9345 // Because the lowering happens after all combining takes place, we need to
9346 // manually combine these blend masks as much as possible so that we create
9347 // a minimal number of high-level vector shuffle nodes.
9349 // First try just blending the halves of V1 or V2.
9350 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9351 return DAG.getUNDEF(SplitVT);
9352 if (!UseLoV2 && !UseHiV2)
9353 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9354 if (!UseLoV1 && !UseHiV1)
9355 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9357 SDValue V1Blend, V2Blend;
9358 if (UseLoV1 && UseHiV1) {
9360 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9362 // We only use half of V1 so map the usage down into the final blend mask.
9363 V1Blend = UseLoV1 ? LoV1 : HiV1;
9364 for (int i = 0; i < SplitNumElements; ++i)
9365 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9366 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9368 if (UseLoV2 && UseHiV2) {
9370 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9372 // We only use half of V2 so map the usage down into the final blend mask.
9373 V2Blend = UseLoV2 ? LoV2 : HiV2;
9374 for (int i = 0; i < SplitNumElements; ++i)
9375 if (BlendMask[i] >= SplitNumElements)
9376 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9378 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9380 SDValue Lo = HalfBlend(LoMask);
9381 SDValue Hi = HalfBlend(HiMask);
9382 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9385 /// \brief Either split a vector in halves or decompose the shuffles and the
9388 /// This is provided as a good fallback for many lowerings of non-single-input
9389 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9390 /// between splitting the shuffle into 128-bit components and stitching those
9391 /// back together vs. extracting the single-input shuffles and blending those
9393 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9394 SDValue V2, ArrayRef<int> Mask,
9395 SelectionDAG &DAG) {
9396 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9397 "lower single-input shuffles as it "
9398 "could then recurse on itself.");
9399 int Size = Mask.size();
9401 // If this can be modeled as a broadcast of two elements followed by a blend,
9402 // prefer that lowering. This is especially important because broadcasts can
9403 // often fold with memory operands.
9404 auto DoBothBroadcast = [&] {
9405 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9408 if (V2BroadcastIdx == -1)
9409 V2BroadcastIdx = M - Size;
9410 else if (M - Size != V2BroadcastIdx)
9412 } else if (M >= 0) {
9413 if (V1BroadcastIdx == -1)
9415 else if (M != V1BroadcastIdx)
9420 if (DoBothBroadcast())
9421 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9424 // If the inputs all stem from a single 128-bit lane of each input, then we
9425 // split them rather than blending because the split will decompose to
9426 // unusually few instructions.
9427 int LaneCount = VT.getSizeInBits() / 128;
9428 int LaneSize = Size / LaneCount;
9429 SmallBitVector LaneInputs[2];
9430 LaneInputs[0].resize(LaneCount, false);
9431 LaneInputs[1].resize(LaneCount, false);
9432 for (int i = 0; i < Size; ++i)
9434 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9435 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9436 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9438 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9439 // that the decomposed single-input shuffles don't end up here.
9440 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9443 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9444 /// a permutation and blend of those lanes.
9446 /// This essentially blends the out-of-lane inputs to each lane into the lane
9447 /// from a permuted copy of the vector. This lowering strategy results in four
9448 /// instructions in the worst case for a single-input cross lane shuffle which
9449 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9450 /// of. Special cases for each particular shuffle pattern should be handled
9451 /// prior to trying this lowering.
9452 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9453 SDValue V1, SDValue V2,
9455 SelectionDAG &DAG) {
9456 // FIXME: This should probably be generalized for 512-bit vectors as well.
9457 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9458 int LaneSize = Mask.size() / 2;
9460 // If there are only inputs from one 128-bit lane, splitting will in fact be
9461 // less expensive. The flags track whether the given lane contains an element
9462 // that crosses to another lane.
9463 bool LaneCrossing[2] = {false, false};
9464 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9465 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9466 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9467 if (!LaneCrossing[0] || !LaneCrossing[1])
9468 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9470 if (isSingleInputShuffleMask(Mask)) {
9471 SmallVector<int, 32> FlippedBlendMask;
9472 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9473 FlippedBlendMask.push_back(
9474 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9476 : Mask[i] % LaneSize +
9477 (i / LaneSize) * LaneSize + Size));
9479 // Flip the vector, and blend the results which should now be in-lane. The
9480 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9481 // 5 for the high source. The value 3 selects the high half of source 2 and
9482 // the value 2 selects the low half of source 2. We only use source 2 to
9483 // allow folding it into a memory operand.
9484 unsigned PERMMask = 3 | 2 << 4;
9485 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9486 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9487 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9490 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9491 // will be handled by the above logic and a blend of the results, much like
9492 // other patterns in AVX.
9493 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9496 /// \brief Handle lowering 2-lane 128-bit shuffles.
9497 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9498 SDValue V2, ArrayRef<int> Mask,
9499 const X86Subtarget *Subtarget,
9500 SelectionDAG &DAG) {
9501 // TODO: If minimizing size and one of the inputs is a zero vector and the
9502 // the zero vector has only one use, we could use a VPERM2X128 to save the
9503 // instruction bytes needed to explicitly generate the zero vector.
9505 // Blends are faster and handle all the non-lane-crossing cases.
9506 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9510 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9511 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9513 // If either input operand is a zero vector, use VPERM2X128 because its mask
9514 // allows us to replace the zero input with an implicit zero.
9515 if (!IsV1Zero && !IsV2Zero) {
9516 // Check for patterns which can be matched with a single insert of a 128-bit
9518 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9519 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9520 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9521 VT.getVectorNumElements() / 2);
9522 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9523 DAG.getIntPtrConstant(0, DL));
9524 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9525 OnlyUsesV1 ? V1 : V2,
9526 DAG.getIntPtrConstant(0, DL));
9527 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9531 // Otherwise form a 128-bit permutation. After accounting for undefs,
9532 // convert the 64-bit shuffle mask selection values into 128-bit
9533 // selection bits by dividing the indexes by 2 and shifting into positions
9534 // defined by a vperm2*128 instruction's immediate control byte.
9536 // The immediate permute control byte looks like this:
9537 // [1:0] - select 128 bits from sources for low half of destination
9539 // [3] - zero low half of destination
9540 // [5:4] - select 128 bits from sources for high half of destination
9542 // [7] - zero high half of destination
9544 int MaskLO = Mask[0];
9545 if (MaskLO == SM_SentinelUndef)
9546 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9548 int MaskHI = Mask[2];
9549 if (MaskHI == SM_SentinelUndef)
9550 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9552 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9554 // If either input is a zero vector, replace it with an undef input.
9555 // Shuffle mask values < 4 are selecting elements of V1.
9556 // Shuffle mask values >= 4 are selecting elements of V2.
9557 // Adjust each half of the permute mask by clearing the half that was
9558 // selecting the zero vector and setting the zero mask bit.
9560 V1 = DAG.getUNDEF(VT);
9562 PermMask = (PermMask & 0xf0) | 0x08;
9564 PermMask = (PermMask & 0x0f) | 0x80;
9567 V2 = DAG.getUNDEF(VT);
9569 PermMask = (PermMask & 0xf0) | 0x08;
9571 PermMask = (PermMask & 0x0f) | 0x80;
9574 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9575 DAG.getConstant(PermMask, DL, MVT::i8));
9578 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9579 /// shuffling each lane.
9581 /// This will only succeed when the result of fixing the 128-bit lanes results
9582 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9583 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9584 /// the lane crosses early and then use simpler shuffles within each lane.
9586 /// FIXME: It might be worthwhile at some point to support this without
9587 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9588 /// in x86 only floating point has interesting non-repeating shuffles, and even
9589 /// those are still *marginally* more expensive.
9590 static SDValue lowerVectorShuffleByMerging128BitLanes(
9591 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9592 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9593 assert(!isSingleInputShuffleMask(Mask) &&
9594 "This is only useful with multiple inputs.");
9596 int Size = Mask.size();
9597 int LaneSize = 128 / VT.getScalarSizeInBits();
9598 int NumLanes = Size / LaneSize;
9599 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9601 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9602 // check whether the in-128-bit lane shuffles share a repeating pattern.
9603 SmallVector<int, 4> Lanes;
9604 Lanes.resize(NumLanes, -1);
9605 SmallVector<int, 4> InLaneMask;
9606 InLaneMask.resize(LaneSize, -1);
9607 for (int i = 0; i < Size; ++i) {
9611 int j = i / LaneSize;
9614 // First entry we've seen for this lane.
9615 Lanes[j] = Mask[i] / LaneSize;
9616 } else if (Lanes[j] != Mask[i] / LaneSize) {
9617 // This doesn't match the lane selected previously!
9621 // Check that within each lane we have a consistent shuffle mask.
9622 int k = i % LaneSize;
9623 if (InLaneMask[k] < 0) {
9624 InLaneMask[k] = Mask[i] % LaneSize;
9625 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9626 // This doesn't fit a repeating in-lane mask.
9631 // First shuffle the lanes into place.
9632 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9633 VT.getSizeInBits() / 64);
9634 SmallVector<int, 8> LaneMask;
9635 LaneMask.resize(NumLanes * 2, -1);
9636 for (int i = 0; i < NumLanes; ++i)
9637 if (Lanes[i] >= 0) {
9638 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9639 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9642 V1 = DAG.getBitcast(LaneVT, V1);
9643 V2 = DAG.getBitcast(LaneVT, V2);
9644 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9646 // Cast it back to the type we actually want.
9647 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9649 // Now do a simple shuffle that isn't lane crossing.
9650 SmallVector<int, 8> NewMask;
9651 NewMask.resize(Size, -1);
9652 for (int i = 0; i < Size; ++i)
9654 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9655 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9656 "Must not introduce lane crosses at this point!");
9658 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9661 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9664 /// This returns true if the elements from a particular input are already in the
9665 /// slot required by the given mask and require no permutation.
9666 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9667 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9668 int Size = Mask.size();
9669 for (int i = 0; i < Size; ++i)
9670 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9676 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9677 ArrayRef<int> Mask, SDValue V1,
9678 SDValue V2, SelectionDAG &DAG) {
9680 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9681 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9682 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9683 int NumElts = VT.getVectorNumElements();
9684 bool ShufpdMask = true;
9685 bool CommutableMask = true;
9686 unsigned Immediate = 0;
9687 for (int i = 0; i < NumElts; ++i) {
9690 int Val = (i & 6) + NumElts * (i & 1);
9691 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9692 if (Mask[i] < Val || Mask[i] > Val + 1)
9694 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9695 CommutableMask = false;
9696 Immediate |= (Mask[i] % 2) << i;
9699 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9700 DAG.getConstant(Immediate, DL, MVT::i8));
9702 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9703 DAG.getConstant(Immediate, DL, MVT::i8));
9707 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9709 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9710 /// isn't available.
9711 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9712 const X86Subtarget *Subtarget,
9713 SelectionDAG &DAG) {
9715 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9716 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9717 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9718 ArrayRef<int> Mask = SVOp->getMask();
9719 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9721 SmallVector<int, 4> WidenedMask;
9722 if (canWidenShuffleElements(Mask, WidenedMask))
9723 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9726 if (isSingleInputShuffleMask(Mask)) {
9727 // Check for being able to broadcast a single element.
9728 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9729 Mask, Subtarget, DAG))
9732 // Use low duplicate instructions for masks that match their pattern.
9733 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9734 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9736 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9737 // Non-half-crossing single input shuffles can be lowerid with an
9738 // interleaved permutation.
9739 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9740 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9741 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9742 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9745 // With AVX2 we have direct support for this permutation.
9746 if (Subtarget->hasAVX2())
9747 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9748 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9750 // Otherwise, fall back.
9751 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9755 // X86 has dedicated unpack instructions that can handle specific blend
9756 // operations: UNPCKH and UNPCKL.
9757 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9758 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9759 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9760 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9761 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9762 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9763 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9764 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9766 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9770 // Check if the blend happens to exactly fit that of SHUFPD.
9772 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9775 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9776 // shuffle. However, if we have AVX2 and either inputs are already in place,
9777 // we will be able to shuffle even across lanes the other input in a single
9778 // instruction so skip this pattern.
9779 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9780 isShuffleMaskInputInPlace(1, Mask))))
9781 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9782 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9785 // If we have AVX2 then we always want to lower with a blend because an v4 we
9786 // can fully permute the elements.
9787 if (Subtarget->hasAVX2())
9788 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9791 // Otherwise fall back on generic lowering.
9792 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9795 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9797 /// This routine is only called when we have AVX2 and thus a reasonable
9798 /// instruction set for v4i64 shuffling..
9799 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9800 const X86Subtarget *Subtarget,
9801 SelectionDAG &DAG) {
9803 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9804 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9805 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9806 ArrayRef<int> Mask = SVOp->getMask();
9807 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9808 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9810 SmallVector<int, 4> WidenedMask;
9811 if (canWidenShuffleElements(Mask, WidenedMask))
9812 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9815 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9819 // Check for being able to broadcast a single element.
9820 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9821 Mask, Subtarget, DAG))
9824 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9825 // use lower latency instructions that will operate on both 128-bit lanes.
9826 SmallVector<int, 2> RepeatedMask;
9827 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9828 if (isSingleInputShuffleMask(Mask)) {
9829 int PSHUFDMask[] = {-1, -1, -1, -1};
9830 for (int i = 0; i < 2; ++i)
9831 if (RepeatedMask[i] >= 0) {
9832 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9833 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9835 return DAG.getBitcast(
9837 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9838 DAG.getBitcast(MVT::v8i32, V1),
9839 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9843 // AVX2 provides a direct instruction for permuting a single input across
9845 if (isSingleInputShuffleMask(Mask))
9846 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9847 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9849 // Try to use shift instructions.
9851 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9854 // Use dedicated unpack instructions for masks that match their pattern.
9855 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9856 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9857 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9858 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9859 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9860 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9861 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9862 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9864 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9865 // shuffle. However, if we have AVX2 and either inputs are already in place,
9866 // we will be able to shuffle even across lanes the other input in a single
9867 // instruction so skip this pattern.
9868 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9869 isShuffleMaskInputInPlace(1, Mask))))
9870 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9871 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9874 // Otherwise fall back on generic blend lowering.
9875 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9879 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9881 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9882 /// isn't available.
9883 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9884 const X86Subtarget *Subtarget,
9885 SelectionDAG &DAG) {
9887 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9888 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9889 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9890 ArrayRef<int> Mask = SVOp->getMask();
9891 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9893 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9897 // Check for being able to broadcast a single element.
9898 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9899 Mask, Subtarget, DAG))
9902 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9903 // options to efficiently lower the shuffle.
9904 SmallVector<int, 4> RepeatedMask;
9905 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9906 assert(RepeatedMask.size() == 4 &&
9907 "Repeated masks must be half the mask width!");
9909 // Use even/odd duplicate instructions for masks that match their pattern.
9910 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9911 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9912 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9913 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9915 if (isSingleInputShuffleMask(Mask))
9916 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9917 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9919 // Use dedicated unpack instructions for masks that match their pattern.
9920 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9921 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9922 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9923 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9924 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9925 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9926 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9927 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9929 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9930 // have already handled any direct blends. We also need to squash the
9931 // repeated mask into a simulated v4f32 mask.
9932 for (int i = 0; i < 4; ++i)
9933 if (RepeatedMask[i] >= 8)
9934 RepeatedMask[i] -= 4;
9935 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9938 // If we have a single input shuffle with different shuffle patterns in the
9939 // two 128-bit lanes use the variable mask to VPERMILPS.
9940 if (isSingleInputShuffleMask(Mask)) {
9941 SDValue VPermMask[8];
9942 for (int i = 0; i < 8; ++i)
9943 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9944 : DAG.getConstant(Mask[i], DL, MVT::i32);
9945 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9947 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9948 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9950 if (Subtarget->hasAVX2())
9952 X86ISD::VPERMV, DL, MVT::v8f32,
9953 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9954 MVT::v8i32, VPermMask)),
9957 // Otherwise, fall back.
9958 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9962 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9964 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9965 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9968 // If we have AVX2 then we always want to lower with a blend because at v8 we
9969 // can fully permute the elements.
9970 if (Subtarget->hasAVX2())
9971 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9974 // Otherwise fall back on generic lowering.
9975 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9978 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9980 /// This routine is only called when we have AVX2 and thus a reasonable
9981 /// instruction set for v8i32 shuffling..
9982 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9983 const X86Subtarget *Subtarget,
9984 SelectionDAG &DAG) {
9986 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9987 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9988 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9989 ArrayRef<int> Mask = SVOp->getMask();
9990 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9991 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9993 // Whenever we can lower this as a zext, that instruction is strictly faster
9994 // than any alternative. It also allows us to fold memory operands into the
9995 // shuffle in many cases.
9996 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9997 Mask, Subtarget, DAG))
10000 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10004 // Check for being able to broadcast a single element.
10005 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10006 Mask, Subtarget, DAG))
10009 // If the shuffle mask is repeated in each 128-bit lane we can use more
10010 // efficient instructions that mirror the shuffles across the two 128-bit
10012 SmallVector<int, 4> RepeatedMask;
10013 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10014 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10015 if (isSingleInputShuffleMask(Mask))
10016 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10017 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10019 // Use dedicated unpack instructions for masks that match their pattern.
10020 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10021 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10022 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10023 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10024 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10025 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10026 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10027 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10030 // Try to use shift instructions.
10031 if (SDValue Shift =
10032 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10035 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10036 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10039 // If the shuffle patterns aren't repeated but it is a single input, directly
10040 // generate a cross-lane VPERMD instruction.
10041 if (isSingleInputShuffleMask(Mask)) {
10042 SDValue VPermMask[8];
10043 for (int i = 0; i < 8; ++i)
10044 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10045 : DAG.getConstant(Mask[i], DL, MVT::i32);
10046 return DAG.getNode(
10047 X86ISD::VPERMV, DL, MVT::v8i32,
10048 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10051 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10053 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10054 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10057 // Otherwise fall back on generic blend lowering.
10058 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10062 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10064 /// This routine is only called when we have AVX2 and thus a reasonable
10065 /// instruction set for v16i16 shuffling..
10066 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10067 const X86Subtarget *Subtarget,
10068 SelectionDAG &DAG) {
10070 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10071 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10072 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10073 ArrayRef<int> Mask = SVOp->getMask();
10074 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10075 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10077 // Whenever we can lower this as a zext, that instruction is strictly faster
10078 // than any alternative. It also allows us to fold memory operands into the
10079 // shuffle in many cases.
10080 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10081 Mask, Subtarget, DAG))
10084 // Check for being able to broadcast a single element.
10085 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10086 Mask, Subtarget, DAG))
10089 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10093 // Use dedicated unpack instructions for masks that match their pattern.
10094 if (isShuffleEquivalent(V1, V2, Mask,
10095 {// First 128-bit lane:
10096 0, 16, 1, 17, 2, 18, 3, 19,
10097 // Second 128-bit lane:
10098 8, 24, 9, 25, 10, 26, 11, 27}))
10099 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10100 if (isShuffleEquivalent(V1, V2, Mask,
10101 {// First 128-bit lane:
10102 4, 20, 5, 21, 6, 22, 7, 23,
10103 // Second 128-bit lane:
10104 12, 28, 13, 29, 14, 30, 15, 31}))
10105 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10107 // Try to use shift instructions.
10108 if (SDValue Shift =
10109 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10112 // Try to use byte rotation instructions.
10113 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10114 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10117 if (isSingleInputShuffleMask(Mask)) {
10118 // There are no generalized cross-lane shuffle operations available on i16
10120 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10121 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10124 SmallVector<int, 8> RepeatedMask;
10125 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10126 // As this is a single-input shuffle, the repeated mask should be
10127 // a strictly valid v8i16 mask that we can pass through to the v8i16
10128 // lowering to handle even the v16 case.
10129 return lowerV8I16GeneralSingleInputVectorShuffle(
10130 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10133 SDValue PSHUFBMask[32];
10134 for (int i = 0; i < 16; ++i) {
10135 if (Mask[i] == -1) {
10136 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10140 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10141 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10142 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10143 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10145 return DAG.getBitcast(MVT::v16i16,
10146 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10147 DAG.getBitcast(MVT::v32i8, V1),
10148 DAG.getNode(ISD::BUILD_VECTOR, DL,
10149 MVT::v32i8, PSHUFBMask)));
10152 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10154 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10155 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10158 // Otherwise fall back on generic lowering.
10159 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10162 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10164 /// This routine is only called when we have AVX2 and thus a reasonable
10165 /// instruction set for v32i8 shuffling..
10166 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10167 const X86Subtarget *Subtarget,
10168 SelectionDAG &DAG) {
10170 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10171 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10172 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10173 ArrayRef<int> Mask = SVOp->getMask();
10174 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10175 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10177 // Whenever we can lower this as a zext, that instruction is strictly faster
10178 // than any alternative. It also allows us to fold memory operands into the
10179 // shuffle in many cases.
10180 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10181 Mask, Subtarget, DAG))
10184 // Check for being able to broadcast a single element.
10185 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10186 Mask, Subtarget, DAG))
10189 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10193 // Use dedicated unpack instructions for masks that match their pattern.
10194 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10196 if (isShuffleEquivalent(
10198 {// First 128-bit lane:
10199 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10200 // Second 128-bit lane:
10201 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10202 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10203 if (isShuffleEquivalent(
10205 {// First 128-bit lane:
10206 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10207 // Second 128-bit lane:
10208 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10209 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10211 // Try to use shift instructions.
10212 if (SDValue Shift =
10213 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10216 // Try to use byte rotation instructions.
10217 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10218 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10221 if (isSingleInputShuffleMask(Mask)) {
10222 // There are no generalized cross-lane shuffle operations available on i8
10224 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10225 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10228 SDValue PSHUFBMask[32];
10229 for (int i = 0; i < 32; ++i)
10232 ? DAG.getUNDEF(MVT::i8)
10233 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10236 return DAG.getNode(
10237 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10238 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10241 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10243 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10244 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10247 // Otherwise fall back on generic lowering.
10248 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10251 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10253 /// This routine either breaks down the specific type of a 256-bit x86 vector
10254 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10255 /// together based on the available instructions.
10256 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10257 MVT VT, const X86Subtarget *Subtarget,
10258 SelectionDAG &DAG) {
10260 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10261 ArrayRef<int> Mask = SVOp->getMask();
10263 // If we have a single input to the zero element, insert that into V1 if we
10264 // can do so cheaply.
10265 int NumElts = VT.getVectorNumElements();
10266 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10267 return M >= NumElts;
10270 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10271 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10272 DL, VT, V1, V2, Mask, Subtarget, DAG))
10275 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10276 // check for those subtargets here and avoid much of the subtarget querying in
10277 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10278 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10279 // floating point types there eventually, just immediately cast everything to
10280 // a float and operate entirely in that domain.
10281 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10282 int ElementBits = VT.getScalarSizeInBits();
10283 if (ElementBits < 32)
10284 // No floating point type available, decompose into 128-bit vectors.
10285 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10287 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10288 VT.getVectorNumElements());
10289 V1 = DAG.getBitcast(FpVT, V1);
10290 V2 = DAG.getBitcast(FpVT, V2);
10291 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10294 switch (VT.SimpleTy) {
10296 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10298 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10300 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10302 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10304 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10306 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10309 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10313 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10314 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10315 const X86Subtarget *Subtarget,
10316 SelectionDAG &DAG) {
10318 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10319 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10320 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10321 ArrayRef<int> Mask = SVOp->getMask();
10322 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10324 // X86 has dedicated unpack instructions that can handle specific blend
10325 // operations: UNPCKH and UNPCKL.
10326 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10327 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10328 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10329 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10331 // FIXME: Implement direct support for this type!
10332 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10335 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10336 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10337 const X86Subtarget *Subtarget,
10338 SelectionDAG &DAG) {
10340 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10341 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10342 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10343 ArrayRef<int> Mask = SVOp->getMask();
10344 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10346 // Use dedicated unpack instructions for masks that match their pattern.
10347 if (isShuffleEquivalent(V1, V2, Mask,
10348 {// First 128-bit lane.
10349 0, 16, 1, 17, 4, 20, 5, 21,
10350 // Second 128-bit lane.
10351 8, 24, 9, 25, 12, 28, 13, 29}))
10352 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10353 if (isShuffleEquivalent(V1, V2, Mask,
10354 {// First 128-bit lane.
10355 2, 18, 3, 19, 6, 22, 7, 23,
10356 // Second 128-bit lane.
10357 10, 26, 11, 27, 14, 30, 15, 31}))
10358 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10360 // FIXME: Implement direct support for this type!
10361 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10364 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10365 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10366 const X86Subtarget *Subtarget,
10367 SelectionDAG &DAG) {
10369 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10370 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10371 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10372 ArrayRef<int> Mask = SVOp->getMask();
10373 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10375 // X86 has dedicated unpack instructions that can handle specific blend
10376 // operations: UNPCKH and UNPCKL.
10377 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10378 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10379 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10380 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10382 // FIXME: Implement direct support for this type!
10383 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10386 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10387 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10388 const X86Subtarget *Subtarget,
10389 SelectionDAG &DAG) {
10391 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10392 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10393 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10394 ArrayRef<int> Mask = SVOp->getMask();
10395 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10397 // Use dedicated unpack instructions for masks that match their pattern.
10398 if (isShuffleEquivalent(V1, V2, Mask,
10399 {// First 128-bit lane.
10400 0, 16, 1, 17, 4, 20, 5, 21,
10401 // Second 128-bit lane.
10402 8, 24, 9, 25, 12, 28, 13, 29}))
10403 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10404 if (isShuffleEquivalent(V1, V2, Mask,
10405 {// First 128-bit lane.
10406 2, 18, 3, 19, 6, 22, 7, 23,
10407 // Second 128-bit lane.
10408 10, 26, 11, 27, 14, 30, 15, 31}))
10409 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10411 // FIXME: Implement direct support for this type!
10412 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10415 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10416 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10417 const X86Subtarget *Subtarget,
10418 SelectionDAG &DAG) {
10420 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10421 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10422 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10423 ArrayRef<int> Mask = SVOp->getMask();
10424 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10425 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10427 // FIXME: Implement direct support for this type!
10428 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10431 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10432 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10433 const X86Subtarget *Subtarget,
10434 SelectionDAG &DAG) {
10436 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10437 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10438 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10439 ArrayRef<int> Mask = SVOp->getMask();
10440 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10441 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10443 // FIXME: Implement direct support for this type!
10444 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10447 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10449 /// This routine either breaks down the specific type of a 512-bit x86 vector
10450 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10451 /// together based on the available instructions.
10452 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10453 MVT VT, const X86Subtarget *Subtarget,
10454 SelectionDAG &DAG) {
10456 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10457 ArrayRef<int> Mask = SVOp->getMask();
10458 assert(Subtarget->hasAVX512() &&
10459 "Cannot lower 512-bit vectors w/ basic ISA!");
10461 // Check for being able to broadcast a single element.
10462 if (SDValue Broadcast =
10463 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10466 // Dispatch to each element type for lowering. If we don't have supprot for
10467 // specific element type shuffles at 512 bits, immediately split them and
10468 // lower them. Each lowering routine of a given type is allowed to assume that
10469 // the requisite ISA extensions for that element type are available.
10470 switch (VT.SimpleTy) {
10472 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10474 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10476 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10478 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10480 if (Subtarget->hasBWI())
10481 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10484 if (Subtarget->hasBWI())
10485 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10489 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10492 // Otherwise fall back on splitting.
10493 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10496 /// \brief Top-level lowering for x86 vector shuffles.
10498 /// This handles decomposition, canonicalization, and lowering of all x86
10499 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10500 /// above in helper routines. The canonicalization attempts to widen shuffles
10501 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10502 /// s.t. only one of the two inputs needs to be tested, etc.
10503 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10504 SelectionDAG &DAG) {
10505 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10506 ArrayRef<int> Mask = SVOp->getMask();
10507 SDValue V1 = Op.getOperand(0);
10508 SDValue V2 = Op.getOperand(1);
10509 MVT VT = Op.getSimpleValueType();
10510 int NumElements = VT.getVectorNumElements();
10513 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10515 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10516 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10517 if (V1IsUndef && V2IsUndef)
10518 return DAG.getUNDEF(VT);
10520 // When we create a shuffle node we put the UNDEF node to second operand,
10521 // but in some cases the first operand may be transformed to UNDEF.
10522 // In this case we should just commute the node.
10524 return DAG.getCommutedVectorShuffle(*SVOp);
10526 // Check for non-undef masks pointing at an undef vector and make the masks
10527 // undef as well. This makes it easier to match the shuffle based solely on
10531 if (M >= NumElements) {
10532 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10533 for (int &M : NewMask)
10534 if (M >= NumElements)
10536 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10539 // We actually see shuffles that are entirely re-arrangements of a set of
10540 // zero inputs. This mostly happens while decomposing complex shuffles into
10541 // simple ones. Directly lower these as a buildvector of zeros.
10542 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10543 if (Zeroable.all())
10544 return getZeroVector(VT, Subtarget, DAG, dl);
10546 // Try to collapse shuffles into using a vector type with fewer elements but
10547 // wider element types. We cap this to not form integers or floating point
10548 // elements wider than 64 bits, but it might be interesting to form i128
10549 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10550 SmallVector<int, 16> WidenedMask;
10551 if (VT.getScalarSizeInBits() < 64 &&
10552 canWidenShuffleElements(Mask, WidenedMask)) {
10553 MVT NewEltVT = VT.isFloatingPoint()
10554 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10555 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10556 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10557 // Make sure that the new vector type is legal. For example, v2f64 isn't
10559 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10560 V1 = DAG.getBitcast(NewVT, V1);
10561 V2 = DAG.getBitcast(NewVT, V2);
10562 return DAG.getBitcast(
10563 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10567 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10568 for (int M : SVOp->getMask())
10570 ++NumUndefElements;
10571 else if (M < NumElements)
10576 // Commute the shuffle as needed such that more elements come from V1 than
10577 // V2. This allows us to match the shuffle pattern strictly on how many
10578 // elements come from V1 without handling the symmetric cases.
10579 if (NumV2Elements > NumV1Elements)
10580 return DAG.getCommutedVectorShuffle(*SVOp);
10582 // When the number of V1 and V2 elements are the same, try to minimize the
10583 // number of uses of V2 in the low half of the vector. When that is tied,
10584 // ensure that the sum of indices for V1 is equal to or lower than the sum
10585 // indices for V2. When those are equal, try to ensure that the number of odd
10586 // indices for V1 is lower than the number of odd indices for V2.
10587 if (NumV1Elements == NumV2Elements) {
10588 int LowV1Elements = 0, LowV2Elements = 0;
10589 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10590 if (M >= NumElements)
10594 if (LowV2Elements > LowV1Elements) {
10595 return DAG.getCommutedVectorShuffle(*SVOp);
10596 } else if (LowV2Elements == LowV1Elements) {
10597 int SumV1Indices = 0, SumV2Indices = 0;
10598 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10599 if (SVOp->getMask()[i] >= NumElements)
10601 else if (SVOp->getMask()[i] >= 0)
10603 if (SumV2Indices < SumV1Indices) {
10604 return DAG.getCommutedVectorShuffle(*SVOp);
10605 } else if (SumV2Indices == SumV1Indices) {
10606 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10607 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10608 if (SVOp->getMask()[i] >= NumElements)
10609 NumV2OddIndices += i % 2;
10610 else if (SVOp->getMask()[i] >= 0)
10611 NumV1OddIndices += i % 2;
10612 if (NumV2OddIndices < NumV1OddIndices)
10613 return DAG.getCommutedVectorShuffle(*SVOp);
10618 // For each vector width, delegate to a specialized lowering routine.
10619 if (VT.getSizeInBits() == 128)
10620 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10622 if (VT.getSizeInBits() == 256)
10623 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10625 // Force AVX-512 vectors to be scalarized for now.
10626 // FIXME: Implement AVX-512 support!
10627 if (VT.getSizeInBits() == 512)
10628 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10630 llvm_unreachable("Unimplemented!");
10633 // This function assumes its argument is a BUILD_VECTOR of constants or
10634 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10636 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10637 unsigned &MaskValue) {
10639 unsigned NumElems = BuildVector->getNumOperands();
10640 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10641 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10642 unsigned NumElemsInLane = NumElems / NumLanes;
10644 // Blend for v16i16 should be symetric for the both lanes.
10645 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10646 SDValue EltCond = BuildVector->getOperand(i);
10647 SDValue SndLaneEltCond =
10648 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10650 int Lane1Cond = -1, Lane2Cond = -1;
10651 if (isa<ConstantSDNode>(EltCond))
10652 Lane1Cond = !isZero(EltCond);
10653 if (isa<ConstantSDNode>(SndLaneEltCond))
10654 Lane2Cond = !isZero(SndLaneEltCond);
10656 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10657 // Lane1Cond != 0, means we want the first argument.
10658 // Lane1Cond == 0, means we want the second argument.
10659 // The encoding of this argument is 0 for the first argument, 1
10660 // for the second. Therefore, invert the condition.
10661 MaskValue |= !Lane1Cond << i;
10662 else if (Lane1Cond < 0)
10663 MaskValue |= !Lane2Cond << i;
10670 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10671 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10672 const X86Subtarget *Subtarget,
10673 SelectionDAG &DAG) {
10674 SDValue Cond = Op.getOperand(0);
10675 SDValue LHS = Op.getOperand(1);
10676 SDValue RHS = Op.getOperand(2);
10678 MVT VT = Op.getSimpleValueType();
10680 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10682 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10684 // Only non-legal VSELECTs reach this lowering, convert those into generic
10685 // shuffles and re-use the shuffle lowering path for blends.
10686 SmallVector<int, 32> Mask;
10687 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10688 SDValue CondElt = CondBV->getOperand(i);
10690 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10692 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10695 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10696 // A vselect where all conditions and data are constants can be optimized into
10697 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10698 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10699 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10700 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10703 // Try to lower this to a blend-style vector shuffle. This can handle all
10704 // constant condition cases.
10705 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10708 // Variable blends are only legal from SSE4.1 onward.
10709 if (!Subtarget->hasSSE41())
10712 // Only some types will be legal on some subtargets. If we can emit a legal
10713 // VSELECT-matching blend, return Op, and but if we need to expand, return
10715 switch (Op.getSimpleValueType().SimpleTy) {
10717 // Most of the vector types have blends past SSE4.1.
10721 // The byte blends for AVX vectors were introduced only in AVX2.
10722 if (Subtarget->hasAVX2())
10729 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10730 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10733 // FIXME: We should custom lower this by fixing the condition and using i8
10739 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10740 MVT VT = Op.getSimpleValueType();
10743 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10746 if (VT.getSizeInBits() == 8) {
10747 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10748 Op.getOperand(0), Op.getOperand(1));
10749 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10750 DAG.getValueType(VT));
10751 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10754 if (VT.getSizeInBits() == 16) {
10755 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10756 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10758 return DAG.getNode(
10759 ISD::TRUNCATE, dl, MVT::i16,
10760 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10761 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10762 Op.getOperand(1)));
10763 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10764 Op.getOperand(0), Op.getOperand(1));
10765 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10766 DAG.getValueType(VT));
10767 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10770 if (VT == MVT::f32) {
10771 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10772 // the result back to FR32 register. It's only worth matching if the
10773 // result has a single use which is a store or a bitcast to i32. And in
10774 // the case of a store, it's not worth it if the index is a constant 0,
10775 // because a MOVSSmr can be used instead, which is smaller and faster.
10776 if (!Op.hasOneUse())
10778 SDNode *User = *Op.getNode()->use_begin();
10779 if ((User->getOpcode() != ISD::STORE ||
10780 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10781 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10782 (User->getOpcode() != ISD::BITCAST ||
10783 User->getValueType(0) != MVT::i32))
10785 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10786 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10788 return DAG.getBitcast(MVT::f32, Extract);
10791 if (VT == MVT::i32 || VT == MVT::i64) {
10792 // ExtractPS/pextrq works with constant index.
10793 if (isa<ConstantSDNode>(Op.getOperand(1)))
10799 /// Extract one bit from mask vector, like v16i1 or v8i1.
10800 /// AVX-512 feature.
10802 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10803 SDValue Vec = Op.getOperand(0);
10805 MVT VecVT = Vec.getSimpleValueType();
10806 SDValue Idx = Op.getOperand(1);
10807 MVT EltVT = Op.getSimpleValueType();
10809 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10810 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10811 "Unexpected vector type in ExtractBitFromMaskVector");
10813 // variable index can't be handled in mask registers,
10814 // extend vector to VR512
10815 if (!isa<ConstantSDNode>(Idx)) {
10816 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10817 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10818 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10819 ExtVT.getVectorElementType(), Ext, Idx);
10820 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10823 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10824 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10825 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10826 rc = getRegClassFor(MVT::v16i1);
10827 unsigned MaxSift = rc->getSize()*8 - 1;
10828 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10829 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10830 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10831 DAG.getConstant(MaxSift, dl, MVT::i8));
10832 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10833 DAG.getIntPtrConstant(0, dl));
10837 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10838 SelectionDAG &DAG) const {
10840 SDValue Vec = Op.getOperand(0);
10841 MVT VecVT = Vec.getSimpleValueType();
10842 SDValue Idx = Op.getOperand(1);
10844 if (Op.getSimpleValueType() == MVT::i1)
10845 return ExtractBitFromMaskVector(Op, DAG);
10847 if (!isa<ConstantSDNode>(Idx)) {
10848 if (VecVT.is512BitVector() ||
10849 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10850 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10853 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10854 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10855 MaskEltVT.getSizeInBits());
10857 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10858 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10859 getZeroVector(MaskVT, Subtarget, DAG, dl),
10860 Idx, DAG.getConstant(0, dl, getPointerTy()));
10861 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10862 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10863 Perm, DAG.getConstant(0, dl, getPointerTy()));
10868 // If this is a 256-bit vector result, first extract the 128-bit vector and
10869 // then extract the element from the 128-bit vector.
10870 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10872 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10873 // Get the 128-bit vector.
10874 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10875 MVT EltVT = VecVT.getVectorElementType();
10877 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10879 //if (IdxVal >= NumElems/2)
10880 // IdxVal -= NumElems/2;
10881 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10882 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10883 DAG.getConstant(IdxVal, dl, MVT::i32));
10886 assert(VecVT.is128BitVector() && "Unexpected vector length");
10888 if (Subtarget->hasSSE41())
10889 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10892 MVT VT = Op.getSimpleValueType();
10893 // TODO: handle v16i8.
10894 if (VT.getSizeInBits() == 16) {
10895 SDValue Vec = Op.getOperand(0);
10896 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10898 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10899 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10900 DAG.getBitcast(MVT::v4i32, Vec),
10901 Op.getOperand(1)));
10902 // Transform it so it match pextrw which produces a 32-bit result.
10903 MVT EltVT = MVT::i32;
10904 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10905 Op.getOperand(0), Op.getOperand(1));
10906 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10907 DAG.getValueType(VT));
10908 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10911 if (VT.getSizeInBits() == 32) {
10912 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10916 // SHUFPS the element to the lowest double word, then movss.
10917 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10918 MVT VVT = Op.getOperand(0).getSimpleValueType();
10919 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10920 DAG.getUNDEF(VVT), Mask);
10921 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10922 DAG.getIntPtrConstant(0, dl));
10925 if (VT.getSizeInBits() == 64) {
10926 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10927 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10928 // to match extract_elt for f64.
10929 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10933 // UNPCKHPD the element to the lowest double word, then movsd.
10934 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10935 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10936 int Mask[2] = { 1, -1 };
10937 MVT VVT = Op.getOperand(0).getSimpleValueType();
10938 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10939 DAG.getUNDEF(VVT), Mask);
10940 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10941 DAG.getIntPtrConstant(0, dl));
10947 /// Insert one bit to mask vector, like v16i1 or v8i1.
10948 /// AVX-512 feature.
10950 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10952 SDValue Vec = Op.getOperand(0);
10953 SDValue Elt = Op.getOperand(1);
10954 SDValue Idx = Op.getOperand(2);
10955 MVT VecVT = Vec.getSimpleValueType();
10957 if (!isa<ConstantSDNode>(Idx)) {
10958 // Non constant index. Extend source and destination,
10959 // insert element and then truncate the result.
10960 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10961 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10962 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10963 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10964 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10965 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10968 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10969 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10971 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10972 DAG.getConstant(IdxVal, dl, MVT::i8));
10973 if (Vec.getOpcode() == ISD::UNDEF)
10975 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10978 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10979 SelectionDAG &DAG) const {
10980 MVT VT = Op.getSimpleValueType();
10981 MVT EltVT = VT.getVectorElementType();
10983 if (EltVT == MVT::i1)
10984 return InsertBitToMaskVector(Op, DAG);
10987 SDValue N0 = Op.getOperand(0);
10988 SDValue N1 = Op.getOperand(1);
10989 SDValue N2 = Op.getOperand(2);
10990 if (!isa<ConstantSDNode>(N2))
10992 auto *N2C = cast<ConstantSDNode>(N2);
10993 unsigned IdxVal = N2C->getZExtValue();
10995 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10996 // into that, and then insert the subvector back into the result.
10997 if (VT.is256BitVector() || VT.is512BitVector()) {
10998 // With a 256-bit vector, we can insert into the zero element efficiently
10999 // using a blend if we have AVX or AVX2 and the right data type.
11000 if (VT.is256BitVector() && IdxVal == 0) {
11001 // TODO: It is worthwhile to cast integer to floating point and back
11002 // and incur a domain crossing penalty if that's what we'll end up
11003 // doing anyway after extracting to a 128-bit vector.
11004 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11005 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11006 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11007 N2 = DAG.getIntPtrConstant(1, dl);
11008 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11012 // Get the desired 128-bit vector chunk.
11013 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11015 // Insert the element into the desired chunk.
11016 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11017 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11019 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11020 DAG.getConstant(IdxIn128, dl, MVT::i32));
11022 // Insert the changed part back into the bigger vector
11023 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11025 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11027 if (Subtarget->hasSSE41()) {
11028 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11030 if (VT == MVT::v8i16) {
11031 Opc = X86ISD::PINSRW;
11033 assert(VT == MVT::v16i8);
11034 Opc = X86ISD::PINSRB;
11037 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11039 if (N1.getValueType() != MVT::i32)
11040 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11041 if (N2.getValueType() != MVT::i32)
11042 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11043 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11046 if (EltVT == MVT::f32) {
11047 // Bits [7:6] of the constant are the source select. This will always be
11048 // zero here. The DAG Combiner may combine an extract_elt index into
11049 // these bits. For example (insert (extract, 3), 2) could be matched by
11050 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11051 // Bits [5:4] of the constant are the destination select. This is the
11052 // value of the incoming immediate.
11053 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11054 // combine either bitwise AND or insert of float 0.0 to set these bits.
11056 const Function *F = DAG.getMachineFunction().getFunction();
11057 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11058 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11059 // If this is an insertion of 32-bits into the low 32-bits of
11060 // a vector, we prefer to generate a blend with immediate rather
11061 // than an insertps. Blends are simpler operations in hardware and so
11062 // will always have equal or better performance than insertps.
11063 // But if optimizing for size and there's a load folding opportunity,
11064 // generate insertps because blendps does not have a 32-bit memory
11066 N2 = DAG.getIntPtrConstant(1, dl);
11067 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11068 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11070 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11071 // Create this as a scalar to vector..
11072 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11073 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11076 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11077 // PINSR* works with constant index.
11082 if (EltVT == MVT::i8)
11085 if (EltVT.getSizeInBits() == 16) {
11086 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11087 // as its second argument.
11088 if (N1.getValueType() != MVT::i32)
11089 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11090 if (N2.getValueType() != MVT::i32)
11091 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11092 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11097 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11099 MVT OpVT = Op.getSimpleValueType();
11101 // If this is a 256-bit vector result, first insert into a 128-bit
11102 // vector and then insert into the 256-bit vector.
11103 if (!OpVT.is128BitVector()) {
11104 // Insert into a 128-bit vector.
11105 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11106 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11107 OpVT.getVectorNumElements() / SizeFactor);
11109 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11111 // Insert the 128-bit vector.
11112 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11115 if (OpVT == MVT::v1i64 &&
11116 Op.getOperand(0).getValueType() == MVT::i64)
11117 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11119 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11120 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11121 return DAG.getBitcast(
11122 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11125 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11126 // a simple subregister reference or explicit instructions to grab
11127 // upper bits of a vector.
11128 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11129 SelectionDAG &DAG) {
11131 SDValue In = Op.getOperand(0);
11132 SDValue Idx = Op.getOperand(1);
11133 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11134 MVT ResVT = Op.getSimpleValueType();
11135 MVT InVT = In.getSimpleValueType();
11137 if (Subtarget->hasFp256()) {
11138 if (ResVT.is128BitVector() &&
11139 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11140 isa<ConstantSDNode>(Idx)) {
11141 return Extract128BitVector(In, IdxVal, DAG, dl);
11143 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11144 isa<ConstantSDNode>(Idx)) {
11145 return Extract256BitVector(In, IdxVal, DAG, dl);
11151 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11152 // simple superregister reference or explicit instructions to insert
11153 // the upper bits of a vector.
11154 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11155 SelectionDAG &DAG) {
11156 if (!Subtarget->hasAVX())
11160 SDValue Vec = Op.getOperand(0);
11161 SDValue SubVec = Op.getOperand(1);
11162 SDValue Idx = Op.getOperand(2);
11164 if (!isa<ConstantSDNode>(Idx))
11167 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11168 MVT OpVT = Op.getSimpleValueType();
11169 MVT SubVecVT = SubVec.getSimpleValueType();
11171 // Fold two 16-byte subvector loads into one 32-byte load:
11172 // (insert_subvector (insert_subvector undef, (load addr), 0),
11173 // (load addr + 16), Elts/2)
11175 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11176 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11177 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11178 !Subtarget->isUnalignedMem32Slow()) {
11179 SDValue SubVec2 = Vec.getOperand(1);
11180 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11181 if (Idx2->getZExtValue() == 0) {
11182 SDValue Ops[] = { SubVec2, SubVec };
11183 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11189 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11190 SubVecVT.is128BitVector())
11191 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11193 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11194 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11196 if (OpVT.getVectorElementType() == MVT::i1) {
11197 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11199 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11200 SDValue Undef = DAG.getUNDEF(OpVT);
11201 unsigned NumElems = OpVT.getVectorNumElements();
11202 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11204 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11205 // Zero upper bits of the Vec
11206 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11207 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11209 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11211 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11212 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11215 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11217 // Zero upper bits of the Vec2
11218 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11219 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11220 // Zero lower bits of the Vec
11221 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11222 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11223 // Merge them together
11224 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11230 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11231 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11232 // one of the above mentioned nodes. It has to be wrapped because otherwise
11233 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11234 // be used to form addressing mode. These wrapped nodes will be selected
11237 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11238 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11240 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11241 // global base reg.
11242 unsigned char OpFlag = 0;
11243 unsigned WrapperKind = X86ISD::Wrapper;
11244 CodeModel::Model M = DAG.getTarget().getCodeModel();
11246 if (Subtarget->isPICStyleRIPRel() &&
11247 (M == CodeModel::Small || M == CodeModel::Kernel))
11248 WrapperKind = X86ISD::WrapperRIP;
11249 else if (Subtarget->isPICStyleGOT())
11250 OpFlag = X86II::MO_GOTOFF;
11251 else if (Subtarget->isPICStyleStubPIC())
11252 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11254 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11255 CP->getAlignment(),
11256 CP->getOffset(), OpFlag);
11258 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11259 // With PIC, the address is actually $g + Offset.
11261 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11262 DAG.getNode(X86ISD::GlobalBaseReg,
11263 SDLoc(), getPointerTy()),
11270 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11271 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11273 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11274 // global base reg.
11275 unsigned char OpFlag = 0;
11276 unsigned WrapperKind = X86ISD::Wrapper;
11277 CodeModel::Model M = DAG.getTarget().getCodeModel();
11279 if (Subtarget->isPICStyleRIPRel() &&
11280 (M == CodeModel::Small || M == CodeModel::Kernel))
11281 WrapperKind = X86ISD::WrapperRIP;
11282 else if (Subtarget->isPICStyleGOT())
11283 OpFlag = X86II::MO_GOTOFF;
11284 else if (Subtarget->isPICStyleStubPIC())
11285 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11287 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11290 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11292 // With PIC, the address is actually $g + Offset.
11294 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11295 DAG.getNode(X86ISD::GlobalBaseReg,
11296 SDLoc(), getPointerTy()),
11303 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11304 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11306 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11307 // global base reg.
11308 unsigned char OpFlag = 0;
11309 unsigned WrapperKind = X86ISD::Wrapper;
11310 CodeModel::Model M = DAG.getTarget().getCodeModel();
11312 if (Subtarget->isPICStyleRIPRel() &&
11313 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11314 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11315 OpFlag = X86II::MO_GOTPCREL;
11316 WrapperKind = X86ISD::WrapperRIP;
11317 } else if (Subtarget->isPICStyleGOT()) {
11318 OpFlag = X86II::MO_GOT;
11319 } else if (Subtarget->isPICStyleStubPIC()) {
11320 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11321 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11322 OpFlag = X86II::MO_DARWIN_NONLAZY;
11325 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11328 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11330 // With PIC, the address is actually $g + Offset.
11331 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11332 !Subtarget->is64Bit()) {
11333 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11334 DAG.getNode(X86ISD::GlobalBaseReg,
11335 SDLoc(), getPointerTy()),
11339 // For symbols that require a load from a stub to get the address, emit the
11341 if (isGlobalStubReference(OpFlag))
11342 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11343 MachinePointerInfo::getGOT(), false, false, false, 0);
11349 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11350 // Create the TargetBlockAddressAddress node.
11351 unsigned char OpFlags =
11352 Subtarget->ClassifyBlockAddressReference();
11353 CodeModel::Model M = DAG.getTarget().getCodeModel();
11354 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11355 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11357 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11360 if (Subtarget->isPICStyleRIPRel() &&
11361 (M == CodeModel::Small || M == CodeModel::Kernel))
11362 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11364 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11366 // With PIC, the address is actually $g + Offset.
11367 if (isGlobalRelativeToPICBase(OpFlags)) {
11368 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11369 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11377 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11378 int64_t Offset, SelectionDAG &DAG) const {
11379 // Create the TargetGlobalAddress node, folding in the constant
11380 // offset if it is legal.
11381 unsigned char OpFlags =
11382 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11383 CodeModel::Model M = DAG.getTarget().getCodeModel();
11385 if (OpFlags == X86II::MO_NO_FLAG &&
11386 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11387 // A direct static reference to a global.
11388 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11391 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11394 if (Subtarget->isPICStyleRIPRel() &&
11395 (M == CodeModel::Small || M == CodeModel::Kernel))
11396 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11398 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11400 // With PIC, the address is actually $g + Offset.
11401 if (isGlobalRelativeToPICBase(OpFlags)) {
11402 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11403 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11407 // For globals that require a load from a stub to get the address, emit the
11409 if (isGlobalStubReference(OpFlags))
11410 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11411 MachinePointerInfo::getGOT(), false, false, false, 0);
11413 // If there was a non-zero offset that we didn't fold, create an explicit
11414 // addition for it.
11416 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11417 DAG.getConstant(Offset, dl, getPointerTy()));
11423 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11424 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11425 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11426 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11430 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11431 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11432 unsigned char OperandFlags, bool LocalDynamic = false) {
11433 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11434 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11436 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11437 GA->getValueType(0),
11441 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11445 SDValue Ops[] = { Chain, TGA, *InFlag };
11446 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11448 SDValue Ops[] = { Chain, TGA };
11449 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11452 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11453 MFI->setAdjustsStack(true);
11454 MFI->setHasCalls(true);
11456 SDValue Flag = Chain.getValue(1);
11457 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11460 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11462 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11465 SDLoc dl(GA); // ? function entry point might be better
11466 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11467 DAG.getNode(X86ISD::GlobalBaseReg,
11468 SDLoc(), PtrVT), InFlag);
11469 InFlag = Chain.getValue(1);
11471 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11474 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11476 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11478 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11479 X86::RAX, X86II::MO_TLSGD);
11482 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11488 // Get the start address of the TLS block for this module.
11489 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11490 .getInfo<X86MachineFunctionInfo>();
11491 MFI->incNumLocalDynamicTLSAccesses();
11495 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11496 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11499 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11500 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11501 InFlag = Chain.getValue(1);
11502 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11503 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11506 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11510 unsigned char OperandFlags = X86II::MO_DTPOFF;
11511 unsigned WrapperKind = X86ISD::Wrapper;
11512 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11513 GA->getValueType(0),
11514 GA->getOffset(), OperandFlags);
11515 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11517 // Add x@dtpoff with the base.
11518 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11521 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11522 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11523 const EVT PtrVT, TLSModel::Model model,
11524 bool is64Bit, bool isPIC) {
11527 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11528 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11529 is64Bit ? 257 : 256));
11531 SDValue ThreadPointer =
11532 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11533 MachinePointerInfo(Ptr), false, false, false, 0);
11535 unsigned char OperandFlags = 0;
11536 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11538 unsigned WrapperKind = X86ISD::Wrapper;
11539 if (model == TLSModel::LocalExec) {
11540 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11541 } else if (model == TLSModel::InitialExec) {
11543 OperandFlags = X86II::MO_GOTTPOFF;
11544 WrapperKind = X86ISD::WrapperRIP;
11546 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11549 llvm_unreachable("Unexpected model");
11552 // emit "addl x@ntpoff,%eax" (local exec)
11553 // or "addl x@indntpoff,%eax" (initial exec)
11554 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11556 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11557 GA->getOffset(), OperandFlags);
11558 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11560 if (model == TLSModel::InitialExec) {
11561 if (isPIC && !is64Bit) {
11562 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11563 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11567 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11568 MachinePointerInfo::getGOT(), false, false, false, 0);
11571 // The address of the thread local variable is the add of the thread
11572 // pointer with the offset of the variable.
11573 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11577 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11579 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11580 const GlobalValue *GV = GA->getGlobal();
11582 if (Subtarget->isTargetELF()) {
11583 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11585 case TLSModel::GeneralDynamic:
11586 if (Subtarget->is64Bit())
11587 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11588 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11589 case TLSModel::LocalDynamic:
11590 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11591 Subtarget->is64Bit());
11592 case TLSModel::InitialExec:
11593 case TLSModel::LocalExec:
11594 return LowerToTLSExecModel(
11595 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11596 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11598 llvm_unreachable("Unknown TLS model.");
11601 if (Subtarget->isTargetDarwin()) {
11602 // Darwin only has one model of TLS. Lower to that.
11603 unsigned char OpFlag = 0;
11604 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11605 X86ISD::WrapperRIP : X86ISD::Wrapper;
11607 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11608 // global base reg.
11609 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11610 !Subtarget->is64Bit();
11612 OpFlag = X86II::MO_TLVP_PIC_BASE;
11614 OpFlag = X86II::MO_TLVP;
11616 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11617 GA->getValueType(0),
11618 GA->getOffset(), OpFlag);
11619 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11621 // With PIC32, the address is actually $g + Offset.
11623 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11624 DAG.getNode(X86ISD::GlobalBaseReg,
11625 SDLoc(), getPointerTy()),
11628 // Lowering the machine isd will make sure everything is in the right
11630 SDValue Chain = DAG.getEntryNode();
11631 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11632 SDValue Args[] = { Chain, Offset };
11633 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11635 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11636 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11637 MFI->setAdjustsStack(true);
11639 // And our return value (tls address) is in the standard call return value
11641 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11642 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11643 Chain.getValue(1));
11646 if (Subtarget->isTargetKnownWindowsMSVC() ||
11647 Subtarget->isTargetWindowsGNU()) {
11648 // Just use the implicit TLS architecture
11649 // Need to generate someting similar to:
11650 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11652 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11653 // mov rcx, qword [rdx+rcx*8]
11654 // mov eax, .tls$:tlsvar
11655 // [rax+rcx] contains the address
11656 // Windows 64bit: gs:0x58
11657 // Windows 32bit: fs:__tls_array
11660 SDValue Chain = DAG.getEntryNode();
11662 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11663 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11664 // use its literal value of 0x2C.
11665 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11666 ? Type::getInt8PtrTy(*DAG.getContext(),
11668 : Type::getInt32PtrTy(*DAG.getContext(),
11672 Subtarget->is64Bit()
11673 ? DAG.getIntPtrConstant(0x58, dl)
11674 : (Subtarget->isTargetWindowsGNU()
11675 ? DAG.getIntPtrConstant(0x2C, dl)
11676 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11678 SDValue ThreadPointer =
11679 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11680 MachinePointerInfo(Ptr), false, false, false, 0);
11683 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11684 res = ThreadPointer;
11686 // Load the _tls_index variable
11687 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11688 if (Subtarget->is64Bit())
11689 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11690 MachinePointerInfo(), MVT::i32, false, false,
11693 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11694 false, false, false, 0);
11696 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11698 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11700 res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11703 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11704 false, false, false, 0);
11706 // Get the offset of start of .tls section
11707 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11708 GA->getValueType(0),
11709 GA->getOffset(), X86II::MO_SECREL);
11710 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11712 // The address of the thread local variable is the add of the thread
11713 // pointer with the offset of the variable.
11714 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11717 llvm_unreachable("TLS not implemented for this target.");
11720 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11721 /// and take a 2 x i32 value to shift plus a shift amount.
11722 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11723 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11724 MVT VT = Op.getSimpleValueType();
11725 unsigned VTBits = VT.getSizeInBits();
11727 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11728 SDValue ShOpLo = Op.getOperand(0);
11729 SDValue ShOpHi = Op.getOperand(1);
11730 SDValue ShAmt = Op.getOperand(2);
11731 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11732 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11734 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11735 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11736 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11737 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11738 : DAG.getConstant(0, dl, VT);
11740 SDValue Tmp2, Tmp3;
11741 if (Op.getOpcode() == ISD::SHL_PARTS) {
11742 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11743 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11745 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11746 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11749 // If the shift amount is larger or equal than the width of a part we can't
11750 // rely on the results of shld/shrd. Insert a test and select the appropriate
11751 // values for large shift amounts.
11752 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11753 DAG.getConstant(VTBits, dl, MVT::i8));
11754 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11755 AndNode, DAG.getConstant(0, dl, MVT::i8));
11758 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11759 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11760 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11762 if (Op.getOpcode() == ISD::SHL_PARTS) {
11763 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11764 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11766 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11767 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11770 SDValue Ops[2] = { Lo, Hi };
11771 return DAG.getMergeValues(Ops, dl);
11774 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11775 SelectionDAG &DAG) const {
11776 SDValue Src = Op.getOperand(0);
11777 MVT SrcVT = Src.getSimpleValueType();
11778 MVT VT = Op.getSimpleValueType();
11781 if (SrcVT.isVector()) {
11782 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11783 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11784 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11785 DAG.getUNDEF(SrcVT)));
11787 if (SrcVT.getVectorElementType() == MVT::i1) {
11788 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11789 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11790 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11795 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11796 "Unknown SINT_TO_FP to lower!");
11798 // These are really Legal; return the operand so the caller accepts it as
11800 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11802 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11803 Subtarget->is64Bit()) {
11807 unsigned Size = SrcVT.getSizeInBits()/8;
11808 MachineFunction &MF = DAG.getMachineFunction();
11809 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11810 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11811 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11813 MachinePointerInfo::getFixedStack(SSFI),
11815 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11818 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11820 SelectionDAG &DAG) const {
11824 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11826 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11828 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11830 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11832 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11833 MachineMemOperand *MMO;
11835 int SSFI = FI->getIndex();
11837 DAG.getMachineFunction()
11838 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11839 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11841 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11842 StackSlot = StackSlot.getOperand(1);
11844 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11845 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11847 Tys, Ops, SrcVT, MMO);
11850 Chain = Result.getValue(1);
11851 SDValue InFlag = Result.getValue(2);
11853 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11854 // shouldn't be necessary except that RFP cannot be live across
11855 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11856 MachineFunction &MF = DAG.getMachineFunction();
11857 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11858 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11859 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11860 Tys = DAG.getVTList(MVT::Other);
11862 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11864 MachineMemOperand *MMO =
11865 DAG.getMachineFunction()
11866 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11867 MachineMemOperand::MOStore, SSFISize, SSFISize);
11869 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11870 Ops, Op.getValueType(), MMO);
11871 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11872 MachinePointerInfo::getFixedStack(SSFI),
11873 false, false, false, 0);
11879 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11880 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11881 SelectionDAG &DAG) const {
11882 // This algorithm is not obvious. Here it is what we're trying to output:
11885 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11886 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11888 haddpd %xmm0, %xmm0
11890 pshufd $0x4e, %xmm0, %xmm1
11896 LLVMContext *Context = DAG.getContext();
11898 // Build some magic constants.
11899 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11900 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11901 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11903 SmallVector<Constant*,2> CV1;
11905 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11906 APInt(64, 0x4330000000000000ULL))));
11908 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11909 APInt(64, 0x4530000000000000ULL))));
11910 Constant *C1 = ConstantVector::get(CV1);
11911 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11913 // Load the 64-bit value into an XMM register.
11914 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11916 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11917 MachinePointerInfo::getConstantPool(),
11918 false, false, false, 16);
11920 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11922 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11923 MachinePointerInfo::getConstantPool(),
11924 false, false, false, 16);
11925 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11926 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11929 if (Subtarget->hasSSE3()) {
11930 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11931 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11933 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11934 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11936 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11937 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11940 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11941 DAG.getIntPtrConstant(0, dl));
11944 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11945 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11946 SelectionDAG &DAG) const {
11948 // FP constant to bias correct the final result.
11949 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11952 // Load the 32-bit value into an XMM register.
11953 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11956 // Zero out the upper parts of the register.
11957 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11959 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11960 DAG.getBitcast(MVT::v2f64, Load),
11961 DAG.getIntPtrConstant(0, dl));
11963 // Or the load with the bias.
11964 SDValue Or = DAG.getNode(
11965 ISD::OR, dl, MVT::v2i64,
11966 DAG.getBitcast(MVT::v2i64,
11967 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11968 DAG.getBitcast(MVT::v2i64,
11969 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11971 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11972 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11974 // Subtract the bias.
11975 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11977 // Handle final rounding.
11978 EVT DestVT = Op.getValueType();
11980 if (DestVT.bitsLT(MVT::f64))
11981 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11982 DAG.getIntPtrConstant(0, dl));
11983 if (DestVT.bitsGT(MVT::f64))
11984 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11986 // Handle final rounding.
11990 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11991 const X86Subtarget &Subtarget) {
11992 // The algorithm is the following:
11993 // #ifdef __SSE4_1__
11994 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11995 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11996 // (uint4) 0x53000000, 0xaa);
11998 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11999 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12001 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12002 // return (float4) lo + fhi;
12005 SDValue V = Op->getOperand(0);
12006 EVT VecIntVT = V.getValueType();
12007 bool Is128 = VecIntVT == MVT::v4i32;
12008 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12009 // If we convert to something else than the supported type, e.g., to v4f64,
12011 if (VecFloatVT != Op->getValueType(0))
12014 unsigned NumElts = VecIntVT.getVectorNumElements();
12015 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12016 "Unsupported custom type");
12017 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12019 // In the #idef/#else code, we have in common:
12020 // - The vector of constants:
12026 // Create the splat vector for 0x4b000000.
12027 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12028 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12029 CstLow, CstLow, CstLow, CstLow};
12030 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12031 makeArrayRef(&CstLowArray[0], NumElts));
12032 // Create the splat vector for 0x53000000.
12033 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12034 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12035 CstHigh, CstHigh, CstHigh, CstHigh};
12036 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12037 makeArrayRef(&CstHighArray[0], NumElts));
12039 // Create the right shift.
12040 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12041 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12042 CstShift, CstShift, CstShift, CstShift};
12043 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12044 makeArrayRef(&CstShiftArray[0], NumElts));
12045 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12048 if (Subtarget.hasSSE41()) {
12049 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12050 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12051 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12052 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12053 // Low will be bitcasted right away, so do not bother bitcasting back to its
12055 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12056 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12057 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12058 // (uint4) 0x53000000, 0xaa);
12059 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12060 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12061 // High will be bitcasted right away, so do not bother bitcasting back to
12062 // its original type.
12063 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12064 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12066 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12067 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12068 CstMask, CstMask, CstMask);
12069 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12070 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12071 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12073 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12074 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12077 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12078 SDValue CstFAdd = DAG.getConstantFP(
12079 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12080 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12081 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12082 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12083 makeArrayRef(&CstFAddArray[0], NumElts));
12085 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12086 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12088 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12089 // return (float4) lo + fhi;
12090 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12091 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12094 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12095 SelectionDAG &DAG) const {
12096 SDValue N0 = Op.getOperand(0);
12097 MVT SVT = N0.getSimpleValueType();
12100 switch (SVT.SimpleTy) {
12102 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12107 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12108 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12109 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12113 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12116 if (Subtarget->hasAVX512())
12117 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12118 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12120 llvm_unreachable(nullptr);
12123 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12124 SelectionDAG &DAG) const {
12125 SDValue N0 = Op.getOperand(0);
12128 if (Op.getValueType().isVector())
12129 return lowerUINT_TO_FP_vec(Op, DAG);
12131 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12132 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12133 // the optimization here.
12134 if (DAG.SignBitIsZero(N0))
12135 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12137 MVT SrcVT = N0.getSimpleValueType();
12138 MVT DstVT = Op.getSimpleValueType();
12139 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12140 return LowerUINT_TO_FP_i64(Op, DAG);
12141 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12142 return LowerUINT_TO_FP_i32(Op, DAG);
12143 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12146 // Make a 64-bit buffer, and use it to build an FILD.
12147 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12148 if (SrcVT == MVT::i32) {
12149 SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
12150 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
12151 getPointerTy(), StackSlot, WordOff);
12152 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12153 StackSlot, MachinePointerInfo(),
12155 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12156 OffsetSlot, MachinePointerInfo(),
12158 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12162 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12163 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12164 StackSlot, MachinePointerInfo(),
12166 // For i64 source, we need to add the appropriate power of 2 if the input
12167 // was negative. This is the same as the optimization in
12168 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12169 // we must be careful to do the computation in x87 extended precision, not
12170 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12171 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12172 MachineMemOperand *MMO =
12173 DAG.getMachineFunction()
12174 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12175 MachineMemOperand::MOLoad, 8, 8);
12177 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12178 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12179 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12182 APInt FF(32, 0x5F800000ULL);
12184 // Check whether the sign bit is set.
12185 SDValue SignSet = DAG.getSetCC(dl,
12186 getSetCCResultType(*DAG.getContext(), MVT::i64),
12188 DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12190 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12191 SDValue FudgePtr = DAG.getConstantPool(
12192 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
12195 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12196 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12197 SDValue Four = DAG.getIntPtrConstant(4, dl);
12198 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12200 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
12202 // Load the value out, extending it from f32 to f80.
12203 // FIXME: Avoid the extend by constructing the right constant pool?
12204 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12205 FudgePtr, MachinePointerInfo::getConstantPool(),
12206 MVT::f32, false, false, false, 4);
12207 // Extend everything to 80 bits to force it to be done on x87.
12208 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12209 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12210 DAG.getIntPtrConstant(0, dl));
12213 std::pair<SDValue,SDValue>
12214 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12215 bool IsSigned, bool IsReplace) const {
12218 EVT DstTy = Op.getValueType();
12220 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12221 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12225 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12226 DstTy.getSimpleVT() >= MVT::i16 &&
12227 "Unknown FP_TO_INT to lower!");
12229 // These are really Legal.
12230 if (DstTy == MVT::i32 &&
12231 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12232 return std::make_pair(SDValue(), SDValue());
12233 if (Subtarget->is64Bit() &&
12234 DstTy == MVT::i64 &&
12235 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12236 return std::make_pair(SDValue(), SDValue());
12238 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12239 // stack slot, or into the FTOL runtime function.
12240 MachineFunction &MF = DAG.getMachineFunction();
12241 unsigned MemSize = DstTy.getSizeInBits()/8;
12242 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12243 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12246 if (!IsSigned && isIntegerTypeFTOL(DstTy))
12247 Opc = X86ISD::WIN_FTOL;
12249 switch (DstTy.getSimpleVT().SimpleTy) {
12250 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12251 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12252 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12253 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12256 SDValue Chain = DAG.getEntryNode();
12257 SDValue Value = Op.getOperand(0);
12258 EVT TheVT = Op.getOperand(0).getValueType();
12259 // FIXME This causes a redundant load/store if the SSE-class value is already
12260 // in memory, such as if it is on the callstack.
12261 if (isScalarFPTypeInSSEReg(TheVT)) {
12262 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12263 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12264 MachinePointerInfo::getFixedStack(SSFI),
12266 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12268 Chain, StackSlot, DAG.getValueType(TheVT)
12271 MachineMemOperand *MMO =
12272 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12273 MachineMemOperand::MOLoad, MemSize, MemSize);
12274 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12275 Chain = Value.getValue(1);
12276 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12277 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12280 MachineMemOperand *MMO =
12281 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12282 MachineMemOperand::MOStore, MemSize, MemSize);
12284 if (Opc != X86ISD::WIN_FTOL) {
12285 // Build the FP_TO_INT*_IN_MEM
12286 SDValue Ops[] = { Chain, Value, StackSlot };
12287 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12289 return std::make_pair(FIST, StackSlot);
12291 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12292 DAG.getVTList(MVT::Other, MVT::Glue),
12294 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12295 MVT::i32, ftol.getValue(1));
12296 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12297 MVT::i32, eax.getValue(2));
12298 SDValue Ops[] = { eax, edx };
12299 SDValue pair = IsReplace
12300 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12301 : DAG.getMergeValues(Ops, DL);
12302 return std::make_pair(pair, SDValue());
12306 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12307 const X86Subtarget *Subtarget) {
12308 MVT VT = Op->getSimpleValueType(0);
12309 SDValue In = Op->getOperand(0);
12310 MVT InVT = In.getSimpleValueType();
12313 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12314 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12316 // Optimize vectors in AVX mode:
12319 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12320 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12321 // Concat upper and lower parts.
12324 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12325 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12326 // Concat upper and lower parts.
12329 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12330 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12331 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12334 if (Subtarget->hasInt256())
12335 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12337 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12338 SDValue Undef = DAG.getUNDEF(InVT);
12339 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12340 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12341 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12343 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12344 VT.getVectorNumElements()/2);
12346 OpLo = DAG.getBitcast(HVT, OpLo);
12347 OpHi = DAG.getBitcast(HVT, OpHi);
12349 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12352 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12353 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12354 MVT VT = Op->getSimpleValueType(0);
12355 SDValue In = Op->getOperand(0);
12356 MVT InVT = In.getSimpleValueType();
12358 unsigned int NumElts = VT.getVectorNumElements();
12359 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12362 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12363 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12365 assert(InVT.getVectorElementType() == MVT::i1);
12366 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12368 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12370 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12372 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12373 if (VT.is512BitVector())
12375 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12378 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12379 SelectionDAG &DAG) {
12380 if (Subtarget->hasFp256())
12381 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12387 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12388 SelectionDAG &DAG) {
12390 MVT VT = Op.getSimpleValueType();
12391 SDValue In = Op.getOperand(0);
12392 MVT SVT = In.getSimpleValueType();
12394 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12395 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12397 if (Subtarget->hasFp256())
12398 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12401 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12402 VT.getVectorNumElements() != SVT.getVectorNumElements());
12406 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12408 MVT VT = Op.getSimpleValueType();
12409 SDValue In = Op.getOperand(0);
12410 MVT InVT = In.getSimpleValueType();
12412 if (VT == MVT::i1) {
12413 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12414 "Invalid scalar TRUNCATE operation");
12415 if (InVT.getSizeInBits() >= 32)
12417 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12418 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12420 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12421 "Invalid TRUNCATE operation");
12423 // move vector to mask - truncate solution for SKX
12424 if (VT.getVectorElementType() == MVT::i1) {
12425 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12426 Subtarget->hasBWI())
12427 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12428 if ((InVT.is256BitVector() || InVT.is128BitVector())
12429 && InVT.getScalarSizeInBits() <= 16 &&
12430 Subtarget->hasBWI() && Subtarget->hasVLX())
12431 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12432 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12433 Subtarget->hasDQI())
12434 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12435 if ((InVT.is256BitVector() || InVT.is128BitVector())
12436 && InVT.getScalarSizeInBits() >= 32 &&
12437 Subtarget->hasDQI() && Subtarget->hasVLX())
12438 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12440 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12441 if (VT.getVectorElementType().getSizeInBits() >=8)
12442 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12444 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12445 unsigned NumElts = InVT.getVectorNumElements();
12446 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12447 if (InVT.getSizeInBits() < 512) {
12448 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12449 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12454 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12455 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12456 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12459 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12460 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12461 if (Subtarget->hasInt256()) {
12462 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12463 In = DAG.getBitcast(MVT::v8i32, In);
12464 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12466 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12467 DAG.getIntPtrConstant(0, DL));
12470 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12471 DAG.getIntPtrConstant(0, DL));
12472 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12473 DAG.getIntPtrConstant(2, DL));
12474 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12475 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12476 static const int ShufMask[] = {0, 2, 4, 6};
12477 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12480 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12481 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12482 if (Subtarget->hasInt256()) {
12483 In = DAG.getBitcast(MVT::v32i8, In);
12485 SmallVector<SDValue,32> pshufbMask;
12486 for (unsigned i = 0; i < 2; ++i) {
12487 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12488 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12489 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12490 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12491 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12492 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12493 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12494 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12495 for (unsigned j = 0; j < 8; ++j)
12496 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12498 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12499 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12500 In = DAG.getBitcast(MVT::v4i64, In);
12502 static const int ShufMask[] = {0, 2, -1, -1};
12503 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12505 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12506 DAG.getIntPtrConstant(0, DL));
12507 return DAG.getBitcast(VT, In);
12510 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12511 DAG.getIntPtrConstant(0, DL));
12513 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12514 DAG.getIntPtrConstant(4, DL));
12516 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12517 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12519 // The PSHUFB mask:
12520 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12521 -1, -1, -1, -1, -1, -1, -1, -1};
12523 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12524 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12525 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12527 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12528 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12530 // The MOVLHPS Mask:
12531 static const int ShufMask2[] = {0, 1, 4, 5};
12532 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12533 return DAG.getBitcast(MVT::v8i16, res);
12536 // Handle truncation of V256 to V128 using shuffles.
12537 if (!VT.is128BitVector() || !InVT.is256BitVector())
12540 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12542 unsigned NumElems = VT.getVectorNumElements();
12543 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12545 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12546 // Prepare truncation shuffle mask
12547 for (unsigned i = 0; i != NumElems; ++i)
12548 MaskVec[i] = i * 2;
12549 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12550 DAG.getUNDEF(NVT), &MaskVec[0]);
12551 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12552 DAG.getIntPtrConstant(0, DL));
12555 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12556 SelectionDAG &DAG) const {
12557 assert(!Op.getSimpleValueType().isVector());
12559 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12560 /*IsSigned=*/ true, /*IsReplace=*/ false);
12561 SDValue FIST = Vals.first, StackSlot = Vals.second;
12562 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12563 if (!FIST.getNode()) return Op;
12565 if (StackSlot.getNode())
12566 // Load the result.
12567 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12568 FIST, StackSlot, MachinePointerInfo(),
12569 false, false, false, 0);
12571 // The node is the result.
12575 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12576 SelectionDAG &DAG) const {
12577 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12578 /*IsSigned=*/ false, /*IsReplace=*/ false);
12579 SDValue FIST = Vals.first, StackSlot = Vals.second;
12580 assert(FIST.getNode() && "Unexpected failure");
12582 if (StackSlot.getNode())
12583 // Load the result.
12584 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12585 FIST, StackSlot, MachinePointerInfo(),
12586 false, false, false, 0);
12588 // The node is the result.
12592 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12594 MVT VT = Op.getSimpleValueType();
12595 SDValue In = Op.getOperand(0);
12596 MVT SVT = In.getSimpleValueType();
12598 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12600 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12601 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12602 In, DAG.getUNDEF(SVT)));
12605 /// The only differences between FABS and FNEG are the mask and the logic op.
12606 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12607 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12608 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12609 "Wrong opcode for lowering FABS or FNEG.");
12611 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12613 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12614 // into an FNABS. We'll lower the FABS after that if it is still in use.
12616 for (SDNode *User : Op->uses())
12617 if (User->getOpcode() == ISD::FNEG)
12620 SDValue Op0 = Op.getOperand(0);
12621 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12624 MVT VT = Op.getSimpleValueType();
12625 // Assume scalar op for initialization; update for vector if needed.
12626 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12627 // generate a 16-byte vector constant and logic op even for the scalar case.
12628 // Using a 16-byte mask allows folding the load of the mask with
12629 // the logic op, so it can save (~4 bytes) on code size.
12631 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12632 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12633 // decide if we should generate a 16-byte constant mask when we only need 4 or
12634 // 8 bytes for the scalar case.
12635 if (VT.isVector()) {
12636 EltVT = VT.getVectorElementType();
12637 NumElts = VT.getVectorNumElements();
12640 unsigned EltBits = EltVT.getSizeInBits();
12641 LLVMContext *Context = DAG.getContext();
12642 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12644 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12645 Constant *C = ConstantInt::get(*Context, MaskElt);
12646 C = ConstantVector::getSplat(NumElts, C);
12647 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12648 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12649 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12650 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12651 MachinePointerInfo::getConstantPool(),
12652 false, false, false, Alignment);
12654 if (VT.isVector()) {
12655 // For a vector, cast operands to a vector type, perform the logic op,
12656 // and cast the result back to the original value type.
12657 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12658 SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12659 SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12660 : DAG.getBitcast(VecVT, Op0);
12661 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12662 return DAG.getBitcast(VT,
12663 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12666 // If not vector, then scalar.
12667 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12668 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12669 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12672 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12673 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12674 LLVMContext *Context = DAG.getContext();
12675 SDValue Op0 = Op.getOperand(0);
12676 SDValue Op1 = Op.getOperand(1);
12678 MVT VT = Op.getSimpleValueType();
12679 MVT SrcVT = Op1.getSimpleValueType();
12681 // If second operand is smaller, extend it first.
12682 if (SrcVT.bitsLT(VT)) {
12683 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12686 // And if it is bigger, shrink it first.
12687 if (SrcVT.bitsGT(VT)) {
12688 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12692 // At this point the operands and the result should have the same
12693 // type, and that won't be f80 since that is not custom lowered.
12695 const fltSemantics &Sem =
12696 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12697 const unsigned SizeInBits = VT.getSizeInBits();
12699 SmallVector<Constant *, 4> CV(
12700 VT == MVT::f64 ? 2 : 4,
12701 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12703 // First, clear all bits but the sign bit from the second operand (sign).
12704 CV[0] = ConstantFP::get(*Context,
12705 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12706 Constant *C = ConstantVector::get(CV);
12707 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12708 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12709 MachinePointerInfo::getConstantPool(),
12710 false, false, false, 16);
12711 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12713 // Next, clear the sign bit from the first operand (magnitude).
12714 // If it's a constant, we can clear it here.
12715 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12716 APFloat APF = Op0CN->getValueAPF();
12717 // If the magnitude is a positive zero, the sign bit alone is enough.
12718 if (APF.isPosZero())
12721 CV[0] = ConstantFP::get(*Context, APF);
12723 CV[0] = ConstantFP::get(
12725 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12727 C = ConstantVector::get(CV);
12728 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12729 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12730 MachinePointerInfo::getConstantPool(),
12731 false, false, false, 16);
12732 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12733 if (!isa<ConstantFPSDNode>(Op0))
12734 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12736 // OR the magnitude value with the sign bit.
12737 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12740 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12741 SDValue N0 = Op.getOperand(0);
12743 MVT VT = Op.getSimpleValueType();
12745 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12746 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12747 DAG.getConstant(1, dl, VT));
12748 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12751 // Check whether an OR'd tree is PTEST-able.
12752 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12753 SelectionDAG &DAG) {
12754 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12756 if (!Subtarget->hasSSE41())
12759 if (!Op->hasOneUse())
12762 SDNode *N = Op.getNode();
12765 SmallVector<SDValue, 8> Opnds;
12766 DenseMap<SDValue, unsigned> VecInMap;
12767 SmallVector<SDValue, 8> VecIns;
12768 EVT VT = MVT::Other;
12770 // Recognize a special case where a vector is casted into wide integer to
12772 Opnds.push_back(N->getOperand(0));
12773 Opnds.push_back(N->getOperand(1));
12775 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12776 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12777 // BFS traverse all OR'd operands.
12778 if (I->getOpcode() == ISD::OR) {
12779 Opnds.push_back(I->getOperand(0));
12780 Opnds.push_back(I->getOperand(1));
12781 // Re-evaluate the number of nodes to be traversed.
12782 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12786 // Quit if a non-EXTRACT_VECTOR_ELT
12787 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12790 // Quit if without a constant index.
12791 SDValue Idx = I->getOperand(1);
12792 if (!isa<ConstantSDNode>(Idx))
12795 SDValue ExtractedFromVec = I->getOperand(0);
12796 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12797 if (M == VecInMap.end()) {
12798 VT = ExtractedFromVec.getValueType();
12799 // Quit if not 128/256-bit vector.
12800 if (!VT.is128BitVector() && !VT.is256BitVector())
12802 // Quit if not the same type.
12803 if (VecInMap.begin() != VecInMap.end() &&
12804 VT != VecInMap.begin()->first.getValueType())
12806 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12807 VecIns.push_back(ExtractedFromVec);
12809 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12812 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12813 "Not extracted from 128-/256-bit vector.");
12815 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12817 for (DenseMap<SDValue, unsigned>::const_iterator
12818 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12819 // Quit if not all elements are used.
12820 if (I->second != FullMask)
12824 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12826 // Cast all vectors into TestVT for PTEST.
12827 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12828 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12830 // If more than one full vectors are evaluated, OR them first before PTEST.
12831 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12832 // Each iteration will OR 2 nodes and append the result until there is only
12833 // 1 node left, i.e. the final OR'd value of all vectors.
12834 SDValue LHS = VecIns[Slot];
12835 SDValue RHS = VecIns[Slot + 1];
12836 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12839 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12840 VecIns.back(), VecIns.back());
12843 /// \brief return true if \c Op has a use that doesn't just read flags.
12844 static bool hasNonFlagsUse(SDValue Op) {
12845 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12847 SDNode *User = *UI;
12848 unsigned UOpNo = UI.getOperandNo();
12849 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12850 // Look pass truncate.
12851 UOpNo = User->use_begin().getOperandNo();
12852 User = *User->use_begin();
12855 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12856 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12862 /// Emit nodes that will be selected as "test Op0,Op0", or something
12864 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12865 SelectionDAG &DAG) const {
12866 if (Op.getValueType() == MVT::i1) {
12867 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12868 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12869 DAG.getConstant(0, dl, MVT::i8));
12871 // CF and OF aren't always set the way we want. Determine which
12872 // of these we need.
12873 bool NeedCF = false;
12874 bool NeedOF = false;
12877 case X86::COND_A: case X86::COND_AE:
12878 case X86::COND_B: case X86::COND_BE:
12881 case X86::COND_G: case X86::COND_GE:
12882 case X86::COND_L: case X86::COND_LE:
12883 case X86::COND_O: case X86::COND_NO: {
12884 // Check if we really need to set the
12885 // Overflow flag. If NoSignedWrap is present
12886 // that is not actually needed.
12887 switch (Op->getOpcode()) {
12892 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12893 if (BinNode->Flags.hasNoSignedWrap())
12903 // See if we can use the EFLAGS value from the operand instead of
12904 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12905 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12906 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12907 // Emit a CMP with 0, which is the TEST pattern.
12908 //if (Op.getValueType() == MVT::i1)
12909 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12910 // DAG.getConstant(0, MVT::i1));
12911 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12912 DAG.getConstant(0, dl, Op.getValueType()));
12914 unsigned Opcode = 0;
12915 unsigned NumOperands = 0;
12917 // Truncate operations may prevent the merge of the SETCC instruction
12918 // and the arithmetic instruction before it. Attempt to truncate the operands
12919 // of the arithmetic instruction and use a reduced bit-width instruction.
12920 bool NeedTruncation = false;
12921 SDValue ArithOp = Op;
12922 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12923 SDValue Arith = Op->getOperand(0);
12924 // Both the trunc and the arithmetic op need to have one user each.
12925 if (Arith->hasOneUse())
12926 switch (Arith.getOpcode()) {
12933 NeedTruncation = true;
12939 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12940 // which may be the result of a CAST. We use the variable 'Op', which is the
12941 // non-casted variable when we check for possible users.
12942 switch (ArithOp.getOpcode()) {
12944 // Due to an isel shortcoming, be conservative if this add is likely to be
12945 // selected as part of a load-modify-store instruction. When the root node
12946 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12947 // uses of other nodes in the match, such as the ADD in this case. This
12948 // leads to the ADD being left around and reselected, with the result being
12949 // two adds in the output. Alas, even if none our users are stores, that
12950 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12951 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12952 // climbing the DAG back to the root, and it doesn't seem to be worth the
12954 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12955 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12956 if (UI->getOpcode() != ISD::CopyToReg &&
12957 UI->getOpcode() != ISD::SETCC &&
12958 UI->getOpcode() != ISD::STORE)
12961 if (ConstantSDNode *C =
12962 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12963 // An add of one will be selected as an INC.
12964 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12965 Opcode = X86ISD::INC;
12970 // An add of negative one (subtract of one) will be selected as a DEC.
12971 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12972 Opcode = X86ISD::DEC;
12978 // Otherwise use a regular EFLAGS-setting add.
12979 Opcode = X86ISD::ADD;
12984 // If we have a constant logical shift that's only used in a comparison
12985 // against zero turn it into an equivalent AND. This allows turning it into
12986 // a TEST instruction later.
12987 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12988 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12989 EVT VT = Op.getValueType();
12990 unsigned BitWidth = VT.getSizeInBits();
12991 unsigned ShAmt = Op->getConstantOperandVal(1);
12992 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12994 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12995 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12996 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12997 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12999 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13000 DAG.getConstant(Mask, dl, VT));
13001 DAG.ReplaceAllUsesWith(Op, New);
13007 // If the primary and result isn't used, don't bother using X86ISD::AND,
13008 // because a TEST instruction will be better.
13009 if (!hasNonFlagsUse(Op))
13015 // Due to the ISEL shortcoming noted above, be conservative if this op is
13016 // likely to be selected as part of a load-modify-store instruction.
13017 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13018 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13019 if (UI->getOpcode() == ISD::STORE)
13022 // Otherwise use a regular EFLAGS-setting instruction.
13023 switch (ArithOp.getOpcode()) {
13024 default: llvm_unreachable("unexpected operator!");
13025 case ISD::SUB: Opcode = X86ISD::SUB; break;
13026 case ISD::XOR: Opcode = X86ISD::XOR; break;
13027 case ISD::AND: Opcode = X86ISD::AND; break;
13029 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13030 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13031 if (EFLAGS.getNode())
13034 Opcode = X86ISD::OR;
13048 return SDValue(Op.getNode(), 1);
13054 // If we found that truncation is beneficial, perform the truncation and
13056 if (NeedTruncation) {
13057 EVT VT = Op.getValueType();
13058 SDValue WideVal = Op->getOperand(0);
13059 EVT WideVT = WideVal.getValueType();
13060 unsigned ConvertedOp = 0;
13061 // Use a target machine opcode to prevent further DAGCombine
13062 // optimizations that may separate the arithmetic operations
13063 // from the setcc node.
13064 switch (WideVal.getOpcode()) {
13066 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13067 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13068 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13069 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13070 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13074 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13075 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13076 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13077 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13078 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13084 // Emit a CMP with 0, which is the TEST pattern.
13085 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13086 DAG.getConstant(0, dl, Op.getValueType()));
13088 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13089 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13091 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13092 DAG.ReplaceAllUsesWith(Op, New);
13093 return SDValue(New.getNode(), 1);
13096 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13098 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13099 SDLoc dl, SelectionDAG &DAG) const {
13100 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13101 if (C->getAPIntValue() == 0)
13102 return EmitTest(Op0, X86CC, dl, DAG);
13104 if (Op0.getValueType() == MVT::i1)
13105 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13108 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13109 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13110 // Do the comparison at i32 if it's smaller, besides the Atom case.
13111 // This avoids subregister aliasing issues. Keep the smaller reference
13112 // if we're optimizing for size, however, as that'll allow better folding
13113 // of memory operations.
13114 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13115 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13116 Attribute::MinSize) &&
13117 !Subtarget->isAtom()) {
13118 unsigned ExtendOp =
13119 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13120 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13121 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13123 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13124 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13125 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13127 return SDValue(Sub.getNode(), 1);
13129 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13132 /// Convert a comparison if required by the subtarget.
13133 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13134 SelectionDAG &DAG) const {
13135 // If the subtarget does not support the FUCOMI instruction, floating-point
13136 // comparisons have to be converted.
13137 if (Subtarget->hasCMov() ||
13138 Cmp.getOpcode() != X86ISD::CMP ||
13139 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13140 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13143 // The instruction selector will select an FUCOM instruction instead of
13144 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13145 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13146 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13148 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13149 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13150 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13151 DAG.getConstant(8, dl, MVT::i8));
13152 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13153 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13156 /// The minimum architected relative accuracy is 2^-12. We need one
13157 /// Newton-Raphson step to have a good float result (24 bits of precision).
13158 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13159 DAGCombinerInfo &DCI,
13160 unsigned &RefinementSteps,
13161 bool &UseOneConstNR) const {
13162 EVT VT = Op.getValueType();
13163 const char *RecipOp;
13165 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13166 // TODO: Add support for AVX512 (v16f32).
13167 // It is likely not profitable to do this for f64 because a double-precision
13168 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13169 // instructions: convert to single, rsqrtss, convert back to double, refine
13170 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13171 // along with FMA, this could be a throughput win.
13172 if (VT == MVT::f32 && Subtarget->hasSSE1())
13174 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13175 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13176 RecipOp = "vec-sqrtf";
13180 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13181 if (!Recips.isEnabled(RecipOp))
13184 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13185 UseOneConstNR = false;
13186 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13189 /// The minimum architected relative accuracy is 2^-12. We need one
13190 /// Newton-Raphson step to have a good float result (24 bits of precision).
13191 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13192 DAGCombinerInfo &DCI,
13193 unsigned &RefinementSteps) const {
13194 EVT VT = Op.getValueType();
13195 const char *RecipOp;
13197 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13198 // TODO: Add support for AVX512 (v16f32).
13199 // It is likely not profitable to do this for f64 because a double-precision
13200 // reciprocal estimate with refinement on x86 prior to FMA requires
13201 // 15 instructions: convert to single, rcpss, convert back to double, refine
13202 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13203 // along with FMA, this could be a throughput win.
13204 if (VT == MVT::f32 && Subtarget->hasSSE1())
13206 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13207 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13208 RecipOp = "vec-divf";
13212 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13213 if (!Recips.isEnabled(RecipOp))
13216 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13217 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13220 /// If we have at least two divisions that use the same divisor, convert to
13221 /// multplication by a reciprocal. This may need to be adjusted for a given
13222 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13223 /// This is because we still need one division to calculate the reciprocal and
13224 /// then we need two multiplies by that reciprocal as replacements for the
13225 /// original divisions.
13226 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13227 return NumUsers > 1;
13230 static bool isAllOnes(SDValue V) {
13231 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13232 return C && C->isAllOnesValue();
13235 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13236 /// if it's possible.
13237 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13238 SDLoc dl, SelectionDAG &DAG) const {
13239 SDValue Op0 = And.getOperand(0);
13240 SDValue Op1 = And.getOperand(1);
13241 if (Op0.getOpcode() == ISD::TRUNCATE)
13242 Op0 = Op0.getOperand(0);
13243 if (Op1.getOpcode() == ISD::TRUNCATE)
13244 Op1 = Op1.getOperand(0);
13247 if (Op1.getOpcode() == ISD::SHL)
13248 std::swap(Op0, Op1);
13249 if (Op0.getOpcode() == ISD::SHL) {
13250 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13251 if (And00C->getZExtValue() == 1) {
13252 // If we looked past a truncate, check that it's only truncating away
13254 unsigned BitWidth = Op0.getValueSizeInBits();
13255 unsigned AndBitWidth = And.getValueSizeInBits();
13256 if (BitWidth > AndBitWidth) {
13258 DAG.computeKnownBits(Op0, Zeros, Ones);
13259 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13263 RHS = Op0.getOperand(1);
13265 } else if (Op1.getOpcode() == ISD::Constant) {
13266 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13267 uint64_t AndRHSVal = AndRHS->getZExtValue();
13268 SDValue AndLHS = Op0;
13270 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13271 LHS = AndLHS.getOperand(0);
13272 RHS = AndLHS.getOperand(1);
13275 // Use BT if the immediate can't be encoded in a TEST instruction.
13276 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13278 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13282 if (LHS.getNode()) {
13283 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13284 // instruction. Since the shift amount is in-range-or-undefined, we know
13285 // that doing a bittest on the i32 value is ok. We extend to i32 because
13286 // the encoding for the i16 version is larger than the i32 version.
13287 // Also promote i16 to i32 for performance / code size reason.
13288 if (LHS.getValueType() == MVT::i8 ||
13289 LHS.getValueType() == MVT::i16)
13290 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13292 // If the operand types disagree, extend the shift amount to match. Since
13293 // BT ignores high bits (like shifts) we can use anyextend.
13294 if (LHS.getValueType() != RHS.getValueType())
13295 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13297 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13298 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13299 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13300 DAG.getConstant(Cond, dl, MVT::i8), BT);
13306 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13308 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13313 // SSE Condition code mapping:
13322 switch (SetCCOpcode) {
13323 default: llvm_unreachable("Unexpected SETCC condition");
13325 case ISD::SETEQ: SSECC = 0; break;
13327 case ISD::SETGT: Swap = true; // Fallthrough
13329 case ISD::SETOLT: SSECC = 1; break;
13331 case ISD::SETGE: Swap = true; // Fallthrough
13333 case ISD::SETOLE: SSECC = 2; break;
13334 case ISD::SETUO: SSECC = 3; break;
13336 case ISD::SETNE: SSECC = 4; break;
13337 case ISD::SETULE: Swap = true; // Fallthrough
13338 case ISD::SETUGE: SSECC = 5; break;
13339 case ISD::SETULT: Swap = true; // Fallthrough
13340 case ISD::SETUGT: SSECC = 6; break;
13341 case ISD::SETO: SSECC = 7; break;
13343 case ISD::SETONE: SSECC = 8; break;
13346 std::swap(Op0, Op1);
13351 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13352 // ones, and then concatenate the result back.
13353 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13354 MVT VT = Op.getSimpleValueType();
13356 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13357 "Unsupported value type for operation");
13359 unsigned NumElems = VT.getVectorNumElements();
13361 SDValue CC = Op.getOperand(2);
13363 // Extract the LHS vectors
13364 SDValue LHS = Op.getOperand(0);
13365 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13366 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13368 // Extract the RHS vectors
13369 SDValue RHS = Op.getOperand(1);
13370 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13371 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13373 // Issue the operation on the smaller types and concatenate the result back
13374 MVT EltVT = VT.getVectorElementType();
13375 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13376 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13377 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13378 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13381 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13382 SDValue Op0 = Op.getOperand(0);
13383 SDValue Op1 = Op.getOperand(1);
13384 SDValue CC = Op.getOperand(2);
13385 MVT VT = Op.getSimpleValueType();
13388 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13389 "Unexpected type for boolean compare operation");
13390 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13391 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13392 DAG.getConstant(-1, dl, VT));
13393 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13394 DAG.getConstant(-1, dl, VT));
13395 switch (SetCCOpcode) {
13396 default: llvm_unreachable("Unexpected SETCC condition");
13398 // (x == y) -> ~(x ^ y)
13399 return DAG.getNode(ISD::XOR, dl, VT,
13400 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13401 DAG.getConstant(-1, dl, VT));
13403 // (x != y) -> (x ^ y)
13404 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13407 // (x > y) -> (x & ~y)
13408 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13411 // (x < y) -> (~x & y)
13412 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13415 // (x <= y) -> (~x | y)
13416 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13419 // (x >=y) -> (x | ~y)
13420 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13424 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13425 const X86Subtarget *Subtarget) {
13426 SDValue Op0 = Op.getOperand(0);
13427 SDValue Op1 = Op.getOperand(1);
13428 SDValue CC = Op.getOperand(2);
13429 MVT VT = Op.getSimpleValueType();
13432 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13433 Op.getValueType().getScalarType() == MVT::i1 &&
13434 "Cannot set masked compare for this operation");
13436 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13438 bool Unsigned = false;
13441 switch (SetCCOpcode) {
13442 default: llvm_unreachable("Unexpected SETCC condition");
13443 case ISD::SETNE: SSECC = 4; break;
13444 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13445 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13446 case ISD::SETLT: Swap = true; //fall-through
13447 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13448 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13449 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13450 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13451 case ISD::SETULE: Unsigned = true; //fall-through
13452 case ISD::SETLE: SSECC = 2; break;
13456 std::swap(Op0, Op1);
13458 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13459 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13460 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13461 DAG.getConstant(SSECC, dl, MVT::i8));
13464 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13465 /// operand \p Op1. If non-trivial (for example because it's not constant)
13466 /// return an empty value.
13467 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13469 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13473 MVT VT = Op1.getSimpleValueType();
13474 MVT EVT = VT.getVectorElementType();
13475 unsigned n = VT.getVectorNumElements();
13476 SmallVector<SDValue, 8> ULTOp1;
13478 for (unsigned i = 0; i < n; ++i) {
13479 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13480 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13483 // Avoid underflow.
13484 APInt Val = Elt->getAPIntValue();
13488 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13491 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13494 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13495 SelectionDAG &DAG) {
13496 SDValue Op0 = Op.getOperand(0);
13497 SDValue Op1 = Op.getOperand(1);
13498 SDValue CC = Op.getOperand(2);
13499 MVT VT = Op.getSimpleValueType();
13500 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13501 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13506 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13507 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13510 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13511 unsigned Opc = X86ISD::CMPP;
13512 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13513 assert(VT.getVectorNumElements() <= 16);
13514 Opc = X86ISD::CMPM;
13516 // In the two special cases we can't handle, emit two comparisons.
13519 unsigned CombineOpc;
13520 if (SetCCOpcode == ISD::SETUEQ) {
13521 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13523 assert(SetCCOpcode == ISD::SETONE);
13524 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13527 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13528 DAG.getConstant(CC0, dl, MVT::i8));
13529 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13530 DAG.getConstant(CC1, dl, MVT::i8));
13531 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13533 // Handle all other FP comparisons here.
13534 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13535 DAG.getConstant(SSECC, dl, MVT::i8));
13538 // Break 256-bit integer vector compare into smaller ones.
13539 if (VT.is256BitVector() && !Subtarget->hasInt256())
13540 return Lower256IntVSETCC(Op, DAG);
13542 EVT OpVT = Op1.getValueType();
13543 if (OpVT.getVectorElementType() == MVT::i1)
13544 return LowerBoolVSETCC_AVX512(Op, DAG);
13546 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13547 if (Subtarget->hasAVX512()) {
13548 if (Op1.getValueType().is512BitVector() ||
13549 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13550 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13551 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13553 // In AVX-512 architecture setcc returns mask with i1 elements,
13554 // But there is no compare instruction for i8 and i16 elements in KNL.
13555 // We are not talking about 512-bit operands in this case, these
13556 // types are illegal.
13558 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13559 OpVT.getVectorElementType().getSizeInBits() >= 8))
13560 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13561 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13564 // We are handling one of the integer comparisons here. Since SSE only has
13565 // GT and EQ comparisons for integer, swapping operands and multiple
13566 // operations may be required for some comparisons.
13568 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13569 bool Subus = false;
13571 switch (SetCCOpcode) {
13572 default: llvm_unreachable("Unexpected SETCC condition");
13573 case ISD::SETNE: Invert = true;
13574 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13575 case ISD::SETLT: Swap = true;
13576 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13577 case ISD::SETGE: Swap = true;
13578 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13579 Invert = true; break;
13580 case ISD::SETULT: Swap = true;
13581 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13582 FlipSigns = true; break;
13583 case ISD::SETUGE: Swap = true;
13584 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13585 FlipSigns = true; Invert = true; break;
13588 // Special case: Use min/max operations for SETULE/SETUGE
13589 MVT VET = VT.getVectorElementType();
13591 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13592 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13595 switch (SetCCOpcode) {
13597 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13598 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13601 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13604 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13605 if (!MinMax && hasSubus) {
13606 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13608 // t = psubus Op0, Op1
13609 // pcmpeq t, <0..0>
13610 switch (SetCCOpcode) {
13612 case ISD::SETULT: {
13613 // If the comparison is against a constant we can turn this into a
13614 // setule. With psubus, setule does not require a swap. This is
13615 // beneficial because the constant in the register is no longer
13616 // destructed as the destination so it can be hoisted out of a loop.
13617 // Only do this pre-AVX since vpcmp* is no longer destructive.
13618 if (Subtarget->hasAVX())
13620 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13621 if (ULEOp1.getNode()) {
13623 Subus = true; Invert = false; Swap = false;
13627 // Psubus is better than flip-sign because it requires no inversion.
13628 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13629 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13633 Opc = X86ISD::SUBUS;
13639 std::swap(Op0, Op1);
13641 // Check that the operation in question is available (most are plain SSE2,
13642 // but PCMPGTQ and PCMPEQQ have different requirements).
13643 if (VT == MVT::v2i64) {
13644 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13645 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13647 // First cast everything to the right type.
13648 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13649 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13651 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13652 // bits of the inputs before performing those operations. The lower
13653 // compare is always unsigned.
13656 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13658 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13659 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13660 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13661 Sign, Zero, Sign, Zero);
13663 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13664 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13666 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13667 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13668 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13670 // Create masks for only the low parts/high parts of the 64 bit integers.
13671 static const int MaskHi[] = { 1, 1, 3, 3 };
13672 static const int MaskLo[] = { 0, 0, 2, 2 };
13673 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13674 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13675 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13677 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13678 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13681 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13683 return DAG.getBitcast(VT, Result);
13686 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13687 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13688 // pcmpeqd + pshufd + pand.
13689 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13691 // First cast everything to the right type.
13692 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13693 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13696 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13698 // Make sure the lower and upper halves are both all-ones.
13699 static const int Mask[] = { 1, 0, 3, 2 };
13700 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13701 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13704 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13706 return DAG.getBitcast(VT, Result);
13710 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13711 // bits of the inputs before performing those operations.
13713 EVT EltVT = VT.getVectorElementType();
13714 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13716 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13717 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13720 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13722 // If the logical-not of the result is required, perform that now.
13724 Result = DAG.getNOT(dl, Result, VT);
13727 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13730 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13731 getZeroVector(VT, Subtarget, DAG, dl));
13736 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13738 MVT VT = Op.getSimpleValueType();
13740 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13742 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13743 && "SetCC type must be 8-bit or 1-bit integer");
13744 SDValue Op0 = Op.getOperand(0);
13745 SDValue Op1 = Op.getOperand(1);
13747 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13749 // Optimize to BT if possible.
13750 // Lower (X & (1 << N)) == 0 to BT(X, N).
13751 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13752 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13753 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13754 Op1.getOpcode() == ISD::Constant &&
13755 cast<ConstantSDNode>(Op1)->isNullValue() &&
13756 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13757 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13758 if (NewSetCC.getNode()) {
13760 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13765 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13767 if (Op1.getOpcode() == ISD::Constant &&
13768 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13769 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13770 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13772 // If the input is a setcc, then reuse the input setcc or use a new one with
13773 // the inverted condition.
13774 if (Op0.getOpcode() == X86ISD::SETCC) {
13775 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13776 bool Invert = (CC == ISD::SETNE) ^
13777 cast<ConstantSDNode>(Op1)->isNullValue();
13781 CCode = X86::GetOppositeBranchCondition(CCode);
13782 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13783 DAG.getConstant(CCode, dl, MVT::i8),
13784 Op0.getOperand(1));
13786 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13790 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13791 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13792 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13794 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13795 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13798 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13799 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13800 if (X86CC == X86::COND_INVALID)
13803 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13804 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13805 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13806 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13808 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13812 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13813 static bool isX86LogicalCmp(SDValue Op) {
13814 unsigned Opc = Op.getNode()->getOpcode();
13815 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13816 Opc == X86ISD::SAHF)
13818 if (Op.getResNo() == 1 &&
13819 (Opc == X86ISD::ADD ||
13820 Opc == X86ISD::SUB ||
13821 Opc == X86ISD::ADC ||
13822 Opc == X86ISD::SBB ||
13823 Opc == X86ISD::SMUL ||
13824 Opc == X86ISD::UMUL ||
13825 Opc == X86ISD::INC ||
13826 Opc == X86ISD::DEC ||
13827 Opc == X86ISD::OR ||
13828 Opc == X86ISD::XOR ||
13829 Opc == X86ISD::AND))
13832 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13838 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13839 if (V.getOpcode() != ISD::TRUNCATE)
13842 SDValue VOp0 = V.getOperand(0);
13843 unsigned InBits = VOp0.getValueSizeInBits();
13844 unsigned Bits = V.getValueSizeInBits();
13845 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13848 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13849 bool addTest = true;
13850 SDValue Cond = Op.getOperand(0);
13851 SDValue Op1 = Op.getOperand(1);
13852 SDValue Op2 = Op.getOperand(2);
13854 EVT VT = Op1.getValueType();
13857 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13858 // are available or VBLENDV if AVX is available.
13859 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13860 if (Cond.getOpcode() == ISD::SETCC &&
13861 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13862 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13863 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13864 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13865 int SSECC = translateX86FSETCC(
13866 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13869 if (Subtarget->hasAVX512()) {
13870 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13871 DAG.getConstant(SSECC, DL, MVT::i8));
13872 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13875 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13876 DAG.getConstant(SSECC, DL, MVT::i8));
13878 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13879 // of 3 logic instructions for size savings and potentially speed.
13880 // Unfortunately, there is no scalar form of VBLENDV.
13882 // If either operand is a constant, don't try this. We can expect to
13883 // optimize away at least one of the logic instructions later in that
13884 // case, so that sequence would be faster than a variable blend.
13886 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13887 // uses XMM0 as the selection register. That may need just as many
13888 // instructions as the AND/ANDN/OR sequence due to register moves, so
13891 if (Subtarget->hasAVX() &&
13892 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13894 // Convert to vectors, do a VSELECT, and convert back to scalar.
13895 // All of the conversions should be optimized away.
13897 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13898 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13899 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13900 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13902 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13903 VCmp = DAG.getBitcast(VCmpVT, VCmp);
13905 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13907 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13908 VSel, DAG.getIntPtrConstant(0, DL));
13910 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13911 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13912 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13916 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13918 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13919 Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13920 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13921 Op1Scalar = Op1.getOperand(0);
13923 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13924 Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13925 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13926 Op2Scalar = Op2.getOperand(0);
13927 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13928 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13929 Op1Scalar.getValueType(),
13930 Cond, Op1Scalar, Op2Scalar);
13931 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13932 return DAG.getBitcast(VT, newSelect);
13933 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13934 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13935 DAG.getIntPtrConstant(0, DL));
13939 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13940 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13941 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13942 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13943 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13944 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13945 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13947 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13950 if (Cond.getOpcode() == ISD::SETCC) {
13951 SDValue NewCond = LowerSETCC(Cond, DAG);
13952 if (NewCond.getNode())
13956 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13957 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13958 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13959 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13960 if (Cond.getOpcode() == X86ISD::SETCC &&
13961 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13962 isZero(Cond.getOperand(1).getOperand(1))) {
13963 SDValue Cmp = Cond.getOperand(1);
13965 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13967 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13968 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13969 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13971 SDValue CmpOp0 = Cmp.getOperand(0);
13972 // Apply further optimizations for special cases
13973 // (select (x != 0), -1, 0) -> neg & sbb
13974 // (select (x == 0), 0, -1) -> neg & sbb
13975 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13976 if (YC->isNullValue() &&
13977 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13978 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13979 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13980 DAG.getConstant(0, DL,
13981 CmpOp0.getValueType()),
13983 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13984 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13985 SDValue(Neg.getNode(), 1));
13989 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13990 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13991 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13993 SDValue Res = // Res = 0 or -1.
13994 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13995 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13997 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13998 Res = DAG.getNOT(DL, Res, Res.getValueType());
14000 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14001 if (!N2C || !N2C->isNullValue())
14002 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14007 // Look past (and (setcc_carry (cmp ...)), 1).
14008 if (Cond.getOpcode() == ISD::AND &&
14009 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14010 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14011 if (C && C->getAPIntValue() == 1)
14012 Cond = Cond.getOperand(0);
14015 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14016 // setting operand in place of the X86ISD::SETCC.
14017 unsigned CondOpcode = Cond.getOpcode();
14018 if (CondOpcode == X86ISD::SETCC ||
14019 CondOpcode == X86ISD::SETCC_CARRY) {
14020 CC = Cond.getOperand(0);
14022 SDValue Cmp = Cond.getOperand(1);
14023 unsigned Opc = Cmp.getOpcode();
14024 MVT VT = Op.getSimpleValueType();
14026 bool IllegalFPCMov = false;
14027 if (VT.isFloatingPoint() && !VT.isVector() &&
14028 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14029 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14031 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14032 Opc == X86ISD::BT) { // FIXME
14036 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14037 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14038 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14039 Cond.getOperand(0).getValueType() != MVT::i8)) {
14040 SDValue LHS = Cond.getOperand(0);
14041 SDValue RHS = Cond.getOperand(1);
14042 unsigned X86Opcode;
14045 switch (CondOpcode) {
14046 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14047 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14048 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14049 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14050 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14051 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14052 default: llvm_unreachable("unexpected overflowing operator");
14054 if (CondOpcode == ISD::UMULO)
14055 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14058 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14060 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14062 if (CondOpcode == ISD::UMULO)
14063 Cond = X86Op.getValue(2);
14065 Cond = X86Op.getValue(1);
14067 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14072 // Look pass the truncate if the high bits are known zero.
14073 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14074 Cond = Cond.getOperand(0);
14076 // We know the result of AND is compared against zero. Try to match
14078 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14079 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14080 if (NewSetCC.getNode()) {
14081 CC = NewSetCC.getOperand(0);
14082 Cond = NewSetCC.getOperand(1);
14089 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14090 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14093 // a < b ? -1 : 0 -> RES = ~setcc_carry
14094 // a < b ? 0 : -1 -> RES = setcc_carry
14095 // a >= b ? -1 : 0 -> RES = setcc_carry
14096 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14097 if (Cond.getOpcode() == X86ISD::SUB) {
14098 Cond = ConvertCmpIfNecessary(Cond, DAG);
14099 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14101 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14102 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14103 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14104 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14106 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14107 return DAG.getNOT(DL, Res, Res.getValueType());
14112 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14113 // widen the cmov and push the truncate through. This avoids introducing a new
14114 // branch during isel and doesn't add any extensions.
14115 if (Op.getValueType() == MVT::i8 &&
14116 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14117 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14118 if (T1.getValueType() == T2.getValueType() &&
14119 // Blacklist CopyFromReg to avoid partial register stalls.
14120 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14121 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14122 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14123 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14127 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14128 // condition is true.
14129 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14130 SDValue Ops[] = { Op2, Op1, CC, Cond };
14131 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14134 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14135 const X86Subtarget *Subtarget,
14136 SelectionDAG &DAG) {
14137 MVT VT = Op->getSimpleValueType(0);
14138 SDValue In = Op->getOperand(0);
14139 MVT InVT = In.getSimpleValueType();
14140 MVT VTElt = VT.getVectorElementType();
14141 MVT InVTElt = InVT.getVectorElementType();
14145 if ((InVTElt == MVT::i1) &&
14146 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14147 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14149 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14150 VTElt.getSizeInBits() <= 16)) ||
14152 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14153 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14155 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14156 VTElt.getSizeInBits() >= 32))))
14157 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14159 unsigned int NumElts = VT.getVectorNumElements();
14161 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14164 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14165 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14166 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14167 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14170 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14171 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14173 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14176 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14178 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14179 if (VT.is512BitVector())
14181 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14184 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14185 const X86Subtarget *Subtarget,
14186 SelectionDAG &DAG) {
14187 SDValue In = Op->getOperand(0);
14188 MVT VT = Op->getSimpleValueType(0);
14189 MVT InVT = In.getSimpleValueType();
14190 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14192 MVT InSVT = InVT.getScalarType();
14193 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14195 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14197 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14202 // SSE41 targets can use the pmovsx* instructions directly.
14203 if (Subtarget->hasSSE41())
14204 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14206 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14210 // As SRAI is only available on i16/i32 types, we expand only up to i32
14211 // and handle i64 separately.
14212 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14213 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14214 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14215 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14216 Curr = DAG.getBitcast(CurrVT, Curr);
14219 SDValue SignExt = Curr;
14220 if (CurrVT != InVT) {
14221 unsigned SignExtShift =
14222 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14223 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14224 DAG.getConstant(SignExtShift, dl, MVT::i8));
14230 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14231 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14232 DAG.getConstant(31, dl, MVT::i8));
14233 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14234 return DAG.getBitcast(VT, Ext);
14240 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14241 SelectionDAG &DAG) {
14242 MVT VT = Op->getSimpleValueType(0);
14243 SDValue In = Op->getOperand(0);
14244 MVT InVT = In.getSimpleValueType();
14247 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14248 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14250 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14251 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14252 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14255 if (Subtarget->hasInt256())
14256 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14258 // Optimize vectors in AVX mode
14259 // Sign extend v8i16 to v8i32 and
14262 // Divide input vector into two parts
14263 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14264 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14265 // concat the vectors to original VT
14267 unsigned NumElems = InVT.getVectorNumElements();
14268 SDValue Undef = DAG.getUNDEF(InVT);
14270 SmallVector<int,8> ShufMask1(NumElems, -1);
14271 for (unsigned i = 0; i != NumElems/2; ++i)
14274 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14276 SmallVector<int,8> ShufMask2(NumElems, -1);
14277 for (unsigned i = 0; i != NumElems/2; ++i)
14278 ShufMask2[i] = i + NumElems/2;
14280 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14282 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14283 VT.getVectorNumElements()/2);
14285 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14286 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14288 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14291 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14292 // may emit an illegal shuffle but the expansion is still better than scalar
14293 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14294 // we'll emit a shuffle and a arithmetic shift.
14295 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14296 // TODO: It is possible to support ZExt by zeroing the undef values during
14297 // the shuffle phase or after the shuffle.
14298 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14299 SelectionDAG &DAG) {
14300 MVT RegVT = Op.getSimpleValueType();
14301 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14302 assert(RegVT.isInteger() &&
14303 "We only custom lower integer vector sext loads.");
14305 // Nothing useful we can do without SSE2 shuffles.
14306 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14308 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14310 EVT MemVT = Ld->getMemoryVT();
14311 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14312 unsigned RegSz = RegVT.getSizeInBits();
14314 ISD::LoadExtType Ext = Ld->getExtensionType();
14316 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14317 && "Only anyext and sext are currently implemented.");
14318 assert(MemVT != RegVT && "Cannot extend to the same type");
14319 assert(MemVT.isVector() && "Must load a vector from memory");
14321 unsigned NumElems = RegVT.getVectorNumElements();
14322 unsigned MemSz = MemVT.getSizeInBits();
14323 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14325 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14326 // The only way in which we have a legal 256-bit vector result but not the
14327 // integer 256-bit operations needed to directly lower a sextload is if we
14328 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14329 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14330 // correctly legalized. We do this late to allow the canonical form of
14331 // sextload to persist throughout the rest of the DAG combiner -- it wants
14332 // to fold together any extensions it can, and so will fuse a sign_extend
14333 // of an sextload into a sextload targeting a wider value.
14335 if (MemSz == 128) {
14336 // Just switch this to a normal load.
14337 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14338 "it must be a legal 128-bit vector "
14340 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14341 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14342 Ld->isInvariant(), Ld->getAlignment());
14344 assert(MemSz < 128 &&
14345 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14346 // Do an sext load to a 128-bit vector type. We want to use the same
14347 // number of elements, but elements half as wide. This will end up being
14348 // recursively lowered by this routine, but will succeed as we definitely
14349 // have all the necessary features if we're using AVX1.
14351 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14352 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14354 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14355 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14356 Ld->isNonTemporal(), Ld->isInvariant(),
14357 Ld->getAlignment());
14360 // Replace chain users with the new chain.
14361 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14362 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14364 // Finally, do a normal sign-extend to the desired register.
14365 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14368 // All sizes must be a power of two.
14369 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14370 "Non-power-of-two elements are not custom lowered!");
14372 // Attempt to load the original value using scalar loads.
14373 // Find the largest scalar type that divides the total loaded size.
14374 MVT SclrLoadTy = MVT::i8;
14375 for (MVT Tp : MVT::integer_valuetypes()) {
14376 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14381 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14382 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14384 SclrLoadTy = MVT::f64;
14386 // Calculate the number of scalar loads that we need to perform
14387 // in order to load our vector from memory.
14388 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14390 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14391 "Can only lower sext loads with a single scalar load!");
14393 unsigned loadRegZize = RegSz;
14394 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14397 // Represent our vector as a sequence of elements which are the
14398 // largest scalar that we can load.
14399 EVT LoadUnitVecVT = EVT::getVectorVT(
14400 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14402 // Represent the data using the same element type that is stored in
14403 // memory. In practice, we ''widen'' MemVT.
14405 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14406 loadRegZize / MemVT.getScalarType().getSizeInBits());
14408 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14409 "Invalid vector type");
14411 // We can't shuffle using an illegal type.
14412 assert(TLI.isTypeLegal(WideVecVT) &&
14413 "We only lower types that form legal widened vector types");
14415 SmallVector<SDValue, 8> Chains;
14416 SDValue Ptr = Ld->getBasePtr();
14417 SDValue Increment =
14418 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14419 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14421 for (unsigned i = 0; i < NumLoads; ++i) {
14422 // Perform a single load.
14423 SDValue ScalarLoad =
14424 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14425 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14426 Ld->getAlignment());
14427 Chains.push_back(ScalarLoad.getValue(1));
14428 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14429 // another round of DAGCombining.
14431 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14433 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14434 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14436 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14439 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14441 // Bitcast the loaded value to a vector of the original element type, in
14442 // the size of the target vector type.
14443 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14444 unsigned SizeRatio = RegSz / MemSz;
14446 if (Ext == ISD::SEXTLOAD) {
14447 // If we have SSE4.1, we can directly emit a VSEXT node.
14448 if (Subtarget->hasSSE41()) {
14449 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14450 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14454 // Otherwise we'll shuffle the small elements in the high bits of the
14455 // larger type and perform an arithmetic shift. If the shift is not legal
14456 // it's better to scalarize.
14457 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14458 "We can't implement a sext load without an arithmetic right shift!");
14460 // Redistribute the loaded elements into the different locations.
14461 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14462 for (unsigned i = 0; i != NumElems; ++i)
14463 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14465 SDValue Shuff = DAG.getVectorShuffle(
14466 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14468 Shuff = DAG.getBitcast(RegVT, Shuff);
14470 // Build the arithmetic shift.
14471 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14472 MemVT.getVectorElementType().getSizeInBits();
14474 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14475 DAG.getConstant(Amt, dl, RegVT));
14477 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14481 // Redistribute the loaded elements into the different locations.
14482 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14483 for (unsigned i = 0; i != NumElems; ++i)
14484 ShuffleVec[i * SizeRatio] = i;
14486 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14487 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14489 // Bitcast to the requested type.
14490 Shuff = DAG.getBitcast(RegVT, Shuff);
14491 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14495 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14496 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14497 // from the AND / OR.
14498 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14499 Opc = Op.getOpcode();
14500 if (Opc != ISD::OR && Opc != ISD::AND)
14502 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14503 Op.getOperand(0).hasOneUse() &&
14504 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14505 Op.getOperand(1).hasOneUse());
14508 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14509 // 1 and that the SETCC node has a single use.
14510 static bool isXor1OfSetCC(SDValue Op) {
14511 if (Op.getOpcode() != ISD::XOR)
14513 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14514 if (N1C && N1C->getAPIntValue() == 1) {
14515 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14516 Op.getOperand(0).hasOneUse();
14521 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14522 bool addTest = true;
14523 SDValue Chain = Op.getOperand(0);
14524 SDValue Cond = Op.getOperand(1);
14525 SDValue Dest = Op.getOperand(2);
14528 bool Inverted = false;
14530 if (Cond.getOpcode() == ISD::SETCC) {
14531 // Check for setcc([su]{add,sub,mul}o == 0).
14532 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14533 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14534 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14535 Cond.getOperand(0).getResNo() == 1 &&
14536 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14537 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14538 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14539 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14540 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14541 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14543 Cond = Cond.getOperand(0);
14545 SDValue NewCond = LowerSETCC(Cond, DAG);
14546 if (NewCond.getNode())
14551 // FIXME: LowerXALUO doesn't handle these!!
14552 else if (Cond.getOpcode() == X86ISD::ADD ||
14553 Cond.getOpcode() == X86ISD::SUB ||
14554 Cond.getOpcode() == X86ISD::SMUL ||
14555 Cond.getOpcode() == X86ISD::UMUL)
14556 Cond = LowerXALUO(Cond, DAG);
14559 // Look pass (and (setcc_carry (cmp ...)), 1).
14560 if (Cond.getOpcode() == ISD::AND &&
14561 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14562 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14563 if (C && C->getAPIntValue() == 1)
14564 Cond = Cond.getOperand(0);
14567 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14568 // setting operand in place of the X86ISD::SETCC.
14569 unsigned CondOpcode = Cond.getOpcode();
14570 if (CondOpcode == X86ISD::SETCC ||
14571 CondOpcode == X86ISD::SETCC_CARRY) {
14572 CC = Cond.getOperand(0);
14574 SDValue Cmp = Cond.getOperand(1);
14575 unsigned Opc = Cmp.getOpcode();
14576 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14577 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14581 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14585 // These can only come from an arithmetic instruction with overflow,
14586 // e.g. SADDO, UADDO.
14587 Cond = Cond.getNode()->getOperand(1);
14593 CondOpcode = Cond.getOpcode();
14594 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14595 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14596 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14597 Cond.getOperand(0).getValueType() != MVT::i8)) {
14598 SDValue LHS = Cond.getOperand(0);
14599 SDValue RHS = Cond.getOperand(1);
14600 unsigned X86Opcode;
14603 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14604 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14606 switch (CondOpcode) {
14607 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14609 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14611 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14614 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14615 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14617 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14619 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14622 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14623 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14624 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14625 default: llvm_unreachable("unexpected overflowing operator");
14628 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14629 if (CondOpcode == ISD::UMULO)
14630 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14633 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14635 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14637 if (CondOpcode == ISD::UMULO)
14638 Cond = X86Op.getValue(2);
14640 Cond = X86Op.getValue(1);
14642 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14646 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14647 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14648 if (CondOpc == ISD::OR) {
14649 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14650 // two branches instead of an explicit OR instruction with a
14652 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14653 isX86LogicalCmp(Cmp)) {
14654 CC = Cond.getOperand(0).getOperand(0);
14655 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14656 Chain, Dest, CC, Cmp);
14657 CC = Cond.getOperand(1).getOperand(0);
14661 } else { // ISD::AND
14662 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14663 // two branches instead of an explicit AND instruction with a
14664 // separate test. However, we only do this if this block doesn't
14665 // have a fall-through edge, because this requires an explicit
14666 // jmp when the condition is false.
14667 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14668 isX86LogicalCmp(Cmp) &&
14669 Op.getNode()->hasOneUse()) {
14670 X86::CondCode CCode =
14671 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14672 CCode = X86::GetOppositeBranchCondition(CCode);
14673 CC = DAG.getConstant(CCode, dl, MVT::i8);
14674 SDNode *User = *Op.getNode()->use_begin();
14675 // Look for an unconditional branch following this conditional branch.
14676 // We need this because we need to reverse the successors in order
14677 // to implement FCMP_OEQ.
14678 if (User->getOpcode() == ISD::BR) {
14679 SDValue FalseBB = User->getOperand(1);
14681 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14682 assert(NewBR == User);
14686 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14687 Chain, Dest, CC, Cmp);
14688 X86::CondCode CCode =
14689 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14690 CCode = X86::GetOppositeBranchCondition(CCode);
14691 CC = DAG.getConstant(CCode, dl, MVT::i8);
14697 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14698 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14699 // It should be transformed during dag combiner except when the condition
14700 // is set by a arithmetics with overflow node.
14701 X86::CondCode CCode =
14702 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14703 CCode = X86::GetOppositeBranchCondition(CCode);
14704 CC = DAG.getConstant(CCode, dl, MVT::i8);
14705 Cond = Cond.getOperand(0).getOperand(1);
14707 } else if (Cond.getOpcode() == ISD::SETCC &&
14708 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14709 // For FCMP_OEQ, we can emit
14710 // two branches instead of an explicit AND instruction with a
14711 // separate test. However, we only do this if this block doesn't
14712 // have a fall-through edge, because this requires an explicit
14713 // jmp when the condition is false.
14714 if (Op.getNode()->hasOneUse()) {
14715 SDNode *User = *Op.getNode()->use_begin();
14716 // Look for an unconditional branch following this conditional branch.
14717 // We need this because we need to reverse the successors in order
14718 // to implement FCMP_OEQ.
14719 if (User->getOpcode() == ISD::BR) {
14720 SDValue FalseBB = User->getOperand(1);
14722 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14723 assert(NewBR == User);
14727 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14728 Cond.getOperand(0), Cond.getOperand(1));
14729 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14730 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14731 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14732 Chain, Dest, CC, Cmp);
14733 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14738 } else if (Cond.getOpcode() == ISD::SETCC &&
14739 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14740 // For FCMP_UNE, we can emit
14741 // two branches instead of an explicit AND instruction with a
14742 // separate test. However, we only do this if this block doesn't
14743 // have a fall-through edge, because this requires an explicit
14744 // jmp when the condition is false.
14745 if (Op.getNode()->hasOneUse()) {
14746 SDNode *User = *Op.getNode()->use_begin();
14747 // Look for an unconditional branch following this conditional branch.
14748 // We need this because we need to reverse the successors in order
14749 // to implement FCMP_UNE.
14750 if (User->getOpcode() == ISD::BR) {
14751 SDValue FalseBB = User->getOperand(1);
14753 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14754 assert(NewBR == User);
14757 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14758 Cond.getOperand(0), Cond.getOperand(1));
14759 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14760 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14761 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14762 Chain, Dest, CC, Cmp);
14763 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14773 // Look pass the truncate if the high bits are known zero.
14774 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14775 Cond = Cond.getOperand(0);
14777 // We know the result of AND is compared against zero. Try to match
14779 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14780 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14781 if (NewSetCC.getNode()) {
14782 CC = NewSetCC.getOperand(0);
14783 Cond = NewSetCC.getOperand(1);
14790 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14791 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14792 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14794 Cond = ConvertCmpIfNecessary(Cond, DAG);
14795 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14796 Chain, Dest, CC, Cond);
14799 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14800 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14801 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14802 // that the guard pages used by the OS virtual memory manager are allocated in
14803 // correct sequence.
14805 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14806 SelectionDAG &DAG) const {
14807 MachineFunction &MF = DAG.getMachineFunction();
14808 bool SplitStack = MF.shouldSplitStack();
14809 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14814 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14815 SDNode* Node = Op.getNode();
14817 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14818 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14819 " not tell us which reg is the stack pointer!");
14820 EVT VT = Node->getValueType(0);
14821 SDValue Tmp1 = SDValue(Node, 0);
14822 SDValue Tmp2 = SDValue(Node, 1);
14823 SDValue Tmp3 = Node->getOperand(2);
14824 SDValue Chain = Tmp1.getOperand(0);
14826 // Chain the dynamic stack allocation so that it doesn't modify the stack
14827 // pointer when other instructions are using the stack.
14828 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14831 SDValue Size = Tmp2.getOperand(1);
14832 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14833 Chain = SP.getValue(1);
14834 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14835 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14836 unsigned StackAlign = TFI.getStackAlignment();
14837 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14838 if (Align > StackAlign)
14839 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14840 DAG.getConstant(-(uint64_t)Align, dl, VT));
14841 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14843 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14844 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14847 SDValue Ops[2] = { Tmp1, Tmp2 };
14848 return DAG.getMergeValues(Ops, dl);
14852 SDValue Chain = Op.getOperand(0);
14853 SDValue Size = Op.getOperand(1);
14854 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14855 EVT VT = Op.getNode()->getValueType(0);
14857 bool Is64Bit = Subtarget->is64Bit();
14858 EVT SPTy = getPointerTy();
14861 MachineRegisterInfo &MRI = MF.getRegInfo();
14864 // The 64 bit implementation of segmented stacks needs to clobber both r10
14865 // r11. This makes it impossible to use it along with nested parameters.
14866 const Function *F = MF.getFunction();
14868 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14870 if (I->hasNestAttr())
14871 report_fatal_error("Cannot use segmented stacks with functions that "
14872 "have nested arguments.");
14875 const TargetRegisterClass *AddrRegClass =
14876 getRegClassFor(getPointerTy());
14877 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14878 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14879 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14880 DAG.getRegister(Vreg, SPTy));
14881 SDValue Ops1[2] = { Value, Chain };
14882 return DAG.getMergeValues(Ops1, dl);
14885 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14887 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14888 Flag = Chain.getValue(1);
14889 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14891 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14893 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14894 unsigned SPReg = RegInfo->getStackRegister();
14895 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14896 Chain = SP.getValue(1);
14899 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14900 DAG.getConstant(-(uint64_t)Align, dl, VT));
14901 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14904 SDValue Ops1[2] = { SP, Chain };
14905 return DAG.getMergeValues(Ops1, dl);
14909 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14910 MachineFunction &MF = DAG.getMachineFunction();
14911 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14913 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14916 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14917 // vastart just stores the address of the VarArgsFrameIndex slot into the
14918 // memory location argument.
14919 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14921 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14922 MachinePointerInfo(SV), false, false, 0);
14926 // gp_offset (0 - 6 * 8)
14927 // fp_offset (48 - 48 + 8 * 16)
14928 // overflow_arg_area (point to parameters coming in memory).
14930 SmallVector<SDValue, 8> MemOps;
14931 SDValue FIN = Op.getOperand(1);
14933 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14934 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14936 FIN, MachinePointerInfo(SV), false, false, 0);
14937 MemOps.push_back(Store);
14940 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14941 FIN, DAG.getIntPtrConstant(4, DL));
14942 Store = DAG.getStore(Op.getOperand(0), DL,
14943 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14945 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14946 MemOps.push_back(Store);
14948 // Store ptr to overflow_arg_area
14949 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14950 FIN, DAG.getIntPtrConstant(4, DL));
14951 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14953 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14954 MachinePointerInfo(SV, 8),
14956 MemOps.push_back(Store);
14958 // Store ptr to reg_save_area.
14959 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14960 FIN, DAG.getIntPtrConstant(8, DL));
14961 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14963 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14964 MachinePointerInfo(SV, 16), false, false, 0);
14965 MemOps.push_back(Store);
14966 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14969 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14970 assert(Subtarget->is64Bit() &&
14971 "LowerVAARG only handles 64-bit va_arg!");
14972 assert((Subtarget->isTargetLinux() ||
14973 Subtarget->isTargetDarwin()) &&
14974 "Unhandled target in LowerVAARG");
14975 assert(Op.getNode()->getNumOperands() == 4);
14976 SDValue Chain = Op.getOperand(0);
14977 SDValue SrcPtr = Op.getOperand(1);
14978 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14979 unsigned Align = Op.getConstantOperandVal(3);
14982 EVT ArgVT = Op.getNode()->getValueType(0);
14983 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14984 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14987 // Decide which area this value should be read from.
14988 // TODO: Implement the AMD64 ABI in its entirety. This simple
14989 // selection mechanism works only for the basic types.
14990 if (ArgVT == MVT::f80) {
14991 llvm_unreachable("va_arg for f80 not yet implemented");
14992 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14993 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14994 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14995 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14997 llvm_unreachable("Unhandled argument type in LowerVAARG");
15000 if (ArgMode == 2) {
15001 // Sanity Check: Make sure using fp_offset makes sense.
15002 assert(!Subtarget->useSoftFloat() &&
15003 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15004 Attribute::NoImplicitFloat)) &&
15005 Subtarget->hasSSE1());
15008 // Insert VAARG_64 node into the DAG
15009 // VAARG_64 returns two values: Variable Argument Address, Chain
15010 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15011 DAG.getConstant(ArgMode, dl, MVT::i8),
15012 DAG.getConstant(Align, dl, MVT::i32)};
15013 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
15014 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15015 VTs, InstOps, MVT::i64,
15016 MachinePointerInfo(SV),
15018 /*Volatile=*/false,
15020 /*WriteMem=*/true);
15021 Chain = VAARG.getValue(1);
15023 // Load the next argument and return it
15024 return DAG.getLoad(ArgVT, dl,
15027 MachinePointerInfo(),
15028 false, false, false, 0);
15031 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15032 SelectionDAG &DAG) {
15033 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15034 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15035 SDValue Chain = Op.getOperand(0);
15036 SDValue DstPtr = Op.getOperand(1);
15037 SDValue SrcPtr = Op.getOperand(2);
15038 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15039 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15042 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15043 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15045 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15048 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15049 // amount is a constant. Takes immediate version of shift as input.
15050 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15051 SDValue SrcOp, uint64_t ShiftAmt,
15052 SelectionDAG &DAG) {
15053 MVT ElementType = VT.getVectorElementType();
15055 // Fold this packed shift into its first operand if ShiftAmt is 0.
15059 // Check for ShiftAmt >= element width
15060 if (ShiftAmt >= ElementType.getSizeInBits()) {
15061 if (Opc == X86ISD::VSRAI)
15062 ShiftAmt = ElementType.getSizeInBits() - 1;
15064 return DAG.getConstant(0, dl, VT);
15067 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15068 && "Unknown target vector shift-by-constant node");
15070 // Fold this packed vector shift into a build vector if SrcOp is a
15071 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15072 if (VT == SrcOp.getSimpleValueType() &&
15073 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15074 SmallVector<SDValue, 8> Elts;
15075 unsigned NumElts = SrcOp->getNumOperands();
15076 ConstantSDNode *ND;
15079 default: llvm_unreachable(nullptr);
15080 case X86ISD::VSHLI:
15081 for (unsigned i=0; i!=NumElts; ++i) {
15082 SDValue CurrentOp = SrcOp->getOperand(i);
15083 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15084 Elts.push_back(CurrentOp);
15087 ND = cast<ConstantSDNode>(CurrentOp);
15088 const APInt &C = ND->getAPIntValue();
15089 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15092 case X86ISD::VSRLI:
15093 for (unsigned i=0; i!=NumElts; ++i) {
15094 SDValue CurrentOp = SrcOp->getOperand(i);
15095 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15096 Elts.push_back(CurrentOp);
15099 ND = cast<ConstantSDNode>(CurrentOp);
15100 const APInt &C = ND->getAPIntValue();
15101 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15104 case X86ISD::VSRAI:
15105 for (unsigned i=0; i!=NumElts; ++i) {
15106 SDValue CurrentOp = SrcOp->getOperand(i);
15107 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15108 Elts.push_back(CurrentOp);
15111 ND = cast<ConstantSDNode>(CurrentOp);
15112 const APInt &C = ND->getAPIntValue();
15113 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15118 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15121 return DAG.getNode(Opc, dl, VT, SrcOp,
15122 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15125 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15126 // may or may not be a constant. Takes immediate version of shift as input.
15127 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15128 SDValue SrcOp, SDValue ShAmt,
15129 SelectionDAG &DAG) {
15130 MVT SVT = ShAmt.getSimpleValueType();
15131 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15133 // Catch shift-by-constant.
15134 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15135 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15136 CShAmt->getZExtValue(), DAG);
15138 // Change opcode to non-immediate version
15140 default: llvm_unreachable("Unknown target vector shift node");
15141 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15142 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15143 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15146 const X86Subtarget &Subtarget =
15147 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15148 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15149 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15150 // Let the shuffle legalizer expand this shift amount node.
15151 SDValue Op0 = ShAmt.getOperand(0);
15152 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15153 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15155 // Need to build a vector containing shift amount.
15156 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15157 SmallVector<SDValue, 4> ShOps;
15158 ShOps.push_back(ShAmt);
15159 if (SVT == MVT::i32) {
15160 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15161 ShOps.push_back(DAG.getUNDEF(SVT));
15163 ShOps.push_back(DAG.getUNDEF(SVT));
15165 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15166 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15169 // The return type has to be a 128-bit type with the same element
15170 // type as the input type.
15171 MVT EltVT = VT.getVectorElementType();
15172 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15174 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15175 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15178 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15179 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15180 /// necessary casting for \p Mask when lowering masking intrinsics.
15181 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15182 SDValue PreservedSrc,
15183 const X86Subtarget *Subtarget,
15184 SelectionDAG &DAG) {
15185 EVT VT = Op.getValueType();
15186 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15187 MVT::i1, VT.getVectorNumElements());
15188 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15189 Mask.getValueType().getSizeInBits());
15192 assert(MaskVT.isSimple() && "invalid mask type");
15194 if (isAllOnes(Mask))
15197 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15198 // are extracted by EXTRACT_SUBVECTOR.
15199 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15200 DAG.getBitcast(BitcastVT, Mask),
15201 DAG.getIntPtrConstant(0, dl));
15203 switch (Op.getOpcode()) {
15205 case X86ISD::PCMPEQM:
15206 case X86ISD::PCMPGTM:
15208 case X86ISD::CMPMU:
15209 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15211 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15212 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15213 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15216 /// \brief Creates an SDNode for a predicated scalar operation.
15217 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15218 /// The mask is comming as MVT::i8 and it should be truncated
15219 /// to MVT::i1 while lowering masking intrinsics.
15220 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15221 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15222 /// a scalar instruction.
15223 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15224 SDValue PreservedSrc,
15225 const X86Subtarget *Subtarget,
15226 SelectionDAG &DAG) {
15227 if (isAllOnes(Mask))
15230 EVT VT = Op.getValueType();
15232 // The mask should be of type MVT::i1
15233 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15235 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15236 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15237 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15240 static int getSEHRegistrationNodeSize(const Function *Fn) {
15241 if (!Fn->hasPersonalityFn())
15242 report_fatal_error(
15243 "querying registration node size for function without personality");
15244 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15245 // WinEHStatePass for the full struct definition.
15246 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15247 case EHPersonality::MSVC_X86SEH: return 24;
15248 case EHPersonality::MSVC_CXX: return 16;
15251 report_fatal_error("can only recover FP for MSVC EH personality functions");
15254 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15255 /// function or when returning to a parent frame after catching an exception, we
15256 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15257 /// Here's the math:
15258 /// RegNodeBase = EntryEBP - RegNodeSize
15259 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15260 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15261 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15262 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15263 SDValue EntryEBP) {
15264 MachineFunction &MF = DAG.getMachineFunction();
15267 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15268 MVT PtrVT = TLI.getPointerTy();
15270 // It's possible that the parent function no longer has a personality function
15271 // if the exceptional code was optimized away, in which case we just return
15272 // the incoming EBP.
15273 if (!Fn->hasPersonalityFn())
15276 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15278 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15280 MCSymbol *OffsetSym =
15281 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15282 GlobalValue::getRealLinkageName(Fn->getName()));
15283 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15284 SDValue RegNodeFrameOffset =
15285 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15287 // RegNodeBase = EntryEBP - RegNodeSize
15288 // ParentFP = RegNodeBase - RegNodeFrameOffset
15289 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15290 DAG.getConstant(RegNodeSize, dl, PtrVT));
15291 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15294 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15295 SelectionDAG &DAG) {
15297 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15298 EVT VT = Op.getValueType();
15299 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15301 switch(IntrData->Type) {
15302 case INTR_TYPE_1OP:
15303 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15304 case INTR_TYPE_2OP:
15305 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15307 case INTR_TYPE_3OP:
15308 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15309 Op.getOperand(2), Op.getOperand(3));
15310 case INTR_TYPE_4OP:
15311 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15312 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15313 case INTR_TYPE_1OP_MASK_RM: {
15314 SDValue Src = Op.getOperand(1);
15315 SDValue PassThru = Op.getOperand(2);
15316 SDValue Mask = Op.getOperand(3);
15317 SDValue RoundingMode;
15318 if (Op.getNumOperands() == 4)
15319 RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15321 RoundingMode = Op.getOperand(4);
15322 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15323 if (IntrWithRoundingModeOpcode != 0) {
15324 unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15325 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15326 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15327 dl, Op.getValueType(), Src, RoundingMode),
15328 Mask, PassThru, Subtarget, DAG);
15330 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15332 Mask, PassThru, Subtarget, DAG);
15334 case INTR_TYPE_1OP_MASK: {
15335 SDValue Src = Op.getOperand(1);
15336 SDValue Passthru = Op.getOperand(2);
15337 SDValue Mask = Op.getOperand(3);
15338 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15339 Mask, Passthru, Subtarget, DAG);
15341 case INTR_TYPE_SCALAR_MASK_RM: {
15342 SDValue Src1 = Op.getOperand(1);
15343 SDValue Src2 = Op.getOperand(2);
15344 SDValue Src0 = Op.getOperand(3);
15345 SDValue Mask = Op.getOperand(4);
15346 // There are 2 kinds of intrinsics in this group:
15347 // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15348 // (2) With rounding mode and sae - 7 operands.
15349 if (Op.getNumOperands() == 6) {
15350 SDValue Sae = Op.getOperand(5);
15351 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15352 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15354 Mask, Src0, Subtarget, DAG);
15356 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15357 SDValue RoundingMode = Op.getOperand(5);
15358 SDValue Sae = Op.getOperand(6);
15359 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15360 RoundingMode, Sae),
15361 Mask, Src0, Subtarget, DAG);
15363 case INTR_TYPE_2OP_MASK: {
15364 SDValue Src1 = Op.getOperand(1);
15365 SDValue Src2 = Op.getOperand(2);
15366 SDValue PassThru = Op.getOperand(3);
15367 SDValue Mask = Op.getOperand(4);
15368 // We specify 2 possible opcodes for intrinsics with rounding modes.
15369 // First, we check if the intrinsic may have non-default rounding mode,
15370 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15371 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15372 if (IntrWithRoundingModeOpcode != 0) {
15373 SDValue Rnd = Op.getOperand(5);
15374 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15375 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15376 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15377 dl, Op.getValueType(),
15379 Mask, PassThru, Subtarget, DAG);
15382 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15384 Mask, PassThru, Subtarget, DAG);
15386 case INTR_TYPE_2OP_MASK_RM: {
15387 SDValue Src1 = Op.getOperand(1);
15388 SDValue Src2 = Op.getOperand(2);
15389 SDValue PassThru = Op.getOperand(3);
15390 SDValue Mask = Op.getOperand(4);
15391 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15392 // First, we check if the intrinsic have rounding mode (6 operands),
15393 // if not, we set rounding mode to "current".
15395 if (Op.getNumOperands() == 6)
15396 Rnd = Op.getOperand(5);
15398 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15399 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15401 Mask, PassThru, Subtarget, DAG);
15403 case INTR_TYPE_3OP_MASK: {
15404 SDValue Src1 = Op.getOperand(1);
15405 SDValue Src2 = Op.getOperand(2);
15406 SDValue Src3 = Op.getOperand(3);
15407 SDValue PassThru = Op.getOperand(4);
15408 SDValue Mask = Op.getOperand(5);
15409 // We specify 2 possible opcodes for intrinsics with rounding modes.
15410 // First, we check if the intrinsic may have non-default rounding mode,
15411 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15412 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15413 if (IntrWithRoundingModeOpcode != 0) {
15414 SDValue Rnd = Op.getOperand(6);
15415 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15416 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15417 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15418 dl, Op.getValueType(),
15419 Src1, Src2, Src3, Rnd),
15420 Mask, PassThru, Subtarget, DAG);
15423 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15425 Mask, PassThru, Subtarget, DAG);
15427 case VPERM_3OP_MASKZ:
15428 case VPERM_3OP_MASK:
15431 case FMA_OP_MASK: {
15432 SDValue Src1 = Op.getOperand(1);
15433 SDValue Src2 = Op.getOperand(2);
15434 SDValue Src3 = Op.getOperand(3);
15435 SDValue Mask = Op.getOperand(4);
15436 EVT VT = Op.getValueType();
15437 SDValue PassThru = SDValue();
15439 // set PassThru element
15440 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15441 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15442 else if (IntrData->Type == FMA_OP_MASK3)
15447 // We specify 2 possible opcodes for intrinsics with rounding modes.
15448 // First, we check if the intrinsic may have non-default rounding mode,
15449 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15450 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15451 if (IntrWithRoundingModeOpcode != 0) {
15452 SDValue Rnd = Op.getOperand(5);
15453 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15454 X86::STATIC_ROUNDING::CUR_DIRECTION)
15455 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15456 dl, Op.getValueType(),
15457 Src1, Src2, Src3, Rnd),
15458 Mask, PassThru, Subtarget, DAG);
15460 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15461 dl, Op.getValueType(),
15463 Mask, PassThru, Subtarget, DAG);
15466 case CMP_MASK_CC: {
15467 // Comparison intrinsics with masks.
15468 // Example of transformation:
15469 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15470 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15472 // (v8i1 (insert_subvector undef,
15473 // (v2i1 (and (PCMPEQM %a, %b),
15474 // (extract_subvector
15475 // (v8i1 (bitcast %mask)), 0))), 0))))
15476 EVT VT = Op.getOperand(1).getValueType();
15477 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15478 VT.getVectorNumElements());
15479 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15480 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15481 Mask.getValueType().getSizeInBits());
15483 if (IntrData->Type == CMP_MASK_CC) {
15484 SDValue CC = Op.getOperand(3);
15485 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15486 // We specify 2 possible opcodes for intrinsics with rounding modes.
15487 // First, we check if the intrinsic may have non-default rounding mode,
15488 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15489 if (IntrData->Opc1 != 0) {
15490 SDValue Rnd = Op.getOperand(5);
15491 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15492 X86::STATIC_ROUNDING::CUR_DIRECTION)
15493 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15494 Op.getOperand(2), CC, Rnd);
15496 //default rounding mode
15498 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15499 Op.getOperand(2), CC);
15502 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15503 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15506 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15507 DAG.getTargetConstant(0, dl,
15510 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15511 DAG.getUNDEF(BitcastVT), CmpMask,
15512 DAG.getIntPtrConstant(0, dl));
15513 return DAG.getBitcast(Op.getValueType(), Res);
15515 case COMI: { // Comparison intrinsics
15516 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15517 SDValue LHS = Op.getOperand(1);
15518 SDValue RHS = Op.getOperand(2);
15519 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15520 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15521 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15522 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15523 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15524 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15527 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15528 Op.getOperand(1), Op.getOperand(2), DAG);
15530 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15531 Op.getSimpleValueType(),
15533 Op.getOperand(2), DAG),
15534 Op.getOperand(4), Op.getOperand(3), Subtarget,
15536 case COMPRESS_EXPAND_IN_REG: {
15537 SDValue Mask = Op.getOperand(3);
15538 SDValue DataToCompress = Op.getOperand(1);
15539 SDValue PassThru = Op.getOperand(2);
15540 if (isAllOnes(Mask)) // return data as is
15541 return Op.getOperand(1);
15543 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15545 Mask, PassThru, Subtarget, DAG);
15548 SDValue Mask = Op.getOperand(3);
15549 EVT VT = Op.getValueType();
15550 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15551 VT.getVectorNumElements());
15552 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15553 Mask.getValueType().getSizeInBits());
15555 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15556 DAG.getBitcast(BitcastVT, Mask),
15557 DAG.getIntPtrConstant(0, dl));
15558 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15567 default: return SDValue(); // Don't custom lower most intrinsics.
15569 case Intrinsic::x86_avx2_permd:
15570 case Intrinsic::x86_avx2_permps:
15571 // Operands intentionally swapped. Mask is last operand to intrinsic,
15572 // but second operand for node/instruction.
15573 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15574 Op.getOperand(2), Op.getOperand(1));
15576 // ptest and testp intrinsics. The intrinsic these come from are designed to
15577 // return an integer value, not just an instruction so lower it to the ptest
15578 // or testp pattern and a setcc for the result.
15579 case Intrinsic::x86_sse41_ptestz:
15580 case Intrinsic::x86_sse41_ptestc:
15581 case Intrinsic::x86_sse41_ptestnzc:
15582 case Intrinsic::x86_avx_ptestz_256:
15583 case Intrinsic::x86_avx_ptestc_256:
15584 case Intrinsic::x86_avx_ptestnzc_256:
15585 case Intrinsic::x86_avx_vtestz_ps:
15586 case Intrinsic::x86_avx_vtestc_ps:
15587 case Intrinsic::x86_avx_vtestnzc_ps:
15588 case Intrinsic::x86_avx_vtestz_pd:
15589 case Intrinsic::x86_avx_vtestc_pd:
15590 case Intrinsic::x86_avx_vtestnzc_pd:
15591 case Intrinsic::x86_avx_vtestz_ps_256:
15592 case Intrinsic::x86_avx_vtestc_ps_256:
15593 case Intrinsic::x86_avx_vtestnzc_ps_256:
15594 case Intrinsic::x86_avx_vtestz_pd_256:
15595 case Intrinsic::x86_avx_vtestc_pd_256:
15596 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15597 bool IsTestPacked = false;
15600 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15601 case Intrinsic::x86_avx_vtestz_ps:
15602 case Intrinsic::x86_avx_vtestz_pd:
15603 case Intrinsic::x86_avx_vtestz_ps_256:
15604 case Intrinsic::x86_avx_vtestz_pd_256:
15605 IsTestPacked = true; // Fallthrough
15606 case Intrinsic::x86_sse41_ptestz:
15607 case Intrinsic::x86_avx_ptestz_256:
15609 X86CC = X86::COND_E;
15611 case Intrinsic::x86_avx_vtestc_ps:
15612 case Intrinsic::x86_avx_vtestc_pd:
15613 case Intrinsic::x86_avx_vtestc_ps_256:
15614 case Intrinsic::x86_avx_vtestc_pd_256:
15615 IsTestPacked = true; // Fallthrough
15616 case Intrinsic::x86_sse41_ptestc:
15617 case Intrinsic::x86_avx_ptestc_256:
15619 X86CC = X86::COND_B;
15621 case Intrinsic::x86_avx_vtestnzc_ps:
15622 case Intrinsic::x86_avx_vtestnzc_pd:
15623 case Intrinsic::x86_avx_vtestnzc_ps_256:
15624 case Intrinsic::x86_avx_vtestnzc_pd_256:
15625 IsTestPacked = true; // Fallthrough
15626 case Intrinsic::x86_sse41_ptestnzc:
15627 case Intrinsic::x86_avx_ptestnzc_256:
15629 X86CC = X86::COND_A;
15633 SDValue LHS = Op.getOperand(1);
15634 SDValue RHS = Op.getOperand(2);
15635 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15636 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15637 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15638 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15639 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15641 case Intrinsic::x86_avx512_kortestz_w:
15642 case Intrinsic::x86_avx512_kortestc_w: {
15643 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15644 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15645 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15646 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15647 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15648 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15649 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15652 case Intrinsic::x86_sse42_pcmpistria128:
15653 case Intrinsic::x86_sse42_pcmpestria128:
15654 case Intrinsic::x86_sse42_pcmpistric128:
15655 case Intrinsic::x86_sse42_pcmpestric128:
15656 case Intrinsic::x86_sse42_pcmpistrio128:
15657 case Intrinsic::x86_sse42_pcmpestrio128:
15658 case Intrinsic::x86_sse42_pcmpistris128:
15659 case Intrinsic::x86_sse42_pcmpestris128:
15660 case Intrinsic::x86_sse42_pcmpistriz128:
15661 case Intrinsic::x86_sse42_pcmpestriz128: {
15665 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15666 case Intrinsic::x86_sse42_pcmpistria128:
15667 Opcode = X86ISD::PCMPISTRI;
15668 X86CC = X86::COND_A;
15670 case Intrinsic::x86_sse42_pcmpestria128:
15671 Opcode = X86ISD::PCMPESTRI;
15672 X86CC = X86::COND_A;
15674 case Intrinsic::x86_sse42_pcmpistric128:
15675 Opcode = X86ISD::PCMPISTRI;
15676 X86CC = X86::COND_B;
15678 case Intrinsic::x86_sse42_pcmpestric128:
15679 Opcode = X86ISD::PCMPESTRI;
15680 X86CC = X86::COND_B;
15682 case Intrinsic::x86_sse42_pcmpistrio128:
15683 Opcode = X86ISD::PCMPISTRI;
15684 X86CC = X86::COND_O;
15686 case Intrinsic::x86_sse42_pcmpestrio128:
15687 Opcode = X86ISD::PCMPESTRI;
15688 X86CC = X86::COND_O;
15690 case Intrinsic::x86_sse42_pcmpistris128:
15691 Opcode = X86ISD::PCMPISTRI;
15692 X86CC = X86::COND_S;
15694 case Intrinsic::x86_sse42_pcmpestris128:
15695 Opcode = X86ISD::PCMPESTRI;
15696 X86CC = X86::COND_S;
15698 case Intrinsic::x86_sse42_pcmpistriz128:
15699 Opcode = X86ISD::PCMPISTRI;
15700 X86CC = X86::COND_E;
15702 case Intrinsic::x86_sse42_pcmpestriz128:
15703 Opcode = X86ISD::PCMPESTRI;
15704 X86CC = X86::COND_E;
15707 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15708 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15709 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15710 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15711 DAG.getConstant(X86CC, dl, MVT::i8),
15712 SDValue(PCMP.getNode(), 1));
15713 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15716 case Intrinsic::x86_sse42_pcmpistri128:
15717 case Intrinsic::x86_sse42_pcmpestri128: {
15719 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15720 Opcode = X86ISD::PCMPISTRI;
15722 Opcode = X86ISD::PCMPESTRI;
15724 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15725 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15726 return DAG.getNode(Opcode, dl, VTs, NewOps);
15729 case Intrinsic::x86_seh_lsda: {
15730 // Compute the symbol for the LSDA. We know it'll get emitted later.
15731 MachineFunction &MF = DAG.getMachineFunction();
15732 SDValue Op1 = Op.getOperand(1);
15733 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15734 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15735 GlobalValue::getRealLinkageName(Fn->getName()));
15737 // Generate a simple absolute symbol reference. This intrinsic is only
15738 // supported on 32-bit Windows, which isn't PIC.
15739 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15740 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15743 case Intrinsic::x86_seh_recoverfp: {
15744 SDValue FnOp = Op.getOperand(1);
15745 SDValue IncomingFPOp = Op.getOperand(2);
15746 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15747 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15749 report_fatal_error(
15750 "llvm.x86.seh.recoverfp must take a function as the first argument");
15751 return recoverFramePointer(DAG, Fn, IncomingFPOp);
15754 case Intrinsic::localaddress: {
15755 // Returns one of the stack, base, or frame pointer registers, depending on
15756 // which is used to reference local variables.
15757 MachineFunction &MF = DAG.getMachineFunction();
15758 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15760 if (RegInfo->hasBasePointer(MF))
15761 Reg = RegInfo->getBaseRegister();
15762 else // This function handles the SP or FP case.
15763 Reg = RegInfo->getPtrSizedFrameRegister(MF);
15764 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15769 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15770 SDValue Src, SDValue Mask, SDValue Base,
15771 SDValue Index, SDValue ScaleOp, SDValue Chain,
15772 const X86Subtarget * Subtarget) {
15774 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15776 llvm_unreachable("Invalid scale type");
15777 unsigned ScaleVal = C->getZExtValue();
15778 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15779 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15781 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15782 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15783 Index.getSimpleValueType().getVectorNumElements());
15785 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15787 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15789 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15790 Mask.getValueType().getSizeInBits());
15792 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15793 // are extracted by EXTRACT_SUBVECTOR.
15794 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15795 DAG.getBitcast(BitcastVT, Mask),
15796 DAG.getIntPtrConstant(0, dl));
15798 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15799 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15800 SDValue Segment = DAG.getRegister(0, MVT::i32);
15801 if (Src.getOpcode() == ISD::UNDEF)
15802 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15803 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15804 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15805 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15806 return DAG.getMergeValues(RetOps, dl);
15809 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15810 SDValue Src, SDValue Mask, SDValue Base,
15811 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15813 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15815 llvm_unreachable("Invalid scale type");
15816 unsigned ScaleVal = C->getZExtValue();
15817 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15818 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15820 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15821 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15822 SDValue Segment = DAG.getRegister(0, MVT::i32);
15823 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15824 Index.getSimpleValueType().getVectorNumElements());
15826 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15828 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15830 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15831 Mask.getValueType().getSizeInBits());
15833 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15834 // are extracted by EXTRACT_SUBVECTOR.
15835 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15836 DAG.getBitcast(BitcastVT, Mask),
15837 DAG.getIntPtrConstant(0, dl));
15839 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15840 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15841 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15842 return SDValue(Res, 1);
15845 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15846 SDValue Mask, SDValue Base, SDValue Index,
15847 SDValue ScaleOp, SDValue Chain) {
15849 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15850 assert(C && "Invalid scale type");
15851 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15852 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15853 SDValue Segment = DAG.getRegister(0, MVT::i32);
15855 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15857 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15859 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15861 MaskInReg = DAG.getBitcast(MaskVT, Mask);
15862 //SDVTList VTs = DAG.getVTList(MVT::Other);
15863 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15864 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15865 return SDValue(Res, 0);
15868 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15869 // read performance monitor counters (x86_rdpmc).
15870 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15871 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15872 SmallVectorImpl<SDValue> &Results) {
15873 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15874 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15877 // The ECX register is used to select the index of the performance counter
15879 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15881 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15883 // Reads the content of a 64-bit performance counter and returns it in the
15884 // registers EDX:EAX.
15885 if (Subtarget->is64Bit()) {
15886 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15887 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15890 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15891 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15894 Chain = HI.getValue(1);
15896 if (Subtarget->is64Bit()) {
15897 // The EAX register is loaded with the low-order 32 bits. The EDX register
15898 // is loaded with the supported high-order bits of the counter.
15899 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15900 DAG.getConstant(32, DL, MVT::i8));
15901 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15902 Results.push_back(Chain);
15906 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15907 SDValue Ops[] = { LO, HI };
15908 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15909 Results.push_back(Pair);
15910 Results.push_back(Chain);
15913 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15914 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15915 // also used to custom lower READCYCLECOUNTER nodes.
15916 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15917 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15918 SmallVectorImpl<SDValue> &Results) {
15919 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15920 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15923 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15924 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15925 // and the EAX register is loaded with the low-order 32 bits.
15926 if (Subtarget->is64Bit()) {
15927 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15928 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15931 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15932 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15935 SDValue Chain = HI.getValue(1);
15937 if (Opcode == X86ISD::RDTSCP_DAG) {
15938 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15940 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15941 // the ECX register. Add 'ecx' explicitly to the chain.
15942 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15944 // Explicitly store the content of ECX at the location passed in input
15945 // to the 'rdtscp' intrinsic.
15946 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15947 MachinePointerInfo(), false, false, 0);
15950 if (Subtarget->is64Bit()) {
15951 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15952 // the EAX register is loaded with the low-order 32 bits.
15953 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15954 DAG.getConstant(32, DL, MVT::i8));
15955 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15956 Results.push_back(Chain);
15960 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15961 SDValue Ops[] = { LO, HI };
15962 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15963 Results.push_back(Pair);
15964 Results.push_back(Chain);
15967 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15968 SelectionDAG &DAG) {
15969 SmallVector<SDValue, 2> Results;
15971 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15973 return DAG.getMergeValues(Results, DL);
15976 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
15977 SelectionDAG &DAG) {
15978 MachineFunction &MF = DAG.getMachineFunction();
15979 const Function *Fn = MF.getFunction();
15981 SDValue Chain = Op.getOperand(0);
15983 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
15984 "using llvm.x86.seh.restoreframe requires a frame pointer");
15986 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15987 MVT VT = TLI.getPointerTy();
15989 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15990 unsigned FrameReg =
15991 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15992 unsigned SPReg = RegInfo->getStackRegister();
15993 unsigned SlotSize = RegInfo->getSlotSize();
15995 // Get incoming EBP.
15996 SDValue IncomingEBP =
15997 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
15999 // SP is saved in the first field of every registration node, so load
16000 // [EBP-RegNodeSize] into SP.
16001 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16002 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16003 DAG.getConstant(-RegNodeSize, dl, VT));
16005 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16006 false, VT.getScalarSizeInBits() / 8);
16007 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16009 if (!RegInfo->needsStackRealignment(MF)) {
16010 // Adjust EBP to point back to the original frame position.
16011 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16012 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16014 assert(RegInfo->hasBasePointer(MF) &&
16015 "functions with Win32 EH must use frame or base pointer register");
16017 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16018 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16019 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16021 // Reload the spilled EBP value, now that the stack and base pointers are
16023 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16024 X86FI->setHasSEHFramePtrSave(true);
16025 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16026 X86FI->setSEHFramePtrSaveIndex(FI);
16027 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16028 MachinePointerInfo(), false, false, false,
16029 VT.getScalarSizeInBits() / 8);
16030 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16036 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16037 SelectionDAG &DAG) {
16038 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16040 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16042 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16043 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16048 switch(IntrData->Type) {
16050 llvm_unreachable("Unknown Intrinsic Type");
16054 // Emit the node with the right value type.
16055 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16056 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16058 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16059 // Otherwise return the value from Rand, which is always 0, casted to i32.
16060 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16061 DAG.getConstant(1, dl, Op->getValueType(1)),
16062 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16063 SDValue(Result.getNode(), 1) };
16064 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16065 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16068 // Return { result, isValid, chain }.
16069 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16070 SDValue(Result.getNode(), 2));
16073 //gather(v1, mask, index, base, scale);
16074 SDValue Chain = Op.getOperand(0);
16075 SDValue Src = Op.getOperand(2);
16076 SDValue Base = Op.getOperand(3);
16077 SDValue Index = Op.getOperand(4);
16078 SDValue Mask = Op.getOperand(5);
16079 SDValue Scale = Op.getOperand(6);
16080 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16084 //scatter(base, mask, index, v1, scale);
16085 SDValue Chain = Op.getOperand(0);
16086 SDValue Base = Op.getOperand(2);
16087 SDValue Mask = Op.getOperand(3);
16088 SDValue Index = Op.getOperand(4);
16089 SDValue Src = Op.getOperand(5);
16090 SDValue Scale = Op.getOperand(6);
16091 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16095 SDValue Hint = Op.getOperand(6);
16096 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16097 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16098 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16099 SDValue Chain = Op.getOperand(0);
16100 SDValue Mask = Op.getOperand(2);
16101 SDValue Index = Op.getOperand(3);
16102 SDValue Base = Op.getOperand(4);
16103 SDValue Scale = Op.getOperand(5);
16104 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16106 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16108 SmallVector<SDValue, 2> Results;
16109 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16111 return DAG.getMergeValues(Results, dl);
16113 // Read Performance Monitoring Counters.
16115 SmallVector<SDValue, 2> Results;
16116 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16117 return DAG.getMergeValues(Results, dl);
16119 // XTEST intrinsics.
16121 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16122 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16123 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16124 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16126 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16127 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16128 Ret, SDValue(InTrans.getNode(), 1));
16132 SmallVector<SDValue, 2> Results;
16133 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16134 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16135 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16136 DAG.getConstant(-1, dl, MVT::i8));
16137 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16138 Op.getOperand(4), GenCF.getValue(1));
16139 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16140 Op.getOperand(5), MachinePointerInfo(),
16142 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16143 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16145 Results.push_back(SetCC);
16146 Results.push_back(Store);
16147 return DAG.getMergeValues(Results, dl);
16149 case COMPRESS_TO_MEM: {
16151 SDValue Mask = Op.getOperand(4);
16152 SDValue DataToCompress = Op.getOperand(3);
16153 SDValue Addr = Op.getOperand(2);
16154 SDValue Chain = Op.getOperand(0);
16156 EVT VT = DataToCompress.getValueType();
16157 if (isAllOnes(Mask)) // return just a store
16158 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16159 MachinePointerInfo(), false, false,
16160 VT.getScalarSizeInBits()/8);
16162 SDValue Compressed =
16163 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16164 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16165 return DAG.getStore(Chain, dl, Compressed, Addr,
16166 MachinePointerInfo(), false, false,
16167 VT.getScalarSizeInBits()/8);
16169 case EXPAND_FROM_MEM: {
16171 SDValue Mask = Op.getOperand(4);
16172 SDValue PassThru = Op.getOperand(3);
16173 SDValue Addr = Op.getOperand(2);
16174 SDValue Chain = Op.getOperand(0);
16175 EVT VT = Op.getValueType();
16177 if (isAllOnes(Mask)) // return just a load
16178 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16179 false, VT.getScalarSizeInBits()/8);
16181 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16182 false, false, false,
16183 VT.getScalarSizeInBits()/8);
16185 SDValue Results[] = {
16186 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16187 Mask, PassThru, Subtarget, DAG), Chain};
16188 return DAG.getMergeValues(Results, dl);
16193 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16194 SelectionDAG &DAG) const {
16195 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16196 MFI->setReturnAddressIsTaken(true);
16198 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16201 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16203 EVT PtrVT = getPointerTy();
16206 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16207 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16208 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16209 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16210 DAG.getNode(ISD::ADD, dl, PtrVT,
16211 FrameAddr, Offset),
16212 MachinePointerInfo(), false, false, false, 0);
16215 // Just load the return address.
16216 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16217 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16218 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16221 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16222 MachineFunction &MF = DAG.getMachineFunction();
16223 MachineFrameInfo *MFI = MF.getFrameInfo();
16224 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16225 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16226 EVT VT = Op.getValueType();
16228 MFI->setFrameAddressIsTaken(true);
16230 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16231 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16232 // is not possible to crawl up the stack without looking at the unwind codes
16234 int FrameAddrIndex = FuncInfo->getFAIndex();
16235 if (!FrameAddrIndex) {
16236 // Set up a frame object for the return address.
16237 unsigned SlotSize = RegInfo->getSlotSize();
16238 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16239 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16240 FuncInfo->setFAIndex(FrameAddrIndex);
16242 return DAG.getFrameIndex(FrameAddrIndex, VT);
16245 unsigned FrameReg =
16246 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16247 SDLoc dl(Op); // FIXME probably not meaningful
16248 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16249 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16250 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16251 "Invalid Frame Register!");
16252 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16254 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16255 MachinePointerInfo(),
16256 false, false, false, 0);
16260 // FIXME? Maybe this could be a TableGen attribute on some registers and
16261 // this table could be generated automatically from RegInfo.
16262 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
16264 unsigned Reg = StringSwitch<unsigned>(RegName)
16265 .Case("esp", X86::ESP)
16266 .Case("rsp", X86::RSP)
16270 report_fatal_error("Invalid register name global variable");
16273 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16274 SelectionDAG &DAG) const {
16275 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16276 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16279 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16280 SDValue Chain = Op.getOperand(0);
16281 SDValue Offset = Op.getOperand(1);
16282 SDValue Handler = Op.getOperand(2);
16285 EVT PtrVT = getPointerTy();
16286 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16287 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16288 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16289 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16290 "Invalid Frame Register!");
16291 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16292 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16294 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16295 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16297 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16298 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16300 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16302 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16303 DAG.getRegister(StoreAddrReg, PtrVT));
16306 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16307 SelectionDAG &DAG) const {
16309 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16310 DAG.getVTList(MVT::i32, MVT::Other),
16311 Op.getOperand(0), Op.getOperand(1));
16314 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16315 SelectionDAG &DAG) const {
16317 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16318 Op.getOperand(0), Op.getOperand(1));
16321 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16322 return Op.getOperand(0);
16325 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16326 SelectionDAG &DAG) const {
16327 SDValue Root = Op.getOperand(0);
16328 SDValue Trmp = Op.getOperand(1); // trampoline
16329 SDValue FPtr = Op.getOperand(2); // nested function
16330 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16333 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16334 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16336 if (Subtarget->is64Bit()) {
16337 SDValue OutChains[6];
16339 // Large code-model.
16340 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16341 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16343 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16344 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16346 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16348 // Load the pointer to the nested function into R11.
16349 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16350 SDValue Addr = Trmp;
16351 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16352 Addr, MachinePointerInfo(TrmpAddr),
16355 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16356 DAG.getConstant(2, dl, MVT::i64));
16357 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16358 MachinePointerInfo(TrmpAddr, 2),
16361 // Load the 'nest' parameter value into R10.
16362 // R10 is specified in X86CallingConv.td
16363 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16364 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16365 DAG.getConstant(10, dl, MVT::i64));
16366 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16367 Addr, MachinePointerInfo(TrmpAddr, 10),
16370 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16371 DAG.getConstant(12, dl, MVT::i64));
16372 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16373 MachinePointerInfo(TrmpAddr, 12),
16376 // Jump to the nested function.
16377 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16378 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16379 DAG.getConstant(20, dl, MVT::i64));
16380 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16381 Addr, MachinePointerInfo(TrmpAddr, 20),
16384 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16385 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16386 DAG.getConstant(22, dl, MVT::i64));
16387 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16388 Addr, MachinePointerInfo(TrmpAddr, 22),
16391 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16393 const Function *Func =
16394 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16395 CallingConv::ID CC = Func->getCallingConv();
16400 llvm_unreachable("Unsupported calling convention");
16401 case CallingConv::C:
16402 case CallingConv::X86_StdCall: {
16403 // Pass 'nest' parameter in ECX.
16404 // Must be kept in sync with X86CallingConv.td
16405 NestReg = X86::ECX;
16407 // Check that ECX wasn't needed by an 'inreg' parameter.
16408 FunctionType *FTy = Func->getFunctionType();
16409 const AttributeSet &Attrs = Func->getAttributes();
16411 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16412 unsigned InRegCount = 0;
16415 for (FunctionType::param_iterator I = FTy->param_begin(),
16416 E = FTy->param_end(); I != E; ++I, ++Idx)
16417 if (Attrs.hasAttribute(Idx, Attribute::InReg))
16418 // FIXME: should only count parameters that are lowered to integers.
16419 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16421 if (InRegCount > 2) {
16422 report_fatal_error("Nest register in use - reduce number of inreg"
16428 case CallingConv::X86_FastCall:
16429 case CallingConv::X86_ThisCall:
16430 case CallingConv::Fast:
16431 // Pass 'nest' parameter in EAX.
16432 // Must be kept in sync with X86CallingConv.td
16433 NestReg = X86::EAX;
16437 SDValue OutChains[4];
16438 SDValue Addr, Disp;
16440 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16441 DAG.getConstant(10, dl, MVT::i32));
16442 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16444 // This is storing the opcode for MOV32ri.
16445 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16446 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16447 OutChains[0] = DAG.getStore(Root, dl,
16448 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16449 Trmp, MachinePointerInfo(TrmpAddr),
16452 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16453 DAG.getConstant(1, dl, MVT::i32));
16454 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16455 MachinePointerInfo(TrmpAddr, 1),
16458 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16459 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16460 DAG.getConstant(5, dl, MVT::i32));
16461 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16462 Addr, MachinePointerInfo(TrmpAddr, 5),
16465 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16466 DAG.getConstant(6, dl, MVT::i32));
16467 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16468 MachinePointerInfo(TrmpAddr, 6),
16471 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16475 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16476 SelectionDAG &DAG) const {
16478 The rounding mode is in bits 11:10 of FPSR, and has the following
16480 00 Round to nearest
16485 FLT_ROUNDS, on the other hand, expects the following:
16492 To perform the conversion, we do:
16493 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16496 MachineFunction &MF = DAG.getMachineFunction();
16497 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16498 unsigned StackAlignment = TFI.getStackAlignment();
16499 MVT VT = Op.getSimpleValueType();
16502 // Save FP Control Word to stack slot
16503 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16504 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16506 MachineMemOperand *MMO =
16507 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16508 MachineMemOperand::MOStore, 2, 2);
16510 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16511 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16512 DAG.getVTList(MVT::Other),
16513 Ops, MVT::i16, MMO);
16515 // Load FP Control Word from stack slot
16516 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16517 MachinePointerInfo(), false, false, false, 0);
16519 // Transform as necessary
16521 DAG.getNode(ISD::SRL, DL, MVT::i16,
16522 DAG.getNode(ISD::AND, DL, MVT::i16,
16523 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16524 DAG.getConstant(11, DL, MVT::i8));
16526 DAG.getNode(ISD::SRL, DL, MVT::i16,
16527 DAG.getNode(ISD::AND, DL, MVT::i16,
16528 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16529 DAG.getConstant(9, DL, MVT::i8));
16532 DAG.getNode(ISD::AND, DL, MVT::i16,
16533 DAG.getNode(ISD::ADD, DL, MVT::i16,
16534 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16535 DAG.getConstant(1, DL, MVT::i16)),
16536 DAG.getConstant(3, DL, MVT::i16));
16538 return DAG.getNode((VT.getSizeInBits() < 16 ?
16539 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16542 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16543 MVT VT = Op.getSimpleValueType();
16545 unsigned NumBits = VT.getSizeInBits();
16548 Op = Op.getOperand(0);
16549 if (VT == MVT::i8) {
16550 // Zero extend to i32 since there is not an i8 bsr.
16552 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16555 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16556 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16557 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16559 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16562 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16563 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16566 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16568 // Finally xor with NumBits-1.
16569 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16570 DAG.getConstant(NumBits - 1, dl, OpVT));
16573 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16577 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16578 MVT VT = Op.getSimpleValueType();
16580 unsigned NumBits = VT.getSizeInBits();
16583 Op = Op.getOperand(0);
16584 if (VT == MVT::i8) {
16585 // Zero extend to i32 since there is not an i8 bsr.
16587 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16590 // Issue a bsr (scan bits in reverse).
16591 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16592 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16594 // And xor with NumBits-1.
16595 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16596 DAG.getConstant(NumBits - 1, dl, OpVT));
16599 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16603 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16604 MVT VT = Op.getSimpleValueType();
16605 unsigned NumBits = VT.getSizeInBits();
16607 Op = Op.getOperand(0);
16609 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16610 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16611 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16613 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16616 DAG.getConstant(NumBits, dl, VT),
16617 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16620 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16623 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16624 // ones, and then concatenate the result back.
16625 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16626 MVT VT = Op.getSimpleValueType();
16628 assert(VT.is256BitVector() && VT.isInteger() &&
16629 "Unsupported value type for operation");
16631 unsigned NumElems = VT.getVectorNumElements();
16634 // Extract the LHS vectors
16635 SDValue LHS = Op.getOperand(0);
16636 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16637 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16639 // Extract the RHS vectors
16640 SDValue RHS = Op.getOperand(1);
16641 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16642 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16644 MVT EltVT = VT.getVectorElementType();
16645 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16647 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16648 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16649 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16652 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16653 if (Op.getValueType() == MVT::i1)
16654 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16655 Op.getOperand(0), Op.getOperand(1));
16656 assert(Op.getSimpleValueType().is256BitVector() &&
16657 Op.getSimpleValueType().isInteger() &&
16658 "Only handle AVX 256-bit vector integer operation");
16659 return Lower256IntArith(Op, DAG);
16662 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16663 if (Op.getValueType() == MVT::i1)
16664 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16665 Op.getOperand(0), Op.getOperand(1));
16666 assert(Op.getSimpleValueType().is256BitVector() &&
16667 Op.getSimpleValueType().isInteger() &&
16668 "Only handle AVX 256-bit vector integer operation");
16669 return Lower256IntArith(Op, DAG);
16672 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16673 SelectionDAG &DAG) {
16675 MVT VT = Op.getSimpleValueType();
16678 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16680 // Decompose 256-bit ops into smaller 128-bit ops.
16681 if (VT.is256BitVector() && !Subtarget->hasInt256())
16682 return Lower256IntArith(Op, DAG);
16684 SDValue A = Op.getOperand(0);
16685 SDValue B = Op.getOperand(1);
16687 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16688 // pairs, multiply and truncate.
16689 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16690 if (Subtarget->hasInt256()) {
16691 if (VT == MVT::v32i8) {
16692 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16693 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16694 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16695 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16696 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16697 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16698 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16699 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16700 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16701 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16704 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16705 return DAG.getNode(
16706 ISD::TRUNCATE, dl, VT,
16707 DAG.getNode(ISD::MUL, dl, ExVT,
16708 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16709 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16712 assert(VT == MVT::v16i8 &&
16713 "Pre-AVX2 support only supports v16i8 multiplication");
16714 MVT ExVT = MVT::v8i16;
16716 // Extract the lo parts and sign extend to i16
16718 if (Subtarget->hasSSE41()) {
16719 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16720 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16722 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16723 -1, 4, -1, 5, -1, 6, -1, 7};
16724 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16725 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16726 ALo = DAG.getBitcast(ExVT, ALo);
16727 BLo = DAG.getBitcast(ExVT, BLo);
16728 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16729 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16732 // Extract the hi parts and sign extend to i16
16734 if (Subtarget->hasSSE41()) {
16735 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16736 -1, -1, -1, -1, -1, -1, -1, -1};
16737 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16738 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16739 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16740 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16742 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16743 -1, 12, -1, 13, -1, 14, -1, 15};
16744 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16745 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16746 AHi = DAG.getBitcast(ExVT, AHi);
16747 BHi = DAG.getBitcast(ExVT, BHi);
16748 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16749 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16752 // Multiply, mask the lower 8bits of the lo/hi results and pack
16753 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16754 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16755 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16756 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16757 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16760 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16761 if (VT == MVT::v4i32) {
16762 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16763 "Should not custom lower when pmuldq is available!");
16765 // Extract the odd parts.
16766 static const int UnpackMask[] = { 1, -1, 3, -1 };
16767 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16768 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16770 // Multiply the even parts.
16771 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16772 // Now multiply odd parts.
16773 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16775 Evens = DAG.getBitcast(VT, Evens);
16776 Odds = DAG.getBitcast(VT, Odds);
16778 // Merge the two vectors back together with a shuffle. This expands into 2
16780 static const int ShufMask[] = { 0, 4, 2, 6 };
16781 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16784 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16785 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16787 // Ahi = psrlqi(a, 32);
16788 // Bhi = psrlqi(b, 32);
16790 // AloBlo = pmuludq(a, b);
16791 // AloBhi = pmuludq(a, Bhi);
16792 // AhiBlo = pmuludq(Ahi, b);
16794 // AloBhi = psllqi(AloBhi, 32);
16795 // AhiBlo = psllqi(AhiBlo, 32);
16796 // return AloBlo + AloBhi + AhiBlo;
16798 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16799 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16801 SDValue AhiBlo = Ahi;
16802 SDValue AloBhi = Bhi;
16803 // Bit cast to 32-bit vectors for MULUDQ
16804 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16805 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16806 A = DAG.getBitcast(MulVT, A);
16807 B = DAG.getBitcast(MulVT, B);
16808 Ahi = DAG.getBitcast(MulVT, Ahi);
16809 Bhi = DAG.getBitcast(MulVT, Bhi);
16811 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16812 // After shifting right const values the result may be all-zero.
16813 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16814 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16815 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16817 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16818 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16819 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16822 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16823 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16826 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16827 assert(Subtarget->isTargetWin64() && "Unexpected target");
16828 EVT VT = Op.getValueType();
16829 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16830 "Unexpected return type for lowering");
16834 switch (Op->getOpcode()) {
16835 default: llvm_unreachable("Unexpected request for libcall!");
16836 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16837 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16838 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16839 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16840 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16841 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16845 SDValue InChain = DAG.getEntryNode();
16847 TargetLowering::ArgListTy Args;
16848 TargetLowering::ArgListEntry Entry;
16849 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16850 EVT ArgVT = Op->getOperand(i).getValueType();
16851 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16852 "Unexpected argument type for lowering");
16853 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16854 Entry.Node = StackPtr;
16855 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16857 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16858 Entry.Ty = PointerType::get(ArgTy,0);
16859 Entry.isSExt = false;
16860 Entry.isZExt = false;
16861 Args.push_back(Entry);
16864 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16867 TargetLowering::CallLoweringInfo CLI(DAG);
16868 CLI.setDebugLoc(dl).setChain(InChain)
16869 .setCallee(getLibcallCallingConv(LC),
16870 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16871 Callee, std::move(Args), 0)
16872 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16874 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16875 return DAG.getBitcast(VT, CallInfo.first);
16878 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16879 SelectionDAG &DAG) {
16880 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16881 EVT VT = Op0.getValueType();
16884 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16885 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16887 // PMULxD operations multiply each even value (starting at 0) of LHS with
16888 // the related value of RHS and produce a widen result.
16889 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16890 // => <2 x i64> <ae|cg>
16892 // In other word, to have all the results, we need to perform two PMULxD:
16893 // 1. one with the even values.
16894 // 2. one with the odd values.
16895 // To achieve #2, with need to place the odd values at an even position.
16897 // Place the odd value at an even position (basically, shift all values 1
16898 // step to the left):
16899 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16900 // <a|b|c|d> => <b|undef|d|undef>
16901 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16902 // <e|f|g|h> => <f|undef|h|undef>
16903 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16905 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16907 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16908 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16910 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16911 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16912 // => <2 x i64> <ae|cg>
16913 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16914 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16915 // => <2 x i64> <bf|dh>
16916 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16918 // Shuffle it back into the right order.
16919 SDValue Highs, Lows;
16920 if (VT == MVT::v8i32) {
16921 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16922 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16923 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16924 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16926 const int HighMask[] = {1, 5, 3, 7};
16927 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16928 const int LowMask[] = {0, 4, 2, 6};
16929 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16932 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16933 // unsigned multiply.
16934 if (IsSigned && !Subtarget->hasSSE41()) {
16936 DAG.getConstant(31, dl,
16937 DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16938 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16939 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16940 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16941 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16943 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16944 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16947 // The first result of MUL_LOHI is actually the low value, followed by the
16949 SDValue Ops[] = {Lows, Highs};
16950 return DAG.getMergeValues(Ops, dl);
16953 // Return true if the requred (according to Opcode) shift-imm form is natively
16954 // supported by the Subtarget
16955 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16957 if (VT.getScalarSizeInBits() < 16)
16960 if (VT.is512BitVector() &&
16961 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16964 bool LShift = VT.is128BitVector() ||
16965 (VT.is256BitVector() && Subtarget->hasInt256());
16967 bool AShift = LShift && (Subtarget->hasVLX() ||
16968 (VT != MVT::v2i64 && VT != MVT::v4i64));
16969 return (Opcode == ISD::SRA) ? AShift : LShift;
16972 // The shift amount is a variable, but it is the same for all vector lanes.
16973 // These instrcutions are defined together with shift-immediate.
16975 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
16977 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16980 // Return true if the requred (according to Opcode) variable-shift form is
16981 // natively supported by the Subtarget
16982 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
16985 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16988 // vXi16 supported only on AVX-512, BWI
16989 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16992 if (VT.is512BitVector() || Subtarget->hasVLX())
16995 bool LShift = VT.is128BitVector() || VT.is256BitVector();
16996 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
16997 return (Opcode == ISD::SRA) ? AShift : LShift;
17000 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17001 const X86Subtarget *Subtarget) {
17002 MVT VT = Op.getSimpleValueType();
17004 SDValue R = Op.getOperand(0);
17005 SDValue Amt = Op.getOperand(1);
17007 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17008 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17010 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17011 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17012 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17013 SDValue Ex = DAG.getBitcast(ExVT, R);
17015 if (ShiftAmt >= 32) {
17016 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17018 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17019 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17020 ShiftAmt - 32, DAG);
17021 if (VT == MVT::v2i64)
17022 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17023 if (VT == MVT::v4i64)
17024 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17025 {9, 1, 11, 3, 13, 5, 15, 7});
17027 // SRA upper i32, SHL whole i64 and select lower i32.
17028 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17031 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17032 Lower = DAG.getBitcast(ExVT, Lower);
17033 if (VT == MVT::v2i64)
17034 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17035 if (VT == MVT::v4i64)
17036 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17037 {8, 1, 10, 3, 12, 5, 14, 7});
17039 return DAG.getBitcast(VT, Ex);
17042 // Optimize shl/srl/sra with constant shift amount.
17043 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17044 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17045 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17047 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17048 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17050 // i64 SRA needs to be performed as partial shifts.
17051 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17052 Op.getOpcode() == ISD::SRA)
17053 return ArithmeticShiftRight64(ShiftAmt);
17055 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17056 unsigned NumElts = VT.getVectorNumElements();
17057 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17059 if (Op.getOpcode() == ISD::SHL) {
17060 // Simple i8 add case
17062 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17064 // Make a large shift.
17065 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17067 SHL = DAG.getBitcast(VT, SHL);
17068 // Zero out the rightmost bits.
17069 SmallVector<SDValue, 32> V(
17070 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17071 return DAG.getNode(ISD::AND, dl, VT, SHL,
17072 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17074 if (Op.getOpcode() == ISD::SRL) {
17075 // Make a large shift.
17076 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17078 SRL = DAG.getBitcast(VT, SRL);
17079 // Zero out the leftmost bits.
17080 SmallVector<SDValue, 32> V(
17081 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17082 return DAG.getNode(ISD::AND, dl, VT, SRL,
17083 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17085 if (Op.getOpcode() == ISD::SRA) {
17086 if (ShiftAmt == 7) {
17087 // R s>> 7 === R s< 0
17088 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17089 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17092 // R s>> a === ((R u>> a) ^ m) - m
17093 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17094 SmallVector<SDValue, 32> V(NumElts,
17095 DAG.getConstant(128 >> ShiftAmt, dl,
17097 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17098 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17099 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17102 llvm_unreachable("Unknown shift opcode.");
17107 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17108 if (!Subtarget->is64Bit() &&
17109 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17110 Amt.getOpcode() == ISD::BITCAST &&
17111 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17112 Amt = Amt.getOperand(0);
17113 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17114 VT.getVectorNumElements();
17115 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17116 uint64_t ShiftAmt = 0;
17117 for (unsigned i = 0; i != Ratio; ++i) {
17118 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17122 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17124 // Check remaining shift amounts.
17125 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17126 uint64_t ShAmt = 0;
17127 for (unsigned j = 0; j != Ratio; ++j) {
17128 ConstantSDNode *C =
17129 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17133 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17135 if (ShAmt != ShiftAmt)
17139 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17140 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17142 if (Op.getOpcode() == ISD::SRA)
17143 return ArithmeticShiftRight64(ShiftAmt);
17149 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17150 const X86Subtarget* Subtarget) {
17151 MVT VT = Op.getSimpleValueType();
17153 SDValue R = Op.getOperand(0);
17154 SDValue Amt = Op.getOperand(1);
17156 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17157 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17159 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17160 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17162 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17164 EVT EltVT = VT.getVectorElementType();
17166 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17167 // Check if this build_vector node is doing a splat.
17168 // If so, then set BaseShAmt equal to the splat value.
17169 BaseShAmt = BV->getSplatValue();
17170 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17171 BaseShAmt = SDValue();
17173 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17174 Amt = Amt.getOperand(0);
17176 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17177 if (SVN && SVN->isSplat()) {
17178 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17179 SDValue InVec = Amt.getOperand(0);
17180 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17181 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17182 "Unexpected shuffle index found!");
17183 BaseShAmt = InVec.getOperand(SplatIdx);
17184 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17185 if (ConstantSDNode *C =
17186 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17187 if (C->getZExtValue() == SplatIdx)
17188 BaseShAmt = InVec.getOperand(1);
17193 // Avoid introducing an extract element from a shuffle.
17194 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17195 DAG.getIntPtrConstant(SplatIdx, dl));
17199 if (BaseShAmt.getNode()) {
17200 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17201 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17202 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17203 else if (EltVT.bitsLT(MVT::i32))
17204 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17206 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17210 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17211 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17212 Amt.getOpcode() == ISD::BITCAST &&
17213 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17214 Amt = Amt.getOperand(0);
17215 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17216 VT.getVectorNumElements();
17217 std::vector<SDValue> Vals(Ratio);
17218 for (unsigned i = 0; i != Ratio; ++i)
17219 Vals[i] = Amt.getOperand(i);
17220 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17221 for (unsigned j = 0; j != Ratio; ++j)
17222 if (Vals[j] != Amt.getOperand(i + j))
17226 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17227 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17232 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17233 SelectionDAG &DAG) {
17234 MVT VT = Op.getSimpleValueType();
17236 SDValue R = Op.getOperand(0);
17237 SDValue Amt = Op.getOperand(1);
17239 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17240 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17242 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17245 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17248 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17251 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17252 // shifts per-lane and then shuffle the partial results back together.
17253 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17254 // Splat the shift amounts so the scalar shifts above will catch it.
17255 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17256 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17257 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17258 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17259 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17262 // If possible, lower this packed shift into a vector multiply instead of
17263 // expanding it into a sequence of scalar shifts.
17264 // Do this only if the vector shift count is a constant build_vector.
17265 if (Op.getOpcode() == ISD::SHL &&
17266 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17267 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17268 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17269 SmallVector<SDValue, 8> Elts;
17270 EVT SVT = VT.getScalarType();
17271 unsigned SVTBits = SVT.getSizeInBits();
17272 const APInt &One = APInt(SVTBits, 1);
17273 unsigned NumElems = VT.getVectorNumElements();
17275 for (unsigned i=0; i !=NumElems; ++i) {
17276 SDValue Op = Amt->getOperand(i);
17277 if (Op->getOpcode() == ISD::UNDEF) {
17278 Elts.push_back(Op);
17282 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17283 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17284 uint64_t ShAmt = C.getZExtValue();
17285 if (ShAmt >= SVTBits) {
17286 Elts.push_back(DAG.getUNDEF(SVT));
17289 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17291 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17292 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17295 // Lower SHL with variable shift amount.
17296 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17297 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17299 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17300 DAG.getConstant(0x3f800000U, dl, VT));
17301 Op = DAG.getBitcast(MVT::v4f32, Op);
17302 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17303 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17306 // If possible, lower this shift as a sequence of two shifts by
17307 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17309 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17311 // Could be rewritten as:
17312 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17314 // The advantage is that the two shifts from the example would be
17315 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17316 // the vector shift into four scalar shifts plus four pairs of vector
17318 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17319 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17320 unsigned TargetOpcode = X86ISD::MOVSS;
17321 bool CanBeSimplified;
17322 // The splat value for the first packed shift (the 'X' from the example).
17323 SDValue Amt1 = Amt->getOperand(0);
17324 // The splat value for the second packed shift (the 'Y' from the example).
17325 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17326 Amt->getOperand(2);
17328 // See if it is possible to replace this node with a sequence of
17329 // two shifts followed by a MOVSS/MOVSD
17330 if (VT == MVT::v4i32) {
17331 // Check if it is legal to use a MOVSS.
17332 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17333 Amt2 == Amt->getOperand(3);
17334 if (!CanBeSimplified) {
17335 // Otherwise, check if we can still simplify this node using a MOVSD.
17336 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17337 Amt->getOperand(2) == Amt->getOperand(3);
17338 TargetOpcode = X86ISD::MOVSD;
17339 Amt2 = Amt->getOperand(2);
17342 // Do similar checks for the case where the machine value type
17344 CanBeSimplified = Amt1 == Amt->getOperand(1);
17345 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17346 CanBeSimplified = Amt2 == Amt->getOperand(i);
17348 if (!CanBeSimplified) {
17349 TargetOpcode = X86ISD::MOVSD;
17350 CanBeSimplified = true;
17351 Amt2 = Amt->getOperand(4);
17352 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17353 CanBeSimplified = Amt1 == Amt->getOperand(i);
17354 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17355 CanBeSimplified = Amt2 == Amt->getOperand(j);
17359 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17360 isa<ConstantSDNode>(Amt2)) {
17361 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17362 EVT CastVT = MVT::v4i32;
17364 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17365 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17367 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17368 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17369 if (TargetOpcode == X86ISD::MOVSD)
17370 CastVT = MVT::v2i64;
17371 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17372 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17373 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17375 return DAG.getBitcast(VT, Result);
17379 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17380 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17381 unsigned ShiftOpcode = Op->getOpcode();
17383 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17384 // On SSE41 targets we make use of the fact that VSELECT lowers
17385 // to PBLENDVB which selects bytes based just on the sign bit.
17386 if (Subtarget->hasSSE41()) {
17387 V0 = DAG.getBitcast(VT, V0);
17388 V1 = DAG.getBitcast(VT, V1);
17389 Sel = DAG.getBitcast(VT, Sel);
17390 return DAG.getBitcast(SelVT,
17391 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17393 // On pre-SSE41 targets we test for the sign bit by comparing to
17394 // zero - a negative value will set all bits of the lanes to true
17395 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17396 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17397 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17398 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17401 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17402 // We can safely do this using i16 shifts as we're only interested in
17403 // the 3 lower bits of each byte.
17404 Amt = DAG.getBitcast(ExtVT, Amt);
17405 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17406 Amt = DAG.getBitcast(VT, Amt);
17408 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17409 // r = VSELECT(r, shift(r, 4), a);
17411 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17412 R = SignBitSelect(VT, Amt, M, R);
17415 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17417 // r = VSELECT(r, shift(r, 2), a);
17418 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17419 R = SignBitSelect(VT, Amt, M, R);
17422 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17424 // return VSELECT(r, shift(r, 1), a);
17425 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17426 R = SignBitSelect(VT, Amt, M, R);
17430 if (Op->getOpcode() == ISD::SRA) {
17431 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17432 // so we can correctly sign extend. We don't care what happens to the
17434 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17435 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17436 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17437 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17438 ALo = DAG.getBitcast(ExtVT, ALo);
17439 AHi = DAG.getBitcast(ExtVT, AHi);
17440 RLo = DAG.getBitcast(ExtVT, RLo);
17441 RHi = DAG.getBitcast(ExtVT, RHi);
17443 // r = VSELECT(r, shift(r, 4), a);
17444 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17445 DAG.getConstant(4, dl, ExtVT));
17446 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17447 DAG.getConstant(4, dl, ExtVT));
17448 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17449 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17452 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17453 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17455 // r = VSELECT(r, shift(r, 2), a);
17456 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17457 DAG.getConstant(2, dl, ExtVT));
17458 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17459 DAG.getConstant(2, dl, ExtVT));
17460 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17461 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17464 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17465 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17467 // r = VSELECT(r, shift(r, 1), a);
17468 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17469 DAG.getConstant(1, dl, ExtVT));
17470 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17471 DAG.getConstant(1, dl, ExtVT));
17472 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17473 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17475 // Logical shift the result back to the lower byte, leaving a zero upper
17477 // meaning that we can safely pack with PACKUSWB.
17479 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17481 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17482 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17486 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17487 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17488 // solution better.
17489 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17490 MVT ExtVT = MVT::v8i32;
17492 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17493 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17494 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17495 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17496 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17499 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17500 MVT ExtVT = MVT::v8i32;
17501 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17502 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17503 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17504 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17505 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17506 ALo = DAG.getBitcast(ExtVT, ALo);
17507 AHi = DAG.getBitcast(ExtVT, AHi);
17508 RLo = DAG.getBitcast(ExtVT, RLo);
17509 RHi = DAG.getBitcast(ExtVT, RHi);
17510 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17511 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17512 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17513 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17514 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17517 if (VT == MVT::v8i16) {
17518 unsigned ShiftOpcode = Op->getOpcode();
17520 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17521 // On SSE41 targets we make use of the fact that VSELECT lowers
17522 // to PBLENDVB which selects bytes based just on the sign bit.
17523 if (Subtarget->hasSSE41()) {
17524 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17525 V0 = DAG.getBitcast(ExtVT, V0);
17526 V1 = DAG.getBitcast(ExtVT, V1);
17527 Sel = DAG.getBitcast(ExtVT, Sel);
17528 return DAG.getBitcast(
17529 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17531 // On pre-SSE41 targets we splat the sign bit - a negative value will
17532 // set all bits of the lanes to true and VSELECT uses that in
17533 // its OR(AND(V0,C),AND(V1,~C)) lowering.
17535 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17536 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17539 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17540 if (Subtarget->hasSSE41()) {
17541 // On SSE41 targets we need to replicate the shift mask in both
17542 // bytes for PBLENDVB.
17545 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17546 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17548 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17551 // r = VSELECT(r, shift(r, 8), a);
17552 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17553 R = SignBitSelect(Amt, M, R);
17556 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17558 // r = VSELECT(r, shift(r, 4), a);
17559 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17560 R = SignBitSelect(Amt, M, R);
17563 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17565 // r = VSELECT(r, shift(r, 2), a);
17566 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17567 R = SignBitSelect(Amt, M, R);
17570 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17572 // return VSELECT(r, shift(r, 1), a);
17573 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17574 R = SignBitSelect(Amt, M, R);
17578 // Decompose 256-bit shifts into smaller 128-bit shifts.
17579 if (VT.is256BitVector()) {
17580 unsigned NumElems = VT.getVectorNumElements();
17581 MVT EltVT = VT.getVectorElementType();
17582 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17584 // Extract the two vectors
17585 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17586 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17588 // Recreate the shift amount vectors
17589 SDValue Amt1, Amt2;
17590 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17591 // Constant shift amount
17592 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17593 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17594 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17596 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17597 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17599 // Variable shift amount
17600 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17601 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17604 // Issue new vector shifts for the smaller types
17605 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17606 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17608 // Concatenate the result back
17609 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17615 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17616 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17617 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17618 // looks for this combo and may remove the "setcc" instruction if the "setcc"
17619 // has only one use.
17620 SDNode *N = Op.getNode();
17621 SDValue LHS = N->getOperand(0);
17622 SDValue RHS = N->getOperand(1);
17623 unsigned BaseOp = 0;
17626 switch (Op.getOpcode()) {
17627 default: llvm_unreachable("Unknown ovf instruction!");
17629 // A subtract of one will be selected as a INC. Note that INC doesn't
17630 // set CF, so we can't do this for UADDO.
17631 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17633 BaseOp = X86ISD::INC;
17634 Cond = X86::COND_O;
17637 BaseOp = X86ISD::ADD;
17638 Cond = X86::COND_O;
17641 BaseOp = X86ISD::ADD;
17642 Cond = X86::COND_B;
17645 // A subtract of one will be selected as a DEC. Note that DEC doesn't
17646 // set CF, so we can't do this for USUBO.
17647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17649 BaseOp = X86ISD::DEC;
17650 Cond = X86::COND_O;
17653 BaseOp = X86ISD::SUB;
17654 Cond = X86::COND_O;
17657 BaseOp = X86ISD::SUB;
17658 Cond = X86::COND_B;
17661 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17662 Cond = X86::COND_O;
17664 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17665 if (N->getValueType(0) == MVT::i8) {
17666 BaseOp = X86ISD::UMUL8;
17667 Cond = X86::COND_O;
17670 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17672 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17675 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17676 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17677 SDValue(Sum.getNode(), 2));
17679 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17683 // Also sets EFLAGS.
17684 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17685 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17688 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17689 DAG.getConstant(Cond, DL, MVT::i32),
17690 SDValue(Sum.getNode(), 1));
17692 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17695 /// Returns true if the operand type is exactly twice the native width, and
17696 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17697 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17698 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17699 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17700 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17703 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17704 else if (OpWidth == 128)
17705 return Subtarget->hasCmpxchg16b();
17710 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17711 return needsCmpXchgNb(SI->getValueOperand()->getType());
17714 // Note: this turns large loads into lock cmpxchg8b/16b.
17715 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17716 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17717 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17718 return needsCmpXchgNb(PTy->getElementType());
17721 TargetLoweringBase::AtomicRMWExpansionKind
17722 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17723 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17724 const Type *MemType = AI->getType();
17726 // If the operand is too big, we must see if cmpxchg8/16b is available
17727 // and default to library calls otherwise.
17728 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17729 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17730 : AtomicRMWExpansionKind::None;
17733 AtomicRMWInst::BinOp Op = AI->getOperation();
17736 llvm_unreachable("Unknown atomic operation");
17737 case AtomicRMWInst::Xchg:
17738 case AtomicRMWInst::Add:
17739 case AtomicRMWInst::Sub:
17740 // It's better to use xadd, xsub or xchg for these in all cases.
17741 return AtomicRMWExpansionKind::None;
17742 case AtomicRMWInst::Or:
17743 case AtomicRMWInst::And:
17744 case AtomicRMWInst::Xor:
17745 // If the atomicrmw's result isn't actually used, we can just add a "lock"
17746 // prefix to a normal instruction for these operations.
17747 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17748 : AtomicRMWExpansionKind::None;
17749 case AtomicRMWInst::Nand:
17750 case AtomicRMWInst::Max:
17751 case AtomicRMWInst::Min:
17752 case AtomicRMWInst::UMax:
17753 case AtomicRMWInst::UMin:
17754 // These always require a non-trivial set of data operations on x86. We must
17755 // use a cmpxchg loop.
17756 return AtomicRMWExpansionKind::CmpXChg;
17760 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17761 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17762 // no-sse2). There isn't any reason to disable it if the target processor
17764 return Subtarget.hasSSE2() || Subtarget.is64Bit();
17768 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17769 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17770 const Type *MemType = AI->getType();
17771 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17772 // there is no benefit in turning such RMWs into loads, and it is actually
17773 // harmful as it introduces a mfence.
17774 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17777 auto Builder = IRBuilder<>(AI);
17778 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17779 auto SynchScope = AI->getSynchScope();
17780 // We must restrict the ordering to avoid generating loads with Release or
17781 // ReleaseAcquire orderings.
17782 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17783 auto Ptr = AI->getPointerOperand();
17785 // Before the load we need a fence. Here is an example lifted from
17786 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17789 // x.store(1, relaxed);
17790 // r1 = y.fetch_add(0, release);
17792 // y.fetch_add(42, acquire);
17793 // r2 = x.load(relaxed);
17794 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17795 // lowered to just a load without a fence. A mfence flushes the store buffer,
17796 // making the optimization clearly correct.
17797 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17798 // otherwise, we might be able to be more agressive on relaxed idempotent
17799 // rmw. In practice, they do not look useful, so we don't try to be
17800 // especially clever.
17801 if (SynchScope == SingleThread)
17802 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17803 // the IR level, so we must wrap it in an intrinsic.
17806 if (!hasMFENCE(*Subtarget))
17807 // FIXME: it might make sense to use a locked operation here but on a
17808 // different cache-line to prevent cache-line bouncing. In practice it
17809 // is probably a small win, and x86 processors without mfence are rare
17810 // enough that we do not bother.
17814 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17815 Builder.CreateCall(MFence, {});
17817 // Finally we can emit the atomic load.
17818 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17819 AI->getType()->getPrimitiveSizeInBits());
17820 Loaded->setAtomic(Order, SynchScope);
17821 AI->replaceAllUsesWith(Loaded);
17822 AI->eraseFromParent();
17826 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17827 SelectionDAG &DAG) {
17829 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17830 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17831 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17832 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17834 // The only fence that needs an instruction is a sequentially-consistent
17835 // cross-thread fence.
17836 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17837 if (hasMFENCE(*Subtarget))
17838 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17840 SDValue Chain = Op.getOperand(0);
17841 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17843 DAG.getRegister(X86::ESP, MVT::i32), // Base
17844 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
17845 DAG.getRegister(0, MVT::i32), // Index
17846 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
17847 DAG.getRegister(0, MVT::i32), // Segment.
17851 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17852 return SDValue(Res, 0);
17855 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17856 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17859 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17860 SelectionDAG &DAG) {
17861 MVT T = Op.getSimpleValueType();
17865 switch(T.SimpleTy) {
17866 default: llvm_unreachable("Invalid value type!");
17867 case MVT::i8: Reg = X86::AL; size = 1; break;
17868 case MVT::i16: Reg = X86::AX; size = 2; break;
17869 case MVT::i32: Reg = X86::EAX; size = 4; break;
17871 assert(Subtarget->is64Bit() && "Node not type legal!");
17872 Reg = X86::RAX; size = 8;
17875 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17876 Op.getOperand(2), SDValue());
17877 SDValue Ops[] = { cpIn.getValue(0),
17880 DAG.getTargetConstant(size, DL, MVT::i8),
17881 cpIn.getValue(1) };
17882 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17883 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17884 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17888 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17889 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17890 MVT::i32, cpOut.getValue(2));
17891 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17892 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17895 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17896 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17897 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17901 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17902 SelectionDAG &DAG) {
17903 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17904 MVT DstVT = Op.getSimpleValueType();
17906 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17907 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17908 if (DstVT != MVT::f64)
17909 // This conversion needs to be expanded.
17912 SDValue InVec = Op->getOperand(0);
17914 unsigned NumElts = SrcVT.getVectorNumElements();
17915 EVT SVT = SrcVT.getVectorElementType();
17917 // Widen the vector in input in the case of MVT::v2i32.
17918 // Example: from MVT::v2i32 to MVT::v4i32.
17919 SmallVector<SDValue, 16> Elts;
17920 for (unsigned i = 0, e = NumElts; i != e; ++i)
17921 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17922 DAG.getIntPtrConstant(i, dl)));
17924 // Explicitly mark the extra elements as Undef.
17925 Elts.append(NumElts, DAG.getUNDEF(SVT));
17927 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17928 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17929 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
17930 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17931 DAG.getIntPtrConstant(0, dl));
17934 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17935 Subtarget->hasMMX() && "Unexpected custom BITCAST");
17936 assert((DstVT == MVT::i64 ||
17937 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17938 "Unexpected custom BITCAST");
17939 // i64 <=> MMX conversions are Legal.
17940 if (SrcVT==MVT::i64 && DstVT.isVector())
17942 if (DstVT==MVT::i64 && SrcVT.isVector())
17944 // MMX <=> MMX conversions are Legal.
17945 if (SrcVT.isVector() && DstVT.isVector())
17947 // All other conversions need to be expanded.
17951 /// Compute the horizontal sum of bytes in V for the elements of VT.
17953 /// Requires V to be a byte vector and VT to be an integer vector type with
17954 /// wider elements than V's type. The width of the elements of VT determines
17955 /// how many bytes of V are summed horizontally to produce each element of the
17957 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
17958 const X86Subtarget *Subtarget,
17959 SelectionDAG &DAG) {
17961 MVT ByteVecVT = V.getSimpleValueType();
17962 MVT EltVT = VT.getVectorElementType();
17963 int NumElts = VT.getVectorNumElements();
17964 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
17965 "Expected value to have byte element type.");
17966 assert(EltVT != MVT::i8 &&
17967 "Horizontal byte sum only makes sense for wider elements!");
17968 unsigned VecSize = VT.getSizeInBits();
17969 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
17971 // PSADBW instruction horizontally add all bytes and leave the result in i64
17972 // chunks, thus directly computes the pop count for v2i64 and v4i64.
17973 if (EltVT == MVT::i64) {
17974 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17975 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
17976 return DAG.getBitcast(VT, V);
17979 if (EltVT == MVT::i32) {
17980 // We unpack the low half and high half into i32s interleaved with zeros so
17981 // that we can use PSADBW to horizontally sum them. The most useful part of
17982 // this is that it lines up the results of two PSADBW instructions to be
17983 // two v2i64 vectors which concatenated are the 4 population counts. We can
17984 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
17985 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
17986 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
17987 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
17989 // Do the horizontal sums into two v2i64s.
17990 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17991 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17992 DAG.getBitcast(ByteVecVT, Low), Zeros);
17993 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17994 DAG.getBitcast(ByteVecVT, High), Zeros);
17996 // Merge them together.
17997 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
17998 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
17999 DAG.getBitcast(ShortVecVT, Low),
18000 DAG.getBitcast(ShortVecVT, High));
18002 return DAG.getBitcast(VT, V);
18005 // The only element type left is i16.
18006 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18008 // To obtain pop count for each i16 element starting from the pop count for
18009 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18010 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18011 // directly supported.
18012 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18013 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18014 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18015 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18016 DAG.getBitcast(ByteVecVT, V));
18017 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18020 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18021 const X86Subtarget *Subtarget,
18022 SelectionDAG &DAG) {
18023 MVT VT = Op.getSimpleValueType();
18024 MVT EltVT = VT.getVectorElementType();
18025 unsigned VecSize = VT.getSizeInBits();
18027 // Implement a lookup table in register by using an algorithm based on:
18028 // http://wm.ite.pl/articles/sse-popcount.html
18030 // The general idea is that every lower byte nibble in the input vector is an
18031 // index into a in-register pre-computed pop count table. We then split up the
18032 // input vector in two new ones: (1) a vector with only the shifted-right
18033 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18034 // masked out higher ones) for each byte. PSHUB is used separately with both
18035 // to index the in-register table. Next, both are added and the result is a
18036 // i8 vector where each element contains the pop count for input byte.
18038 // To obtain the pop count for elements != i8, we follow up with the same
18039 // approach and use additional tricks as described below.
18041 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18042 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18043 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18044 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18046 int NumByteElts = VecSize / 8;
18047 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18048 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18049 SmallVector<SDValue, 16> LUTVec;
18050 for (int i = 0; i < NumByteElts; ++i)
18051 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18052 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18053 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18054 DAG.getConstant(0x0F, DL, MVT::i8));
18055 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18058 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18059 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18060 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18063 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18065 // The input vector is used as the shuffle mask that index elements into the
18066 // LUT. After counting low and high nibbles, add the vector to obtain the
18067 // final pop count per i8 element.
18068 SDValue HighPopCnt =
18069 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18070 SDValue LowPopCnt =
18071 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18072 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18074 if (EltVT == MVT::i8)
18077 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18080 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18081 const X86Subtarget *Subtarget,
18082 SelectionDAG &DAG) {
18083 MVT VT = Op.getSimpleValueType();
18084 assert(VT.is128BitVector() &&
18085 "Only 128-bit vector bitmath lowering supported.");
18087 int VecSize = VT.getSizeInBits();
18088 MVT EltVT = VT.getVectorElementType();
18089 int Len = EltVT.getSizeInBits();
18091 // This is the vectorized version of the "best" algorithm from
18092 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18093 // with a minor tweak to use a series of adds + shifts instead of vector
18094 // multiplications. Implemented for all integer vector types. We only use
18095 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18096 // much faster, even faster than using native popcnt instructions.
18098 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18099 MVT VT = V.getSimpleValueType();
18100 SmallVector<SDValue, 32> Shifters(
18101 VT.getVectorNumElements(),
18102 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18103 return DAG.getNode(OpCode, DL, VT, V,
18104 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18106 auto GetMask = [&](SDValue V, APInt Mask) {
18107 MVT VT = V.getSimpleValueType();
18108 SmallVector<SDValue, 32> Masks(
18109 VT.getVectorNumElements(),
18110 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18111 return DAG.getNode(ISD::AND, DL, VT, V,
18112 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18115 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18116 // x86, so set the SRL type to have elements at least i16 wide. This is
18117 // correct because all of our SRLs are followed immediately by a mask anyways
18118 // that handles any bits that sneak into the high bits of the byte elements.
18119 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18123 // v = v - ((v >> 1) & 0x55555555...)
18125 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18126 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18127 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18129 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18130 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18131 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18132 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18133 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18135 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18136 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18137 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18138 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18140 // At this point, V contains the byte-wise population count, and we are
18141 // merely doing a horizontal sum if necessary to get the wider element
18143 if (EltVT == MVT::i8)
18146 return LowerHorizontalByteSum(
18147 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18151 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18152 SelectionDAG &DAG) {
18153 MVT VT = Op.getSimpleValueType();
18154 // FIXME: Need to add AVX-512 support here!
18155 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18156 "Unknown CTPOP type to handle");
18157 SDLoc DL(Op.getNode());
18158 SDValue Op0 = Op.getOperand(0);
18160 if (!Subtarget->hasSSSE3()) {
18161 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18162 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18163 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18166 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18167 unsigned NumElems = VT.getVectorNumElements();
18169 // Extract each 128-bit vector, compute pop count and concat the result.
18170 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18171 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18173 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18174 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18175 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18178 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18181 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18182 SelectionDAG &DAG) {
18183 assert(Op.getValueType().isVector() &&
18184 "We only do custom lowering for vector population count.");
18185 return LowerVectorCTPOP(Op, Subtarget, DAG);
18188 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18189 SDNode *Node = Op.getNode();
18191 EVT T = Node->getValueType(0);
18192 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18193 DAG.getConstant(0, dl, T), Node->getOperand(2));
18194 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18195 cast<AtomicSDNode>(Node)->getMemoryVT(),
18196 Node->getOperand(0),
18197 Node->getOperand(1), negOp,
18198 cast<AtomicSDNode>(Node)->getMemOperand(),
18199 cast<AtomicSDNode>(Node)->getOrdering(),
18200 cast<AtomicSDNode>(Node)->getSynchScope());
18203 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18204 SDNode *Node = Op.getNode();
18206 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18208 // Convert seq_cst store -> xchg
18209 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18210 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18211 // (The only way to get a 16-byte store is cmpxchg16b)
18212 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18213 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18214 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18215 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18216 cast<AtomicSDNode>(Node)->getMemoryVT(),
18217 Node->getOperand(0),
18218 Node->getOperand(1), Node->getOperand(2),
18219 cast<AtomicSDNode>(Node)->getMemOperand(),
18220 cast<AtomicSDNode>(Node)->getOrdering(),
18221 cast<AtomicSDNode>(Node)->getSynchScope());
18222 return Swap.getValue(1);
18224 // Other atomic stores have a simple pattern.
18228 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18229 EVT VT = Op.getNode()->getSimpleValueType(0);
18231 // Let legalize expand this if it isn't a legal type yet.
18232 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18235 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18238 bool ExtraOp = false;
18239 switch (Op.getOpcode()) {
18240 default: llvm_unreachable("Invalid code");
18241 case ISD::ADDC: Opc = X86ISD::ADD; break;
18242 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18243 case ISD::SUBC: Opc = X86ISD::SUB; break;
18244 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18248 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18250 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18251 Op.getOperand(1), Op.getOperand(2));
18254 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18255 SelectionDAG &DAG) {
18256 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18258 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18259 // which returns the values as { float, float } (in XMM0) or
18260 // { double, double } (which is returned in XMM0, XMM1).
18262 SDValue Arg = Op.getOperand(0);
18263 EVT ArgVT = Arg.getValueType();
18264 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18266 TargetLowering::ArgListTy Args;
18267 TargetLowering::ArgListEntry Entry;
18271 Entry.isSExt = false;
18272 Entry.isZExt = false;
18273 Args.push_back(Entry);
18275 bool isF64 = ArgVT == MVT::f64;
18276 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18277 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18278 // the results are returned via SRet in memory.
18279 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18281 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
18283 Type *RetTy = isF64
18284 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18285 : (Type*)VectorType::get(ArgTy, 4);
18287 TargetLowering::CallLoweringInfo CLI(DAG);
18288 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18289 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18291 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18294 // Returned in xmm0 and xmm1.
18295 return CallResult.first;
18297 // Returned in bits 0:31 and 32:64 xmm0.
18298 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18299 CallResult.first, DAG.getIntPtrConstant(0, dl));
18300 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18301 CallResult.first, DAG.getIntPtrConstant(1, dl));
18302 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18303 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18306 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18307 SelectionDAG &DAG) {
18308 assert(Subtarget->hasAVX512() &&
18309 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18311 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18312 EVT VT = N->getValue().getValueType();
18313 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18316 // X86 scatter kills mask register, so its type should be added to
18317 // the list of return values
18318 if (N->getNumValues() == 1) {
18319 SDValue Index = N->getIndex();
18320 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18321 !Index.getValueType().is512BitVector())
18322 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18324 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18325 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18326 N->getOperand(3), Index };
18328 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18329 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18330 return SDValue(NewScatter.getNode(), 0);
18335 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18336 SelectionDAG &DAG) {
18337 assert(Subtarget->hasAVX512() &&
18338 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18340 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18341 EVT VT = Op.getValueType();
18342 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18345 SDValue Index = N->getIndex();
18346 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18347 !Index.getValueType().is512BitVector()) {
18348 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18349 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18350 N->getOperand(3), Index };
18351 DAG.UpdateNodeOperands(N, Ops);
18356 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18357 SelectionDAG &DAG) const {
18358 // TODO: Eventually, the lowering of these nodes should be informed by or
18359 // deferred to the GC strategy for the function in which they appear. For
18360 // now, however, they must be lowered to something. Since they are logically
18361 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18362 // require special handling for these nodes), lower them as literal NOOPs for
18364 SmallVector<SDValue, 2> Ops;
18366 Ops.push_back(Op.getOperand(0));
18367 if (Op->getGluedNode())
18368 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18371 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18372 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18377 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18378 SelectionDAG &DAG) const {
18379 // TODO: Eventually, the lowering of these nodes should be informed by or
18380 // deferred to the GC strategy for the function in which they appear. For
18381 // now, however, they must be lowered to something. Since they are logically
18382 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18383 // require special handling for these nodes), lower them as literal NOOPs for
18385 SmallVector<SDValue, 2> Ops;
18387 Ops.push_back(Op.getOperand(0));
18388 if (Op->getGluedNode())
18389 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18392 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18393 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18398 /// LowerOperation - Provide custom lowering hooks for some operations.
18400 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18401 switch (Op.getOpcode()) {
18402 default: llvm_unreachable("Should not custom lower this!");
18403 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18404 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18405 return LowerCMP_SWAP(Op, Subtarget, DAG);
18406 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18407 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18408 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18409 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18410 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18411 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18412 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18413 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18414 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18415 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18416 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18417 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18418 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18419 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18420 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18421 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18422 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18423 case ISD::SHL_PARTS:
18424 case ISD::SRA_PARTS:
18425 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18426 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18427 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18428 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18429 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18430 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18431 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18432 case ISD::SIGN_EXTEND_VECTOR_INREG:
18433 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18434 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18435 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18436 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18437 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18439 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18440 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18441 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18442 case ISD::SETCC: return LowerSETCC(Op, DAG);
18443 case ISD::SELECT: return LowerSELECT(Op, DAG);
18444 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18445 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18446 case ISD::VASTART: return LowerVASTART(Op, DAG);
18447 case ISD::VAARG: return LowerVAARG(Op, DAG);
18448 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18449 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18450 case ISD::INTRINSIC_VOID:
18451 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18452 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18453 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18454 case ISD::FRAME_TO_ARGS_OFFSET:
18455 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18456 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18457 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18458 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18459 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18460 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18461 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18462 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18463 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18464 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18465 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18466 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18467 case ISD::UMUL_LOHI:
18468 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18471 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18477 case ISD::UMULO: return LowerXALUO(Op, DAG);
18478 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18479 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18483 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18484 case ISD::ADD: return LowerADD(Op, DAG);
18485 case ISD::SUB: return LowerSUB(Op, DAG);
18486 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18487 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18488 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18489 case ISD::GC_TRANSITION_START:
18490 return LowerGC_TRANSITION_START(Op, DAG);
18491 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18495 /// ReplaceNodeResults - Replace a node with an illegal result type
18496 /// with a new node built out of custom code.
18497 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18498 SmallVectorImpl<SDValue>&Results,
18499 SelectionDAG &DAG) const {
18501 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18502 switch (N->getOpcode()) {
18504 llvm_unreachable("Do not know how to custom type legalize this operation!");
18505 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18506 case X86ISD::FMINC:
18508 case X86ISD::FMAXC:
18509 case X86ISD::FMAX: {
18510 EVT VT = N->getValueType(0);
18511 if (VT != MVT::v2f32)
18512 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18513 SDValue UNDEF = DAG.getUNDEF(VT);
18514 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18515 N->getOperand(0), UNDEF);
18516 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18517 N->getOperand(1), UNDEF);
18518 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18521 case ISD::SIGN_EXTEND_INREG:
18526 // We don't want to expand or promote these.
18533 case ISD::UDIVREM: {
18534 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18535 Results.push_back(V);
18538 case ISD::FP_TO_SINT:
18539 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
18540 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18541 if (N->getOperand(0).getValueType() == MVT::f16)
18544 case ISD::FP_TO_UINT: {
18545 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18547 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18550 std::pair<SDValue,SDValue> Vals =
18551 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18552 SDValue FIST = Vals.first, StackSlot = Vals.second;
18553 if (FIST.getNode()) {
18554 EVT VT = N->getValueType(0);
18555 // Return a load from the stack slot.
18556 if (StackSlot.getNode())
18557 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18558 MachinePointerInfo(),
18559 false, false, false, 0));
18561 Results.push_back(FIST);
18565 case ISD::UINT_TO_FP: {
18566 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18567 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18568 N->getValueType(0) != MVT::v2f32)
18570 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18572 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18574 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18575 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18576 DAG.getBitcast(MVT::v2i64, VBias));
18577 Or = DAG.getBitcast(MVT::v2f64, Or);
18578 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18579 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18582 case ISD::FP_ROUND: {
18583 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18585 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18586 Results.push_back(V);
18589 case ISD::FP_EXTEND: {
18590 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18591 // No other ValueType for FP_EXTEND should reach this point.
18592 assert(N->getValueType(0) == MVT::v2f32 &&
18593 "Do not know how to legalize this Node");
18596 case ISD::INTRINSIC_W_CHAIN: {
18597 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18599 default : llvm_unreachable("Do not know how to custom type "
18600 "legalize this intrinsic operation!");
18601 case Intrinsic::x86_rdtsc:
18602 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18604 case Intrinsic::x86_rdtscp:
18605 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18607 case Intrinsic::x86_rdpmc:
18608 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18611 case ISD::READCYCLECOUNTER: {
18612 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18615 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18616 EVT T = N->getValueType(0);
18617 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18618 bool Regs64bit = T == MVT::i128;
18619 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18620 SDValue cpInL, cpInH;
18621 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18622 DAG.getConstant(0, dl, HalfT));
18623 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18624 DAG.getConstant(1, dl, HalfT));
18625 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18626 Regs64bit ? X86::RAX : X86::EAX,
18628 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18629 Regs64bit ? X86::RDX : X86::EDX,
18630 cpInH, cpInL.getValue(1));
18631 SDValue swapInL, swapInH;
18632 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18633 DAG.getConstant(0, dl, HalfT));
18634 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18635 DAG.getConstant(1, dl, HalfT));
18636 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18637 Regs64bit ? X86::RBX : X86::EBX,
18638 swapInL, cpInH.getValue(1));
18639 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18640 Regs64bit ? X86::RCX : X86::ECX,
18641 swapInH, swapInL.getValue(1));
18642 SDValue Ops[] = { swapInH.getValue(0),
18644 swapInH.getValue(1) };
18645 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18646 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18647 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18648 X86ISD::LCMPXCHG8_DAG;
18649 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18650 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18651 Regs64bit ? X86::RAX : X86::EAX,
18652 HalfT, Result.getValue(1));
18653 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18654 Regs64bit ? X86::RDX : X86::EDX,
18655 HalfT, cpOutL.getValue(2));
18656 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18658 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18659 MVT::i32, cpOutH.getValue(2));
18661 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18662 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18663 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18665 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18666 Results.push_back(Success);
18667 Results.push_back(EFLAGS.getValue(1));
18670 case ISD::ATOMIC_SWAP:
18671 case ISD::ATOMIC_LOAD_ADD:
18672 case ISD::ATOMIC_LOAD_SUB:
18673 case ISD::ATOMIC_LOAD_AND:
18674 case ISD::ATOMIC_LOAD_OR:
18675 case ISD::ATOMIC_LOAD_XOR:
18676 case ISD::ATOMIC_LOAD_NAND:
18677 case ISD::ATOMIC_LOAD_MIN:
18678 case ISD::ATOMIC_LOAD_MAX:
18679 case ISD::ATOMIC_LOAD_UMIN:
18680 case ISD::ATOMIC_LOAD_UMAX:
18681 case ISD::ATOMIC_LOAD: {
18682 // Delegate to generic TypeLegalization. Situations we can really handle
18683 // should have already been dealt with by AtomicExpandPass.cpp.
18686 case ISD::BITCAST: {
18687 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18688 EVT DstVT = N->getValueType(0);
18689 EVT SrcVT = N->getOperand(0)->getValueType(0);
18691 if (SrcVT != MVT::f64 ||
18692 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18695 unsigned NumElts = DstVT.getVectorNumElements();
18696 EVT SVT = DstVT.getVectorElementType();
18697 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18698 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18699 MVT::v2f64, N->getOperand(0));
18700 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18702 if (ExperimentalVectorWideningLegalization) {
18703 // If we are legalizing vectors by widening, we already have the desired
18704 // legal vector type, just return it.
18705 Results.push_back(ToVecInt);
18709 SmallVector<SDValue, 8> Elts;
18710 for (unsigned i = 0, e = NumElts; i != e; ++i)
18711 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18712 ToVecInt, DAG.getIntPtrConstant(i, dl)));
18714 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18719 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18720 switch ((X86ISD::NodeType)Opcode) {
18721 case X86ISD::FIRST_NUMBER: break;
18722 case X86ISD::BSF: return "X86ISD::BSF";
18723 case X86ISD::BSR: return "X86ISD::BSR";
18724 case X86ISD::SHLD: return "X86ISD::SHLD";
18725 case X86ISD::SHRD: return "X86ISD::SHRD";
18726 case X86ISD::FAND: return "X86ISD::FAND";
18727 case X86ISD::FANDN: return "X86ISD::FANDN";
18728 case X86ISD::FOR: return "X86ISD::FOR";
18729 case X86ISD::FXOR: return "X86ISD::FXOR";
18730 case X86ISD::FILD: return "X86ISD::FILD";
18731 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
18732 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18733 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18734 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18735 case X86ISD::FLD: return "X86ISD::FLD";
18736 case X86ISD::FST: return "X86ISD::FST";
18737 case X86ISD::CALL: return "X86ISD::CALL";
18738 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
18739 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
18740 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
18741 case X86ISD::BT: return "X86ISD::BT";
18742 case X86ISD::CMP: return "X86ISD::CMP";
18743 case X86ISD::COMI: return "X86ISD::COMI";
18744 case X86ISD::UCOMI: return "X86ISD::UCOMI";
18745 case X86ISD::CMPM: return "X86ISD::CMPM";
18746 case X86ISD::CMPMU: return "X86ISD::CMPMU";
18747 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
18748 case X86ISD::SETCC: return "X86ISD::SETCC";
18749 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
18750 case X86ISD::FSETCC: return "X86ISD::FSETCC";
18751 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
18752 case X86ISD::CMOV: return "X86ISD::CMOV";
18753 case X86ISD::BRCOND: return "X86ISD::BRCOND";
18754 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
18755 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
18756 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
18757 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
18758 case X86ISD::Wrapper: return "X86ISD::Wrapper";
18759 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
18760 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
18761 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
18762 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
18763 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
18764 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
18765 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
18766 case X86ISD::PINSRB: return "X86ISD::PINSRB";
18767 case X86ISD::PINSRW: return "X86ISD::PINSRW";
18768 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
18769 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
18770 case X86ISD::ANDNP: return "X86ISD::ANDNP";
18771 case X86ISD::PSIGN: return "X86ISD::PSIGN";
18772 case X86ISD::BLENDI: return "X86ISD::BLENDI";
18773 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
18774 case X86ISD::ADDUS: return "X86ISD::ADDUS";
18775 case X86ISD::SUBUS: return "X86ISD::SUBUS";
18776 case X86ISD::HADD: return "X86ISD::HADD";
18777 case X86ISD::HSUB: return "X86ISD::HSUB";
18778 case X86ISD::FHADD: return "X86ISD::FHADD";
18779 case X86ISD::FHSUB: return "X86ISD::FHSUB";
18780 case X86ISD::ABS: return "X86ISD::ABS";
18781 case X86ISD::FMAX: return "X86ISD::FMAX";
18782 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
18783 case X86ISD::FMIN: return "X86ISD::FMIN";
18784 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
18785 case X86ISD::FMAXC: return "X86ISD::FMAXC";
18786 case X86ISD::FMINC: return "X86ISD::FMINC";
18787 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
18788 case X86ISD::FRCP: return "X86ISD::FRCP";
18789 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
18790 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
18791 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
18792 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
18793 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
18794 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
18795 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
18796 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
18797 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
18798 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
18799 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
18800 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
18801 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
18802 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
18803 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
18804 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
18805 case X86ISD::VZEXT: return "X86ISD::VZEXT";
18806 case X86ISD::VSEXT: return "X86ISD::VSEXT";
18807 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
18808 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
18809 case X86ISD::VINSERT: return "X86ISD::VINSERT";
18810 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
18811 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
18812 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
18813 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
18814 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
18815 case X86ISD::VSHL: return "X86ISD::VSHL";
18816 case X86ISD::VSRL: return "X86ISD::VSRL";
18817 case X86ISD::VSRA: return "X86ISD::VSRA";
18818 case X86ISD::VSHLI: return "X86ISD::VSHLI";
18819 case X86ISD::VSRLI: return "X86ISD::VSRLI";
18820 case X86ISD::VSRAI: return "X86ISD::VSRAI";
18821 case X86ISD::CMPP: return "X86ISD::CMPP";
18822 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
18823 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
18824 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
18825 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
18826 case X86ISD::ADD: return "X86ISD::ADD";
18827 case X86ISD::SUB: return "X86ISD::SUB";
18828 case X86ISD::ADC: return "X86ISD::ADC";
18829 case X86ISD::SBB: return "X86ISD::SBB";
18830 case X86ISD::SMUL: return "X86ISD::SMUL";
18831 case X86ISD::UMUL: return "X86ISD::UMUL";
18832 case X86ISD::SMUL8: return "X86ISD::SMUL8";
18833 case X86ISD::UMUL8: return "X86ISD::UMUL8";
18834 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18835 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18836 case X86ISD::INC: return "X86ISD::INC";
18837 case X86ISD::DEC: return "X86ISD::DEC";
18838 case X86ISD::OR: return "X86ISD::OR";
18839 case X86ISD::XOR: return "X86ISD::XOR";
18840 case X86ISD::AND: return "X86ISD::AND";
18841 case X86ISD::BEXTR: return "X86ISD::BEXTR";
18842 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
18843 case X86ISD::PTEST: return "X86ISD::PTEST";
18844 case X86ISD::TESTP: return "X86ISD::TESTP";
18845 case X86ISD::TESTM: return "X86ISD::TESTM";
18846 case X86ISD::TESTNM: return "X86ISD::TESTNM";
18847 case X86ISD::KORTEST: return "X86ISD::KORTEST";
18848 case X86ISD::PACKSS: return "X86ISD::PACKSS";
18849 case X86ISD::PACKUS: return "X86ISD::PACKUS";
18850 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
18851 case X86ISD::VALIGN: return "X86ISD::VALIGN";
18852 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
18853 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
18854 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
18855 case X86ISD::SHUFP: return "X86ISD::SHUFP";
18856 case X86ISD::SHUF128: return "X86ISD::SHUF128";
18857 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
18858 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
18859 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
18860 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
18861 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
18862 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
18863 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
18864 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
18865 case X86ISD::MOVSD: return "X86ISD::MOVSD";
18866 case X86ISD::MOVSS: return "X86ISD::MOVSS";
18867 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
18868 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
18869 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
18870 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
18871 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
18872 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
18873 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
18874 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
18875 case X86ISD::VPERMV: return "X86ISD::VPERMV";
18876 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
18877 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
18878 case X86ISD::VPERMI: return "X86ISD::VPERMI";
18879 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
18880 case X86ISD::VRANGE: return "X86ISD::VRANGE";
18881 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
18882 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
18883 case X86ISD::PSADBW: return "X86ISD::PSADBW";
18884 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18885 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
18886 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
18887 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
18888 case X86ISD::MFENCE: return "X86ISD::MFENCE";
18889 case X86ISD::SFENCE: return "X86ISD::SFENCE";
18890 case X86ISD::LFENCE: return "X86ISD::LFENCE";
18891 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
18892 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
18893 case X86ISD::SAHF: return "X86ISD::SAHF";
18894 case X86ISD::RDRAND: return "X86ISD::RDRAND";
18895 case X86ISD::RDSEED: return "X86ISD::RDSEED";
18896 case X86ISD::FMADD: return "X86ISD::FMADD";
18897 case X86ISD::FMSUB: return "X86ISD::FMSUB";
18898 case X86ISD::FNMADD: return "X86ISD::FNMADD";
18899 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
18900 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
18901 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
18902 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
18903 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
18904 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
18905 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
18906 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
18907 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
18908 case X86ISD::RNDSCALE: return "X86ISD::RNDSCALE";
18909 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
18910 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
18911 case X86ISD::XTEST: return "X86ISD::XTEST";
18912 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
18913 case X86ISD::EXPAND: return "X86ISD::EXPAND";
18914 case X86ISD::SELECT: return "X86ISD::SELECT";
18915 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
18916 case X86ISD::RCP28: return "X86ISD::RCP28";
18917 case X86ISD::EXP2: return "X86ISD::EXP2";
18918 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
18919 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
18920 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
18921 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
18922 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
18923 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
18924 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
18925 case X86ISD::SCALEF: return "X86ISD::SCALEF";
18926 case X86ISD::ADDS: return "X86ISD::ADDS";
18927 case X86ISD::SUBS: return "X86ISD::SUBS";
18928 case X86ISD::AVG: return "X86ISD::AVG";
18929 case X86ISD::MULHRS: return "X86ISD::MULHRS";
18930 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
18931 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
18936 // isLegalAddressingMode - Return true if the addressing mode represented
18937 // by AM is legal for this target, for a load/store of the specified type.
18938 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18940 unsigned AS) const {
18941 // X86 supports extremely general addressing modes.
18942 CodeModel::Model M = getTargetMachine().getCodeModel();
18943 Reloc::Model R = getTargetMachine().getRelocationModel();
18945 // X86 allows a sign-extended 32-bit immediate field as a displacement.
18946 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18951 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18953 // If a reference to this global requires an extra load, we can't fold it.
18954 if (isGlobalStubReference(GVFlags))
18957 // If BaseGV requires a register for the PIC base, we cannot also have a
18958 // BaseReg specified.
18959 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18962 // If lower 4G is not available, then we must use rip-relative addressing.
18963 if ((M != CodeModel::Small || R != Reloc::Static) &&
18964 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18968 switch (AM.Scale) {
18974 // These scales always work.
18979 // These scales are formed with basereg+scalereg. Only accept if there is
18984 default: // Other stuff never works.
18991 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18992 unsigned Bits = Ty->getScalarSizeInBits();
18994 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18995 // particularly cheaper than those without.
18999 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19000 // variable shifts just as cheap as scalar ones.
19001 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19004 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19005 // fully general vector.
19009 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19010 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19012 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19013 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19014 return NumBits1 > NumBits2;
19017 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19018 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19021 if (!isTypeLegal(EVT::getEVT(Ty1)))
19024 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19026 // Assuming the caller doesn't have a zeroext or signext return parameter,
19027 // truncation all the way down to i1 is valid.
19031 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19032 return isInt<32>(Imm);
19035 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19036 // Can also use sub to handle negated immediates.
19037 return isInt<32>(Imm);
19040 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19041 if (!VT1.isInteger() || !VT2.isInteger())
19043 unsigned NumBits1 = VT1.getSizeInBits();
19044 unsigned NumBits2 = VT2.getSizeInBits();
19045 return NumBits1 > NumBits2;
19048 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19049 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19050 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19053 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19054 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19055 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19058 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19059 EVT VT1 = Val.getValueType();
19060 if (isZExtFree(VT1, VT2))
19063 if (Val.getOpcode() != ISD::LOAD)
19066 if (!VT1.isSimple() || !VT1.isInteger() ||
19067 !VT2.isSimple() || !VT2.isInteger())
19070 switch (VT1.getSimpleVT().SimpleTy) {
19075 // X86 has 8, 16, and 32-bit zero-extending loads.
19082 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19085 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19086 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19089 VT = VT.getScalarType();
19091 if (!VT.isSimple())
19094 switch (VT.getSimpleVT().SimpleTy) {
19105 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19106 // i16 instructions are longer (0x66 prefix) and potentially slower.
19107 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19110 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19111 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19112 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19113 /// are assumed to be legal.
19115 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19117 if (!VT.isSimple())
19120 // Not for i1 vectors
19121 if (VT.getScalarType() == MVT::i1)
19124 // Very little shuffling can be done for 64-bit vectors right now.
19125 if (VT.getSizeInBits() == 64)
19128 // We only care that the types being shuffled are legal. The lowering can
19129 // handle any possible shuffle mask that results.
19130 return isTypeLegal(VT.getSimpleVT());
19134 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19136 // Just delegate to the generic legality, clear masks aren't special.
19137 return isShuffleMaskLegal(Mask, VT);
19140 //===----------------------------------------------------------------------===//
19141 // X86 Scheduler Hooks
19142 //===----------------------------------------------------------------------===//
19144 /// Utility function to emit xbegin specifying the start of an RTM region.
19145 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19146 const TargetInstrInfo *TII) {
19147 DebugLoc DL = MI->getDebugLoc();
19149 const BasicBlock *BB = MBB->getBasicBlock();
19150 MachineFunction::iterator I = MBB;
19153 // For the v = xbegin(), we generate
19164 MachineBasicBlock *thisMBB = MBB;
19165 MachineFunction *MF = MBB->getParent();
19166 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19167 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19168 MF->insert(I, mainMBB);
19169 MF->insert(I, sinkMBB);
19171 // Transfer the remainder of BB and its successor edges to sinkMBB.
19172 sinkMBB->splice(sinkMBB->begin(), MBB,
19173 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19174 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19178 // # fallthrough to mainMBB
19179 // # abortion to sinkMBB
19180 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19181 thisMBB->addSuccessor(mainMBB);
19182 thisMBB->addSuccessor(sinkMBB);
19186 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19187 mainMBB->addSuccessor(sinkMBB);
19190 // EAX is live into the sinkMBB
19191 sinkMBB->addLiveIn(X86::EAX);
19192 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19193 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19196 MI->eraseFromParent();
19200 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19201 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19202 // in the .td file.
19203 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19204 const TargetInstrInfo *TII) {
19206 switch (MI->getOpcode()) {
19207 default: llvm_unreachable("illegal opcode!");
19208 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19209 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19210 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19211 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19212 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19213 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19214 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19215 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19218 DebugLoc dl = MI->getDebugLoc();
19219 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19221 unsigned NumArgs = MI->getNumOperands();
19222 for (unsigned i = 1; i < NumArgs; ++i) {
19223 MachineOperand &Op = MI->getOperand(i);
19224 if (!(Op.isReg() && Op.isImplicit()))
19225 MIB.addOperand(Op);
19227 if (MI->hasOneMemOperand())
19228 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19230 BuildMI(*BB, MI, dl,
19231 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19232 .addReg(X86::XMM0);
19234 MI->eraseFromParent();
19238 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19239 // defs in an instruction pattern
19240 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19241 const TargetInstrInfo *TII) {
19243 switch (MI->getOpcode()) {
19244 default: llvm_unreachable("illegal opcode!");
19245 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19246 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19247 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19248 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19249 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19250 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19251 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19252 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19255 DebugLoc dl = MI->getDebugLoc();
19256 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19258 unsigned NumArgs = MI->getNumOperands(); // remove the results
19259 for (unsigned i = 1; i < NumArgs; ++i) {
19260 MachineOperand &Op = MI->getOperand(i);
19261 if (!(Op.isReg() && Op.isImplicit()))
19262 MIB.addOperand(Op);
19264 if (MI->hasOneMemOperand())
19265 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19267 BuildMI(*BB, MI, dl,
19268 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19271 MI->eraseFromParent();
19275 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19276 const X86Subtarget *Subtarget) {
19277 DebugLoc dl = MI->getDebugLoc();
19278 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19279 // Address into RAX/EAX, other two args into ECX, EDX.
19280 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19281 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19282 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19283 for (int i = 0; i < X86::AddrNumOperands; ++i)
19284 MIB.addOperand(MI->getOperand(i));
19286 unsigned ValOps = X86::AddrNumOperands;
19287 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19288 .addReg(MI->getOperand(ValOps).getReg());
19289 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19290 .addReg(MI->getOperand(ValOps+1).getReg());
19292 // The instruction doesn't actually take any operands though.
19293 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19295 MI->eraseFromParent(); // The pseudo is gone now.
19299 MachineBasicBlock *
19300 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19301 MachineBasicBlock *MBB) const {
19302 // Emit va_arg instruction on X86-64.
19304 // Operands to this pseudo-instruction:
19305 // 0 ) Output : destination address (reg)
19306 // 1-5) Input : va_list address (addr, i64mem)
19307 // 6 ) ArgSize : Size (in bytes) of vararg type
19308 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19309 // 8 ) Align : Alignment of type
19310 // 9 ) EFLAGS (implicit-def)
19312 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19313 static_assert(X86::AddrNumOperands == 5,
19314 "VAARG_64 assumes 5 address operands");
19316 unsigned DestReg = MI->getOperand(0).getReg();
19317 MachineOperand &Base = MI->getOperand(1);
19318 MachineOperand &Scale = MI->getOperand(2);
19319 MachineOperand &Index = MI->getOperand(3);
19320 MachineOperand &Disp = MI->getOperand(4);
19321 MachineOperand &Segment = MI->getOperand(5);
19322 unsigned ArgSize = MI->getOperand(6).getImm();
19323 unsigned ArgMode = MI->getOperand(7).getImm();
19324 unsigned Align = MI->getOperand(8).getImm();
19326 // Memory Reference
19327 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19328 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19329 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19331 // Machine Information
19332 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19333 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19334 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19335 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19336 DebugLoc DL = MI->getDebugLoc();
19338 // struct va_list {
19341 // i64 overflow_area (address)
19342 // i64 reg_save_area (address)
19344 // sizeof(va_list) = 24
19345 // alignment(va_list) = 8
19347 unsigned TotalNumIntRegs = 6;
19348 unsigned TotalNumXMMRegs = 8;
19349 bool UseGPOffset = (ArgMode == 1);
19350 bool UseFPOffset = (ArgMode == 2);
19351 unsigned MaxOffset = TotalNumIntRegs * 8 +
19352 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19354 /* Align ArgSize to a multiple of 8 */
19355 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19356 bool NeedsAlign = (Align > 8);
19358 MachineBasicBlock *thisMBB = MBB;
19359 MachineBasicBlock *overflowMBB;
19360 MachineBasicBlock *offsetMBB;
19361 MachineBasicBlock *endMBB;
19363 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19364 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19365 unsigned OffsetReg = 0;
19367 if (!UseGPOffset && !UseFPOffset) {
19368 // If we only pull from the overflow region, we don't create a branch.
19369 // We don't need to alter control flow.
19370 OffsetDestReg = 0; // unused
19371 OverflowDestReg = DestReg;
19373 offsetMBB = nullptr;
19374 overflowMBB = thisMBB;
19377 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19378 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19379 // If not, pull from overflow_area. (branch to overflowMBB)
19384 // offsetMBB overflowMBB
19389 // Registers for the PHI in endMBB
19390 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19391 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19393 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19394 MachineFunction *MF = MBB->getParent();
19395 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19396 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19397 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19399 MachineFunction::iterator MBBIter = MBB;
19402 // Insert the new basic blocks
19403 MF->insert(MBBIter, offsetMBB);
19404 MF->insert(MBBIter, overflowMBB);
19405 MF->insert(MBBIter, endMBB);
19407 // Transfer the remainder of MBB and its successor edges to endMBB.
19408 endMBB->splice(endMBB->begin(), thisMBB,
19409 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19410 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19412 // Make offsetMBB and overflowMBB successors of thisMBB
19413 thisMBB->addSuccessor(offsetMBB);
19414 thisMBB->addSuccessor(overflowMBB);
19416 // endMBB is a successor of both offsetMBB and overflowMBB
19417 offsetMBB->addSuccessor(endMBB);
19418 overflowMBB->addSuccessor(endMBB);
19420 // Load the offset value into a register
19421 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19422 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19426 .addDisp(Disp, UseFPOffset ? 4 : 0)
19427 .addOperand(Segment)
19428 .setMemRefs(MMOBegin, MMOEnd);
19430 // Check if there is enough room left to pull this argument.
19431 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19433 .addImm(MaxOffset + 8 - ArgSizeA8);
19435 // Branch to "overflowMBB" if offset >= max
19436 // Fall through to "offsetMBB" otherwise
19437 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19438 .addMBB(overflowMBB);
19441 // In offsetMBB, emit code to use the reg_save_area.
19443 assert(OffsetReg != 0);
19445 // Read the reg_save_area address.
19446 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19447 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19452 .addOperand(Segment)
19453 .setMemRefs(MMOBegin, MMOEnd);
19455 // Zero-extend the offset
19456 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19457 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19460 .addImm(X86::sub_32bit);
19462 // Add the offset to the reg_save_area to get the final address.
19463 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19464 .addReg(OffsetReg64)
19465 .addReg(RegSaveReg);
19467 // Compute the offset for the next argument
19468 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19469 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19471 .addImm(UseFPOffset ? 16 : 8);
19473 // Store it back into the va_list.
19474 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19478 .addDisp(Disp, UseFPOffset ? 4 : 0)
19479 .addOperand(Segment)
19480 .addReg(NextOffsetReg)
19481 .setMemRefs(MMOBegin, MMOEnd);
19484 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19489 // Emit code to use overflow area
19492 // Load the overflow_area address into a register.
19493 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19494 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19499 .addOperand(Segment)
19500 .setMemRefs(MMOBegin, MMOEnd);
19502 // If we need to align it, do so. Otherwise, just copy the address
19503 // to OverflowDestReg.
19505 // Align the overflow address
19506 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19507 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19509 // aligned_addr = (addr + (align-1)) & ~(align-1)
19510 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19511 .addReg(OverflowAddrReg)
19514 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19516 .addImm(~(uint64_t)(Align-1));
19518 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19519 .addReg(OverflowAddrReg);
19522 // Compute the next overflow address after this argument.
19523 // (the overflow address should be kept 8-byte aligned)
19524 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19525 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19526 .addReg(OverflowDestReg)
19527 .addImm(ArgSizeA8);
19529 // Store the new overflow address.
19530 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19535 .addOperand(Segment)
19536 .addReg(NextAddrReg)
19537 .setMemRefs(MMOBegin, MMOEnd);
19539 // If we branched, emit the PHI to the front of endMBB.
19541 BuildMI(*endMBB, endMBB->begin(), DL,
19542 TII->get(X86::PHI), DestReg)
19543 .addReg(OffsetDestReg).addMBB(offsetMBB)
19544 .addReg(OverflowDestReg).addMBB(overflowMBB);
19547 // Erase the pseudo instruction
19548 MI->eraseFromParent();
19553 MachineBasicBlock *
19554 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19556 MachineBasicBlock *MBB) const {
19557 // Emit code to save XMM registers to the stack. The ABI says that the
19558 // number of registers to save is given in %al, so it's theoretically
19559 // possible to do an indirect jump trick to avoid saving all of them,
19560 // however this code takes a simpler approach and just executes all
19561 // of the stores if %al is non-zero. It's less code, and it's probably
19562 // easier on the hardware branch predictor, and stores aren't all that
19563 // expensive anyway.
19565 // Create the new basic blocks. One block contains all the XMM stores,
19566 // and one block is the final destination regardless of whether any
19567 // stores were performed.
19568 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19569 MachineFunction *F = MBB->getParent();
19570 MachineFunction::iterator MBBIter = MBB;
19572 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19573 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19574 F->insert(MBBIter, XMMSaveMBB);
19575 F->insert(MBBIter, EndMBB);
19577 // Transfer the remainder of MBB and its successor edges to EndMBB.
19578 EndMBB->splice(EndMBB->begin(), MBB,
19579 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19580 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19582 // The original block will now fall through to the XMM save block.
19583 MBB->addSuccessor(XMMSaveMBB);
19584 // The XMMSaveMBB will fall through to the end block.
19585 XMMSaveMBB->addSuccessor(EndMBB);
19587 // Now add the instructions.
19588 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19589 DebugLoc DL = MI->getDebugLoc();
19591 unsigned CountReg = MI->getOperand(0).getReg();
19592 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19593 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19595 if (!Subtarget->isTargetWin64()) {
19596 // If %al is 0, branch around the XMM save block.
19597 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19598 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19599 MBB->addSuccessor(EndMBB);
19602 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19603 // that was just emitted, but clearly shouldn't be "saved".
19604 assert((MI->getNumOperands() <= 3 ||
19605 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19606 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19607 && "Expected last argument to be EFLAGS");
19608 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19609 // In the XMM save block, save all the XMM argument registers.
19610 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19611 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19612 MachineMemOperand *MMO =
19613 F->getMachineMemOperand(
19614 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19615 MachineMemOperand::MOStore,
19616 /*Size=*/16, /*Align=*/16);
19617 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19618 .addFrameIndex(RegSaveFrameIndex)
19619 .addImm(/*Scale=*/1)
19620 .addReg(/*IndexReg=*/0)
19621 .addImm(/*Disp=*/Offset)
19622 .addReg(/*Segment=*/0)
19623 .addReg(MI->getOperand(i).getReg())
19624 .addMemOperand(MMO);
19627 MI->eraseFromParent(); // The pseudo instruction is gone now.
19632 // The EFLAGS operand of SelectItr might be missing a kill marker
19633 // because there were multiple uses of EFLAGS, and ISel didn't know
19634 // which to mark. Figure out whether SelectItr should have had a
19635 // kill marker, and set it if it should. Returns the correct kill
19637 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19638 MachineBasicBlock* BB,
19639 const TargetRegisterInfo* TRI) {
19640 // Scan forward through BB for a use/def of EFLAGS.
19641 MachineBasicBlock::iterator miI(std::next(SelectItr));
19642 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19643 const MachineInstr& mi = *miI;
19644 if (mi.readsRegister(X86::EFLAGS))
19646 if (mi.definesRegister(X86::EFLAGS))
19647 break; // Should have kill-flag - update below.
19650 // If we hit the end of the block, check whether EFLAGS is live into a
19652 if (miI == BB->end()) {
19653 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19654 sEnd = BB->succ_end();
19655 sItr != sEnd; ++sItr) {
19656 MachineBasicBlock* succ = *sItr;
19657 if (succ->isLiveIn(X86::EFLAGS))
19662 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19663 // out. SelectMI should have a kill flag on EFLAGS.
19664 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19668 MachineBasicBlock *
19669 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19670 MachineBasicBlock *BB) const {
19671 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19672 DebugLoc DL = MI->getDebugLoc();
19674 // To "insert" a SELECT_CC instruction, we actually have to insert the
19675 // diamond control-flow pattern. The incoming instruction knows the
19676 // destination vreg to set, the condition code register to branch on, the
19677 // true/false values to select between, and a branch opcode to use.
19678 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19679 MachineFunction::iterator It = BB;
19685 // cmpTY ccX, r1, r2
19687 // fallthrough --> copy0MBB
19688 MachineBasicBlock *thisMBB = BB;
19689 MachineFunction *F = BB->getParent();
19691 // We also lower double CMOVs:
19692 // (CMOV (CMOV F, T, cc1), T, cc2)
19693 // to two successives branches. For that, we look for another CMOV as the
19694 // following instruction.
19696 // Without this, we would add a PHI between the two jumps, which ends up
19697 // creating a few copies all around. For instance, for
19699 // (sitofp (zext (fcmp une)))
19701 // we would generate:
19703 // ucomiss %xmm1, %xmm0
19704 // movss <1.0f>, %xmm0
19705 // movaps %xmm0, %xmm1
19707 // xorps %xmm1, %xmm1
19710 // movaps %xmm1, %xmm0
19714 // because this custom-inserter would have generated:
19726 // A: X = ...; Y = ...
19728 // C: Z = PHI [X, A], [Y, B]
19730 // E: PHI [X, C], [Z, D]
19732 // If we lower both CMOVs in a single step, we can instead generate:
19744 // A: X = ...; Y = ...
19746 // E: PHI [X, A], [X, C], [Y, D]
19748 // Which, in our sitofp/fcmp example, gives us something like:
19750 // ucomiss %xmm1, %xmm0
19751 // movss <1.0f>, %xmm0
19754 // xorps %xmm0, %xmm0
19758 MachineInstr *NextCMOV = nullptr;
19759 MachineBasicBlock::iterator NextMIIt =
19760 std::next(MachineBasicBlock::iterator(MI));
19761 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19762 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19763 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19764 NextCMOV = &*NextMIIt;
19766 MachineBasicBlock *jcc1MBB = nullptr;
19768 // If we have a double CMOV, we lower it to two successive branches to
19769 // the same block. EFLAGS is used by both, so mark it as live in the second.
19771 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19772 F->insert(It, jcc1MBB);
19773 jcc1MBB->addLiveIn(X86::EFLAGS);
19776 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19777 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19778 F->insert(It, copy0MBB);
19779 F->insert(It, sinkMBB);
19781 // If the EFLAGS register isn't dead in the terminator, then claim that it's
19782 // live into the sink and copy blocks.
19783 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19785 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19786 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19787 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19788 copy0MBB->addLiveIn(X86::EFLAGS);
19789 sinkMBB->addLiveIn(X86::EFLAGS);
19792 // Transfer the remainder of BB and its successor edges to sinkMBB.
19793 sinkMBB->splice(sinkMBB->begin(), BB,
19794 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19795 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19797 // Add the true and fallthrough blocks as its successors.
19799 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19800 BB->addSuccessor(jcc1MBB);
19802 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19803 // jump to the sinkMBB.
19804 jcc1MBB->addSuccessor(copy0MBB);
19805 jcc1MBB->addSuccessor(sinkMBB);
19807 BB->addSuccessor(copy0MBB);
19810 // The true block target of the first (or only) branch is always sinkMBB.
19811 BB->addSuccessor(sinkMBB);
19813 // Create the conditional branch instruction.
19815 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19816 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19819 unsigned Opc2 = X86::GetCondBranchFromCond(
19820 (X86::CondCode)NextCMOV->getOperand(3).getImm());
19821 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19825 // %FalseValue = ...
19826 // # fallthrough to sinkMBB
19827 copy0MBB->addSuccessor(sinkMBB);
19830 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19832 MachineInstrBuilder MIB =
19833 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19834 MI->getOperand(0).getReg())
19835 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19836 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19838 // If we have a double CMOV, the second Jcc provides the same incoming
19839 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19841 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19842 // Copy the PHI result to the register defined by the second CMOV.
19843 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19844 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19845 .addReg(MI->getOperand(0).getReg());
19846 NextCMOV->eraseFromParent();
19849 MI->eraseFromParent(); // The pseudo instruction is gone now.
19853 MachineBasicBlock *
19854 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19855 MachineBasicBlock *BB) const {
19856 MachineFunction *MF = BB->getParent();
19857 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19858 DebugLoc DL = MI->getDebugLoc();
19859 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19861 assert(MF->shouldSplitStack());
19863 const bool Is64Bit = Subtarget->is64Bit();
19864 const bool IsLP64 = Subtarget->isTarget64BitLP64();
19866 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19867 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19870 // ... [Till the alloca]
19871 // If stacklet is not large enough, jump to mallocMBB
19874 // Allocate by subtracting from RSP
19875 // Jump to continueMBB
19878 // Allocate by call to runtime
19882 // [rest of original BB]
19885 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19886 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19887 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19889 MachineRegisterInfo &MRI = MF->getRegInfo();
19890 const TargetRegisterClass *AddrRegClass =
19891 getRegClassFor(getPointerTy());
19893 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19894 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19895 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19896 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19897 sizeVReg = MI->getOperand(1).getReg(),
19898 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19900 MachineFunction::iterator MBBIter = BB;
19903 MF->insert(MBBIter, bumpMBB);
19904 MF->insert(MBBIter, mallocMBB);
19905 MF->insert(MBBIter, continueMBB);
19907 continueMBB->splice(continueMBB->begin(), BB,
19908 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19909 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19911 // Add code to the main basic block to check if the stack limit has been hit,
19912 // and if so, jump to mallocMBB otherwise to bumpMBB.
19913 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19914 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19915 .addReg(tmpSPVReg).addReg(sizeVReg);
19916 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19917 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19918 .addReg(SPLimitVReg);
19919 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19921 // bumpMBB simply decreases the stack pointer, since we know the current
19922 // stacklet has enough space.
19923 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19924 .addReg(SPLimitVReg);
19925 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19926 .addReg(SPLimitVReg);
19927 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19929 // Calls into a routine in libgcc to allocate more space from the heap.
19930 const uint32_t *RegMask =
19931 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19933 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19935 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19936 .addExternalSymbol("__morestack_allocate_stack_space")
19937 .addRegMask(RegMask)
19938 .addReg(X86::RDI, RegState::Implicit)
19939 .addReg(X86::RAX, RegState::ImplicitDefine);
19940 } else if (Is64Bit) {
19941 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19943 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19944 .addExternalSymbol("__morestack_allocate_stack_space")
19945 .addRegMask(RegMask)
19946 .addReg(X86::EDI, RegState::Implicit)
19947 .addReg(X86::EAX, RegState::ImplicitDefine);
19949 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19951 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19952 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19953 .addExternalSymbol("__morestack_allocate_stack_space")
19954 .addRegMask(RegMask)
19955 .addReg(X86::EAX, RegState::ImplicitDefine);
19959 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19962 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19963 .addReg(IsLP64 ? X86::RAX : X86::EAX);
19964 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19966 // Set up the CFG correctly.
19967 BB->addSuccessor(bumpMBB);
19968 BB->addSuccessor(mallocMBB);
19969 mallocMBB->addSuccessor(continueMBB);
19970 bumpMBB->addSuccessor(continueMBB);
19972 // Take care of the PHI nodes.
19973 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19974 MI->getOperand(0).getReg())
19975 .addReg(mallocPtrVReg).addMBB(mallocMBB)
19976 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19978 // Delete the original pseudo instruction.
19979 MI->eraseFromParent();
19982 return continueMBB;
19985 MachineBasicBlock *
19986 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19987 MachineBasicBlock *BB) const {
19988 DebugLoc DL = MI->getDebugLoc();
19990 assert(!Subtarget->isTargetMachO());
19992 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
19995 MI->eraseFromParent(); // The pseudo instruction is gone now.
19999 MachineBasicBlock *
20000 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20001 MachineBasicBlock *BB) const {
20002 // This is pretty easy. We're taking the value that we received from
20003 // our load from the relocation, sticking it in either RDI (x86-64)
20004 // or EAX and doing an indirect call. The return value will then
20005 // be in the normal return register.
20006 MachineFunction *F = BB->getParent();
20007 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20008 DebugLoc DL = MI->getDebugLoc();
20010 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20011 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20013 // Get a register mask for the lowered call.
20014 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20015 // proper register mask.
20016 const uint32_t *RegMask =
20017 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20018 if (Subtarget->is64Bit()) {
20019 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20020 TII->get(X86::MOV64rm), X86::RDI)
20022 .addImm(0).addReg(0)
20023 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20024 MI->getOperand(3).getTargetFlags())
20026 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20027 addDirectMem(MIB, X86::RDI);
20028 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20029 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20030 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20031 TII->get(X86::MOV32rm), X86::EAX)
20033 .addImm(0).addReg(0)
20034 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20035 MI->getOperand(3).getTargetFlags())
20037 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20038 addDirectMem(MIB, X86::EAX);
20039 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20041 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20042 TII->get(X86::MOV32rm), X86::EAX)
20043 .addReg(TII->getGlobalBaseReg(F))
20044 .addImm(0).addReg(0)
20045 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20046 MI->getOperand(3).getTargetFlags())
20048 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20049 addDirectMem(MIB, X86::EAX);
20050 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20053 MI->eraseFromParent(); // The pseudo instruction is gone now.
20057 MachineBasicBlock *
20058 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20059 MachineBasicBlock *MBB) const {
20060 DebugLoc DL = MI->getDebugLoc();
20061 MachineFunction *MF = MBB->getParent();
20062 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20063 MachineRegisterInfo &MRI = MF->getRegInfo();
20065 const BasicBlock *BB = MBB->getBasicBlock();
20066 MachineFunction::iterator I = MBB;
20069 // Memory Reference
20070 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20071 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20074 unsigned MemOpndSlot = 0;
20076 unsigned CurOp = 0;
20078 DstReg = MI->getOperand(CurOp++).getReg();
20079 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20080 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20081 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20082 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20084 MemOpndSlot = CurOp;
20086 MVT PVT = getPointerTy();
20087 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20088 "Invalid Pointer Size!");
20090 // For v = setjmp(buf), we generate
20093 // buf[LabelOffset] = restoreMBB
20094 // SjLjSetup restoreMBB
20100 // v = phi(main, restore)
20103 // if base pointer being used, load it from frame
20106 MachineBasicBlock *thisMBB = MBB;
20107 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20108 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20109 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20110 MF->insert(I, mainMBB);
20111 MF->insert(I, sinkMBB);
20112 MF->push_back(restoreMBB);
20114 MachineInstrBuilder MIB;
20116 // Transfer the remainder of BB and its successor edges to sinkMBB.
20117 sinkMBB->splice(sinkMBB->begin(), MBB,
20118 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20119 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20122 unsigned PtrStoreOpc = 0;
20123 unsigned LabelReg = 0;
20124 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20125 Reloc::Model RM = MF->getTarget().getRelocationModel();
20126 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20127 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20129 // Prepare IP either in reg or imm.
20130 if (!UseImmLabel) {
20131 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20132 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20133 LabelReg = MRI.createVirtualRegister(PtrRC);
20134 if (Subtarget->is64Bit()) {
20135 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20139 .addMBB(restoreMBB)
20142 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20143 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20144 .addReg(XII->getGlobalBaseReg(MF))
20147 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20151 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20153 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20154 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20155 if (i == X86::AddrDisp)
20156 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20158 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20161 MIB.addReg(LabelReg);
20163 MIB.addMBB(restoreMBB);
20164 MIB.setMemRefs(MMOBegin, MMOEnd);
20166 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20167 .addMBB(restoreMBB);
20169 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20170 MIB.addRegMask(RegInfo->getNoPreservedMask());
20171 thisMBB->addSuccessor(mainMBB);
20172 thisMBB->addSuccessor(restoreMBB);
20176 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20177 mainMBB->addSuccessor(sinkMBB);
20180 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20181 TII->get(X86::PHI), DstReg)
20182 .addReg(mainDstReg).addMBB(mainMBB)
20183 .addReg(restoreDstReg).addMBB(restoreMBB);
20186 if (RegInfo->hasBasePointer(*MF)) {
20187 const bool Uses64BitFramePtr =
20188 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20189 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20190 X86FI->setRestoreBasePointer(MF);
20191 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20192 unsigned BasePtr = RegInfo->getBaseRegister();
20193 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20194 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20195 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20196 .setMIFlag(MachineInstr::FrameSetup);
20198 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20199 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20200 restoreMBB->addSuccessor(sinkMBB);
20202 MI->eraseFromParent();
20206 MachineBasicBlock *
20207 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20208 MachineBasicBlock *MBB) const {
20209 DebugLoc DL = MI->getDebugLoc();
20210 MachineFunction *MF = MBB->getParent();
20211 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20212 MachineRegisterInfo &MRI = MF->getRegInfo();
20214 // Memory Reference
20215 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20216 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20218 MVT PVT = getPointerTy();
20219 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20220 "Invalid Pointer Size!");
20222 const TargetRegisterClass *RC =
20223 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20224 unsigned Tmp = MRI.createVirtualRegister(RC);
20225 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20226 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20227 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20228 unsigned SP = RegInfo->getStackRegister();
20230 MachineInstrBuilder MIB;
20232 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20233 const int64_t SPOffset = 2 * PVT.getStoreSize();
20235 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20236 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20239 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20240 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20241 MIB.addOperand(MI->getOperand(i));
20242 MIB.setMemRefs(MMOBegin, MMOEnd);
20244 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20245 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20246 if (i == X86::AddrDisp)
20247 MIB.addDisp(MI->getOperand(i), LabelOffset);
20249 MIB.addOperand(MI->getOperand(i));
20251 MIB.setMemRefs(MMOBegin, MMOEnd);
20253 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20254 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20255 if (i == X86::AddrDisp)
20256 MIB.addDisp(MI->getOperand(i), SPOffset);
20258 MIB.addOperand(MI->getOperand(i));
20260 MIB.setMemRefs(MMOBegin, MMOEnd);
20262 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20264 MI->eraseFromParent();
20268 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20269 // accumulator loops. Writing back to the accumulator allows the coalescer
20270 // to remove extra copies in the loop.
20271 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20272 MachineBasicBlock *
20273 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20274 MachineBasicBlock *MBB) const {
20275 MachineOperand &AddendOp = MI->getOperand(3);
20277 // Bail out early if the addend isn't a register - we can't switch these.
20278 if (!AddendOp.isReg())
20281 MachineFunction &MF = *MBB->getParent();
20282 MachineRegisterInfo &MRI = MF.getRegInfo();
20284 // Check whether the addend is defined by a PHI:
20285 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20286 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20287 if (!AddendDef.isPHI())
20290 // Look for the following pattern:
20292 // %addend = phi [%entry, 0], [%loop, %result]
20294 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20298 // %addend = phi [%entry, 0], [%loop, %result]
20300 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20302 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20303 assert(AddendDef.getOperand(i).isReg());
20304 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20305 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20306 if (&PHISrcInst == MI) {
20307 // Found a matching instruction.
20308 unsigned NewFMAOpc = 0;
20309 switch (MI->getOpcode()) {
20310 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20311 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20312 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20313 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20314 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20315 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20316 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20317 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20318 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20319 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20320 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20321 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20322 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20323 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20324 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20325 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20326 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20327 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20328 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20329 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20331 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20332 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20333 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20334 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20335 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20336 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20337 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20338 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20339 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20340 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20341 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20342 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20343 default: llvm_unreachable("Unrecognized FMA variant.");
20346 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20347 MachineInstrBuilder MIB =
20348 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20349 .addOperand(MI->getOperand(0))
20350 .addOperand(MI->getOperand(3))
20351 .addOperand(MI->getOperand(2))
20352 .addOperand(MI->getOperand(1));
20353 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20354 MI->eraseFromParent();
20361 MachineBasicBlock *
20362 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20363 MachineBasicBlock *BB) const {
20364 switch (MI->getOpcode()) {
20365 default: llvm_unreachable("Unexpected instr type to insert");
20366 case X86::TAILJMPd64:
20367 case X86::TAILJMPr64:
20368 case X86::TAILJMPm64:
20369 case X86::TAILJMPd64_REX:
20370 case X86::TAILJMPr64_REX:
20371 case X86::TAILJMPm64_REX:
20372 llvm_unreachable("TAILJMP64 would not be touched here.");
20373 case X86::TCRETURNdi64:
20374 case X86::TCRETURNri64:
20375 case X86::TCRETURNmi64:
20377 case X86::WIN_ALLOCA:
20378 return EmitLoweredWinAlloca(MI, BB);
20379 case X86::SEG_ALLOCA_32:
20380 case X86::SEG_ALLOCA_64:
20381 return EmitLoweredSegAlloca(MI, BB);
20382 case X86::TLSCall_32:
20383 case X86::TLSCall_64:
20384 return EmitLoweredTLSCall(MI, BB);
20385 case X86::CMOV_GR8:
20386 case X86::CMOV_FR32:
20387 case X86::CMOV_FR64:
20388 case X86::CMOV_V4F32:
20389 case X86::CMOV_V2F64:
20390 case X86::CMOV_V2I64:
20391 case X86::CMOV_V8F32:
20392 case X86::CMOV_V4F64:
20393 case X86::CMOV_V4I64:
20394 case X86::CMOV_V16F32:
20395 case X86::CMOV_V8F64:
20396 case X86::CMOV_V8I64:
20397 case X86::CMOV_GR16:
20398 case X86::CMOV_GR32:
20399 case X86::CMOV_RFP32:
20400 case X86::CMOV_RFP64:
20401 case X86::CMOV_RFP80:
20402 case X86::CMOV_V8I1:
20403 case X86::CMOV_V16I1:
20404 case X86::CMOV_V32I1:
20405 case X86::CMOV_V64I1:
20406 return EmitLoweredSelect(MI, BB);
20408 case X86::FP32_TO_INT16_IN_MEM:
20409 case X86::FP32_TO_INT32_IN_MEM:
20410 case X86::FP32_TO_INT64_IN_MEM:
20411 case X86::FP64_TO_INT16_IN_MEM:
20412 case X86::FP64_TO_INT32_IN_MEM:
20413 case X86::FP64_TO_INT64_IN_MEM:
20414 case X86::FP80_TO_INT16_IN_MEM:
20415 case X86::FP80_TO_INT32_IN_MEM:
20416 case X86::FP80_TO_INT64_IN_MEM: {
20417 MachineFunction *F = BB->getParent();
20418 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20419 DebugLoc DL = MI->getDebugLoc();
20421 // Change the floating point control register to use "round towards zero"
20422 // mode when truncating to an integer value.
20423 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20424 addFrameReference(BuildMI(*BB, MI, DL,
20425 TII->get(X86::FNSTCW16m)), CWFrameIdx);
20427 // Load the old value of the high byte of the control word...
20429 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20430 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20433 // Set the high part to be round to zero...
20434 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20437 // Reload the modified control word now...
20438 addFrameReference(BuildMI(*BB, MI, DL,
20439 TII->get(X86::FLDCW16m)), CWFrameIdx);
20441 // Restore the memory image of control word to original value
20442 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20445 // Get the X86 opcode to use.
20447 switch (MI->getOpcode()) {
20448 default: llvm_unreachable("illegal opcode!");
20449 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20450 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20451 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20452 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20453 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20454 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20455 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20456 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20457 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20461 MachineOperand &Op = MI->getOperand(0);
20463 AM.BaseType = X86AddressMode::RegBase;
20464 AM.Base.Reg = Op.getReg();
20466 AM.BaseType = X86AddressMode::FrameIndexBase;
20467 AM.Base.FrameIndex = Op.getIndex();
20469 Op = MI->getOperand(1);
20471 AM.Scale = Op.getImm();
20472 Op = MI->getOperand(2);
20474 AM.IndexReg = Op.getImm();
20475 Op = MI->getOperand(3);
20476 if (Op.isGlobal()) {
20477 AM.GV = Op.getGlobal();
20479 AM.Disp = Op.getImm();
20481 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20482 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20484 // Reload the original control word now.
20485 addFrameReference(BuildMI(*BB, MI, DL,
20486 TII->get(X86::FLDCW16m)), CWFrameIdx);
20488 MI->eraseFromParent(); // The pseudo instruction is gone now.
20491 // String/text processing lowering.
20492 case X86::PCMPISTRM128REG:
20493 case X86::VPCMPISTRM128REG:
20494 case X86::PCMPISTRM128MEM:
20495 case X86::VPCMPISTRM128MEM:
20496 case X86::PCMPESTRM128REG:
20497 case X86::VPCMPESTRM128REG:
20498 case X86::PCMPESTRM128MEM:
20499 case X86::VPCMPESTRM128MEM:
20500 assert(Subtarget->hasSSE42() &&
20501 "Target must have SSE4.2 or AVX features enabled");
20502 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20504 // String/text processing lowering.
20505 case X86::PCMPISTRIREG:
20506 case X86::VPCMPISTRIREG:
20507 case X86::PCMPISTRIMEM:
20508 case X86::VPCMPISTRIMEM:
20509 case X86::PCMPESTRIREG:
20510 case X86::VPCMPESTRIREG:
20511 case X86::PCMPESTRIMEM:
20512 case X86::VPCMPESTRIMEM:
20513 assert(Subtarget->hasSSE42() &&
20514 "Target must have SSE4.2 or AVX features enabled");
20515 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20517 // Thread synchronization.
20519 return EmitMonitor(MI, BB, Subtarget);
20523 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20525 case X86::VASTART_SAVE_XMM_REGS:
20526 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20528 case X86::VAARG_64:
20529 return EmitVAARG64WithCustomInserter(MI, BB);
20531 case X86::EH_SjLj_SetJmp32:
20532 case X86::EH_SjLj_SetJmp64:
20533 return emitEHSjLjSetJmp(MI, BB);
20535 case X86::EH_SjLj_LongJmp32:
20536 case X86::EH_SjLj_LongJmp64:
20537 return emitEHSjLjLongJmp(MI, BB);
20539 case TargetOpcode::STATEPOINT:
20540 // As an implementation detail, STATEPOINT shares the STACKMAP format at
20541 // this point in the process. We diverge later.
20542 return emitPatchPoint(MI, BB);
20544 case TargetOpcode::STACKMAP:
20545 case TargetOpcode::PATCHPOINT:
20546 return emitPatchPoint(MI, BB);
20548 case X86::VFMADDPDr213r:
20549 case X86::VFMADDPSr213r:
20550 case X86::VFMADDSDr213r:
20551 case X86::VFMADDSSr213r:
20552 case X86::VFMSUBPDr213r:
20553 case X86::VFMSUBPSr213r:
20554 case X86::VFMSUBSDr213r:
20555 case X86::VFMSUBSSr213r:
20556 case X86::VFNMADDPDr213r:
20557 case X86::VFNMADDPSr213r:
20558 case X86::VFNMADDSDr213r:
20559 case X86::VFNMADDSSr213r:
20560 case X86::VFNMSUBPDr213r:
20561 case X86::VFNMSUBPSr213r:
20562 case X86::VFNMSUBSDr213r:
20563 case X86::VFNMSUBSSr213r:
20564 case X86::VFMADDSUBPDr213r:
20565 case X86::VFMADDSUBPSr213r:
20566 case X86::VFMSUBADDPDr213r:
20567 case X86::VFMSUBADDPSr213r:
20568 case X86::VFMADDPDr213rY:
20569 case X86::VFMADDPSr213rY:
20570 case X86::VFMSUBPDr213rY:
20571 case X86::VFMSUBPSr213rY:
20572 case X86::VFNMADDPDr213rY:
20573 case X86::VFNMADDPSr213rY:
20574 case X86::VFNMSUBPDr213rY:
20575 case X86::VFNMSUBPSr213rY:
20576 case X86::VFMADDSUBPDr213rY:
20577 case X86::VFMADDSUBPSr213rY:
20578 case X86::VFMSUBADDPDr213rY:
20579 case X86::VFMSUBADDPSr213rY:
20580 return emitFMA3Instr(MI, BB);
20584 //===----------------------------------------------------------------------===//
20585 // X86 Optimization Hooks
20586 //===----------------------------------------------------------------------===//
20588 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20591 const SelectionDAG &DAG,
20592 unsigned Depth) const {
20593 unsigned BitWidth = KnownZero.getBitWidth();
20594 unsigned Opc = Op.getOpcode();
20595 assert((Opc >= ISD::BUILTIN_OP_END ||
20596 Opc == ISD::INTRINSIC_WO_CHAIN ||
20597 Opc == ISD::INTRINSIC_W_CHAIN ||
20598 Opc == ISD::INTRINSIC_VOID) &&
20599 "Should use MaskedValueIsZero if you don't know whether Op"
20600 " is a target node!");
20602 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
20616 // These nodes' second result is a boolean.
20617 if (Op.getResNo() == 0)
20620 case X86ISD::SETCC:
20621 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20623 case ISD::INTRINSIC_WO_CHAIN: {
20624 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20625 unsigned NumLoBits = 0;
20628 case Intrinsic::x86_sse_movmsk_ps:
20629 case Intrinsic::x86_avx_movmsk_ps_256:
20630 case Intrinsic::x86_sse2_movmsk_pd:
20631 case Intrinsic::x86_avx_movmsk_pd_256:
20632 case Intrinsic::x86_mmx_pmovmskb:
20633 case Intrinsic::x86_sse2_pmovmskb_128:
20634 case Intrinsic::x86_avx2_pmovmskb: {
20635 // High bits of movmskp{s|d}, pmovmskb are known zero.
20637 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
20638 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
20639 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
20640 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
20641 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
20642 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
20643 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
20644 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
20646 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20655 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20657 const SelectionDAG &,
20658 unsigned Depth) const {
20659 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20660 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20661 return Op.getValueType().getScalarType().getSizeInBits();
20667 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20668 /// node is a GlobalAddress + offset.
20669 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20670 const GlobalValue* &GA,
20671 int64_t &Offset) const {
20672 if (N->getOpcode() == X86ISD::Wrapper) {
20673 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20674 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20675 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20679 return TargetLowering::isGAPlusOffset(N, GA, Offset);
20682 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20683 /// same as extracting the high 128-bit part of 256-bit vector and then
20684 /// inserting the result into the low part of a new 256-bit vector
20685 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20686 EVT VT = SVOp->getValueType(0);
20687 unsigned NumElems = VT.getVectorNumElements();
20689 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20690 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20691 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20692 SVOp->getMaskElt(j) >= 0)
20698 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20699 /// same as extracting the low 128-bit part of 256-bit vector and then
20700 /// inserting the result into the high part of a new 256-bit vector
20701 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20702 EVT VT = SVOp->getValueType(0);
20703 unsigned NumElems = VT.getVectorNumElements();
20705 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20706 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20707 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20708 SVOp->getMaskElt(j) >= 0)
20714 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20715 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20716 TargetLowering::DAGCombinerInfo &DCI,
20717 const X86Subtarget* Subtarget) {
20719 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20720 SDValue V1 = SVOp->getOperand(0);
20721 SDValue V2 = SVOp->getOperand(1);
20722 EVT VT = SVOp->getValueType(0);
20723 unsigned NumElems = VT.getVectorNumElements();
20725 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20726 V2.getOpcode() == ISD::CONCAT_VECTORS) {
20730 // V UNDEF BUILD_VECTOR UNDEF
20732 // CONCAT_VECTOR CONCAT_VECTOR
20735 // RESULT: V + zero extended
20737 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20738 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20739 V1.getOperand(1).getOpcode() != ISD::UNDEF)
20742 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20745 // To match the shuffle mask, the first half of the mask should
20746 // be exactly the first vector, and all the rest a splat with the
20747 // first element of the second one.
20748 for (unsigned i = 0; i != NumElems/2; ++i)
20749 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20750 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20753 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20754 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20755 if (Ld->hasNUsesOfValue(1, 0)) {
20756 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20757 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20759 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20761 Ld->getPointerInfo(),
20762 Ld->getAlignment(),
20763 false/*isVolatile*/, true/*ReadMem*/,
20764 false/*WriteMem*/);
20766 // Make sure the newly-created LOAD is in the same position as Ld in
20767 // terms of dependency. We create a TokenFactor for Ld and ResNode,
20768 // and update uses of Ld's output chain to use the TokenFactor.
20769 if (Ld->hasAnyUseOfValue(1)) {
20770 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20771 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20772 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20773 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20774 SDValue(ResNode.getNode(), 1));
20777 return DAG.getBitcast(VT, ResNode);
20781 // Emit a zeroed vector and insert the desired subvector on its
20783 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20784 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20785 return DCI.CombineTo(N, InsV);
20788 //===--------------------------------------------------------------------===//
20789 // Combine some shuffles into subvector extracts and inserts:
20792 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20793 if (isShuffleHigh128VectorInsertLow(SVOp)) {
20794 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20795 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20796 return DCI.CombineTo(N, InsV);
20799 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20800 if (isShuffleLow128VectorInsertHigh(SVOp)) {
20801 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20802 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20803 return DCI.CombineTo(N, InsV);
20809 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20812 /// This is the leaf of the recursive combinine below. When we have found some
20813 /// chain of single-use x86 shuffle instructions and accumulated the combined
20814 /// shuffle mask represented by them, this will try to pattern match that mask
20815 /// into either a single instruction if there is a special purpose instruction
20816 /// for this operation, or into a PSHUFB instruction which is a fully general
20817 /// instruction but should only be used to replace chains over a certain depth.
20818 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20819 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20820 TargetLowering::DAGCombinerInfo &DCI,
20821 const X86Subtarget *Subtarget) {
20822 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20824 // Find the operand that enters the chain. Note that multiple uses are OK
20825 // here, we're not going to remove the operand we find.
20826 SDValue Input = Op.getOperand(0);
20827 while (Input.getOpcode() == ISD::BITCAST)
20828 Input = Input.getOperand(0);
20830 MVT VT = Input.getSimpleValueType();
20831 MVT RootVT = Root.getSimpleValueType();
20834 // Just remove no-op shuffle masks.
20835 if (Mask.size() == 1) {
20836 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20841 // Use the float domain if the operand type is a floating point type.
20842 bool FloatDomain = VT.isFloatingPoint();
20844 // For floating point shuffles, we don't have free copies in the shuffle
20845 // instructions or the ability to load as part of the instruction, so
20846 // canonicalize their shuffles to UNPCK or MOV variants.
20848 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20849 // vectors because it can have a load folded into it that UNPCK cannot. This
20850 // doesn't preclude something switching to the shorter encoding post-RA.
20852 // FIXME: Should teach these routines about AVX vector widths.
20853 if (FloatDomain && VT.getSizeInBits() == 128) {
20854 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20855 bool Lo = Mask.equals({0, 0});
20858 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20859 // is no slower than UNPCKLPD but has the option to fold the input operand
20860 // into even an unaligned memory load.
20861 if (Lo && Subtarget->hasSSE3()) {
20862 Shuffle = X86ISD::MOVDDUP;
20863 ShuffleVT = MVT::v2f64;
20865 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20866 // than the UNPCK variants.
20867 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20868 ShuffleVT = MVT::v4f32;
20870 if (Depth == 1 && Root->getOpcode() == Shuffle)
20871 return false; // Nothing to do!
20872 Op = DAG.getBitcast(ShuffleVT, Input);
20873 DCI.AddToWorklist(Op.getNode());
20874 if (Shuffle == X86ISD::MOVDDUP)
20875 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20877 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20878 DCI.AddToWorklist(Op.getNode());
20879 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20883 if (Subtarget->hasSSE3() &&
20884 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20885 bool Lo = Mask.equals({0, 0, 2, 2});
20886 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20887 MVT ShuffleVT = MVT::v4f32;
20888 if (Depth == 1 && Root->getOpcode() == Shuffle)
20889 return false; // Nothing to do!
20890 Op = DAG.getBitcast(ShuffleVT, Input);
20891 DCI.AddToWorklist(Op.getNode());
20892 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20893 DCI.AddToWorklist(Op.getNode());
20894 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20898 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20899 bool Lo = Mask.equals({0, 0, 1, 1});
20900 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20901 MVT ShuffleVT = MVT::v4f32;
20902 if (Depth == 1 && Root->getOpcode() == Shuffle)
20903 return false; // Nothing to do!
20904 Op = DAG.getBitcast(ShuffleVT, Input);
20905 DCI.AddToWorklist(Op.getNode());
20906 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20907 DCI.AddToWorklist(Op.getNode());
20908 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20914 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20915 // variants as none of these have single-instruction variants that are
20916 // superior to the UNPCK formulation.
20917 if (!FloatDomain && VT.getSizeInBits() == 128 &&
20918 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20919 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20920 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20922 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20923 bool Lo = Mask[0] == 0;
20924 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20925 if (Depth == 1 && Root->getOpcode() == Shuffle)
20926 return false; // Nothing to do!
20928 switch (Mask.size()) {
20930 ShuffleVT = MVT::v8i16;
20933 ShuffleVT = MVT::v16i8;
20936 llvm_unreachable("Impossible mask size!");
20938 Op = DAG.getBitcast(ShuffleVT, Input);
20939 DCI.AddToWorklist(Op.getNode());
20940 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20941 DCI.AddToWorklist(Op.getNode());
20942 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20947 // Don't try to re-form single instruction chains under any circumstances now
20948 // that we've done encoding canonicalization for them.
20952 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20953 // can replace them with a single PSHUFB instruction profitably. Intel's
20954 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20955 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20956 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20957 SmallVector<SDValue, 16> PSHUFBMask;
20958 int NumBytes = VT.getSizeInBits() / 8;
20959 int Ratio = NumBytes / Mask.size();
20960 for (int i = 0; i < NumBytes; ++i) {
20961 if (Mask[i / Ratio] == SM_SentinelUndef) {
20962 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20965 int M = Mask[i / Ratio] != SM_SentinelZero
20966 ? Ratio * Mask[i / Ratio] + i % Ratio
20968 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20970 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20971 Op = DAG.getBitcast(ByteVT, Input);
20972 DCI.AddToWorklist(Op.getNode());
20973 SDValue PSHUFBMaskOp =
20974 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20975 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20976 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20977 DCI.AddToWorklist(Op.getNode());
20978 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20983 // Failed to find any combines.
20987 /// \brief Fully generic combining of x86 shuffle instructions.
20989 /// This should be the last combine run over the x86 shuffle instructions. Once
20990 /// they have been fully optimized, this will recursively consider all chains
20991 /// of single-use shuffle instructions, build a generic model of the cumulative
20992 /// shuffle operation, and check for simpler instructions which implement this
20993 /// operation. We use this primarily for two purposes:
20995 /// 1) Collapse generic shuffles to specialized single instructions when
20996 /// equivalent. In most cases, this is just an encoding size win, but
20997 /// sometimes we will collapse multiple generic shuffles into a single
20998 /// special-purpose shuffle.
20999 /// 2) Look for sequences of shuffle instructions with 3 or more total
21000 /// instructions, and replace them with the slightly more expensive SSSE3
21001 /// PSHUFB instruction if available. We do this as the last combining step
21002 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21003 /// a suitable short sequence of other instructions. The PHUFB will either
21004 /// use a register or have to read from memory and so is slightly (but only
21005 /// slightly) more expensive than the other shuffle instructions.
21007 /// Because this is inherently a quadratic operation (for each shuffle in
21008 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21009 /// This should never be an issue in practice as the shuffle lowering doesn't
21010 /// produce sequences of more than 8 instructions.
21012 /// FIXME: We will currently miss some cases where the redundant shuffling
21013 /// would simplify under the threshold for PSHUFB formation because of
21014 /// combine-ordering. To fix this, we should do the redundant instruction
21015 /// combining in this recursive walk.
21016 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21017 ArrayRef<int> RootMask,
21018 int Depth, bool HasPSHUFB,
21020 TargetLowering::DAGCombinerInfo &DCI,
21021 const X86Subtarget *Subtarget) {
21022 // Bound the depth of our recursive combine because this is ultimately
21023 // quadratic in nature.
21027 // Directly rip through bitcasts to find the underlying operand.
21028 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21029 Op = Op.getOperand(0);
21031 MVT VT = Op.getSimpleValueType();
21032 if (!VT.isVector())
21033 return false; // Bail if we hit a non-vector.
21035 assert(Root.getSimpleValueType().isVector() &&
21036 "Shuffles operate on vector types!");
21037 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21038 "Can only combine shuffles of the same vector register size.");
21040 if (!isTargetShuffle(Op.getOpcode()))
21042 SmallVector<int, 16> OpMask;
21044 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21045 // We only can combine unary shuffles which we can decode the mask for.
21046 if (!HaveMask || !IsUnary)
21049 assert(VT.getVectorNumElements() == OpMask.size() &&
21050 "Different mask size from vector size!");
21051 assert(((RootMask.size() > OpMask.size() &&
21052 RootMask.size() % OpMask.size() == 0) ||
21053 (OpMask.size() > RootMask.size() &&
21054 OpMask.size() % RootMask.size() == 0) ||
21055 OpMask.size() == RootMask.size()) &&
21056 "The smaller number of elements must divide the larger.");
21057 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21058 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21059 assert(((RootRatio == 1 && OpRatio == 1) ||
21060 (RootRatio == 1) != (OpRatio == 1)) &&
21061 "Must not have a ratio for both incoming and op masks!");
21063 SmallVector<int, 16> Mask;
21064 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21066 // Merge this shuffle operation's mask into our accumulated mask. Note that
21067 // this shuffle's mask will be the first applied to the input, followed by the
21068 // root mask to get us all the way to the root value arrangement. The reason
21069 // for this order is that we are recursing up the operation chain.
21070 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21071 int RootIdx = i / RootRatio;
21072 if (RootMask[RootIdx] < 0) {
21073 // This is a zero or undef lane, we're done.
21074 Mask.push_back(RootMask[RootIdx]);
21078 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21079 int OpIdx = RootMaskedIdx / OpRatio;
21080 if (OpMask[OpIdx] < 0) {
21081 // The incoming lanes are zero or undef, it doesn't matter which ones we
21083 Mask.push_back(OpMask[OpIdx]);
21087 // Ok, we have non-zero lanes, map them through.
21088 Mask.push_back(OpMask[OpIdx] * OpRatio +
21089 RootMaskedIdx % OpRatio);
21092 // See if we can recurse into the operand to combine more things.
21093 switch (Op.getOpcode()) {
21094 case X86ISD::PSHUFB:
21096 case X86ISD::PSHUFD:
21097 case X86ISD::PSHUFHW:
21098 case X86ISD::PSHUFLW:
21099 if (Op.getOperand(0).hasOneUse() &&
21100 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21101 HasPSHUFB, DAG, DCI, Subtarget))
21105 case X86ISD::UNPCKL:
21106 case X86ISD::UNPCKH:
21107 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21108 // We can't check for single use, we have to check that this shuffle is the only user.
21109 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21110 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21111 HasPSHUFB, DAG, DCI, Subtarget))
21116 // Minor canonicalization of the accumulated shuffle mask to make it easier
21117 // to match below. All this does is detect masks with squential pairs of
21118 // elements, and shrink them to the half-width mask. It does this in a loop
21119 // so it will reduce the size of the mask to the minimal width mask which
21120 // performs an equivalent shuffle.
21121 SmallVector<int, 16> WidenedMask;
21122 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21123 Mask = std::move(WidenedMask);
21124 WidenedMask.clear();
21127 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21131 /// \brief Get the PSHUF-style mask from PSHUF node.
21133 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21134 /// PSHUF-style masks that can be reused with such instructions.
21135 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21136 MVT VT = N.getSimpleValueType();
21137 SmallVector<int, 4> Mask;
21139 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21143 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21144 // matter. Check that the upper masks are repeats and remove them.
21145 if (VT.getSizeInBits() > 128) {
21146 int LaneElts = 128 / VT.getScalarSizeInBits();
21148 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21149 for (int j = 0; j < LaneElts; ++j)
21150 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21151 "Mask doesn't repeat in high 128-bit lanes!");
21153 Mask.resize(LaneElts);
21156 switch (N.getOpcode()) {
21157 case X86ISD::PSHUFD:
21159 case X86ISD::PSHUFLW:
21162 case X86ISD::PSHUFHW:
21163 Mask.erase(Mask.begin(), Mask.begin() + 4);
21164 for (int &M : Mask)
21168 llvm_unreachable("No valid shuffle instruction found!");
21172 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21174 /// We walk up the chain and look for a combinable shuffle, skipping over
21175 /// shuffles that we could hoist this shuffle's transformation past without
21176 /// altering anything.
21178 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21180 TargetLowering::DAGCombinerInfo &DCI) {
21181 assert(N.getOpcode() == X86ISD::PSHUFD &&
21182 "Called with something other than an x86 128-bit half shuffle!");
21185 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21186 // of the shuffles in the chain so that we can form a fresh chain to replace
21188 SmallVector<SDValue, 8> Chain;
21189 SDValue V = N.getOperand(0);
21190 for (; V.hasOneUse(); V = V.getOperand(0)) {
21191 switch (V.getOpcode()) {
21193 return SDValue(); // Nothing combined!
21196 // Skip bitcasts as we always know the type for the target specific
21200 case X86ISD::PSHUFD:
21201 // Found another dword shuffle.
21204 case X86ISD::PSHUFLW:
21205 // Check that the low words (being shuffled) are the identity in the
21206 // dword shuffle, and the high words are self-contained.
21207 if (Mask[0] != 0 || Mask[1] != 1 ||
21208 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21211 Chain.push_back(V);
21214 case X86ISD::PSHUFHW:
21215 // Check that the high words (being shuffled) are the identity in the
21216 // dword shuffle, and the low words are self-contained.
21217 if (Mask[2] != 2 || Mask[3] != 3 ||
21218 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21221 Chain.push_back(V);
21224 case X86ISD::UNPCKL:
21225 case X86ISD::UNPCKH:
21226 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21227 // shuffle into a preceding word shuffle.
21228 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21229 V.getSimpleValueType().getScalarType() != MVT::i16)
21232 // Search for a half-shuffle which we can combine with.
21233 unsigned CombineOp =
21234 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21235 if (V.getOperand(0) != V.getOperand(1) ||
21236 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21238 Chain.push_back(V);
21239 V = V.getOperand(0);
21241 switch (V.getOpcode()) {
21243 return SDValue(); // Nothing to combine.
21245 case X86ISD::PSHUFLW:
21246 case X86ISD::PSHUFHW:
21247 if (V.getOpcode() == CombineOp)
21250 Chain.push_back(V);
21254 V = V.getOperand(0);
21258 } while (V.hasOneUse());
21261 // Break out of the loop if we break out of the switch.
21265 if (!V.hasOneUse())
21266 // We fell out of the loop without finding a viable combining instruction.
21269 // Merge this node's mask and our incoming mask.
21270 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21271 for (int &M : Mask)
21273 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21274 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21276 // Rebuild the chain around this new shuffle.
21277 while (!Chain.empty()) {
21278 SDValue W = Chain.pop_back_val();
21280 if (V.getValueType() != W.getOperand(0).getValueType())
21281 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21283 switch (W.getOpcode()) {
21285 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21287 case X86ISD::UNPCKL:
21288 case X86ISD::UNPCKH:
21289 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21292 case X86ISD::PSHUFD:
21293 case X86ISD::PSHUFLW:
21294 case X86ISD::PSHUFHW:
21295 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21299 if (V.getValueType() != N.getValueType())
21300 V = DAG.getBitcast(N.getValueType(), V);
21302 // Return the new chain to replace N.
21306 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21308 /// We walk up the chain, skipping shuffles of the other half and looking
21309 /// through shuffles which switch halves trying to find a shuffle of the same
21310 /// pair of dwords.
21311 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21313 TargetLowering::DAGCombinerInfo &DCI) {
21315 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21316 "Called with something other than an x86 128-bit half shuffle!");
21318 unsigned CombineOpcode = N.getOpcode();
21320 // Walk up a single-use chain looking for a combinable shuffle.
21321 SDValue V = N.getOperand(0);
21322 for (; V.hasOneUse(); V = V.getOperand(0)) {
21323 switch (V.getOpcode()) {
21325 return false; // Nothing combined!
21328 // Skip bitcasts as we always know the type for the target specific
21332 case X86ISD::PSHUFLW:
21333 case X86ISD::PSHUFHW:
21334 if (V.getOpcode() == CombineOpcode)
21337 // Other-half shuffles are no-ops.
21340 // Break out of the loop if we break out of the switch.
21344 if (!V.hasOneUse())
21345 // We fell out of the loop without finding a viable combining instruction.
21348 // Combine away the bottom node as its shuffle will be accumulated into
21349 // a preceding shuffle.
21350 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21352 // Record the old value.
21355 // Merge this node's mask and our incoming mask (adjusted to account for all
21356 // the pshufd instructions encountered).
21357 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21358 for (int &M : Mask)
21360 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21361 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21363 // Check that the shuffles didn't cancel each other out. If not, we need to
21364 // combine to the new one.
21366 // Replace the combinable shuffle with the combined one, updating all users
21367 // so that we re-evaluate the chain here.
21368 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21373 /// \brief Try to combine x86 target specific shuffles.
21374 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21375 TargetLowering::DAGCombinerInfo &DCI,
21376 const X86Subtarget *Subtarget) {
21378 MVT VT = N.getSimpleValueType();
21379 SmallVector<int, 4> Mask;
21381 switch (N.getOpcode()) {
21382 case X86ISD::PSHUFD:
21383 case X86ISD::PSHUFLW:
21384 case X86ISD::PSHUFHW:
21385 Mask = getPSHUFShuffleMask(N);
21386 assert(Mask.size() == 4);
21392 // Nuke no-op shuffles that show up after combining.
21393 if (isNoopShuffleMask(Mask))
21394 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21396 // Look for simplifications involving one or two shuffle instructions.
21397 SDValue V = N.getOperand(0);
21398 switch (N.getOpcode()) {
21401 case X86ISD::PSHUFLW:
21402 case X86ISD::PSHUFHW:
21403 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21405 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21406 return SDValue(); // We combined away this shuffle, so we're done.
21408 // See if this reduces to a PSHUFD which is no more expensive and can
21409 // combine with more operations. Note that it has to at least flip the
21410 // dwords as otherwise it would have been removed as a no-op.
21411 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21412 int DMask[] = {0, 1, 2, 3};
21413 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21414 DMask[DOffset + 0] = DOffset + 1;
21415 DMask[DOffset + 1] = DOffset + 0;
21416 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21417 V = DAG.getBitcast(DVT, V);
21418 DCI.AddToWorklist(V.getNode());
21419 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21420 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21421 DCI.AddToWorklist(V.getNode());
21422 return DAG.getBitcast(VT, V);
21425 // Look for shuffle patterns which can be implemented as a single unpack.
21426 // FIXME: This doesn't handle the location of the PSHUFD generically, and
21427 // only works when we have a PSHUFD followed by two half-shuffles.
21428 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21429 (V.getOpcode() == X86ISD::PSHUFLW ||
21430 V.getOpcode() == X86ISD::PSHUFHW) &&
21431 V.getOpcode() != N.getOpcode() &&
21433 SDValue D = V.getOperand(0);
21434 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21435 D = D.getOperand(0);
21436 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21437 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21438 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21439 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21440 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21442 for (int i = 0; i < 4; ++i) {
21443 WordMask[i + NOffset] = Mask[i] + NOffset;
21444 WordMask[i + VOffset] = VMask[i] + VOffset;
21446 // Map the word mask through the DWord mask.
21448 for (int i = 0; i < 8; ++i)
21449 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21450 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21451 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21452 // We can replace all three shuffles with an unpack.
21453 V = DAG.getBitcast(VT, D.getOperand(0));
21454 DCI.AddToWorklist(V.getNode());
21455 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21464 case X86ISD::PSHUFD:
21465 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21474 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21476 /// We combine this directly on the abstract vector shuffle nodes so it is
21477 /// easier to generically match. We also insert dummy vector shuffle nodes for
21478 /// the operands which explicitly discard the lanes which are unused by this
21479 /// operation to try to flow through the rest of the combiner the fact that
21480 /// they're unused.
21481 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21483 EVT VT = N->getValueType(0);
21485 // We only handle target-independent shuffles.
21486 // FIXME: It would be easy and harmless to use the target shuffle mask
21487 // extraction tool to support more.
21488 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21491 auto *SVN = cast<ShuffleVectorSDNode>(N);
21492 ArrayRef<int> Mask = SVN->getMask();
21493 SDValue V1 = N->getOperand(0);
21494 SDValue V2 = N->getOperand(1);
21496 // We require the first shuffle operand to be the SUB node, and the second to
21497 // be the ADD node.
21498 // FIXME: We should support the commuted patterns.
21499 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21502 // If there are other uses of these operations we can't fold them.
21503 if (!V1->hasOneUse() || !V2->hasOneUse())
21506 // Ensure that both operations have the same operands. Note that we can
21507 // commute the FADD operands.
21508 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21509 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21510 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21513 // We're looking for blends between FADD and FSUB nodes. We insist on these
21514 // nodes being lined up in a specific expected pattern.
21515 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21516 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21517 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21520 // Only specific types are legal at this point, assert so we notice if and
21521 // when these change.
21522 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21523 VT == MVT::v4f64) &&
21524 "Unknown vector type encountered!");
21526 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21529 /// PerformShuffleCombine - Performs several different shuffle combines.
21530 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21531 TargetLowering::DAGCombinerInfo &DCI,
21532 const X86Subtarget *Subtarget) {
21534 SDValue N0 = N->getOperand(0);
21535 SDValue N1 = N->getOperand(1);
21536 EVT VT = N->getValueType(0);
21538 // Don't create instructions with illegal types after legalize types has run.
21539 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21540 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21543 // If we have legalized the vector types, look for blends of FADD and FSUB
21544 // nodes that we can fuse into an ADDSUB node.
21545 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21546 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21549 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21550 if (Subtarget->hasFp256() && VT.is256BitVector() &&
21551 N->getOpcode() == ISD::VECTOR_SHUFFLE)
21552 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21554 // During Type Legalization, when promoting illegal vector types,
21555 // the backend might introduce new shuffle dag nodes and bitcasts.
21557 // This code performs the following transformation:
21558 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21559 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21561 // We do this only if both the bitcast and the BINOP dag nodes have
21562 // one use. Also, perform this transformation only if the new binary
21563 // operation is legal. This is to avoid introducing dag nodes that
21564 // potentially need to be further expanded (or custom lowered) into a
21565 // less optimal sequence of dag nodes.
21566 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21567 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21568 N0.getOpcode() == ISD::BITCAST) {
21569 SDValue BC0 = N0.getOperand(0);
21570 EVT SVT = BC0.getValueType();
21571 unsigned Opcode = BC0.getOpcode();
21572 unsigned NumElts = VT.getVectorNumElements();
21574 if (BC0.hasOneUse() && SVT.isVector() &&
21575 SVT.getVectorNumElements() * 2 == NumElts &&
21576 TLI.isOperationLegal(Opcode, VT)) {
21577 bool CanFold = false;
21589 unsigned SVTNumElts = SVT.getVectorNumElements();
21590 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21591 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21592 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21593 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21594 CanFold = SVOp->getMaskElt(i) < 0;
21597 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21598 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21599 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21600 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21605 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21606 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21607 // consecutive, non-overlapping, and in the right order.
21608 SmallVector<SDValue, 16> Elts;
21609 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21610 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21612 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21615 if (isTargetShuffle(N->getOpcode())) {
21617 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21618 if (Shuffle.getNode())
21621 // Try recursively combining arbitrary sequences of x86 shuffle
21622 // instructions into higher-order shuffles. We do this after combining
21623 // specific PSHUF instruction sequences into their minimal form so that we
21624 // can evaluate how many specialized shuffle instructions are involved in
21625 // a particular chain.
21626 SmallVector<int, 1> NonceMask; // Just a placeholder.
21627 NonceMask.push_back(0);
21628 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21629 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21631 return SDValue(); // This routine will use CombineTo to replace N.
21637 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21638 /// specific shuffle of a load can be folded into a single element load.
21639 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21640 /// shuffles have been custom lowered so we need to handle those here.
21641 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21642 TargetLowering::DAGCombinerInfo &DCI) {
21643 if (DCI.isBeforeLegalizeOps())
21646 SDValue InVec = N->getOperand(0);
21647 SDValue EltNo = N->getOperand(1);
21649 if (!isa<ConstantSDNode>(EltNo))
21652 EVT OriginalVT = InVec.getValueType();
21654 if (InVec.getOpcode() == ISD::BITCAST) {
21655 // Don't duplicate a load with other uses.
21656 if (!InVec.hasOneUse())
21658 EVT BCVT = InVec.getOperand(0).getValueType();
21659 if (!BCVT.isVector() ||
21660 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21662 InVec = InVec.getOperand(0);
21665 EVT CurrentVT = InVec.getValueType();
21667 if (!isTargetShuffle(InVec.getOpcode()))
21670 // Don't duplicate a load with other uses.
21671 if (!InVec.hasOneUse())
21674 SmallVector<int, 16> ShuffleMask;
21676 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21677 ShuffleMask, UnaryShuffle))
21680 // Select the input vector, guarding against out of range extract vector.
21681 unsigned NumElems = CurrentVT.getVectorNumElements();
21682 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21683 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21684 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21685 : InVec.getOperand(1);
21687 // If inputs to shuffle are the same for both ops, then allow 2 uses
21688 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21689 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21691 if (LdNode.getOpcode() == ISD::BITCAST) {
21692 // Don't duplicate a load with other uses.
21693 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21696 AllowedUses = 1; // only allow 1 load use if we have a bitcast
21697 LdNode = LdNode.getOperand(0);
21700 if (!ISD::isNormalLoad(LdNode.getNode()))
21703 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21705 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21708 EVT EltVT = N->getValueType(0);
21709 // If there's a bitcast before the shuffle, check if the load type and
21710 // alignment is valid.
21711 unsigned Align = LN0->getAlignment();
21712 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21713 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
21714 EltVT.getTypeForEVT(*DAG.getContext()));
21716 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21719 // All checks match so transform back to vector_shuffle so that DAG combiner
21720 // can finish the job
21723 // Create shuffle node taking into account the case that its a unary shuffle
21724 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21725 : InVec.getOperand(1);
21726 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21727 InVec.getOperand(0), Shuffle,
21729 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21730 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21734 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21735 /// special and don't usually play with other vector types, it's better to
21736 /// handle them early to be sure we emit efficient code by avoiding
21737 /// store-load conversions.
21738 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21739 if (N->getValueType(0) != MVT::x86mmx ||
21740 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21741 N->getOperand(0)->getValueType(0) != MVT::v2i32)
21744 SDValue V = N->getOperand(0);
21745 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21746 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21747 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21748 N->getValueType(0), V.getOperand(0));
21753 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21754 /// generation and convert it from being a bunch of shuffles and extracts
21755 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21756 /// storing the value and loading scalars back, while for x64 we should
21757 /// use 64-bit extracts and shifts.
21758 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21759 TargetLowering::DAGCombinerInfo &DCI) {
21760 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21763 SDValue InputVector = N->getOperand(0);
21764 SDLoc dl(InputVector);
21765 // Detect mmx to i32 conversion through a v2i32 elt extract.
21766 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21767 N->getValueType(0) == MVT::i32 &&
21768 InputVector.getValueType() == MVT::v2i32) {
21770 // The bitcast source is a direct mmx result.
21771 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21772 if (MMXSrc.getValueType() == MVT::x86mmx)
21773 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21774 N->getValueType(0),
21775 InputVector.getNode()->getOperand(0));
21777 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21778 SDValue MMXSrcOp = MMXSrc.getOperand(0);
21779 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21780 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21781 MMXSrcOp.getOpcode() == ISD::BITCAST &&
21782 MMXSrcOp.getValueType() == MVT::v1i64 &&
21783 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21784 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21785 N->getValueType(0),
21786 MMXSrcOp.getOperand(0));
21789 EVT VT = N->getValueType(0);
21791 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21792 InputVector.getOpcode() == ISD::BITCAST &&
21793 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21794 uint64_t ExtractedElt =
21795 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21796 uint64_t InputValue =
21797 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21798 uint64_t Res = (InputValue >> ExtractedElt) & 1;
21799 return DAG.getConstant(Res, dl, MVT::i1);
21801 // Only operate on vectors of 4 elements, where the alternative shuffling
21802 // gets to be more expensive.
21803 if (InputVector.getValueType() != MVT::v4i32)
21806 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21807 // single use which is a sign-extend or zero-extend, and all elements are
21809 SmallVector<SDNode *, 4> Uses;
21810 unsigned ExtractedElements = 0;
21811 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21812 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21813 if (UI.getUse().getResNo() != InputVector.getResNo())
21816 SDNode *Extract = *UI;
21817 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21820 if (Extract->getValueType(0) != MVT::i32)
21822 if (!Extract->hasOneUse())
21824 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21825 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21827 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21830 // Record which element was extracted.
21831 ExtractedElements |=
21832 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21834 Uses.push_back(Extract);
21837 // If not all the elements were used, this may not be worthwhile.
21838 if (ExtractedElements != 15)
21841 // Ok, we've now decided to do the transformation.
21842 // If 64-bit shifts are legal, use the extract-shift sequence,
21843 // otherwise bounce the vector off the cache.
21844 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21847 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21848 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21849 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21850 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21851 DAG.getConstant(0, dl, VecIdxTy));
21852 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21853 DAG.getConstant(1, dl, VecIdxTy));
21855 SDValue ShAmt = DAG.getConstant(32, dl,
21856 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21857 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21858 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21859 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21860 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21861 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21862 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21864 // Store the value to a temporary stack slot.
21865 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21866 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21867 MachinePointerInfo(), false, false, 0);
21869 EVT ElementType = InputVector.getValueType().getVectorElementType();
21870 unsigned EltSize = ElementType.getSizeInBits() / 8;
21872 // Replace each use (extract) with a load of the appropriate element.
21873 for (unsigned i = 0; i < 4; ++i) {
21874 uint64_t Offset = EltSize * i;
21875 SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21877 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21878 StackPtr, OffsetVal);
21880 // Load the scalar.
21881 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21882 ScalarAddr, MachinePointerInfo(),
21883 false, false, false, 0);
21888 // Replace the extracts
21889 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21890 UE = Uses.end(); UI != UE; ++UI) {
21891 SDNode *Extract = *UI;
21893 SDValue Idx = Extract->getOperand(1);
21894 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21895 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21898 // The replacement was made in place; don't return anything.
21902 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21903 static std::pair<unsigned, bool>
21904 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21905 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21906 if (!VT.isVector())
21907 return std::make_pair(0, false);
21909 bool NeedSplit = false;
21910 switch (VT.getSimpleVT().SimpleTy) {
21911 default: return std::make_pair(0, false);
21914 if (!Subtarget->hasVLX())
21915 return std::make_pair(0, false);
21919 if (!Subtarget->hasBWI())
21920 return std::make_pair(0, false);
21924 if (!Subtarget->hasAVX512())
21925 return std::make_pair(0, false);
21930 if (!Subtarget->hasAVX2())
21932 if (!Subtarget->hasAVX())
21933 return std::make_pair(0, false);
21938 if (!Subtarget->hasSSE2())
21939 return std::make_pair(0, false);
21942 // SSE2 has only a small subset of the operations.
21943 bool hasUnsigned = Subtarget->hasSSE41() ||
21944 (Subtarget->hasSSE2() && VT == MVT::v16i8);
21945 bool hasSigned = Subtarget->hasSSE41() ||
21946 (Subtarget->hasSSE2() && VT == MVT::v8i16);
21948 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21951 // Check for x CC y ? x : y.
21952 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21953 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21958 Opc = hasUnsigned ? ISD::UMIN : 0; break;
21961 Opc = hasUnsigned ? ISD::UMAX : 0; break;
21964 Opc = hasSigned ? ISD::SMIN : 0; break;
21967 Opc = hasSigned ? ISD::SMAX : 0; break;
21969 // Check for x CC y ? y : x -- a min/max with reversed arms.
21970 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21971 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21976 Opc = hasUnsigned ? ISD::UMAX : 0; break;
21979 Opc = hasUnsigned ? ISD::UMIN : 0; break;
21982 Opc = hasSigned ? ISD::SMAX : 0; break;
21985 Opc = hasSigned ? ISD::SMIN : 0; break;
21989 return std::make_pair(Opc, NeedSplit);
21993 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21994 const X86Subtarget *Subtarget) {
21996 SDValue Cond = N->getOperand(0);
21997 SDValue LHS = N->getOperand(1);
21998 SDValue RHS = N->getOperand(2);
22000 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22001 SDValue CondSrc = Cond->getOperand(0);
22002 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22003 Cond = CondSrc->getOperand(0);
22006 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22009 // A vselect where all conditions and data are constants can be optimized into
22010 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22011 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22012 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22015 unsigned MaskValue = 0;
22016 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22019 MVT VT = N->getSimpleValueType(0);
22020 unsigned NumElems = VT.getVectorNumElements();
22021 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22022 for (unsigned i = 0; i < NumElems; ++i) {
22023 // Be sure we emit undef where we can.
22024 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22025 ShuffleMask[i] = -1;
22027 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22030 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22031 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22033 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22036 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22038 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22039 TargetLowering::DAGCombinerInfo &DCI,
22040 const X86Subtarget *Subtarget) {
22042 SDValue Cond = N->getOperand(0);
22043 // Get the LHS/RHS of the select.
22044 SDValue LHS = N->getOperand(1);
22045 SDValue RHS = N->getOperand(2);
22046 EVT VT = LHS.getValueType();
22047 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22049 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22050 // instructions match the semantics of the common C idiom x<y?x:y but not
22051 // x<=y?x:y, because of how they handle negative zero (which can be
22052 // ignored in unsafe-math mode).
22053 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22054 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22055 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22056 (Subtarget->hasSSE2() ||
22057 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22058 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22060 unsigned Opcode = 0;
22061 // Check for x CC y ? x : y.
22062 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22063 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22067 // Converting this to a min would handle NaNs incorrectly, and swapping
22068 // the operands would cause it to handle comparisons between positive
22069 // and negative zero incorrectly.
22070 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22071 if (!DAG.getTarget().Options.UnsafeFPMath &&
22072 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22074 std::swap(LHS, RHS);
22076 Opcode = X86ISD::FMIN;
22079 // Converting this to a min would handle comparisons between positive
22080 // and negative zero incorrectly.
22081 if (!DAG.getTarget().Options.UnsafeFPMath &&
22082 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22084 Opcode = X86ISD::FMIN;
22087 // Converting this to a min would handle both negative zeros and NaNs
22088 // incorrectly, but we can swap the operands to fix both.
22089 std::swap(LHS, RHS);
22093 Opcode = X86ISD::FMIN;
22097 // Converting this to a max would handle comparisons between positive
22098 // and negative zero incorrectly.
22099 if (!DAG.getTarget().Options.UnsafeFPMath &&
22100 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22102 Opcode = X86ISD::FMAX;
22105 // Converting this to a max would handle NaNs incorrectly, and swapping
22106 // the operands would cause it to handle comparisons between positive
22107 // and negative zero incorrectly.
22108 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22109 if (!DAG.getTarget().Options.UnsafeFPMath &&
22110 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22112 std::swap(LHS, RHS);
22114 Opcode = X86ISD::FMAX;
22117 // Converting this to a max would handle both negative zeros and NaNs
22118 // incorrectly, but we can swap the operands to fix both.
22119 std::swap(LHS, RHS);
22123 Opcode = X86ISD::FMAX;
22126 // Check for x CC y ? y : x -- a min/max with reversed arms.
22127 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22128 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22132 // Converting this to a min would handle comparisons between positive
22133 // and negative zero incorrectly, and swapping the operands would
22134 // cause it to handle NaNs incorrectly.
22135 if (!DAG.getTarget().Options.UnsafeFPMath &&
22136 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22137 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22139 std::swap(LHS, RHS);
22141 Opcode = X86ISD::FMIN;
22144 // Converting this to a min would handle NaNs incorrectly.
22145 if (!DAG.getTarget().Options.UnsafeFPMath &&
22146 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22148 Opcode = X86ISD::FMIN;
22151 // Converting this to a min would handle both negative zeros and NaNs
22152 // incorrectly, but we can swap the operands to fix both.
22153 std::swap(LHS, RHS);
22157 Opcode = X86ISD::FMIN;
22161 // Converting this to a max would handle NaNs incorrectly.
22162 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22164 Opcode = X86ISD::FMAX;
22167 // Converting this to a max would handle comparisons between positive
22168 // and negative zero incorrectly, and swapping the operands would
22169 // cause it to handle NaNs incorrectly.
22170 if (!DAG.getTarget().Options.UnsafeFPMath &&
22171 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22172 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22174 std::swap(LHS, RHS);
22176 Opcode = X86ISD::FMAX;
22179 // Converting this to a max would handle both negative zeros and NaNs
22180 // incorrectly, but we can swap the operands to fix both.
22181 std::swap(LHS, RHS);
22185 Opcode = X86ISD::FMAX;
22191 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22194 EVT CondVT = Cond.getValueType();
22195 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22196 CondVT.getVectorElementType() == MVT::i1) {
22197 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22198 // lowering on KNL. In this case we convert it to
22199 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22200 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22201 // Since SKX these selects have a proper lowering.
22202 EVT OpVT = LHS.getValueType();
22203 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22204 (OpVT.getVectorElementType() == MVT::i8 ||
22205 OpVT.getVectorElementType() == MVT::i16) &&
22206 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22207 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22208 DCI.AddToWorklist(Cond.getNode());
22209 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22212 // If this is a select between two integer constants, try to do some
22214 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22215 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22216 // Don't do this for crazy integer types.
22217 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22218 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22219 // so that TrueC (the true value) is larger than FalseC.
22220 bool NeedsCondInvert = false;
22222 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22223 // Efficiently invertible.
22224 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22225 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22226 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22227 NeedsCondInvert = true;
22228 std::swap(TrueC, FalseC);
22231 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22232 if (FalseC->getAPIntValue() == 0 &&
22233 TrueC->getAPIntValue().isPowerOf2()) {
22234 if (NeedsCondInvert) // Invert the condition if needed.
22235 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22236 DAG.getConstant(1, DL, Cond.getValueType()));
22238 // Zero extend the condition if needed.
22239 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22241 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22242 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22243 DAG.getConstant(ShAmt, DL, MVT::i8));
22246 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22247 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22248 if (NeedsCondInvert) // Invert the condition if needed.
22249 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22250 DAG.getConstant(1, DL, Cond.getValueType()));
22252 // Zero extend the condition if needed.
22253 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22254 FalseC->getValueType(0), Cond);
22255 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22256 SDValue(FalseC, 0));
22259 // Optimize cases that will turn into an LEA instruction. This requires
22260 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22261 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22262 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22263 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22265 bool isFastMultiplier = false;
22267 switch ((unsigned char)Diff) {
22269 case 1: // result = add base, cond
22270 case 2: // result = lea base( , cond*2)
22271 case 3: // result = lea base(cond, cond*2)
22272 case 4: // result = lea base( , cond*4)
22273 case 5: // result = lea base(cond, cond*4)
22274 case 8: // result = lea base( , cond*8)
22275 case 9: // result = lea base(cond, cond*8)
22276 isFastMultiplier = true;
22281 if (isFastMultiplier) {
22282 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22283 if (NeedsCondInvert) // Invert the condition if needed.
22284 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22285 DAG.getConstant(1, DL, Cond.getValueType()));
22287 // Zero extend the condition if needed.
22288 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22290 // Scale the condition by the difference.
22292 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22293 DAG.getConstant(Diff, DL,
22294 Cond.getValueType()));
22296 // Add the base if non-zero.
22297 if (FalseC->getAPIntValue() != 0)
22298 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22299 SDValue(FalseC, 0));
22306 // Canonicalize max and min:
22307 // (x > y) ? x : y -> (x >= y) ? x : y
22308 // (x < y) ? x : y -> (x <= y) ? x : y
22309 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22310 // the need for an extra compare
22311 // against zero. e.g.
22312 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22314 // testl %edi, %edi
22316 // cmovgl %edi, %eax
22320 // cmovsl %eax, %edi
22321 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22322 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22323 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22324 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22329 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22330 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22331 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22332 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22337 // Early exit check
22338 if (!TLI.isTypeLegal(VT))
22341 // Match VSELECTs into subs with unsigned saturation.
22342 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22343 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22344 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22345 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22346 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22348 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22349 // left side invert the predicate to simplify logic below.
22351 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22353 CC = ISD::getSetCCInverse(CC, true);
22354 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22358 if (Other.getNode() && Other->getNumOperands() == 2 &&
22359 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22360 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22361 SDValue CondRHS = Cond->getOperand(1);
22363 // Look for a general sub with unsigned saturation first.
22364 // x >= y ? x-y : 0 --> subus x, y
22365 // x > y ? x-y : 0 --> subus x, y
22366 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22367 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22368 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22370 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22371 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22372 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22373 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22374 // If the RHS is a constant we have to reverse the const
22375 // canonicalization.
22376 // x > C-1 ? x+-C : 0 --> subus x, C
22377 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22378 CondRHSConst->getAPIntValue() ==
22379 (-OpRHSConst->getAPIntValue() - 1))
22380 return DAG.getNode(
22381 X86ISD::SUBUS, DL, VT, OpLHS,
22382 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22384 // Another special case: If C was a sign bit, the sub has been
22385 // canonicalized into a xor.
22386 // FIXME: Would it be better to use computeKnownBits to determine
22387 // whether it's safe to decanonicalize the xor?
22388 // x s< 0 ? x^C : 0 --> subus x, C
22389 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22390 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22391 OpRHSConst->getAPIntValue().isSignBit())
22392 // Note that we have to rebuild the RHS constant here to ensure we
22393 // don't rely on particular values of undef lanes.
22394 return DAG.getNode(
22395 X86ISD::SUBUS, DL, VT, OpLHS,
22396 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22401 // Try to match a min/max vector operation.
22402 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22403 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22404 unsigned Opc = ret.first;
22405 bool NeedSplit = ret.second;
22407 if (Opc && NeedSplit) {
22408 unsigned NumElems = VT.getVectorNumElements();
22409 // Extract the LHS vectors
22410 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22411 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22413 // Extract the RHS vectors
22414 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22415 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22417 // Create min/max for each subvector
22418 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22419 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22421 // Merge the result
22422 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22424 return DAG.getNode(Opc, DL, VT, LHS, RHS);
22427 // Simplify vector selection if condition value type matches vselect
22429 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22430 assert(Cond.getValueType().isVector() &&
22431 "vector select expects a vector selector!");
22433 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22434 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22436 // Try invert the condition if true value is not all 1s and false value
22438 if (!TValIsAllOnes && !FValIsAllZeros &&
22439 // Check if the selector will be produced by CMPP*/PCMP*
22440 Cond.getOpcode() == ISD::SETCC &&
22441 // Check if SETCC has already been promoted
22442 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
22443 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22444 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22446 if (TValIsAllZeros || FValIsAllOnes) {
22447 SDValue CC = Cond.getOperand(2);
22448 ISD::CondCode NewCC =
22449 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22450 Cond.getOperand(0).getValueType().isInteger());
22451 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22452 std::swap(LHS, RHS);
22453 TValIsAllOnes = FValIsAllOnes;
22454 FValIsAllZeros = TValIsAllZeros;
22458 if (TValIsAllOnes || FValIsAllZeros) {
22461 if (TValIsAllOnes && FValIsAllZeros)
22463 else if (TValIsAllOnes)
22465 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22466 else if (FValIsAllZeros)
22467 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22468 DAG.getBitcast(CondVT, LHS));
22470 return DAG.getBitcast(VT, Ret);
22474 // We should generate an X86ISD::BLENDI from a vselect if its argument
22475 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22476 // constants. This specific pattern gets generated when we split a
22477 // selector for a 512 bit vector in a machine without AVX512 (but with
22478 // 256-bit vectors), during legalization:
22480 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22482 // Iff we find this pattern and the build_vectors are built from
22483 // constants, we translate the vselect into a shuffle_vector that we
22484 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22485 if ((N->getOpcode() == ISD::VSELECT ||
22486 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22487 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22488 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22489 if (Shuffle.getNode())
22493 // If this is a *dynamic* select (non-constant condition) and we can match
22494 // this node with one of the variable blend instructions, restructure the
22495 // condition so that the blends can use the high bit of each element and use
22496 // SimplifyDemandedBits to simplify the condition operand.
22497 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22498 !DCI.isBeforeLegalize() &&
22499 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22500 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22502 // Don't optimize vector selects that map to mask-registers.
22506 // We can only handle the cases where VSELECT is directly legal on the
22507 // subtarget. We custom lower VSELECT nodes with constant conditions and
22508 // this makes it hard to see whether a dynamic VSELECT will correctly
22509 // lower, so we both check the operation's status and explicitly handle the
22510 // cases where a *dynamic* blend will fail even though a constant-condition
22511 // blend could be custom lowered.
22512 // FIXME: We should find a better way to handle this class of problems.
22513 // Potentially, we should combine constant-condition vselect nodes
22514 // pre-legalization into shuffles and not mark as many types as custom
22516 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22518 // FIXME: We don't support i16-element blends currently. We could and
22519 // should support them by making *all* the bits in the condition be set
22520 // rather than just the high bit and using an i8-element blend.
22521 if (VT.getScalarType() == MVT::i16)
22523 // Dynamic blending was only available from SSE4.1 onward.
22524 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22526 // Byte blends are only available in AVX2
22527 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22528 !Subtarget->hasAVX2())
22531 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22532 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22534 APInt KnownZero, KnownOne;
22535 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22536 DCI.isBeforeLegalizeOps());
22537 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22538 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22540 // If we changed the computation somewhere in the DAG, this change
22541 // will affect all users of Cond.
22542 // Make sure it is fine and update all the nodes so that we do not
22543 // use the generic VSELECT anymore. Otherwise, we may perform
22544 // wrong optimizations as we messed up with the actual expectation
22545 // for the vector boolean values.
22546 if (Cond != TLO.Old) {
22547 // Check all uses of that condition operand to check whether it will be
22548 // consumed by non-BLEND instructions, which may depend on all bits are
22550 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22552 if (I->getOpcode() != ISD::VSELECT)
22553 // TODO: Add other opcodes eventually lowered into BLEND.
22556 // Update all the users of the condition, before committing the change,
22557 // so that the VSELECT optimizations that expect the correct vector
22558 // boolean value will not be triggered.
22559 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22561 DAG.ReplaceAllUsesOfValueWith(
22563 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22564 Cond, I->getOperand(1), I->getOperand(2)));
22565 DCI.CommitTargetLoweringOpt(TLO);
22568 // At this point, only Cond is changed. Change the condition
22569 // just for N to keep the opportunity to optimize all other
22570 // users their own way.
22571 DAG.ReplaceAllUsesOfValueWith(
22573 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22574 TLO.New, N->getOperand(1), N->getOperand(2)));
22582 // Check whether a boolean test is testing a boolean value generated by
22583 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22586 // Simplify the following patterns:
22587 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22588 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22589 // to (Op EFLAGS Cond)
22591 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22592 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22593 // to (Op EFLAGS !Cond)
22595 // where Op could be BRCOND or CMOV.
22597 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22598 // Quit if not CMP and SUB with its value result used.
22599 if (Cmp.getOpcode() != X86ISD::CMP &&
22600 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22603 // Quit if not used as a boolean value.
22604 if (CC != X86::COND_E && CC != X86::COND_NE)
22607 // Check CMP operands. One of them should be 0 or 1 and the other should be
22608 // an SetCC or extended from it.
22609 SDValue Op1 = Cmp.getOperand(0);
22610 SDValue Op2 = Cmp.getOperand(1);
22613 const ConstantSDNode* C = nullptr;
22614 bool needOppositeCond = (CC == X86::COND_E);
22615 bool checkAgainstTrue = false; // Is it a comparison against 1?
22617 if ((C = dyn_cast<ConstantSDNode>(Op1)))
22619 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22621 else // Quit if all operands are not constants.
22624 if (C->getZExtValue() == 1) {
22625 needOppositeCond = !needOppositeCond;
22626 checkAgainstTrue = true;
22627 } else if (C->getZExtValue() != 0)
22628 // Quit if the constant is neither 0 or 1.
22631 bool truncatedToBoolWithAnd = false;
22632 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22633 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22634 SetCC.getOpcode() == ISD::TRUNCATE ||
22635 SetCC.getOpcode() == ISD::AND) {
22636 if (SetCC.getOpcode() == ISD::AND) {
22638 ConstantSDNode *CS;
22639 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22640 CS->getZExtValue() == 1)
22642 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22643 CS->getZExtValue() == 1)
22647 SetCC = SetCC.getOperand(OpIdx);
22648 truncatedToBoolWithAnd = true;
22650 SetCC = SetCC.getOperand(0);
22653 switch (SetCC.getOpcode()) {
22654 case X86ISD::SETCC_CARRY:
22655 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22656 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22657 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22658 // truncated to i1 using 'and'.
22659 if (checkAgainstTrue && !truncatedToBoolWithAnd)
22661 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22662 "Invalid use of SETCC_CARRY!");
22664 case X86ISD::SETCC:
22665 // Set the condition code or opposite one if necessary.
22666 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22667 if (needOppositeCond)
22668 CC = X86::GetOppositeBranchCondition(CC);
22669 return SetCC.getOperand(1);
22670 case X86ISD::CMOV: {
22671 // Check whether false/true value has canonical one, i.e. 0 or 1.
22672 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22673 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22674 // Quit if true value is not a constant.
22677 // Quit if false value is not a constant.
22679 SDValue Op = SetCC.getOperand(0);
22680 // Skip 'zext' or 'trunc' node.
22681 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22682 Op.getOpcode() == ISD::TRUNCATE)
22683 Op = Op.getOperand(0);
22684 // A special case for rdrand/rdseed, where 0 is set if false cond is
22686 if ((Op.getOpcode() != X86ISD::RDRAND &&
22687 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22690 // Quit if false value is not the constant 0 or 1.
22691 bool FValIsFalse = true;
22692 if (FVal && FVal->getZExtValue() != 0) {
22693 if (FVal->getZExtValue() != 1)
22695 // If FVal is 1, opposite cond is needed.
22696 needOppositeCond = !needOppositeCond;
22697 FValIsFalse = false;
22699 // Quit if TVal is not the constant opposite of FVal.
22700 if (FValIsFalse && TVal->getZExtValue() != 1)
22702 if (!FValIsFalse && TVal->getZExtValue() != 0)
22704 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22705 if (needOppositeCond)
22706 CC = X86::GetOppositeBranchCondition(CC);
22707 return SetCC.getOperand(3);
22714 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22716 /// (X86or (X86setcc) (X86setcc))
22717 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
22718 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22719 X86::CondCode &CC1, SDValue &Flags,
22721 if (Cond->getOpcode() == X86ISD::CMP) {
22722 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22723 if (!CondOp1C || !CondOp1C->isNullValue())
22726 Cond = Cond->getOperand(0);
22731 SDValue SetCC0, SetCC1;
22732 switch (Cond->getOpcode()) {
22733 default: return false;
22740 SetCC0 = Cond->getOperand(0);
22741 SetCC1 = Cond->getOperand(1);
22745 // Make sure we have SETCC nodes, using the same flags value.
22746 if (SetCC0.getOpcode() != X86ISD::SETCC ||
22747 SetCC1.getOpcode() != X86ISD::SETCC ||
22748 SetCC0->getOperand(1) != SetCC1->getOperand(1))
22751 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22752 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22753 Flags = SetCC0->getOperand(1);
22757 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22758 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22759 TargetLowering::DAGCombinerInfo &DCI,
22760 const X86Subtarget *Subtarget) {
22763 // If the flag operand isn't dead, don't touch this CMOV.
22764 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22767 SDValue FalseOp = N->getOperand(0);
22768 SDValue TrueOp = N->getOperand(1);
22769 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22770 SDValue Cond = N->getOperand(3);
22772 if (CC == X86::COND_E || CC == X86::COND_NE) {
22773 switch (Cond.getOpcode()) {
22777 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22778 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22779 return (CC == X86::COND_E) ? FalseOp : TrueOp;
22785 Flags = checkBoolTestSetCCCombine(Cond, CC);
22786 if (Flags.getNode() &&
22787 // Extra check as FCMOV only supports a subset of X86 cond.
22788 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22789 SDValue Ops[] = { FalseOp, TrueOp,
22790 DAG.getConstant(CC, DL, MVT::i8), Flags };
22791 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22794 // If this is a select between two integer constants, try to do some
22795 // optimizations. Note that the operands are ordered the opposite of SELECT
22797 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22798 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22799 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22800 // larger than FalseC (the false value).
22801 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22802 CC = X86::GetOppositeBranchCondition(CC);
22803 std::swap(TrueC, FalseC);
22804 std::swap(TrueOp, FalseOp);
22807 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
22808 // This is efficient for any integer data type (including i8/i16) and
22810 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22811 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22812 DAG.getConstant(CC, DL, MVT::i8), Cond);
22814 // Zero extend the condition if needed.
22815 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22817 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22818 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22819 DAG.getConstant(ShAmt, DL, MVT::i8));
22820 if (N->getNumValues() == 2) // Dead flag value?
22821 return DCI.CombineTo(N, Cond, SDValue());
22825 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
22826 // for any integer data type, including i8/i16.
22827 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22828 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22829 DAG.getConstant(CC, DL, MVT::i8), Cond);
22831 // Zero extend the condition if needed.
22832 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22833 FalseC->getValueType(0), Cond);
22834 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22835 SDValue(FalseC, 0));
22837 if (N->getNumValues() == 2) // Dead flag value?
22838 return DCI.CombineTo(N, Cond, SDValue());
22842 // Optimize cases that will turn into an LEA instruction. This requires
22843 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22844 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22845 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22846 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22848 bool isFastMultiplier = false;
22850 switch ((unsigned char)Diff) {
22852 case 1: // result = add base, cond
22853 case 2: // result = lea base( , cond*2)
22854 case 3: // result = lea base(cond, cond*2)
22855 case 4: // result = lea base( , cond*4)
22856 case 5: // result = lea base(cond, cond*4)
22857 case 8: // result = lea base( , cond*8)
22858 case 9: // result = lea base(cond, cond*8)
22859 isFastMultiplier = true;
22864 if (isFastMultiplier) {
22865 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22866 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22867 DAG.getConstant(CC, DL, MVT::i8), Cond);
22868 // Zero extend the condition if needed.
22869 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22871 // Scale the condition by the difference.
22873 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22874 DAG.getConstant(Diff, DL, Cond.getValueType()));
22876 // Add the base if non-zero.
22877 if (FalseC->getAPIntValue() != 0)
22878 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22879 SDValue(FalseC, 0));
22880 if (N->getNumValues() == 2) // Dead flag value?
22881 return DCI.CombineTo(N, Cond, SDValue());
22888 // Handle these cases:
22889 // (select (x != c), e, c) -> select (x != c), e, x),
22890 // (select (x == c), c, e) -> select (x == c), x, e)
22891 // where the c is an integer constant, and the "select" is the combination
22892 // of CMOV and CMP.
22894 // The rationale for this change is that the conditional-move from a constant
22895 // needs two instructions, however, conditional-move from a register needs
22896 // only one instruction.
22898 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22899 // some instruction-combining opportunities. This opt needs to be
22900 // postponed as late as possible.
22902 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22903 // the DCI.xxxx conditions are provided to postpone the optimization as
22904 // late as possible.
22906 ConstantSDNode *CmpAgainst = nullptr;
22907 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22908 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22909 !isa<ConstantSDNode>(Cond.getOperand(0))) {
22911 if (CC == X86::COND_NE &&
22912 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22913 CC = X86::GetOppositeBranchCondition(CC);
22914 std::swap(TrueOp, FalseOp);
22917 if (CC == X86::COND_E &&
22918 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22919 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22920 DAG.getConstant(CC, DL, MVT::i8), Cond };
22921 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22926 // Fold and/or of setcc's to double CMOV:
22927 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22928 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22930 // This combine lets us generate:
22931 // cmovcc1 (jcc1 if we don't have CMOV)
22937 // cmovne (jne if we don't have CMOV)
22938 // When we can't use the CMOV instruction, it might increase branch
22940 // When we can use CMOV, or when there is no mispredict, this improves
22941 // throughput and reduces register pressure.
22943 if (CC == X86::COND_NE) {
22945 X86::CondCode CC0, CC1;
22947 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22949 std::swap(FalseOp, TrueOp);
22950 CC0 = X86::GetOppositeBranchCondition(CC0);
22951 CC1 = X86::GetOppositeBranchCondition(CC1);
22954 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22956 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22957 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22958 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22959 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22967 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22968 const X86Subtarget *Subtarget) {
22969 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22971 default: return SDValue();
22972 // SSE/AVX/AVX2 blend intrinsics.
22973 case Intrinsic::x86_avx2_pblendvb:
22974 // Don't try to simplify this intrinsic if we don't have AVX2.
22975 if (!Subtarget->hasAVX2())
22978 case Intrinsic::x86_avx_blendv_pd_256:
22979 case Intrinsic::x86_avx_blendv_ps_256:
22980 // Don't try to simplify this intrinsic if we don't have AVX.
22981 if (!Subtarget->hasAVX())
22984 case Intrinsic::x86_sse41_blendvps:
22985 case Intrinsic::x86_sse41_blendvpd:
22986 case Intrinsic::x86_sse41_pblendvb: {
22987 SDValue Op0 = N->getOperand(1);
22988 SDValue Op1 = N->getOperand(2);
22989 SDValue Mask = N->getOperand(3);
22991 // Don't try to simplify this intrinsic if we don't have SSE4.1.
22992 if (!Subtarget->hasSSE41())
22995 // fold (blend A, A, Mask) -> A
22998 // fold (blend A, B, allZeros) -> A
22999 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23001 // fold (blend A, B, allOnes) -> B
23002 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23005 // Simplify the case where the mask is a constant i32 value.
23006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23007 if (C->isNullValue())
23009 if (C->isAllOnesValue())
23016 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23017 case Intrinsic::x86_sse2_psrai_w:
23018 case Intrinsic::x86_sse2_psrai_d:
23019 case Intrinsic::x86_avx2_psrai_w:
23020 case Intrinsic::x86_avx2_psrai_d:
23021 case Intrinsic::x86_sse2_psra_w:
23022 case Intrinsic::x86_sse2_psra_d:
23023 case Intrinsic::x86_avx2_psra_w:
23024 case Intrinsic::x86_avx2_psra_d: {
23025 SDValue Op0 = N->getOperand(1);
23026 SDValue Op1 = N->getOperand(2);
23027 EVT VT = Op0.getValueType();
23028 assert(VT.isVector() && "Expected a vector type!");
23030 if (isa<BuildVectorSDNode>(Op1))
23031 Op1 = Op1.getOperand(0);
23033 if (!isa<ConstantSDNode>(Op1))
23036 EVT SVT = VT.getVectorElementType();
23037 unsigned SVTBits = SVT.getSizeInBits();
23039 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23040 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23041 uint64_t ShAmt = C.getZExtValue();
23043 // Don't try to convert this shift into a ISD::SRA if the shift
23044 // count is bigger than or equal to the element size.
23045 if (ShAmt >= SVTBits)
23048 // Trivial case: if the shift count is zero, then fold this
23049 // into the first operand.
23053 // Replace this packed shift intrinsic with a target independent
23056 SDValue Splat = DAG.getConstant(C, DL, VT);
23057 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23062 /// PerformMulCombine - Optimize a single multiply with constant into two
23063 /// in order to implement it with two cheaper instructions, e.g.
23064 /// LEA + SHL, LEA + LEA.
23065 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23066 TargetLowering::DAGCombinerInfo &DCI) {
23067 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23070 EVT VT = N->getValueType(0);
23071 if (VT != MVT::i64 && VT != MVT::i32)
23074 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23077 uint64_t MulAmt = C->getZExtValue();
23078 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23081 uint64_t MulAmt1 = 0;
23082 uint64_t MulAmt2 = 0;
23083 if ((MulAmt % 9) == 0) {
23085 MulAmt2 = MulAmt / 9;
23086 } else if ((MulAmt % 5) == 0) {
23088 MulAmt2 = MulAmt / 5;
23089 } else if ((MulAmt % 3) == 0) {
23091 MulAmt2 = MulAmt / 3;
23094 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23097 if (isPowerOf2_64(MulAmt2) &&
23098 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23099 // If second multiplifer is pow2, issue it first. We want the multiply by
23100 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23102 std::swap(MulAmt1, MulAmt2);
23105 if (isPowerOf2_64(MulAmt1))
23106 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23107 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23109 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23110 DAG.getConstant(MulAmt1, DL, VT));
23112 if (isPowerOf2_64(MulAmt2))
23113 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23114 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23116 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23117 DAG.getConstant(MulAmt2, DL, VT));
23119 // Do not add new nodes to DAG combiner worklist.
23120 DCI.CombineTo(N, NewMul, false);
23125 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23126 SDValue N0 = N->getOperand(0);
23127 SDValue N1 = N->getOperand(1);
23128 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23129 EVT VT = N0.getValueType();
23131 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23132 // since the result of setcc_c is all zero's or all ones.
23133 if (VT.isInteger() && !VT.isVector() &&
23134 N1C && N0.getOpcode() == ISD::AND &&
23135 N0.getOperand(1).getOpcode() == ISD::Constant) {
23136 SDValue N00 = N0.getOperand(0);
23137 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23138 ((N00.getOpcode() == ISD::ANY_EXTEND ||
23139 N00.getOpcode() == ISD::ZERO_EXTEND) &&
23140 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23141 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23142 APInt ShAmt = N1C->getAPIntValue();
23143 Mask = Mask.shl(ShAmt);
23146 return DAG.getNode(ISD::AND, DL, VT,
23147 N00, DAG.getConstant(Mask, DL, VT));
23152 // Hardware support for vector shifts is sparse which makes us scalarize the
23153 // vector operations in many cases. Also, on sandybridge ADD is faster than
23155 // (shl V, 1) -> add V,V
23156 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23157 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23158 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23159 // We shift all of the values by one. In many cases we do not have
23160 // hardware support for this operation. This is better expressed as an ADD
23162 if (N1SplatC->getZExtValue() == 1)
23163 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23169 /// \brief Returns a vector of 0s if the node in input is a vector logical
23170 /// shift by a constant amount which is known to be bigger than or equal
23171 /// to the vector element size in bits.
23172 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23173 const X86Subtarget *Subtarget) {
23174 EVT VT = N->getValueType(0);
23176 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23177 (!Subtarget->hasInt256() ||
23178 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23181 SDValue Amt = N->getOperand(1);
23183 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23184 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23185 APInt ShiftAmt = AmtSplat->getAPIntValue();
23186 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23188 // SSE2/AVX2 logical shifts always return a vector of 0s
23189 // if the shift amount is bigger than or equal to
23190 // the element size. The constant shift amount will be
23191 // encoded as a 8-bit immediate.
23192 if (ShiftAmt.trunc(8).uge(MaxAmount))
23193 return getZeroVector(VT, Subtarget, DAG, DL);
23199 /// PerformShiftCombine - Combine shifts.
23200 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23201 TargetLowering::DAGCombinerInfo &DCI,
23202 const X86Subtarget *Subtarget) {
23203 if (N->getOpcode() == ISD::SHL)
23204 if (SDValue V = PerformSHLCombine(N, DAG))
23207 // Try to fold this logical shift into a zero vector.
23208 if (N->getOpcode() != ISD::SRA)
23209 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23215 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23216 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23217 // and friends. Likewise for OR -> CMPNEQSS.
23218 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23219 TargetLowering::DAGCombinerInfo &DCI,
23220 const X86Subtarget *Subtarget) {
23223 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23224 // we're requiring SSE2 for both.
23225 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23226 SDValue N0 = N->getOperand(0);
23227 SDValue N1 = N->getOperand(1);
23228 SDValue CMP0 = N0->getOperand(1);
23229 SDValue CMP1 = N1->getOperand(1);
23232 // The SETCCs should both refer to the same CMP.
23233 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23236 SDValue CMP00 = CMP0->getOperand(0);
23237 SDValue CMP01 = CMP0->getOperand(1);
23238 EVT VT = CMP00.getValueType();
23240 if (VT == MVT::f32 || VT == MVT::f64) {
23241 bool ExpectingFlags = false;
23242 // Check for any users that want flags:
23243 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23244 !ExpectingFlags && UI != UE; ++UI)
23245 switch (UI->getOpcode()) {
23250 ExpectingFlags = true;
23252 case ISD::CopyToReg:
23253 case ISD::SIGN_EXTEND:
23254 case ISD::ZERO_EXTEND:
23255 case ISD::ANY_EXTEND:
23259 if (!ExpectingFlags) {
23260 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23261 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23263 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23264 X86::CondCode tmp = cc0;
23269 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23270 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23271 // FIXME: need symbolic constants for these magic numbers.
23272 // See X86ATTInstPrinter.cpp:printSSECC().
23273 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23274 if (Subtarget->hasAVX512()) {
23275 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23277 DAG.getConstant(x86cc, DL, MVT::i8));
23278 if (N->getValueType(0) != MVT::i1)
23279 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23283 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23284 CMP00.getValueType(), CMP00, CMP01,
23285 DAG.getConstant(x86cc, DL,
23288 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23289 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23291 if (is64BitFP && !Subtarget->is64Bit()) {
23292 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23293 // 64-bit integer, since that's not a legal type. Since
23294 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23295 // bits, but can do this little dance to extract the lowest 32 bits
23296 // and work with those going forward.
23297 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23299 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23300 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23301 Vector32, DAG.getIntPtrConstant(0, DL));
23305 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23306 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23307 DAG.getConstant(1, DL, IntVT));
23308 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23310 return OneBitOfTruth;
23318 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23319 /// so it can be folded inside ANDNP.
23320 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23321 EVT VT = N->getValueType(0);
23323 // Match direct AllOnes for 128 and 256-bit vectors
23324 if (ISD::isBuildVectorAllOnes(N))
23327 // Look through a bit convert.
23328 if (N->getOpcode() == ISD::BITCAST)
23329 N = N->getOperand(0).getNode();
23331 // Sometimes the operand may come from a insert_subvector building a 256-bit
23333 if (VT.is256BitVector() &&
23334 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23335 SDValue V1 = N->getOperand(0);
23336 SDValue V2 = N->getOperand(1);
23338 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23339 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23340 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23341 ISD::isBuildVectorAllOnes(V2.getNode()))
23348 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23349 // register. In most cases we actually compare or select YMM-sized registers
23350 // and mixing the two types creates horrible code. This method optimizes
23351 // some of the transition sequences.
23352 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23353 TargetLowering::DAGCombinerInfo &DCI,
23354 const X86Subtarget *Subtarget) {
23355 EVT VT = N->getValueType(0);
23356 if (!VT.is256BitVector())
23359 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23360 N->getOpcode() == ISD::ZERO_EXTEND ||
23361 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23363 SDValue Narrow = N->getOperand(0);
23364 EVT NarrowVT = Narrow->getValueType(0);
23365 if (!NarrowVT.is128BitVector())
23368 if (Narrow->getOpcode() != ISD::XOR &&
23369 Narrow->getOpcode() != ISD::AND &&
23370 Narrow->getOpcode() != ISD::OR)
23373 SDValue N0 = Narrow->getOperand(0);
23374 SDValue N1 = Narrow->getOperand(1);
23377 // The Left side has to be a trunc.
23378 if (N0.getOpcode() != ISD::TRUNCATE)
23381 // The type of the truncated inputs.
23382 EVT WideVT = N0->getOperand(0)->getValueType(0);
23386 // The right side has to be a 'trunc' or a constant vector.
23387 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23388 ConstantSDNode *RHSConstSplat = nullptr;
23389 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23390 RHSConstSplat = RHSBV->getConstantSplatNode();
23391 if (!RHSTrunc && !RHSConstSplat)
23394 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23396 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23399 // Set N0 and N1 to hold the inputs to the new wide operation.
23400 N0 = N0->getOperand(0);
23401 if (RHSConstSplat) {
23402 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23403 SDValue(RHSConstSplat, 0));
23404 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23405 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23406 } else if (RHSTrunc) {
23407 N1 = N1->getOperand(0);
23410 // Generate the wide operation.
23411 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23412 unsigned Opcode = N->getOpcode();
23414 case ISD::ANY_EXTEND:
23416 case ISD::ZERO_EXTEND: {
23417 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23418 APInt Mask = APInt::getAllOnesValue(InBits);
23419 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23420 return DAG.getNode(ISD::AND, DL, VT,
23421 Op, DAG.getConstant(Mask, DL, VT));
23423 case ISD::SIGN_EXTEND:
23424 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23425 Op, DAG.getValueType(NarrowVT));
23427 llvm_unreachable("Unexpected opcode");
23431 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23432 TargetLowering::DAGCombinerInfo &DCI,
23433 const X86Subtarget *Subtarget) {
23434 SDValue N0 = N->getOperand(0);
23435 SDValue N1 = N->getOperand(1);
23438 // A vector zext_in_reg may be represented as a shuffle,
23439 // feeding into a bitcast (this represents anyext) feeding into
23440 // an and with a mask.
23441 // We'd like to try to combine that into a shuffle with zero
23442 // plus a bitcast, removing the and.
23443 if (N0.getOpcode() != ISD::BITCAST ||
23444 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23447 // The other side of the AND should be a splat of 2^C, where C
23448 // is the number of bits in the source type.
23449 if (N1.getOpcode() == ISD::BITCAST)
23450 N1 = N1.getOperand(0);
23451 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23453 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23455 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23456 EVT SrcType = Shuffle->getValueType(0);
23458 // We expect a single-source shuffle
23459 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23462 unsigned SrcSize = SrcType.getScalarSizeInBits();
23464 APInt SplatValue, SplatUndef;
23465 unsigned SplatBitSize;
23467 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23468 SplatBitSize, HasAnyUndefs))
23471 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23472 // Make sure the splat matches the mask we expect
23473 if (SplatBitSize > ResSize ||
23474 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23477 // Make sure the input and output size make sense
23478 if (SrcSize >= ResSize || ResSize % SrcSize)
23481 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23482 // The number of u's between each two values depends on the ratio between
23483 // the source and dest type.
23484 unsigned ZextRatio = ResSize / SrcSize;
23485 bool IsZext = true;
23486 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23487 if (i % ZextRatio) {
23488 if (Shuffle->getMaskElt(i) > 0) {
23494 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23495 // Expected element number
23505 // Ok, perform the transformation - replace the shuffle with
23506 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23507 // (instead of undef) where the k elements come from the zero vector.
23508 SmallVector<int, 8> Mask;
23509 unsigned NumElems = SrcType.getVectorNumElements();
23510 for (unsigned i = 0; i < NumElems; ++i)
23512 Mask.push_back(NumElems);
23514 Mask.push_back(i / ZextRatio);
23516 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23517 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23518 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23521 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23522 TargetLowering::DAGCombinerInfo &DCI,
23523 const X86Subtarget *Subtarget) {
23524 if (DCI.isBeforeLegalizeOps())
23527 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23530 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23533 EVT VT = N->getValueType(0);
23534 SDValue N0 = N->getOperand(0);
23535 SDValue N1 = N->getOperand(1);
23538 // Create BEXTR instructions
23539 // BEXTR is ((X >> imm) & (2**size-1))
23540 if (VT == MVT::i32 || VT == MVT::i64) {
23541 // Check for BEXTR.
23542 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23543 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23544 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23545 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23546 if (MaskNode && ShiftNode) {
23547 uint64_t Mask = MaskNode->getZExtValue();
23548 uint64_t Shift = ShiftNode->getZExtValue();
23549 if (isMask_64(Mask)) {
23550 uint64_t MaskSize = countPopulation(Mask);
23551 if (Shift + MaskSize <= VT.getSizeInBits())
23552 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23553 DAG.getConstant(Shift | (MaskSize << 8), DL,
23562 // Want to form ANDNP nodes:
23563 // 1) In the hopes of then easily combining them with OR and AND nodes
23564 // to form PBLEND/PSIGN.
23565 // 2) To match ANDN packed intrinsics
23566 if (VT != MVT::v2i64 && VT != MVT::v4i64)
23569 // Check LHS for vnot
23570 if (N0.getOpcode() == ISD::XOR &&
23571 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23572 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23573 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23575 // Check RHS for vnot
23576 if (N1.getOpcode() == ISD::XOR &&
23577 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23578 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23579 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23584 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23585 TargetLowering::DAGCombinerInfo &DCI,
23586 const X86Subtarget *Subtarget) {
23587 if (DCI.isBeforeLegalizeOps())
23590 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23593 SDValue N0 = N->getOperand(0);
23594 SDValue N1 = N->getOperand(1);
23595 EVT VT = N->getValueType(0);
23597 // look for psign/blend
23598 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23599 if (!Subtarget->hasSSSE3() ||
23600 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23603 // Canonicalize pandn to RHS
23604 if (N0.getOpcode() == X86ISD::ANDNP)
23606 // or (and (m, y), (pandn m, x))
23607 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23608 SDValue Mask = N1.getOperand(0);
23609 SDValue X = N1.getOperand(1);
23611 if (N0.getOperand(0) == Mask)
23612 Y = N0.getOperand(1);
23613 if (N0.getOperand(1) == Mask)
23614 Y = N0.getOperand(0);
23616 // Check to see if the mask appeared in both the AND and ANDNP and
23620 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23621 // Look through mask bitcast.
23622 if (Mask.getOpcode() == ISD::BITCAST)
23623 Mask = Mask.getOperand(0);
23624 if (X.getOpcode() == ISD::BITCAST)
23625 X = X.getOperand(0);
23626 if (Y.getOpcode() == ISD::BITCAST)
23627 Y = Y.getOperand(0);
23629 EVT MaskVT = Mask.getValueType();
23631 // Validate that the Mask operand is a vector sra node.
23632 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23633 // there is no psrai.b
23634 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23635 unsigned SraAmt = ~0;
23636 if (Mask.getOpcode() == ISD::SRA) {
23637 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23638 if (auto *AmtConst = AmtBV->getConstantSplatNode())
23639 SraAmt = AmtConst->getZExtValue();
23640 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23641 SDValue SraC = Mask.getOperand(1);
23642 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
23644 if ((SraAmt + 1) != EltBits)
23649 // Now we know we at least have a plendvb with the mask val. See if
23650 // we can form a psignb/w/d.
23651 // psign = x.type == y.type == mask.type && y = sub(0, x);
23652 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23653 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23654 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23655 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23656 "Unsupported VT for PSIGN");
23657 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23658 return DAG.getBitcast(VT, Mask);
23660 // PBLENDVB only available on SSE 4.1
23661 if (!Subtarget->hasSSE41())
23664 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23666 X = DAG.getBitcast(BlendVT, X);
23667 Y = DAG.getBitcast(BlendVT, Y);
23668 Mask = DAG.getBitcast(BlendVT, Mask);
23669 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23670 return DAG.getBitcast(VT, Mask);
23674 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23677 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23678 MachineFunction &MF = DAG.getMachineFunction();
23680 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23682 // SHLD/SHRD instructions have lower register pressure, but on some
23683 // platforms they have higher latency than the equivalent
23684 // series of shifts/or that would otherwise be generated.
23685 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23686 // have higher latencies and we are not optimizing for size.
23687 if (!OptForSize && Subtarget->isSHLDSlow())
23690 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23692 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23694 if (!N0.hasOneUse() || !N1.hasOneUse())
23697 SDValue ShAmt0 = N0.getOperand(1);
23698 if (ShAmt0.getValueType() != MVT::i8)
23700 SDValue ShAmt1 = N1.getOperand(1);
23701 if (ShAmt1.getValueType() != MVT::i8)
23703 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23704 ShAmt0 = ShAmt0.getOperand(0);
23705 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23706 ShAmt1 = ShAmt1.getOperand(0);
23709 unsigned Opc = X86ISD::SHLD;
23710 SDValue Op0 = N0.getOperand(0);
23711 SDValue Op1 = N1.getOperand(0);
23712 if (ShAmt0.getOpcode() == ISD::SUB) {
23713 Opc = X86ISD::SHRD;
23714 std::swap(Op0, Op1);
23715 std::swap(ShAmt0, ShAmt1);
23718 unsigned Bits = VT.getSizeInBits();
23719 if (ShAmt1.getOpcode() == ISD::SUB) {
23720 SDValue Sum = ShAmt1.getOperand(0);
23721 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23722 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23723 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23724 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23725 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23726 return DAG.getNode(Opc, DL, VT,
23728 DAG.getNode(ISD::TRUNCATE, DL,
23731 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23732 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23734 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23735 return DAG.getNode(Opc, DL, VT,
23736 N0.getOperand(0), N1.getOperand(0),
23737 DAG.getNode(ISD::TRUNCATE, DL,
23744 // Generate NEG and CMOV for integer abs.
23745 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23746 EVT VT = N->getValueType(0);
23748 // Since X86 does not have CMOV for 8-bit integer, we don't convert
23749 // 8-bit integer abs to NEG and CMOV.
23750 if (VT.isInteger() && VT.getSizeInBits() == 8)
23753 SDValue N0 = N->getOperand(0);
23754 SDValue N1 = N->getOperand(1);
23757 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23758 // and change it to SUB and CMOV.
23759 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23760 N0.getOpcode() == ISD::ADD &&
23761 N0.getOperand(1) == N1 &&
23762 N1.getOpcode() == ISD::SRA &&
23763 N1.getOperand(0) == N0.getOperand(0))
23764 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23765 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23766 // Generate SUB & CMOV.
23767 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23768 DAG.getConstant(0, DL, VT), N0.getOperand(0));
23770 SDValue Ops[] = { N0.getOperand(0), Neg,
23771 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23772 SDValue(Neg.getNode(), 1) };
23773 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23778 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23779 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23780 TargetLowering::DAGCombinerInfo &DCI,
23781 const X86Subtarget *Subtarget) {
23782 if (DCI.isBeforeLegalizeOps())
23785 if (Subtarget->hasCMov())
23786 if (SDValue RV = performIntegerAbsCombine(N, DAG))
23792 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23793 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23794 TargetLowering::DAGCombinerInfo &DCI,
23795 const X86Subtarget *Subtarget) {
23796 LoadSDNode *Ld = cast<LoadSDNode>(N);
23797 EVT RegVT = Ld->getValueType(0);
23798 EVT MemVT = Ld->getMemoryVT();
23800 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23802 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23803 // into two 16-byte operations.
23804 ISD::LoadExtType Ext = Ld->getExtensionType();
23805 unsigned Alignment = Ld->getAlignment();
23806 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23807 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23808 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23809 unsigned NumElems = RegVT.getVectorNumElements();
23813 SDValue Ptr = Ld->getBasePtr();
23814 SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23816 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23818 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23819 Ld->getPointerInfo(), Ld->isVolatile(),
23820 Ld->isNonTemporal(), Ld->isInvariant(),
23822 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23823 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23824 Ld->getPointerInfo(), Ld->isVolatile(),
23825 Ld->isNonTemporal(), Ld->isInvariant(),
23826 std::min(16U, Alignment));
23827 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23829 Load2.getValue(1));
23831 SDValue NewVec = DAG.getUNDEF(RegVT);
23832 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23833 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23834 return DCI.CombineTo(N, NewVec, TF, true);
23840 /// PerformMLOADCombine - Resolve extending loads
23841 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23842 TargetLowering::DAGCombinerInfo &DCI,
23843 const X86Subtarget *Subtarget) {
23844 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23845 if (Mld->getExtensionType() != ISD::SEXTLOAD)
23848 EVT VT = Mld->getValueType(0);
23849 unsigned NumElems = VT.getVectorNumElements();
23850 EVT LdVT = Mld->getMemoryVT();
23853 assert(LdVT != VT && "Cannot extend to the same type");
23854 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23855 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23856 // From, To sizes and ElemCount must be pow of two
23857 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23858 "Unexpected size for extending masked load");
23860 unsigned SizeRatio = ToSz / FromSz;
23861 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23863 // Create a type on which we perform the shuffle
23864 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23865 LdVT.getScalarType(), NumElems*SizeRatio);
23866 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23868 // Convert Src0 value
23869 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23870 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23871 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23872 for (unsigned i = 0; i != NumElems; ++i)
23873 ShuffleVec[i] = i * SizeRatio;
23875 // Can't shuffle using an illegal type.
23876 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23877 && "WideVecVT should be legal");
23878 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23879 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23881 // Prepare the new mask
23883 SDValue Mask = Mld->getMask();
23884 if (Mask.getValueType() == VT) {
23885 // Mask and original value have the same type
23886 NewMask = DAG.getBitcast(WideVecVT, Mask);
23887 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23888 for (unsigned i = 0; i != NumElems; ++i)
23889 ShuffleVec[i] = i * SizeRatio;
23890 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23891 ShuffleVec[i] = NumElems*SizeRatio;
23892 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23893 DAG.getConstant(0, dl, WideVecVT),
23897 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23898 unsigned WidenNumElts = NumElems*SizeRatio;
23899 unsigned MaskNumElts = VT.getVectorNumElements();
23900 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23903 unsigned NumConcat = WidenNumElts / MaskNumElts;
23904 SmallVector<SDValue, 16> Ops(NumConcat);
23905 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23907 for (unsigned i = 1; i != NumConcat; ++i)
23910 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23913 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23914 Mld->getBasePtr(), NewMask, WideSrc0,
23915 Mld->getMemoryVT(), Mld->getMemOperand(),
23917 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23918 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23921 /// PerformMSTORECombine - Resolve truncating stores
23922 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23923 const X86Subtarget *Subtarget) {
23924 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23925 if (!Mst->isTruncatingStore())
23928 EVT VT = Mst->getValue().getValueType();
23929 unsigned NumElems = VT.getVectorNumElements();
23930 EVT StVT = Mst->getMemoryVT();
23933 assert(StVT != VT && "Cannot truncate to the same type");
23934 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23935 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23937 // From, To sizes and ElemCount must be pow of two
23938 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23939 "Unexpected size for truncating masked store");
23940 // We are going to use the original vector elt for storing.
23941 // Accumulated smaller vector elements must be a multiple of the store size.
23942 assert (((NumElems * FromSz) % ToSz) == 0 &&
23943 "Unexpected ratio for truncating masked store");
23945 unsigned SizeRatio = FromSz / ToSz;
23946 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23948 // Create a type on which we perform the shuffle
23949 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23950 StVT.getScalarType(), NumElems*SizeRatio);
23952 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23954 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
23955 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23956 for (unsigned i = 0; i != NumElems; ++i)
23957 ShuffleVec[i] = i * SizeRatio;
23959 // Can't shuffle using an illegal type.
23960 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23961 && "WideVecVT should be legal");
23963 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23964 DAG.getUNDEF(WideVecVT),
23968 SDValue Mask = Mst->getMask();
23969 if (Mask.getValueType() == VT) {
23970 // Mask and original value have the same type
23971 NewMask = DAG.getBitcast(WideVecVT, Mask);
23972 for (unsigned i = 0; i != NumElems; ++i)
23973 ShuffleVec[i] = i * SizeRatio;
23974 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23975 ShuffleVec[i] = NumElems*SizeRatio;
23976 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23977 DAG.getConstant(0, dl, WideVecVT),
23981 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23982 unsigned WidenNumElts = NumElems*SizeRatio;
23983 unsigned MaskNumElts = VT.getVectorNumElements();
23984 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23987 unsigned NumConcat = WidenNumElts / MaskNumElts;
23988 SmallVector<SDValue, 16> Ops(NumConcat);
23989 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23991 for (unsigned i = 1; i != NumConcat; ++i)
23994 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23997 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23998 NewMask, StVT, Mst->getMemOperand(), false);
24000 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24001 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24002 const X86Subtarget *Subtarget) {
24003 StoreSDNode *St = cast<StoreSDNode>(N);
24004 EVT VT = St->getValue().getValueType();
24005 EVT StVT = St->getMemoryVT();
24007 SDValue StoredVal = St->getOperand(1);
24008 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24010 // If we are saving a concatenation of two XMM registers and 32-byte stores
24011 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24012 unsigned Alignment = St->getAlignment();
24013 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24014 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24015 StVT == VT && !IsAligned) {
24016 unsigned NumElems = VT.getVectorNumElements();
24020 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24021 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24023 SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
24024 SDValue Ptr0 = St->getBasePtr();
24025 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24027 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24028 St->getPointerInfo(), St->isVolatile(),
24029 St->isNonTemporal(), Alignment);
24030 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24031 St->getPointerInfo(), St->isVolatile(),
24032 St->isNonTemporal(),
24033 std::min(16U, Alignment));
24034 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24037 // Optimize trunc store (of multiple scalars) to shuffle and store.
24038 // First, pack all of the elements in one place. Next, store to memory
24039 // in fewer chunks.
24040 if (St->isTruncatingStore() && VT.isVector()) {
24041 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24042 unsigned NumElems = VT.getVectorNumElements();
24043 assert(StVT != VT && "Cannot truncate to the same type");
24044 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24045 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24047 // From, To sizes and ElemCount must be pow of two
24048 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24049 // We are going to use the original vector elt for storing.
24050 // Accumulated smaller vector elements must be a multiple of the store size.
24051 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24053 unsigned SizeRatio = FromSz / ToSz;
24055 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24057 // Create a type on which we perform the shuffle
24058 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24059 StVT.getScalarType(), NumElems*SizeRatio);
24061 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24063 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24064 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24065 for (unsigned i = 0; i != NumElems; ++i)
24066 ShuffleVec[i] = i * SizeRatio;
24068 // Can't shuffle using an illegal type.
24069 if (!TLI.isTypeLegal(WideVecVT))
24072 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24073 DAG.getUNDEF(WideVecVT),
24075 // At this point all of the data is stored at the bottom of the
24076 // register. We now need to save it to mem.
24078 // Find the largest store unit
24079 MVT StoreType = MVT::i8;
24080 for (MVT Tp : MVT::integer_valuetypes()) {
24081 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24085 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24086 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24087 (64 <= NumElems * ToSz))
24088 StoreType = MVT::f64;
24090 // Bitcast the original vector into a vector of store-size units
24091 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24092 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24093 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24094 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24095 SmallVector<SDValue, 8> Chains;
24096 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
24097 TLI.getPointerTy());
24098 SDValue Ptr = St->getBasePtr();
24100 // Perform one or more big stores into memory.
24101 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24102 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24103 StoreType, ShuffWide,
24104 DAG.getIntPtrConstant(i, dl));
24105 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24106 St->getPointerInfo(), St->isVolatile(),
24107 St->isNonTemporal(), St->getAlignment());
24108 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24109 Chains.push_back(Ch);
24112 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24115 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24116 // the FP state in cases where an emms may be missing.
24117 // A preferable solution to the general problem is to figure out the right
24118 // places to insert EMMS. This qualifies as a quick hack.
24120 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24121 if (VT.getSizeInBits() != 64)
24124 const Function *F = DAG.getMachineFunction().getFunction();
24125 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24127 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24128 if ((VT.isVector() ||
24129 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24130 isa<LoadSDNode>(St->getValue()) &&
24131 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24132 St->getChain().hasOneUse() && !St->isVolatile()) {
24133 SDNode* LdVal = St->getValue().getNode();
24134 LoadSDNode *Ld = nullptr;
24135 int TokenFactorIndex = -1;
24136 SmallVector<SDValue, 8> Ops;
24137 SDNode* ChainVal = St->getChain().getNode();
24138 // Must be a store of a load. We currently handle two cases: the load
24139 // is a direct child, and it's under an intervening TokenFactor. It is
24140 // possible to dig deeper under nested TokenFactors.
24141 if (ChainVal == LdVal)
24142 Ld = cast<LoadSDNode>(St->getChain());
24143 else if (St->getValue().hasOneUse() &&
24144 ChainVal->getOpcode() == ISD::TokenFactor) {
24145 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24146 if (ChainVal->getOperand(i).getNode() == LdVal) {
24147 TokenFactorIndex = i;
24148 Ld = cast<LoadSDNode>(St->getValue());
24150 Ops.push_back(ChainVal->getOperand(i));
24154 if (!Ld || !ISD::isNormalLoad(Ld))
24157 // If this is not the MMX case, i.e. we are just turning i64 load/store
24158 // into f64 load/store, avoid the transformation if there are multiple
24159 // uses of the loaded value.
24160 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24165 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24166 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24168 if (Subtarget->is64Bit() || F64IsLegal) {
24169 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24170 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24171 Ld->getPointerInfo(), Ld->isVolatile(),
24172 Ld->isNonTemporal(), Ld->isInvariant(),
24173 Ld->getAlignment());
24174 SDValue NewChain = NewLd.getValue(1);
24175 if (TokenFactorIndex != -1) {
24176 Ops.push_back(NewChain);
24177 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24179 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24180 St->getPointerInfo(),
24181 St->isVolatile(), St->isNonTemporal(),
24182 St->getAlignment());
24185 // Otherwise, lower to two pairs of 32-bit loads / stores.
24186 SDValue LoAddr = Ld->getBasePtr();
24187 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24188 DAG.getConstant(4, LdDL, MVT::i32));
24190 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24191 Ld->getPointerInfo(),
24192 Ld->isVolatile(), Ld->isNonTemporal(),
24193 Ld->isInvariant(), Ld->getAlignment());
24194 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24195 Ld->getPointerInfo().getWithOffset(4),
24196 Ld->isVolatile(), Ld->isNonTemporal(),
24198 MinAlign(Ld->getAlignment(), 4));
24200 SDValue NewChain = LoLd.getValue(1);
24201 if (TokenFactorIndex != -1) {
24202 Ops.push_back(LoLd);
24203 Ops.push_back(HiLd);
24204 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24207 LoAddr = St->getBasePtr();
24208 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24209 DAG.getConstant(4, StDL, MVT::i32));
24211 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24212 St->getPointerInfo(),
24213 St->isVolatile(), St->isNonTemporal(),
24214 St->getAlignment());
24215 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24216 St->getPointerInfo().getWithOffset(4),
24218 St->isNonTemporal(),
24219 MinAlign(St->getAlignment(), 4));
24220 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24223 // This is similar to the above case, but here we handle a scalar 64-bit
24224 // integer store that is extracted from a vector on a 32-bit target.
24225 // If we have SSE2, then we can treat it like a floating-point double
24226 // to get past legalization. The execution dependencies fixup pass will
24227 // choose the optimal machine instruction for the store if this really is
24228 // an integer or v2f32 rather than an f64.
24229 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24230 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24231 SDValue OldExtract = St->getOperand(1);
24232 SDValue ExtOp0 = OldExtract.getOperand(0);
24233 unsigned VecSize = ExtOp0.getValueSizeInBits();
24234 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24235 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24236 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24237 BitCast, OldExtract.getOperand(1));
24238 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24239 St->getPointerInfo(), St->isVolatile(),
24240 St->isNonTemporal(), St->getAlignment());
24246 /// Return 'true' if this vector operation is "horizontal"
24247 /// and return the operands for the horizontal operation in LHS and RHS. A
24248 /// horizontal operation performs the binary operation on successive elements
24249 /// of its first operand, then on successive elements of its second operand,
24250 /// returning the resulting values in a vector. For example, if
24251 /// A = < float a0, float a1, float a2, float a3 >
24253 /// B = < float b0, float b1, float b2, float b3 >
24254 /// then the result of doing a horizontal operation on A and B is
24255 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24256 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24257 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24258 /// set to A, RHS to B, and the routine returns 'true'.
24259 /// Note that the binary operation should have the property that if one of the
24260 /// operands is UNDEF then the result is UNDEF.
24261 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24262 // Look for the following pattern: if
24263 // A = < float a0, float a1, float a2, float a3 >
24264 // B = < float b0, float b1, float b2, float b3 >
24266 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24267 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24268 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24269 // which is A horizontal-op B.
24271 // At least one of the operands should be a vector shuffle.
24272 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24273 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24276 MVT VT = LHS.getSimpleValueType();
24278 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24279 "Unsupported vector type for horizontal add/sub");
24281 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24282 // operate independently on 128-bit lanes.
24283 unsigned NumElts = VT.getVectorNumElements();
24284 unsigned NumLanes = VT.getSizeInBits()/128;
24285 unsigned NumLaneElts = NumElts / NumLanes;
24286 assert((NumLaneElts % 2 == 0) &&
24287 "Vector type should have an even number of elements in each lane");
24288 unsigned HalfLaneElts = NumLaneElts/2;
24290 // View LHS in the form
24291 // LHS = VECTOR_SHUFFLE A, B, LMask
24292 // If LHS is not a shuffle then pretend it is the shuffle
24293 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24294 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24297 SmallVector<int, 16> LMask(NumElts);
24298 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24299 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24300 A = LHS.getOperand(0);
24301 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24302 B = LHS.getOperand(1);
24303 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24304 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24306 if (LHS.getOpcode() != ISD::UNDEF)
24308 for (unsigned i = 0; i != NumElts; ++i)
24312 // Likewise, view RHS in the form
24313 // RHS = VECTOR_SHUFFLE C, D, RMask
24315 SmallVector<int, 16> RMask(NumElts);
24316 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24317 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24318 C = RHS.getOperand(0);
24319 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24320 D = RHS.getOperand(1);
24321 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24322 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24324 if (RHS.getOpcode() != ISD::UNDEF)
24326 for (unsigned i = 0; i != NumElts; ++i)
24330 // Check that the shuffles are both shuffling the same vectors.
24331 if (!(A == C && B == D) && !(A == D && B == C))
24334 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24335 if (!A.getNode() && !B.getNode())
24338 // If A and B occur in reverse order in RHS, then "swap" them (which means
24339 // rewriting the mask).
24341 ShuffleVectorSDNode::commuteMask(RMask);
24343 // At this point LHS and RHS are equivalent to
24344 // LHS = VECTOR_SHUFFLE A, B, LMask
24345 // RHS = VECTOR_SHUFFLE A, B, RMask
24346 // Check that the masks correspond to performing a horizontal operation.
24347 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24348 for (unsigned i = 0; i != NumLaneElts; ++i) {
24349 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24351 // Ignore any UNDEF components.
24352 if (LIdx < 0 || RIdx < 0 ||
24353 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24354 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24357 // Check that successive elements are being operated on. If not, this is
24358 // not a horizontal operation.
24359 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24360 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24361 if (!(LIdx == Index && RIdx == Index + 1) &&
24362 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24367 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24368 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24372 /// Do target-specific dag combines on floating point adds.
24373 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24374 const X86Subtarget *Subtarget) {
24375 EVT VT = N->getValueType(0);
24376 SDValue LHS = N->getOperand(0);
24377 SDValue RHS = N->getOperand(1);
24379 // Try to synthesize horizontal adds from adds of shuffles.
24380 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24381 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24382 isHorizontalBinOp(LHS, RHS, true))
24383 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24387 /// Do target-specific dag combines on floating point subs.
24388 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24389 const X86Subtarget *Subtarget) {
24390 EVT VT = N->getValueType(0);
24391 SDValue LHS = N->getOperand(0);
24392 SDValue RHS = N->getOperand(1);
24394 // Try to synthesize horizontal subs from subs of shuffles.
24395 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24396 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24397 isHorizontalBinOp(LHS, RHS, false))
24398 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24402 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24403 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24404 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24406 // F[X]OR(0.0, x) -> x
24407 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24408 if (C->getValueAPF().isPosZero())
24409 return N->getOperand(1);
24411 // F[X]OR(x, 0.0) -> x
24412 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24413 if (C->getValueAPF().isPosZero())
24414 return N->getOperand(0);
24418 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24419 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24420 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24422 // Only perform optimizations if UnsafeMath is used.
24423 if (!DAG.getTarget().Options.UnsafeFPMath)
24426 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24427 // into FMINC and FMAXC, which are Commutative operations.
24428 unsigned NewOp = 0;
24429 switch (N->getOpcode()) {
24430 default: llvm_unreachable("unknown opcode");
24431 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24432 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24435 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24436 N->getOperand(0), N->getOperand(1));
24439 /// Do target-specific dag combines on X86ISD::FAND nodes.
24440 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24441 // FAND(0.0, x) -> 0.0
24442 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24443 if (C->getValueAPF().isPosZero())
24444 return N->getOperand(0);
24446 // FAND(x, 0.0) -> 0.0
24447 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24448 if (C->getValueAPF().isPosZero())
24449 return N->getOperand(1);
24454 /// Do target-specific dag combines on X86ISD::FANDN nodes
24455 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24456 // FANDN(0.0, x) -> x
24457 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24458 if (C->getValueAPF().isPosZero())
24459 return N->getOperand(1);
24461 // FANDN(x, 0.0) -> 0.0
24462 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24463 if (C->getValueAPF().isPosZero())
24464 return N->getOperand(1);
24469 static SDValue PerformBTCombine(SDNode *N,
24471 TargetLowering::DAGCombinerInfo &DCI) {
24472 // BT ignores high bits in the bit index operand.
24473 SDValue Op1 = N->getOperand(1);
24474 if (Op1.hasOneUse()) {
24475 unsigned BitWidth = Op1.getValueSizeInBits();
24476 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24477 APInt KnownZero, KnownOne;
24478 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24479 !DCI.isBeforeLegalizeOps());
24480 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24481 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24482 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24483 DCI.CommitTargetLoweringOpt(TLO);
24488 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24489 SDValue Op = N->getOperand(0);
24490 if (Op.getOpcode() == ISD::BITCAST)
24491 Op = Op.getOperand(0);
24492 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24493 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24494 VT.getVectorElementType().getSizeInBits() ==
24495 OpVT.getVectorElementType().getSizeInBits()) {
24496 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24501 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24502 const X86Subtarget *Subtarget) {
24503 EVT VT = N->getValueType(0);
24504 if (!VT.isVector())
24507 SDValue N0 = N->getOperand(0);
24508 SDValue N1 = N->getOperand(1);
24509 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24512 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24513 // both SSE and AVX2 since there is no sign-extended shift right
24514 // operation on a vector with 64-bit elements.
24515 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24516 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24517 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24518 N0.getOpcode() == ISD::SIGN_EXTEND)) {
24519 SDValue N00 = N0.getOperand(0);
24521 // EXTLOAD has a better solution on AVX2,
24522 // it may be replaced with X86ISD::VSEXT node.
24523 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24524 if (!ISD::isNormalLoad(N00.getNode()))
24527 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24528 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24530 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24536 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24537 TargetLowering::DAGCombinerInfo &DCI,
24538 const X86Subtarget *Subtarget) {
24539 SDValue N0 = N->getOperand(0);
24540 EVT VT = N->getValueType(0);
24541 EVT SVT = VT.getScalarType();
24542 EVT InVT = N0.getValueType();
24543 EVT InSVT = InVT.getScalarType();
24546 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24547 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24548 // This exposes the sext to the sdivrem lowering, so that it directly extends
24549 // from AH (which we otherwise need to do contortions to access).
24550 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24551 InVT == MVT::i8 && VT == MVT::i32) {
24552 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24553 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24554 N0.getOperand(0), N0.getOperand(1));
24555 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24556 return R.getValue(1);
24559 if (!DCI.isBeforeLegalizeOps()) {
24560 if (InVT == MVT::i1) {
24561 SDValue Zero = DAG.getConstant(0, DL, VT);
24563 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24564 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24569 if (VT.isVector() && Subtarget->hasSSE2()) {
24570 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24571 EVT InVT = N.getValueType();
24572 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24573 Size / InVT.getScalarSizeInBits());
24574 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24575 DAG.getUNDEF(InVT));
24577 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24580 // If target-size is less than 128-bits, extend to a type that would extend
24581 // to 128 bits, extend that and extract the original target vector.
24582 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24583 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24584 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24585 unsigned Scale = 128 / VT.getSizeInBits();
24587 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24588 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24589 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24590 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24591 DAG.getIntPtrConstant(0, DL));
24594 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24595 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24596 if (VT.getSizeInBits() == 128 &&
24597 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24598 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24599 SDValue ExOp = ExtendVecSize(DL, N0, 128);
24600 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24603 // On pre-AVX2 targets, split into 128-bit nodes of
24604 // ISD::SIGN_EXTEND_VECTOR_INREG.
24605 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24606 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24607 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24608 unsigned NumVecs = VT.getSizeInBits() / 128;
24609 unsigned NumSubElts = 128 / SVT.getSizeInBits();
24610 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24611 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24613 SmallVector<SDValue, 8> Opnds;
24614 for (unsigned i = 0, Offset = 0; i != NumVecs;
24615 ++i, Offset += NumSubElts) {
24616 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24617 DAG.getIntPtrConstant(Offset, DL));
24618 SrcVec = ExtendVecSize(DL, SrcVec, 128);
24619 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24620 Opnds.push_back(SrcVec);
24622 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24626 if (!Subtarget->hasFp256())
24629 if (VT.isVector() && VT.getSizeInBits() == 256)
24630 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24636 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24637 const X86Subtarget* Subtarget) {
24639 EVT VT = N->getValueType(0);
24641 // Let legalize expand this if it isn't a legal type yet.
24642 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24645 EVT ScalarVT = VT.getScalarType();
24646 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24647 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24648 !Subtarget->hasAVX512()))
24651 SDValue A = N->getOperand(0);
24652 SDValue B = N->getOperand(1);
24653 SDValue C = N->getOperand(2);
24655 bool NegA = (A.getOpcode() == ISD::FNEG);
24656 bool NegB = (B.getOpcode() == ISD::FNEG);
24657 bool NegC = (C.getOpcode() == ISD::FNEG);
24659 // Negative multiplication when NegA xor NegB
24660 bool NegMul = (NegA != NegB);
24662 A = A.getOperand(0);
24664 B = B.getOperand(0);
24666 C = C.getOperand(0);
24670 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24672 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24674 return DAG.getNode(Opcode, dl, VT, A, B, C);
24677 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24678 TargetLowering::DAGCombinerInfo &DCI,
24679 const X86Subtarget *Subtarget) {
24680 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
24681 // (and (i32 x86isd::setcc_carry), 1)
24682 // This eliminates the zext. This transformation is necessary because
24683 // ISD::SETCC is always legalized to i8.
24685 SDValue N0 = N->getOperand(0);
24686 EVT VT = N->getValueType(0);
24688 if (N0.getOpcode() == ISD::AND &&
24690 N0.getOperand(0).hasOneUse()) {
24691 SDValue N00 = N0.getOperand(0);
24692 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24693 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24694 if (!C || C->getZExtValue() != 1)
24696 return DAG.getNode(ISD::AND, dl, VT,
24697 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24698 N00.getOperand(0), N00.getOperand(1)),
24699 DAG.getConstant(1, dl, VT));
24703 if (N0.getOpcode() == ISD::TRUNCATE &&
24705 N0.getOperand(0).hasOneUse()) {
24706 SDValue N00 = N0.getOperand(0);
24707 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24708 return DAG.getNode(ISD::AND, dl, VT,
24709 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24710 N00.getOperand(0), N00.getOperand(1)),
24711 DAG.getConstant(1, dl, VT));
24715 if (VT.is256BitVector())
24716 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24719 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24720 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24721 // This exposes the zext to the udivrem lowering, so that it directly extends
24722 // from AH (which we otherwise need to do contortions to access).
24723 if (N0.getOpcode() == ISD::UDIVREM &&
24724 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24725 (VT == MVT::i32 || VT == MVT::i64)) {
24726 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24727 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24728 N0.getOperand(0), N0.getOperand(1));
24729 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24730 return R.getValue(1);
24736 // Optimize x == -y --> x+y == 0
24737 // x != -y --> x+y != 0
24738 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24739 const X86Subtarget* Subtarget) {
24740 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24741 SDValue LHS = N->getOperand(0);
24742 SDValue RHS = N->getOperand(1);
24743 EVT VT = N->getValueType(0);
24746 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24747 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24748 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24749 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24750 LHS.getOperand(1));
24751 return DAG.getSetCC(DL, N->getValueType(0), addV,
24752 DAG.getConstant(0, DL, addV.getValueType()), CC);
24754 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24755 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24756 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24757 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24758 RHS.getOperand(1));
24759 return DAG.getSetCC(DL, N->getValueType(0), addV,
24760 DAG.getConstant(0, DL, addV.getValueType()), CC);
24763 if (VT.getScalarType() == MVT::i1 &&
24764 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24766 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24767 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24768 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24770 if (!IsSEXT0 || !IsVZero1) {
24771 // Swap the operands and update the condition code.
24772 std::swap(LHS, RHS);
24773 CC = ISD::getSetCCSwappedOperands(CC);
24775 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24776 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24777 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24780 if (IsSEXT0 && IsVZero1) {
24781 assert(VT == LHS.getOperand(0).getValueType() &&
24782 "Uexpected operand type");
24783 if (CC == ISD::SETGT)
24784 return DAG.getConstant(0, DL, VT);
24785 if (CC == ISD::SETLE)
24786 return DAG.getConstant(1, DL, VT);
24787 if (CC == ISD::SETEQ || CC == ISD::SETGE)
24788 return DAG.getNOT(DL, LHS.getOperand(0), VT);
24790 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24791 "Unexpected condition code!");
24792 return LHS.getOperand(0);
24799 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24800 SelectionDAG &DAG) {
24802 MVT VT = Load->getSimpleValueType(0);
24803 MVT EVT = VT.getVectorElementType();
24804 SDValue Addr = Load->getOperand(1);
24805 SDValue NewAddr = DAG.getNode(
24806 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24807 DAG.getConstant(Index * EVT.getStoreSize(), dl,
24808 Addr.getSimpleValueType()));
24811 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24812 DAG.getMachineFunction().getMachineMemOperand(
24813 Load->getMemOperand(), 0, EVT.getStoreSize()));
24817 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24818 const X86Subtarget *Subtarget) {
24820 MVT VT = N->getOperand(1)->getSimpleValueType(0);
24821 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24822 "X86insertps is only defined for v4x32");
24824 SDValue Ld = N->getOperand(1);
24825 if (MayFoldLoad(Ld)) {
24826 // Extract the countS bits from the immediate so we can get the proper
24827 // address when narrowing the vector load to a specific element.
24828 // When the second source op is a memory address, insertps doesn't use
24829 // countS and just gets an f32 from that address.
24830 unsigned DestIndex =
24831 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24833 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24835 // Create this as a scalar to vector to match the instruction pattern.
24836 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24837 // countS bits are ignored when loading from memory on insertps, which
24838 // means we don't need to explicitly set them to 0.
24839 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24840 LoadScalarToVector, N->getOperand(2));
24845 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24846 SDValue V0 = N->getOperand(0);
24847 SDValue V1 = N->getOperand(1);
24849 EVT VT = N->getValueType(0);
24851 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24852 // operands and changing the mask to 1. This saves us a bunch of
24853 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24854 // x86InstrInfo knows how to commute this back after instruction selection
24855 // if it would help register allocation.
24857 // TODO: If optimizing for size or a processor that doesn't suffer from
24858 // partial register update stalls, this should be transformed into a MOVSD
24859 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24861 if (VT == MVT::v2f64)
24862 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24863 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24864 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24865 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24871 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24872 // as "sbb reg,reg", since it can be extended without zext and produces
24873 // an all-ones bit which is more useful than 0/1 in some cases.
24874 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24877 return DAG.getNode(ISD::AND, DL, VT,
24878 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24879 DAG.getConstant(X86::COND_B, DL, MVT::i8),
24881 DAG.getConstant(1, DL, VT));
24882 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24883 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24884 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24885 DAG.getConstant(X86::COND_B, DL, MVT::i8),
24889 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24890 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24891 TargetLowering::DAGCombinerInfo &DCI,
24892 const X86Subtarget *Subtarget) {
24894 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24895 SDValue EFLAGS = N->getOperand(1);
24897 if (CC == X86::COND_A) {
24898 // Try to convert COND_A into COND_B in an attempt to facilitate
24899 // materializing "setb reg".
24901 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24902 // cannot take an immediate as its first operand.
24904 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24905 EFLAGS.getValueType().isInteger() &&
24906 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24907 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24908 EFLAGS.getNode()->getVTList(),
24909 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24910 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24911 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24915 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24916 // a zext and produces an all-ones bit which is more useful than 0/1 in some
24918 if (CC == X86::COND_B)
24919 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24921 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24922 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24923 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24929 // Optimize branch condition evaluation.
24931 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24932 TargetLowering::DAGCombinerInfo &DCI,
24933 const X86Subtarget *Subtarget) {
24935 SDValue Chain = N->getOperand(0);
24936 SDValue Dest = N->getOperand(1);
24937 SDValue EFLAGS = N->getOperand(3);
24938 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24940 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24941 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24942 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24949 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24950 SelectionDAG &DAG) {
24951 // Take advantage of vector comparisons producing 0 or -1 in each lane to
24952 // optimize away operation when it's from a constant.
24954 // The general transformation is:
24955 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24956 // AND(VECTOR_CMP(x,y), constant2)
24957 // constant2 = UNARYOP(constant)
24959 // Early exit if this isn't a vector operation, the operand of the
24960 // unary operation isn't a bitwise AND, or if the sizes of the operations
24961 // aren't the same.
24962 EVT VT = N->getValueType(0);
24963 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24964 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24965 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24968 // Now check that the other operand of the AND is a constant. We could
24969 // make the transformation for non-constant splats as well, but it's unclear
24970 // that would be a benefit as it would not eliminate any operations, just
24971 // perform one more step in scalar code before moving to the vector unit.
24972 if (BuildVectorSDNode *BV =
24973 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24974 // Bail out if the vector isn't a constant.
24975 if (!BV->isConstant())
24978 // Everything checks out. Build up the new and improved node.
24980 EVT IntVT = BV->getValueType(0);
24981 // Create a new constant of the appropriate type for the transformed
24983 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24984 // The AND node needs bitcasts to/from an integer vector type around it.
24985 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
24986 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24987 N->getOperand(0)->getOperand(0), MaskConst);
24988 SDValue Res = DAG.getBitcast(VT, NewAnd);
24995 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24996 const X86Subtarget *Subtarget) {
24997 SDValue Op0 = N->getOperand(0);
24998 EVT VT = N->getValueType(0);
24999 EVT InVT = Op0.getValueType();
25000 EVT InSVT = InVT.getScalarType();
25001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25003 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25004 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25005 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25007 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25008 InVT.getVectorNumElements());
25009 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25011 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25012 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25014 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25020 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25021 const X86Subtarget *Subtarget) {
25022 // First try to optimize away the conversion entirely when it's
25023 // conditionally from a constant. Vectors only.
25024 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25027 // Now move on to more general possibilities.
25028 SDValue Op0 = N->getOperand(0);
25029 EVT VT = N->getValueType(0);
25030 EVT InVT = Op0.getValueType();
25031 EVT InSVT = InVT.getScalarType();
25033 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25034 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25035 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25037 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25038 InVT.getVectorNumElements());
25039 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25040 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25043 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25044 // a 32-bit target where SSE doesn't support i64->FP operations.
25045 if (Op0.getOpcode() == ISD::LOAD) {
25046 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25047 EVT LdVT = Ld->getValueType(0);
25049 // This transformation is not supported if the result type is f16
25050 if (VT == MVT::f16)
25053 if (!Ld->isVolatile() && !VT.isVector() &&
25054 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25055 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25056 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25057 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25058 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25065 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25066 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25067 X86TargetLowering::DAGCombinerInfo &DCI) {
25068 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25069 // the result is either zero or one (depending on the input carry bit).
25070 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25071 if (X86::isZeroNode(N->getOperand(0)) &&
25072 X86::isZeroNode(N->getOperand(1)) &&
25073 // We don't have a good way to replace an EFLAGS use, so only do this when
25075 SDValue(N, 1).use_empty()) {
25077 EVT VT = N->getValueType(0);
25078 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25079 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25080 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25081 DAG.getConstant(X86::COND_B, DL,
25084 DAG.getConstant(1, DL, VT));
25085 return DCI.CombineTo(N, Res1, CarryOut);
25091 // fold (add Y, (sete X, 0)) -> adc 0, Y
25092 // (add Y, (setne X, 0)) -> sbb -1, Y
25093 // (sub (sete X, 0), Y) -> sbb 0, Y
25094 // (sub (setne X, 0), Y) -> adc -1, Y
25095 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25098 // Look through ZExts.
25099 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25100 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25103 SDValue SetCC = Ext.getOperand(0);
25104 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25107 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25108 if (CC != X86::COND_E && CC != X86::COND_NE)
25111 SDValue Cmp = SetCC.getOperand(1);
25112 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25113 !X86::isZeroNode(Cmp.getOperand(1)) ||
25114 !Cmp.getOperand(0).getValueType().isInteger())
25117 SDValue CmpOp0 = Cmp.getOperand(0);
25118 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25119 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25121 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25122 if (CC == X86::COND_NE)
25123 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25124 DL, OtherVal.getValueType(), OtherVal,
25125 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25127 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25128 DL, OtherVal.getValueType(), OtherVal,
25129 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25132 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25133 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25134 const X86Subtarget *Subtarget) {
25135 EVT VT = N->getValueType(0);
25136 SDValue Op0 = N->getOperand(0);
25137 SDValue Op1 = N->getOperand(1);
25139 // Try to synthesize horizontal adds from adds of shuffles.
25140 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25141 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25142 isHorizontalBinOp(Op0, Op1, true))
25143 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25145 return OptimizeConditionalInDecrement(N, DAG);
25148 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25149 const X86Subtarget *Subtarget) {
25150 SDValue Op0 = N->getOperand(0);
25151 SDValue Op1 = N->getOperand(1);
25153 // X86 can't encode an immediate LHS of a sub. See if we can push the
25154 // negation into a preceding instruction.
25155 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25156 // If the RHS of the sub is a XOR with one use and a constant, invert the
25157 // immediate. Then add one to the LHS of the sub so we can turn
25158 // X-Y -> X+~Y+1, saving one register.
25159 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25160 isa<ConstantSDNode>(Op1.getOperand(1))) {
25161 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25162 EVT VT = Op0.getValueType();
25163 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25165 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25166 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25167 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25171 // Try to synthesize horizontal adds from adds of shuffles.
25172 EVT VT = N->getValueType(0);
25173 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25174 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25175 isHorizontalBinOp(Op0, Op1, true))
25176 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25178 return OptimizeConditionalInDecrement(N, DAG);
25181 /// performVZEXTCombine - Performs build vector combines
25182 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25183 TargetLowering::DAGCombinerInfo &DCI,
25184 const X86Subtarget *Subtarget) {
25186 MVT VT = N->getSimpleValueType(0);
25187 SDValue Op = N->getOperand(0);
25188 MVT OpVT = Op.getSimpleValueType();
25189 MVT OpEltVT = OpVT.getVectorElementType();
25190 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25192 // (vzext (bitcast (vzext (x)) -> (vzext x)
25194 while (V.getOpcode() == ISD::BITCAST)
25195 V = V.getOperand(0);
25197 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25198 MVT InnerVT = V.getSimpleValueType();
25199 MVT InnerEltVT = InnerVT.getVectorElementType();
25201 // If the element sizes match exactly, we can just do one larger vzext. This
25202 // is always an exact type match as vzext operates on integer types.
25203 if (OpEltVT == InnerEltVT) {
25204 assert(OpVT == InnerVT && "Types must match for vzext!");
25205 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25208 // The only other way we can combine them is if only a single element of the
25209 // inner vzext is used in the input to the outer vzext.
25210 if (InnerEltVT.getSizeInBits() < InputBits)
25213 // In this case, the inner vzext is completely dead because we're going to
25214 // only look at bits inside of the low element. Just do the outer vzext on
25215 // a bitcast of the input to the inner.
25216 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25219 // Check if we can bypass extracting and re-inserting an element of an input
25220 // vector. Essentialy:
25221 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25222 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25223 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25224 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25225 SDValue ExtractedV = V.getOperand(0);
25226 SDValue OrigV = ExtractedV.getOperand(0);
25227 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25228 if (ExtractIdx->getZExtValue() == 0) {
25229 MVT OrigVT = OrigV.getSimpleValueType();
25230 // Extract a subvector if necessary...
25231 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25232 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25233 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25234 OrigVT.getVectorNumElements() / Ratio);
25235 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25236 DAG.getIntPtrConstant(0, DL));
25238 Op = DAG.getBitcast(OpVT, OrigV);
25239 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25246 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25247 DAGCombinerInfo &DCI) const {
25248 SelectionDAG &DAG = DCI.DAG;
25249 switch (N->getOpcode()) {
25251 case ISD::EXTRACT_VECTOR_ELT:
25252 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25255 case X86ISD::SHRUNKBLEND:
25256 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25257 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25258 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25259 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25260 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25261 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25262 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25265 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25266 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25267 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25268 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25269 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25270 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25271 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25272 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25273 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25274 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25275 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25276 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25278 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25280 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25281 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25282 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25283 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25284 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25285 case ISD::ANY_EXTEND:
25286 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25287 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25288 case ISD::SIGN_EXTEND_INREG:
25289 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25290 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25291 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25292 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25293 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25294 case X86ISD::SHUFP: // Handle all target specific shuffles
25295 case X86ISD::PALIGNR:
25296 case X86ISD::UNPCKH:
25297 case X86ISD::UNPCKL:
25298 case X86ISD::MOVHLPS:
25299 case X86ISD::MOVLHPS:
25300 case X86ISD::PSHUFB:
25301 case X86ISD::PSHUFD:
25302 case X86ISD::PSHUFHW:
25303 case X86ISD::PSHUFLW:
25304 case X86ISD::MOVSS:
25305 case X86ISD::MOVSD:
25306 case X86ISD::VPERMILPI:
25307 case X86ISD::VPERM2X128:
25308 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25309 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25310 case ISD::INTRINSIC_WO_CHAIN:
25311 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25312 case X86ISD::INSERTPS: {
25313 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25314 return PerformINSERTPSCombine(N, DAG, Subtarget);
25317 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25323 /// isTypeDesirableForOp - Return true if the target has native support for
25324 /// the specified value type and it is 'desirable' to use the type for the
25325 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25326 /// instruction encodings are longer and some i16 instructions are slow.
25327 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25328 if (!isTypeLegal(VT))
25330 if (VT != MVT::i16)
25337 case ISD::SIGN_EXTEND:
25338 case ISD::ZERO_EXTEND:
25339 case ISD::ANY_EXTEND:
25352 /// IsDesirableToPromoteOp - This method query the target whether it is
25353 /// beneficial for dag combiner to promote the specified node. If true, it
25354 /// should return the desired promotion type by reference.
25355 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25356 EVT VT = Op.getValueType();
25357 if (VT != MVT::i16)
25360 bool Promote = false;
25361 bool Commute = false;
25362 switch (Op.getOpcode()) {
25365 LoadSDNode *LD = cast<LoadSDNode>(Op);
25366 // If the non-extending load has a single use and it's not live out, then it
25367 // might be folded.
25368 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25369 Op.hasOneUse()*/) {
25370 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25371 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25372 // The only case where we'd want to promote LOAD (rather then it being
25373 // promoted as an operand is when it's only use is liveout.
25374 if (UI->getOpcode() != ISD::CopyToReg)
25381 case ISD::SIGN_EXTEND:
25382 case ISD::ZERO_EXTEND:
25383 case ISD::ANY_EXTEND:
25388 SDValue N0 = Op.getOperand(0);
25389 // Look out for (store (shl (load), x)).
25390 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25403 SDValue N0 = Op.getOperand(0);
25404 SDValue N1 = Op.getOperand(1);
25405 if (!Commute && MayFoldLoad(N1))
25407 // Avoid disabling potential load folding opportunities.
25408 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25410 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25420 //===----------------------------------------------------------------------===//
25421 // X86 Inline Assembly Support
25422 //===----------------------------------------------------------------------===//
25424 // Helper to match a string separated by whitespace.
25425 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25426 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25428 for (StringRef Piece : Pieces) {
25429 if (!S.startswith(Piece)) // Check if the piece matches.
25432 S = S.substr(Piece.size());
25433 StringRef::size_type Pos = S.find_first_not_of(" \t");
25434 if (Pos == 0) // We matched a prefix.
25443 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25445 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25446 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25447 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25448 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25450 if (AsmPieces.size() == 3)
25452 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25459 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25460 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25462 std::string AsmStr = IA->getAsmString();
25464 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25465 if (!Ty || Ty->getBitWidth() % 16 != 0)
25468 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25469 SmallVector<StringRef, 4> AsmPieces;
25470 SplitString(AsmStr, AsmPieces, ";\n");
25472 switch (AsmPieces.size()) {
25473 default: return false;
25475 // FIXME: this should verify that we are targeting a 486 or better. If not,
25476 // we will turn this bswap into something that will be lowered to logical
25477 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25478 // lower so don't worry about this.
25480 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25481 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25482 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25483 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25484 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25485 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25486 // No need to check constraints, nothing other than the equivalent of
25487 // "=r,0" would be valid here.
25488 return IntrinsicLowering::LowerToByteSwap(CI);
25491 // rorw $$8, ${0:w} --> llvm.bswap.i16
25492 if (CI->getType()->isIntegerTy(16) &&
25493 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25494 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25495 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25497 StringRef ConstraintsStr = IA->getConstraintString();
25498 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25499 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25500 if (clobbersFlagRegisters(AsmPieces))
25501 return IntrinsicLowering::LowerToByteSwap(CI);
25505 if (CI->getType()->isIntegerTy(32) &&
25506 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25507 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25508 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25509 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25511 StringRef ConstraintsStr = IA->getConstraintString();
25512 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25513 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25514 if (clobbersFlagRegisters(AsmPieces))
25515 return IntrinsicLowering::LowerToByteSwap(CI);
25518 if (CI->getType()->isIntegerTy(64)) {
25519 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25520 if (Constraints.size() >= 2 &&
25521 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25522 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25523 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
25524 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25525 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25526 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25527 return IntrinsicLowering::LowerToByteSwap(CI);
25535 /// getConstraintType - Given a constraint letter, return the type of
25536 /// constraint it is for this target.
25537 X86TargetLowering::ConstraintType
25538 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25539 if (Constraint.size() == 1) {
25540 switch (Constraint[0]) {
25551 return C_RegisterClass;
25575 return TargetLowering::getConstraintType(Constraint);
25578 /// Examine constraint type and operand type and determine a weight value.
25579 /// This object must already have been set up with the operand type
25580 /// and the current alternative constraint selected.
25581 TargetLowering::ConstraintWeight
25582 X86TargetLowering::getSingleConstraintMatchWeight(
25583 AsmOperandInfo &info, const char *constraint) const {
25584 ConstraintWeight weight = CW_Invalid;
25585 Value *CallOperandVal = info.CallOperandVal;
25586 // If we don't have a value, we can't do a match,
25587 // but allow it at the lowest weight.
25588 if (!CallOperandVal)
25590 Type *type = CallOperandVal->getType();
25591 // Look at the constraint type.
25592 switch (*constraint) {
25594 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25605 if (CallOperandVal->getType()->isIntegerTy())
25606 weight = CW_SpecificReg;
25611 if (type->isFloatingPointTy())
25612 weight = CW_SpecificReg;
25615 if (type->isX86_MMXTy() && Subtarget->hasMMX())
25616 weight = CW_SpecificReg;
25620 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25621 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25622 weight = CW_Register;
25625 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25626 if (C->getZExtValue() <= 31)
25627 weight = CW_Constant;
25631 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25632 if (C->getZExtValue() <= 63)
25633 weight = CW_Constant;
25637 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25638 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25639 weight = CW_Constant;
25643 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25644 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25645 weight = CW_Constant;
25649 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25650 if (C->getZExtValue() <= 3)
25651 weight = CW_Constant;
25655 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25656 if (C->getZExtValue() <= 0xff)
25657 weight = CW_Constant;
25662 if (isa<ConstantFP>(CallOperandVal)) {
25663 weight = CW_Constant;
25667 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25668 if ((C->getSExtValue() >= -0x80000000LL) &&
25669 (C->getSExtValue() <= 0x7fffffffLL))
25670 weight = CW_Constant;
25674 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25675 if (C->getZExtValue() <= 0xffffffff)
25676 weight = CW_Constant;
25683 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25684 /// with another that has more specific requirements based on the type of the
25685 /// corresponding operand.
25686 const char *X86TargetLowering::
25687 LowerXConstraint(EVT ConstraintVT) const {
25688 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25689 // 'f' like normal targets.
25690 if (ConstraintVT.isFloatingPoint()) {
25691 if (Subtarget->hasSSE2())
25693 if (Subtarget->hasSSE1())
25697 return TargetLowering::LowerXConstraint(ConstraintVT);
25700 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25701 /// vector. If it is invalid, don't add anything to Ops.
25702 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25703 std::string &Constraint,
25704 std::vector<SDValue>&Ops,
25705 SelectionDAG &DAG) const {
25708 // Only support length 1 constraints for now.
25709 if (Constraint.length() > 1) return;
25711 char ConstraintLetter = Constraint[0];
25712 switch (ConstraintLetter) {
25715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25716 if (C->getZExtValue() <= 31) {
25717 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25718 Op.getValueType());
25724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25725 if (C->getZExtValue() <= 63) {
25726 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25727 Op.getValueType());
25733 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25734 if (isInt<8>(C->getSExtValue())) {
25735 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25736 Op.getValueType());
25742 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25743 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25744 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25745 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25746 Op.getValueType());
25752 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25753 if (C->getZExtValue() <= 3) {
25754 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25755 Op.getValueType());
25761 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25762 if (C->getZExtValue() <= 255) {
25763 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25764 Op.getValueType());
25770 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25771 if (C->getZExtValue() <= 127) {
25772 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25773 Op.getValueType());
25779 // 32-bit signed value
25780 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25781 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25782 C->getSExtValue())) {
25783 // Widen to 64 bits here to get it sign extended.
25784 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25787 // FIXME gcc accepts some relocatable values here too, but only in certain
25788 // memory models; it's complicated.
25793 // 32-bit unsigned value
25794 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25795 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25796 C->getZExtValue())) {
25797 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25798 Op.getValueType());
25802 // FIXME gcc accepts some relocatable values here too, but only in certain
25803 // memory models; it's complicated.
25807 // Literal immediates are always ok.
25808 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25809 // Widen to 64 bits here to get it sign extended.
25810 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25814 // In any sort of PIC mode addresses need to be computed at runtime by
25815 // adding in a register or some sort of table lookup. These can't
25816 // be used as immediates.
25817 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25820 // If we are in non-pic codegen mode, we allow the address of a global (with
25821 // an optional displacement) to be used with 'i'.
25822 GlobalAddressSDNode *GA = nullptr;
25823 int64_t Offset = 0;
25825 // Match either (GA), (GA+C), (GA+C1+C2), etc.
25827 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25828 Offset += GA->getOffset();
25830 } else if (Op.getOpcode() == ISD::ADD) {
25831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25832 Offset += C->getZExtValue();
25833 Op = Op.getOperand(0);
25836 } else if (Op.getOpcode() == ISD::SUB) {
25837 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25838 Offset += -C->getZExtValue();
25839 Op = Op.getOperand(0);
25844 // Otherwise, this isn't something we can handle, reject it.
25848 const GlobalValue *GV = GA->getGlobal();
25849 // If we require an extra load to get this address, as in PIC mode, we
25850 // can't accept it.
25851 if (isGlobalStubReference(
25852 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25855 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25856 GA->getValueType(0), Offset);
25861 if (Result.getNode()) {
25862 Ops.push_back(Result);
25865 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25868 std::pair<unsigned, const TargetRegisterClass *>
25869 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25870 StringRef Constraint,
25872 // First, see if this is a constraint that directly corresponds to an LLVM
25874 if (Constraint.size() == 1) {
25875 // GCC Constraint Letters
25876 switch (Constraint[0]) {
25878 // TODO: Slight differences here in allocation order and leaving
25879 // RIP in the class. Do they matter any more here than they do
25880 // in the normal allocation?
25881 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25882 if (Subtarget->is64Bit()) {
25883 if (VT == MVT::i32 || VT == MVT::f32)
25884 return std::make_pair(0U, &X86::GR32RegClass);
25885 if (VT == MVT::i16)
25886 return std::make_pair(0U, &X86::GR16RegClass);
25887 if (VT == MVT::i8 || VT == MVT::i1)
25888 return std::make_pair(0U, &X86::GR8RegClass);
25889 if (VT == MVT::i64 || VT == MVT::f64)
25890 return std::make_pair(0U, &X86::GR64RegClass);
25893 // 32-bit fallthrough
25894 case 'Q': // Q_REGS
25895 if (VT == MVT::i32 || VT == MVT::f32)
25896 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25897 if (VT == MVT::i16)
25898 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25899 if (VT == MVT::i8 || VT == MVT::i1)
25900 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25901 if (VT == MVT::i64)
25902 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25904 case 'r': // GENERAL_REGS
25905 case 'l': // INDEX_REGS
25906 if (VT == MVT::i8 || VT == MVT::i1)
25907 return std::make_pair(0U, &X86::GR8RegClass);
25908 if (VT == MVT::i16)
25909 return std::make_pair(0U, &X86::GR16RegClass);
25910 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25911 return std::make_pair(0U, &X86::GR32RegClass);
25912 return std::make_pair(0U, &X86::GR64RegClass);
25913 case 'R': // LEGACY_REGS
25914 if (VT == MVT::i8 || VT == MVT::i1)
25915 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25916 if (VT == MVT::i16)
25917 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25918 if (VT == MVT::i32 || !Subtarget->is64Bit())
25919 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25920 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25921 case 'f': // FP Stack registers.
25922 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25923 // value to the correct fpstack register class.
25924 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25925 return std::make_pair(0U, &X86::RFP32RegClass);
25926 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25927 return std::make_pair(0U, &X86::RFP64RegClass);
25928 return std::make_pair(0U, &X86::RFP80RegClass);
25929 case 'y': // MMX_REGS if MMX allowed.
25930 if (!Subtarget->hasMMX()) break;
25931 return std::make_pair(0U, &X86::VR64RegClass);
25932 case 'Y': // SSE_REGS if SSE2 allowed
25933 if (!Subtarget->hasSSE2()) break;
25935 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25936 if (!Subtarget->hasSSE1()) break;
25938 switch (VT.SimpleTy) {
25940 // Scalar SSE types.
25943 return std::make_pair(0U, &X86::FR32RegClass);
25946 return std::make_pair(0U, &X86::FR64RegClass);
25954 return std::make_pair(0U, &X86::VR128RegClass);
25962 return std::make_pair(0U, &X86::VR256RegClass);
25967 return std::make_pair(0U, &X86::VR512RegClass);
25973 // Use the default implementation in TargetLowering to convert the register
25974 // constraint into a member of a register class.
25975 std::pair<unsigned, const TargetRegisterClass*> Res;
25976 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25978 // Not found as a standard register?
25980 // Map st(0) -> st(7) -> ST0
25981 if (Constraint.size() == 7 && Constraint[0] == '{' &&
25982 tolower(Constraint[1]) == 's' &&
25983 tolower(Constraint[2]) == 't' &&
25984 Constraint[3] == '(' &&
25985 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25986 Constraint[5] == ')' &&
25987 Constraint[6] == '}') {
25989 Res.first = X86::FP0+Constraint[4]-'0';
25990 Res.second = &X86::RFP80RegClass;
25994 // GCC allows "st(0)" to be called just plain "st".
25995 if (StringRef("{st}").equals_lower(Constraint)) {
25996 Res.first = X86::FP0;
25997 Res.second = &X86::RFP80RegClass;
26002 if (StringRef("{flags}").equals_lower(Constraint)) {
26003 Res.first = X86::EFLAGS;
26004 Res.second = &X86::CCRRegClass;
26008 // 'A' means EAX + EDX.
26009 if (Constraint == "A") {
26010 Res.first = X86::EAX;
26011 Res.second = &X86::GR32_ADRegClass;
26017 // Otherwise, check to see if this is a register class of the wrong value
26018 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26019 // turn into {ax},{dx}.
26020 // MVT::Other is used to specify clobber names.
26021 if (Res.second->hasType(VT) || VT == MVT::Other)
26022 return Res; // Correct type already, nothing to do.
26024 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26025 // return "eax". This should even work for things like getting 64bit integer
26026 // registers when given an f64 type.
26027 const TargetRegisterClass *Class = Res.second;
26028 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26029 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26030 unsigned Size = VT.getSizeInBits();
26031 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26032 : Size == 16 ? MVT::i16
26033 : Size == 32 ? MVT::i32
26034 : Size == 64 ? MVT::i64
26036 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26038 Res.first = DestReg;
26039 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26040 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26041 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26042 : &X86::GR64RegClass;
26043 assert(Res.second->contains(Res.first) && "Register in register class");
26045 // No register found/type mismatch.
26047 Res.second = nullptr;
26049 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26050 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26051 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26052 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26053 Class == &X86::VR512RegClass) {
26054 // Handle references to XMM physical registers that got mapped into the
26055 // wrong class. This can happen with constraints like {xmm0} where the
26056 // target independent register mapper will just pick the first match it can
26057 // find, ignoring the required type.
26059 if (VT == MVT::f32 || VT == MVT::i32)
26060 Res.second = &X86::FR32RegClass;
26061 else if (VT == MVT::f64 || VT == MVT::i64)
26062 Res.second = &X86::FR64RegClass;
26063 else if (X86::VR128RegClass.hasType(VT))
26064 Res.second = &X86::VR128RegClass;
26065 else if (X86::VR256RegClass.hasType(VT))
26066 Res.second = &X86::VR256RegClass;
26067 else if (X86::VR512RegClass.hasType(VT))
26068 Res.second = &X86::VR512RegClass;
26070 // Type mismatch and not a clobber: Return an error;
26072 Res.second = nullptr;
26079 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26081 unsigned AS) const {
26082 // Scaling factors are not free at all.
26083 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26084 // will take 2 allocations in the out of order engine instead of 1
26085 // for plain addressing mode, i.e. inst (reg1).
26087 // vaddps (%rsi,%drx), %ymm0, %ymm1
26088 // Requires two allocations (one for the load, one for the computation)
26090 // vaddps (%rsi), %ymm0, %ymm1
26091 // Requires just 1 allocation, i.e., freeing allocations for other operations
26092 // and having less micro operations to execute.
26094 // For some X86 architectures, this is even worse because for instance for
26095 // stores, the complex addressing mode forces the instruction to use the
26096 // "load" ports instead of the dedicated "store" port.
26097 // E.g., on Haswell:
26098 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26099 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26100 if (isLegalAddressingMode(AM, Ty, AS))
26101 // Scale represents reg2 * scale, thus account for 1
26102 // as soon as we use a second register.
26103 return AM.Scale != 0;
26107 bool X86TargetLowering::isTargetFTOL() const {
26108 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();