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();
79 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
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, PtrVT, 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 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1352 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1353 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1354 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1355 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1356 if (Subtarget->hasVLX()){
1357 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1358 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1359 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1360 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1361 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1363 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1364 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1365 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1366 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1367 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1369 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1372 if (Subtarget->hasDQI()) {
1373 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1374 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1376 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1378 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1379 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1380 if (Subtarget->hasVLX()) {
1381 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1382 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1383 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1384 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1385 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1386 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1387 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1388 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1391 if (Subtarget->hasVLX()) {
1392 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1393 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1394 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1395 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1396 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1397 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1398 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1399 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1401 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1402 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1403 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1404 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1405 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1406 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1407 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1408 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1409 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1410 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1411 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1412 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1413 if (Subtarget->hasDQI()) {
1414 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1415 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1417 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1418 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1419 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1420 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1421 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1422 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1423 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1424 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1425 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1426 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1428 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1429 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1430 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1431 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1432 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1434 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1435 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1437 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1439 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1440 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1441 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1442 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1443 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1444 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1445 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1446 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1447 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1448 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1449 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1451 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1452 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1453 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1454 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1455 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1456 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1457 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1458 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1460 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1461 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1463 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1464 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1466 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1468 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1469 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1471 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1472 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1474 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1475 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1477 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1478 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1479 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1481 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1482 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1484 if (Subtarget->hasCDI()) {
1485 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1486 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1488 if (Subtarget->hasDQI()) {
1489 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1490 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1491 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1493 // Custom lower several nodes.
1494 for (MVT VT : MVT::vector_valuetypes()) {
1495 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1497 setOperationAction(ISD::AND, VT, Legal);
1498 setOperationAction(ISD::OR, VT, Legal);
1499 setOperationAction(ISD::XOR, VT, Legal);
1501 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1502 setOperationAction(ISD::MGATHER, VT, Custom);
1503 setOperationAction(ISD::MSCATTER, VT, Custom);
1505 // Extract subvector is special because the value type
1506 // (result) is 256/128-bit but the source is 512-bit wide.
1507 if (VT.is128BitVector() || VT.is256BitVector()) {
1508 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1510 if (VT.getVectorElementType() == MVT::i1)
1511 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1513 // Do not attempt to custom lower other non-512-bit vectors
1514 if (!VT.is512BitVector())
1517 if (EltSize >= 32) {
1518 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1519 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1520 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1521 setOperationAction(ISD::VSELECT, VT, Legal);
1522 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1523 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1524 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1525 setOperationAction(ISD::MLOAD, VT, Legal);
1526 setOperationAction(ISD::MSTORE, VT, Legal);
1529 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1530 MVT VT = (MVT::SimpleValueType)i;
1532 // Do not attempt to promote non-512-bit vectors.
1533 if (!VT.is512BitVector())
1536 setOperationAction(ISD::SELECT, VT, Promote);
1537 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1541 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1542 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1543 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1545 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1546 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1548 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1549 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1550 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1551 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1552 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1553 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1554 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1555 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1556 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1557 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1558 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1559 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1560 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1561 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1562 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1563 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1564 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1565 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1566 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1567 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1568 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1569 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1570 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1571 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1572 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1573 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1574 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1575 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1576 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1577 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1579 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1580 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1581 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1582 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1583 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1584 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1585 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1586 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1588 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1589 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1590 if (Subtarget->hasVLX())
1591 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1593 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1594 const MVT VT = (MVT::SimpleValueType)i;
1596 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1598 // Do not attempt to promote non-512-bit vectors.
1599 if (!VT.is512BitVector())
1603 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1604 setOperationAction(ISD::VSELECT, VT, Legal);
1609 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1610 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1611 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1613 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1614 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1615 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1616 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1617 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1618 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1619 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1620 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1621 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1622 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1624 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1625 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1626 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1627 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1628 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1629 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1630 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1631 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1633 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1634 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1635 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1636 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1637 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1638 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1639 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1640 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1643 // We want to custom lower some of our intrinsics.
1644 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1645 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1646 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1647 if (!Subtarget->is64Bit())
1648 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1650 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1651 // handle type legalization for these operations here.
1653 // FIXME: We really should do custom legalization for addition and
1654 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1655 // than generic legalization for 64-bit multiplication-with-overflow, though.
1656 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1657 // Add/Sub/Mul with overflow operations are custom lowered.
1659 setOperationAction(ISD::SADDO, VT, Custom);
1660 setOperationAction(ISD::UADDO, VT, Custom);
1661 setOperationAction(ISD::SSUBO, VT, Custom);
1662 setOperationAction(ISD::USUBO, VT, Custom);
1663 setOperationAction(ISD::SMULO, VT, Custom);
1664 setOperationAction(ISD::UMULO, VT, Custom);
1668 if (!Subtarget->is64Bit()) {
1669 // These libcalls are not available in 32-bit.
1670 setLibcallName(RTLIB::SHL_I128, nullptr);
1671 setLibcallName(RTLIB::SRL_I128, nullptr);
1672 setLibcallName(RTLIB::SRA_I128, nullptr);
1675 // Combine sin / cos into one node or libcall if possible.
1676 if (Subtarget->hasSinCos()) {
1677 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1678 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1679 if (Subtarget->isTargetDarwin()) {
1680 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1681 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1682 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1683 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1687 if (Subtarget->isTargetWin64()) {
1688 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1689 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1690 setOperationAction(ISD::SREM, MVT::i128, Custom);
1691 setOperationAction(ISD::UREM, MVT::i128, Custom);
1692 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1693 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1696 // We have target-specific dag combine patterns for the following nodes:
1697 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1698 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1699 setTargetDAGCombine(ISD::BITCAST);
1700 setTargetDAGCombine(ISD::VSELECT);
1701 setTargetDAGCombine(ISD::SELECT);
1702 setTargetDAGCombine(ISD::SHL);
1703 setTargetDAGCombine(ISD::SRA);
1704 setTargetDAGCombine(ISD::SRL);
1705 setTargetDAGCombine(ISD::OR);
1706 setTargetDAGCombine(ISD::AND);
1707 setTargetDAGCombine(ISD::ADD);
1708 setTargetDAGCombine(ISD::FADD);
1709 setTargetDAGCombine(ISD::FSUB);
1710 setTargetDAGCombine(ISD::FMA);
1711 setTargetDAGCombine(ISD::SUB);
1712 setTargetDAGCombine(ISD::LOAD);
1713 setTargetDAGCombine(ISD::MLOAD);
1714 setTargetDAGCombine(ISD::STORE);
1715 setTargetDAGCombine(ISD::MSTORE);
1716 setTargetDAGCombine(ISD::ZERO_EXTEND);
1717 setTargetDAGCombine(ISD::ANY_EXTEND);
1718 setTargetDAGCombine(ISD::SIGN_EXTEND);
1719 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1720 setTargetDAGCombine(ISD::SINT_TO_FP);
1721 setTargetDAGCombine(ISD::UINT_TO_FP);
1722 setTargetDAGCombine(ISD::SETCC);
1723 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1724 setTargetDAGCombine(ISD::BUILD_VECTOR);
1725 setTargetDAGCombine(ISD::MUL);
1726 setTargetDAGCombine(ISD::XOR);
1728 computeRegisterProperties(Subtarget->getRegisterInfo());
1730 // On Darwin, -Os means optimize for size without hurting performance,
1731 // do not reduce the limit.
1732 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1733 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1734 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1735 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1736 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1737 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1738 setPrefLoopAlignment(4); // 2^4 bytes.
1740 // Predictable cmov don't hurt on atom because it's in-order.
1741 PredictableSelectIsExpensive = !Subtarget->isAtom();
1742 EnableExtLdPromotion = true;
1743 setPrefFunctionAlignment(4); // 2^4 bytes.
1745 verifyIntrinsicTables();
1748 // This has so far only been implemented for 64-bit MachO.
1749 bool X86TargetLowering::useLoadStackGuardNode() const {
1750 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1753 TargetLoweringBase::LegalizeTypeAction
1754 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1755 if (ExperimentalVectorWideningLegalization &&
1756 VT.getVectorNumElements() != 1 &&
1757 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1758 return TypeWidenVector;
1760 return TargetLoweringBase::getPreferredVectorAction(VT);
1763 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1766 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1768 const unsigned NumElts = VT.getVectorNumElements();
1769 const EVT EltVT = VT.getVectorElementType();
1770 if (VT.is512BitVector()) {
1771 if (Subtarget->hasAVX512())
1772 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1773 EltVT == MVT::f32 || EltVT == MVT::f64)
1775 case 8: return MVT::v8i1;
1776 case 16: return MVT::v16i1;
1778 if (Subtarget->hasBWI())
1779 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1781 case 32: return MVT::v32i1;
1782 case 64: return MVT::v64i1;
1786 if (VT.is256BitVector() || VT.is128BitVector()) {
1787 if (Subtarget->hasVLX())
1788 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1789 EltVT == MVT::f32 || EltVT == MVT::f64)
1791 case 2: return MVT::v2i1;
1792 case 4: return MVT::v4i1;
1793 case 8: return MVT::v8i1;
1795 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1796 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1798 case 8: return MVT::v8i1;
1799 case 16: return MVT::v16i1;
1800 case 32: return MVT::v32i1;
1804 return VT.changeVectorElementTypeToInteger();
1807 /// Helper for getByValTypeAlignment to determine
1808 /// the desired ByVal argument alignment.
1809 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1812 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1813 if (VTy->getBitWidth() == 128)
1815 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1816 unsigned EltAlign = 0;
1817 getMaxByValAlign(ATy->getElementType(), EltAlign);
1818 if (EltAlign > MaxAlign)
1819 MaxAlign = EltAlign;
1820 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1821 for (auto *EltTy : STy->elements()) {
1822 unsigned EltAlign = 0;
1823 getMaxByValAlign(EltTy, EltAlign);
1824 if (EltAlign > MaxAlign)
1825 MaxAlign = EltAlign;
1832 /// Return the desired alignment for ByVal aggregate
1833 /// function arguments in the caller parameter area. For X86, aggregates
1834 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1835 /// are at 4-byte boundaries.
1836 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1837 const DataLayout &DL) const {
1838 if (Subtarget->is64Bit()) {
1839 // Max of 8 and alignment of type.
1840 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1847 if (Subtarget->hasSSE1())
1848 getMaxByValAlign(Ty, Align);
1852 /// Returns the target specific optimal type for load
1853 /// and store operations as a result of memset, memcpy, and memmove
1854 /// lowering. If DstAlign is zero that means it's safe to destination
1855 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1856 /// means there isn't a need to check it against alignment requirement,
1857 /// probably because the source does not need to be loaded. If 'IsMemset' is
1858 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1859 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1860 /// source is constant so it does not need to be loaded.
1861 /// It returns EVT::Other if the type should be determined using generic
1862 /// target-independent logic.
1864 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1865 unsigned DstAlign, unsigned SrcAlign,
1866 bool IsMemset, bool ZeroMemset,
1868 MachineFunction &MF) const {
1869 const Function *F = MF.getFunction();
1870 if ((!IsMemset || ZeroMemset) &&
1871 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1873 (Subtarget->isUnalignedMemAccessFast() ||
1874 ((DstAlign == 0 || DstAlign >= 16) &&
1875 (SrcAlign == 0 || SrcAlign >= 16)))) {
1877 if (Subtarget->hasInt256())
1879 if (Subtarget->hasFp256())
1882 if (Subtarget->hasSSE2())
1884 if (Subtarget->hasSSE1())
1886 } else if (!MemcpyStrSrc && Size >= 8 &&
1887 !Subtarget->is64Bit() &&
1888 Subtarget->hasSSE2()) {
1889 // Do not use f64 to lower memcpy if source is string constant. It's
1890 // better to use i32 to avoid the loads.
1894 if (Subtarget->is64Bit() && Size >= 8)
1899 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1901 return X86ScalarSSEf32;
1902 else if (VT == MVT::f64)
1903 return X86ScalarSSEf64;
1908 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1913 *Fast = Subtarget->isUnalignedMemAccessFast();
1917 /// Return the entry encoding for a jump table in the
1918 /// current function. The returned value is a member of the
1919 /// MachineJumpTableInfo::JTEntryKind enum.
1920 unsigned X86TargetLowering::getJumpTableEncoding() const {
1921 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1923 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1924 Subtarget->isPICStyleGOT())
1925 return MachineJumpTableInfo::EK_Custom32;
1927 // Otherwise, use the normal jump table encoding heuristics.
1928 return TargetLowering::getJumpTableEncoding();
1931 bool X86TargetLowering::useSoftFloat() const {
1932 return Subtarget->useSoftFloat();
1936 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1937 const MachineBasicBlock *MBB,
1938 unsigned uid,MCContext &Ctx) const{
1939 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1940 Subtarget->isPICStyleGOT());
1941 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1943 return MCSymbolRefExpr::create(MBB->getSymbol(),
1944 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1947 /// Returns relocation base for the given PIC jumptable.
1948 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1949 SelectionDAG &DAG) const {
1950 if (!Subtarget->is64Bit())
1951 // This doesn't have SDLoc associated with it, but is not really the
1952 // same as a Register.
1953 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1954 getPointerTy(DAG.getDataLayout()));
1958 /// This returns the relocation base for the given PIC jumptable,
1959 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1960 const MCExpr *X86TargetLowering::
1961 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1962 MCContext &Ctx) const {
1963 // X86-64 uses RIP relative addressing based on the jump table label.
1964 if (Subtarget->isPICStyleRIPRel())
1965 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1967 // Otherwise, the reference is relative to the PIC base.
1968 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1971 std::pair<const TargetRegisterClass *, uint8_t>
1972 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1974 const TargetRegisterClass *RRC = nullptr;
1976 switch (VT.SimpleTy) {
1978 return TargetLowering::findRepresentativeClass(TRI, VT);
1979 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1980 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1983 RRC = &X86::VR64RegClass;
1985 case MVT::f32: case MVT::f64:
1986 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1987 case MVT::v4f32: case MVT::v2f64:
1988 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1990 RRC = &X86::VR128RegClass;
1993 return std::make_pair(RRC, Cost);
1996 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1997 unsigned &Offset) const {
1998 if (!Subtarget->isTargetLinux())
2001 if (Subtarget->is64Bit()) {
2002 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2004 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2016 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2017 unsigned DestAS) const {
2018 assert(SrcAS != DestAS && "Expected different address spaces!");
2020 return SrcAS < 256 && DestAS < 256;
2023 //===----------------------------------------------------------------------===//
2024 // Return Value Calling Convention Implementation
2025 //===----------------------------------------------------------------------===//
2027 #include "X86GenCallingConv.inc"
2030 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2031 MachineFunction &MF, bool isVarArg,
2032 const SmallVectorImpl<ISD::OutputArg> &Outs,
2033 LLVMContext &Context) const {
2034 SmallVector<CCValAssign, 16> RVLocs;
2035 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2036 return CCInfo.CheckReturn(Outs, RetCC_X86);
2039 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2040 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2045 X86TargetLowering::LowerReturn(SDValue Chain,
2046 CallingConv::ID CallConv, bool isVarArg,
2047 const SmallVectorImpl<ISD::OutputArg> &Outs,
2048 const SmallVectorImpl<SDValue> &OutVals,
2049 SDLoc dl, SelectionDAG &DAG) const {
2050 MachineFunction &MF = DAG.getMachineFunction();
2051 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2053 SmallVector<CCValAssign, 16> RVLocs;
2054 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2055 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2058 SmallVector<SDValue, 6> RetOps;
2059 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2060 // Operand #1 = Bytes To Pop
2061 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2064 // Copy the result values into the output registers.
2065 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2066 CCValAssign &VA = RVLocs[i];
2067 assert(VA.isRegLoc() && "Can only return in registers!");
2068 SDValue ValToCopy = OutVals[i];
2069 EVT ValVT = ValToCopy.getValueType();
2071 // Promote values to the appropriate types.
2072 if (VA.getLocInfo() == CCValAssign::SExt)
2073 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2074 else if (VA.getLocInfo() == CCValAssign::ZExt)
2075 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2076 else if (VA.getLocInfo() == CCValAssign::AExt) {
2077 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2078 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2080 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2082 else if (VA.getLocInfo() == CCValAssign::BCvt)
2083 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2085 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2086 "Unexpected FP-extend for return value.");
2088 // If this is x86-64, and we disabled SSE, we can't return FP values,
2089 // or SSE or MMX vectors.
2090 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2091 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2092 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2093 report_fatal_error("SSE register return with SSE disabled");
2095 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2096 // llvm-gcc has never done it right and no one has noticed, so this
2097 // should be OK for now.
2098 if (ValVT == MVT::f64 &&
2099 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2100 report_fatal_error("SSE2 register return with SSE2 disabled");
2102 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2103 // the RET instruction and handled by the FP Stackifier.
2104 if (VA.getLocReg() == X86::FP0 ||
2105 VA.getLocReg() == X86::FP1) {
2106 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2107 // change the value to the FP stack register class.
2108 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2109 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2110 RetOps.push_back(ValToCopy);
2111 // Don't emit a copytoreg.
2115 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2116 // which is returned in RAX / RDX.
2117 if (Subtarget->is64Bit()) {
2118 if (ValVT == MVT::x86mmx) {
2119 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2120 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2121 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2123 // If we don't have SSE2 available, convert to v4f32 so the generated
2124 // register is legal.
2125 if (!Subtarget->hasSSE2())
2126 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2131 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2132 Flag = Chain.getValue(1);
2133 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2136 // All x86 ABIs require that for returning structs by value we copy
2137 // the sret argument into %rax/%eax (depending on ABI) for the return.
2138 // We saved the argument into a virtual register in the entry block,
2139 // so now we copy the value out and into %rax/%eax.
2141 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2142 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2143 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2144 // either case FuncInfo->setSRetReturnReg() will have been called.
2145 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2146 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2147 getPointerTy(MF.getDataLayout()));
2150 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2151 X86::RAX : X86::EAX;
2152 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2153 Flag = Chain.getValue(1);
2155 // RAX/EAX now acts like a return value.
2157 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2160 RetOps[0] = Chain; // Update chain.
2162 // Add the flag if we have it.
2164 RetOps.push_back(Flag);
2166 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2169 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2170 if (N->getNumValues() != 1)
2172 if (!N->hasNUsesOfValue(1, 0))
2175 SDValue TCChain = Chain;
2176 SDNode *Copy = *N->use_begin();
2177 if (Copy->getOpcode() == ISD::CopyToReg) {
2178 // If the copy has a glue operand, we conservatively assume it isn't safe to
2179 // perform a tail call.
2180 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2182 TCChain = Copy->getOperand(0);
2183 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2186 bool HasRet = false;
2187 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2189 if (UI->getOpcode() != X86ISD::RET_FLAG)
2191 // If we are returning more than one value, we can definitely
2192 // not make a tail call see PR19530
2193 if (UI->getNumOperands() > 4)
2195 if (UI->getNumOperands() == 4 &&
2196 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2209 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2210 ISD::NodeType ExtendKind) const {
2212 // TODO: Is this also valid on 32-bit?
2213 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2214 ReturnMVT = MVT::i8;
2216 ReturnMVT = MVT::i32;
2218 EVT MinVT = getRegisterType(Context, ReturnMVT);
2219 return VT.bitsLT(MinVT) ? MinVT : VT;
2222 /// Lower the result values of a call into the
2223 /// appropriate copies out of appropriate physical registers.
2226 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2227 CallingConv::ID CallConv, bool isVarArg,
2228 const SmallVectorImpl<ISD::InputArg> &Ins,
2229 SDLoc dl, SelectionDAG &DAG,
2230 SmallVectorImpl<SDValue> &InVals) const {
2232 // Assign locations to each value returned by this call.
2233 SmallVector<CCValAssign, 16> RVLocs;
2234 bool Is64Bit = Subtarget->is64Bit();
2235 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2237 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2239 // Copy all of the result registers out of their specified physreg.
2240 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2241 CCValAssign &VA = RVLocs[i];
2242 EVT CopyVT = VA.getLocVT();
2244 // If this is x86-64, and we disabled SSE, we can't return FP values
2245 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2246 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2247 report_fatal_error("SSE register return with SSE disabled");
2250 // If we prefer to use the value in xmm registers, copy it out as f80 and
2251 // use a truncate to move it from fp stack reg to xmm reg.
2252 bool RoundAfterCopy = false;
2253 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2254 isScalarFPTypeInSSEReg(VA.getValVT())) {
2256 RoundAfterCopy = (CopyVT != VA.getLocVT());
2259 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2260 CopyVT, InFlag).getValue(1);
2261 SDValue Val = Chain.getValue(0);
2264 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2265 // This truncation won't change the value.
2266 DAG.getIntPtrConstant(1, dl));
2268 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2269 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2271 InFlag = Chain.getValue(2);
2272 InVals.push_back(Val);
2278 //===----------------------------------------------------------------------===//
2279 // C & StdCall & Fast Calling Convention implementation
2280 //===----------------------------------------------------------------------===//
2281 // StdCall calling convention seems to be standard for many Windows' API
2282 // routines and around. It differs from C calling convention just a little:
2283 // callee should clean up the stack, not caller. Symbols should be also
2284 // decorated in some fancy way :) It doesn't support any vector arguments.
2285 // For info on fast calling convention see Fast Calling Convention (tail call)
2286 // implementation LowerX86_32FastCCCallTo.
2288 /// CallIsStructReturn - Determines whether a call uses struct return
2290 enum StructReturnType {
2295 static StructReturnType
2296 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2298 return NotStructReturn;
2300 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2301 if (!Flags.isSRet())
2302 return NotStructReturn;
2303 if (Flags.isInReg())
2304 return RegStructReturn;
2305 return StackStructReturn;
2308 /// Determines whether a function uses struct return semantics.
2309 static StructReturnType
2310 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2312 return NotStructReturn;
2314 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2315 if (!Flags.isSRet())
2316 return NotStructReturn;
2317 if (Flags.isInReg())
2318 return RegStructReturn;
2319 return StackStructReturn;
2322 /// Make a copy of an aggregate at address specified by "Src" to address
2323 /// "Dst" with size and alignment information specified by the specific
2324 /// parameter attribute. The copy will be passed as a byval function parameter.
2326 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2327 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2329 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2331 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2332 /*isVolatile*/false, /*AlwaysInline=*/true,
2333 /*isTailCall*/false,
2334 MachinePointerInfo(), MachinePointerInfo());
2337 /// Return true if the calling convention is one that
2338 /// supports tail call optimization.
2339 static bool IsTailCallConvention(CallingConv::ID CC) {
2340 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2341 CC == CallingConv::HiPE);
2344 /// \brief Return true if the calling convention is a C calling convention.
2345 static bool IsCCallConvention(CallingConv::ID CC) {
2346 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2347 CC == CallingConv::X86_64_SysV);
2350 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2352 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2353 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2357 CallingConv::ID CalleeCC = CS.getCallingConv();
2358 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2364 /// Return true if the function is being made into
2365 /// a tailcall target by changing its ABI.
2366 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2367 bool GuaranteedTailCallOpt) {
2368 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2372 X86TargetLowering::LowerMemArgument(SDValue Chain,
2373 CallingConv::ID CallConv,
2374 const SmallVectorImpl<ISD::InputArg> &Ins,
2375 SDLoc dl, SelectionDAG &DAG,
2376 const CCValAssign &VA,
2377 MachineFrameInfo *MFI,
2379 // Create the nodes corresponding to a load from this parameter slot.
2380 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2381 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2382 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2383 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2386 // If value is passed by pointer we have address passed instead of the value
2388 bool ExtendedInMem = VA.isExtInLoc() &&
2389 VA.getValVT().getScalarType() == MVT::i1;
2391 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2392 ValVT = VA.getLocVT();
2394 ValVT = VA.getValVT();
2396 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2397 // changed with more analysis.
2398 // In case of tail call optimization mark all arguments mutable. Since they
2399 // could be overwritten by lowering of arguments in case of a tail call.
2400 if (Flags.isByVal()) {
2401 unsigned Bytes = Flags.getByValSize();
2402 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2403 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2404 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2406 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2407 VA.getLocMemOffset(), isImmutable);
2408 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2409 SDValue Val = DAG.getLoad(ValVT, dl, Chain, FIN,
2410 MachinePointerInfo::getFixedStack(FI),
2411 false, false, false, 0);
2412 return ExtendedInMem ?
2413 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2417 // FIXME: Get this from tablegen.
2418 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2419 const X86Subtarget *Subtarget) {
2420 assert(Subtarget->is64Bit());
2422 if (Subtarget->isCallingConvWin64(CallConv)) {
2423 static const MCPhysReg GPR64ArgRegsWin64[] = {
2424 X86::RCX, X86::RDX, X86::R8, X86::R9
2426 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2429 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2430 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2432 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2435 // FIXME: Get this from tablegen.
2436 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2437 CallingConv::ID CallConv,
2438 const X86Subtarget *Subtarget) {
2439 assert(Subtarget->is64Bit());
2440 if (Subtarget->isCallingConvWin64(CallConv)) {
2441 // The XMM registers which might contain var arg parameters are shadowed
2442 // in their paired GPR. So we only need to save the GPR to their home
2444 // TODO: __vectorcall will change this.
2448 const Function *Fn = MF.getFunction();
2449 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2450 bool isSoftFloat = Subtarget->useSoftFloat();
2451 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2452 "SSE register cannot be used when SSE is disabled!");
2453 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2454 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2458 static const MCPhysReg XMMArgRegs64Bit[] = {
2459 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2460 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2462 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2466 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2467 CallingConv::ID CallConv,
2469 const SmallVectorImpl<ISD::InputArg> &Ins,
2472 SmallVectorImpl<SDValue> &InVals)
2474 MachineFunction &MF = DAG.getMachineFunction();
2475 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2476 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2478 const Function* Fn = MF.getFunction();
2479 if (Fn->hasExternalLinkage() &&
2480 Subtarget->isTargetCygMing() &&
2481 Fn->getName() == "main")
2482 FuncInfo->setForceFramePointer(true);
2484 MachineFrameInfo *MFI = MF.getFrameInfo();
2485 bool Is64Bit = Subtarget->is64Bit();
2486 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2488 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2489 "Var args not supported with calling convention fastcc, ghc or hipe");
2491 // Assign locations to all of the incoming arguments.
2492 SmallVector<CCValAssign, 16> ArgLocs;
2493 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2495 // Allocate shadow area for Win64
2497 CCInfo.AllocateStack(32, 8);
2499 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2501 unsigned LastVal = ~0U;
2503 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504 CCValAssign &VA = ArgLocs[i];
2505 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2507 assert(VA.getValNo() != LastVal &&
2508 "Don't support value assigned to multiple locs yet");
2510 LastVal = VA.getValNo();
2512 if (VA.isRegLoc()) {
2513 EVT RegVT = VA.getLocVT();
2514 const TargetRegisterClass *RC;
2515 if (RegVT == MVT::i32)
2516 RC = &X86::GR32RegClass;
2517 else if (Is64Bit && RegVT == MVT::i64)
2518 RC = &X86::GR64RegClass;
2519 else if (RegVT == MVT::f32)
2520 RC = &X86::FR32RegClass;
2521 else if (RegVT == MVT::f64)
2522 RC = &X86::FR64RegClass;
2523 else if (RegVT.is512BitVector())
2524 RC = &X86::VR512RegClass;
2525 else if (RegVT.is256BitVector())
2526 RC = &X86::VR256RegClass;
2527 else if (RegVT.is128BitVector())
2528 RC = &X86::VR128RegClass;
2529 else if (RegVT == MVT::x86mmx)
2530 RC = &X86::VR64RegClass;
2531 else if (RegVT == MVT::i1)
2532 RC = &X86::VK1RegClass;
2533 else if (RegVT == MVT::v8i1)
2534 RC = &X86::VK8RegClass;
2535 else if (RegVT == MVT::v16i1)
2536 RC = &X86::VK16RegClass;
2537 else if (RegVT == MVT::v32i1)
2538 RC = &X86::VK32RegClass;
2539 else if (RegVT == MVT::v64i1)
2540 RC = &X86::VK64RegClass;
2542 llvm_unreachable("Unknown argument type!");
2544 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2545 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2547 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2548 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2550 if (VA.getLocInfo() == CCValAssign::SExt)
2551 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2552 DAG.getValueType(VA.getValVT()));
2553 else if (VA.getLocInfo() == CCValAssign::ZExt)
2554 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2555 DAG.getValueType(VA.getValVT()));
2556 else if (VA.getLocInfo() == CCValAssign::BCvt)
2557 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2559 if (VA.isExtInLoc()) {
2560 // Handle MMX values passed in XMM regs.
2561 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2562 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2564 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2567 assert(VA.isMemLoc());
2568 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2571 // If value is passed via pointer - do a load.
2572 if (VA.getLocInfo() == CCValAssign::Indirect)
2573 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2574 MachinePointerInfo(), false, false, false, 0);
2576 InVals.push_back(ArgValue);
2579 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2580 // All x86 ABIs require that for returning structs by value we copy the
2581 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2582 // the argument into a virtual register so that we can access it from the
2584 if (Ins[i].Flags.isSRet()) {
2585 unsigned Reg = FuncInfo->getSRetReturnReg();
2587 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2588 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2589 FuncInfo->setSRetReturnReg(Reg);
2591 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2592 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2597 unsigned StackSize = CCInfo.getNextStackOffset();
2598 // Align stack specially for tail calls.
2599 if (FuncIsMadeTailCallSafe(CallConv,
2600 MF.getTarget().Options.GuaranteedTailCallOpt))
2601 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2603 // If the function takes variable number of arguments, make a frame index for
2604 // the start of the first vararg value... for expansion of llvm.va_start. We
2605 // can skip this if there are no va_start calls.
2606 if (MFI->hasVAStart() &&
2607 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2608 CallConv != CallingConv::X86_ThisCall))) {
2609 FuncInfo->setVarArgsFrameIndex(
2610 MFI->CreateFixedObject(1, StackSize, true));
2613 MachineModuleInfo &MMI = MF.getMMI();
2614 const Function *WinEHParent = nullptr;
2615 if (MMI.hasWinEHFuncInfo(Fn))
2616 WinEHParent = MMI.getWinEHParent(Fn);
2617 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2618 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2620 // Figure out if XMM registers are in use.
2621 assert(!(Subtarget->useSoftFloat() &&
2622 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2623 "SSE register cannot be used when SSE is disabled!");
2625 // 64-bit calling conventions support varargs and register parameters, so we
2626 // have to do extra work to spill them in the prologue.
2627 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2628 // Find the first unallocated argument registers.
2629 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2630 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2631 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2632 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2633 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2634 "SSE register cannot be used when SSE is disabled!");
2636 // Gather all the live in physical registers.
2637 SmallVector<SDValue, 6> LiveGPRs;
2638 SmallVector<SDValue, 8> LiveXMMRegs;
2640 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2641 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2643 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2645 if (!ArgXMMs.empty()) {
2646 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2647 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2648 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2649 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2650 LiveXMMRegs.push_back(
2651 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2656 // Get to the caller-allocated home save location. Add 8 to account
2657 // for the return address.
2658 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2659 FuncInfo->setRegSaveFrameIndex(
2660 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2661 // Fixup to set vararg frame on shadow area (4 x i64).
2663 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2665 // For X86-64, if there are vararg parameters that are passed via
2666 // registers, then we must store them to their spots on the stack so
2667 // they may be loaded by deferencing the result of va_next.
2668 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2669 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2670 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2671 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2674 // Store the integer parameter registers.
2675 SmallVector<SDValue, 8> MemOps;
2676 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2677 getPointerTy(DAG.getDataLayout()));
2678 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2679 for (SDValue Val : LiveGPRs) {
2680 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2681 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2683 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2684 MachinePointerInfo::getFixedStack(
2685 FuncInfo->getRegSaveFrameIndex(), Offset),
2687 MemOps.push_back(Store);
2691 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2692 // Now store the XMM (fp + vector) parameter registers.
2693 SmallVector<SDValue, 12> SaveXMMOps;
2694 SaveXMMOps.push_back(Chain);
2695 SaveXMMOps.push_back(ALVal);
2696 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2697 FuncInfo->getRegSaveFrameIndex(), dl));
2698 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2699 FuncInfo->getVarArgsFPOffset(), dl));
2700 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2702 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2703 MVT::Other, SaveXMMOps));
2706 if (!MemOps.empty())
2707 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2708 } else if (IsWin64 && IsWinEHOutlined) {
2709 // Get to the caller-allocated home save location. Add 8 to account
2710 // for the return address.
2711 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2712 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2713 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2715 MMI.getWinEHFuncInfo(Fn)
2716 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2717 FuncInfo->getRegSaveFrameIndex();
2719 // Store the second integer parameter (rdx) into rsp+16 relative to the
2720 // stack pointer at the entry of the function.
2721 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2722 getPointerTy(DAG.getDataLayout()));
2723 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2724 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2725 Chain = DAG.getStore(
2726 Val.getValue(1), dl, Val, RSFIN,
2727 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2728 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2731 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2732 // Find the largest legal vector type.
2733 MVT VecVT = MVT::Other;
2734 // FIXME: Only some x86_32 calling conventions support AVX512.
2735 if (Subtarget->hasAVX512() &&
2736 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2737 CallConv == CallingConv::Intel_OCL_BI)))
2738 VecVT = MVT::v16f32;
2739 else if (Subtarget->hasAVX())
2741 else if (Subtarget->hasSSE2())
2744 // We forward some GPRs and some vector types.
2745 SmallVector<MVT, 2> RegParmTypes;
2746 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2747 RegParmTypes.push_back(IntVT);
2748 if (VecVT != MVT::Other)
2749 RegParmTypes.push_back(VecVT);
2751 // Compute the set of forwarded registers. The rest are scratch.
2752 SmallVectorImpl<ForwardedRegister> &Forwards =
2753 FuncInfo->getForwardedMustTailRegParms();
2754 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2756 // Conservatively forward AL on x86_64, since it might be used for varargs.
2757 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2758 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2759 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2762 // Copy all forwards from physical to virtual registers.
2763 for (ForwardedRegister &F : Forwards) {
2764 // FIXME: Can we use a less constrained schedule?
2765 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2766 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2767 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2771 // Some CCs need callee pop.
2772 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2773 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2774 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2776 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2777 // If this is an sret function, the return should pop the hidden pointer.
2778 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2779 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2780 argsAreStructReturn(Ins) == StackStructReturn)
2781 FuncInfo->setBytesToPopOnReturn(4);
2785 // RegSaveFrameIndex is X86-64 only.
2786 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2787 if (CallConv == CallingConv::X86_FastCall ||
2788 CallConv == CallingConv::X86_ThisCall)
2789 // fastcc functions can't have varargs.
2790 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2793 FuncInfo->setArgumentStackSize(StackSize);
2795 if (IsWinEHParent) {
2797 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2798 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2799 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2800 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2801 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2802 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2803 /*isVolatile=*/true,
2804 /*isNonTemporal=*/false, /*Alignment=*/0);
2806 // Functions using Win32 EH are considered to have opaque SP adjustments
2807 // to force local variables to be addressed from the frame or base
2809 MFI->setHasOpaqueSPAdjustment(true);
2817 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2818 SDValue StackPtr, SDValue Arg,
2819 SDLoc dl, SelectionDAG &DAG,
2820 const CCValAssign &VA,
2821 ISD::ArgFlagsTy Flags) const {
2822 unsigned LocMemOffset = VA.getLocMemOffset();
2823 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2824 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2826 if (Flags.isByVal())
2827 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2829 return DAG.getStore(Chain, dl, Arg, PtrOff,
2830 MachinePointerInfo::getStack(LocMemOffset),
2834 /// Emit a load of return address if tail call
2835 /// optimization is performed and it is required.
2837 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2838 SDValue &OutRetAddr, SDValue Chain,
2839 bool IsTailCall, bool Is64Bit,
2840 int FPDiff, SDLoc dl) const {
2841 // Adjust the Return address stack slot.
2842 EVT VT = getPointerTy(DAG.getDataLayout());
2843 OutRetAddr = getReturnAddressFrameIndex(DAG);
2845 // Load the "old" Return address.
2846 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2847 false, false, false, 0);
2848 return SDValue(OutRetAddr.getNode(), 1);
2851 /// Emit a store of the return address if tail call
2852 /// optimization is performed and it is required (FPDiff!=0).
2853 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2854 SDValue Chain, SDValue RetAddrFrIdx,
2855 EVT PtrVT, unsigned SlotSize,
2856 int FPDiff, SDLoc dl) {
2857 // Store the return address to the appropriate stack slot.
2858 if (!FPDiff) return Chain;
2859 // Calculate the new stack slot for the return address.
2860 int NewReturnAddrFI =
2861 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2863 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2864 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2865 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2871 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2872 SmallVectorImpl<SDValue> &InVals) const {
2873 SelectionDAG &DAG = CLI.DAG;
2875 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2876 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2877 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2878 SDValue Chain = CLI.Chain;
2879 SDValue Callee = CLI.Callee;
2880 CallingConv::ID CallConv = CLI.CallConv;
2881 bool &isTailCall = CLI.IsTailCall;
2882 bool isVarArg = CLI.IsVarArg;
2884 MachineFunction &MF = DAG.getMachineFunction();
2885 bool Is64Bit = Subtarget->is64Bit();
2886 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2887 StructReturnType SR = callIsStructReturn(Outs);
2888 bool IsSibcall = false;
2889 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2890 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2892 if (Attr.getValueAsString() == "true")
2895 if (Subtarget->isPICStyleGOT() &&
2896 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2897 // If we are using a GOT, disable tail calls to external symbols with
2898 // default visibility. Tail calling such a symbol requires using a GOT
2899 // relocation, which forces early binding of the symbol. This breaks code
2900 // that require lazy function symbol resolution. Using musttail or
2901 // GuaranteedTailCallOpt will override this.
2902 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2903 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2904 G->getGlobal()->hasDefaultVisibility()))
2908 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2910 // Force this to be a tail call. The verifier rules are enough to ensure
2911 // that we can lower this successfully without moving the return address
2914 } else if (isTailCall) {
2915 // Check if it's really possible to do a tail call.
2916 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2917 isVarArg, SR != NotStructReturn,
2918 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2919 Outs, OutVals, Ins, DAG);
2921 // Sibcalls are automatically detected tailcalls which do not require
2923 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2930 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2931 "Var args not supported with calling convention fastcc, ghc or hipe");
2933 // Analyze operands of the call, assigning locations to each operand.
2934 SmallVector<CCValAssign, 16> ArgLocs;
2935 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2937 // Allocate shadow area for Win64
2939 CCInfo.AllocateStack(32, 8);
2941 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2943 // Get a count of how many bytes are to be pushed on the stack.
2944 unsigned NumBytes = CCInfo.getNextStackOffset();
2946 // This is a sibcall. The memory operands are available in caller's
2947 // own caller's stack.
2949 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2950 IsTailCallConvention(CallConv))
2951 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2954 if (isTailCall && !IsSibcall && !IsMustTail) {
2955 // Lower arguments at fp - stackoffset + fpdiff.
2956 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2958 FPDiff = NumBytesCallerPushed - NumBytes;
2960 // Set the delta of movement of the returnaddr stackslot.
2961 // But only set if delta is greater than previous delta.
2962 if (FPDiff < X86Info->getTCReturnAddrDelta())
2963 X86Info->setTCReturnAddrDelta(FPDiff);
2966 unsigned NumBytesToPush = NumBytes;
2967 unsigned NumBytesToPop = NumBytes;
2969 // If we have an inalloca argument, all stack space has already been allocated
2970 // for us and be right at the top of the stack. We don't support multiple
2971 // arguments passed in memory when using inalloca.
2972 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2974 if (!ArgLocs.back().isMemLoc())
2975 report_fatal_error("cannot use inalloca attribute on a register "
2977 if (ArgLocs.back().getLocMemOffset() != 0)
2978 report_fatal_error("any parameter with the inalloca attribute must be "
2979 "the only memory argument");
2983 Chain = DAG.getCALLSEQ_START(
2984 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2986 SDValue RetAddrFrIdx;
2987 // Load return address for tail calls.
2988 if (isTailCall && FPDiff)
2989 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2990 Is64Bit, FPDiff, dl);
2992 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2993 SmallVector<SDValue, 8> MemOpChains;
2996 // Walk the register/memloc assignments, inserting copies/loads. In the case
2997 // of tail call optimization arguments are handle later.
2998 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2999 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3000 // Skip inalloca arguments, they have already been written.
3001 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3002 if (Flags.isInAlloca())
3005 CCValAssign &VA = ArgLocs[i];
3006 EVT RegVT = VA.getLocVT();
3007 SDValue Arg = OutVals[i];
3008 bool isByVal = Flags.isByVal();
3010 // Promote the value if needed.
3011 switch (VA.getLocInfo()) {
3012 default: llvm_unreachable("Unknown loc info!");
3013 case CCValAssign::Full: break;
3014 case CCValAssign::SExt:
3015 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3017 case CCValAssign::ZExt:
3018 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3020 case CCValAssign::AExt:
3021 if (Arg.getValueType().isVector() &&
3022 Arg.getValueType().getScalarType() == MVT::i1)
3023 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3024 else if (RegVT.is128BitVector()) {
3025 // Special case: passing MMX values in XMM registers.
3026 Arg = DAG.getBitcast(MVT::i64, Arg);
3027 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3028 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3030 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3032 case CCValAssign::BCvt:
3033 Arg = DAG.getBitcast(RegVT, Arg);
3035 case CCValAssign::Indirect: {
3036 // Store the argument.
3037 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3038 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3039 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3040 MachinePointerInfo::getFixedStack(FI),
3047 if (VA.isRegLoc()) {
3048 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3049 if (isVarArg && IsWin64) {
3050 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3051 // shadow reg if callee is a varargs function.
3052 unsigned ShadowReg = 0;
3053 switch (VA.getLocReg()) {
3054 case X86::XMM0: ShadowReg = X86::RCX; break;
3055 case X86::XMM1: ShadowReg = X86::RDX; break;
3056 case X86::XMM2: ShadowReg = X86::R8; break;
3057 case X86::XMM3: ShadowReg = X86::R9; break;
3060 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3062 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3063 assert(VA.isMemLoc());
3064 if (!StackPtr.getNode())
3065 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3066 getPointerTy(DAG.getDataLayout()));
3067 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3068 dl, DAG, VA, Flags));
3072 if (!MemOpChains.empty())
3073 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3075 if (Subtarget->isPICStyleGOT()) {
3076 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3079 RegsToPass.push_back(std::make_pair(
3080 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3081 getPointerTy(DAG.getDataLayout()))));
3083 // If we are tail calling and generating PIC/GOT style code load the
3084 // address of the callee into ECX. The value in ecx is used as target of
3085 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3086 // for tail calls on PIC/GOT architectures. Normally we would just put the
3087 // address of GOT into ebx and then call target@PLT. But for tail calls
3088 // ebx would be restored (since ebx is callee saved) before jumping to the
3091 // Note: The actual moving to ECX is done further down.
3092 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3093 if (G && !G->getGlobal()->hasLocalLinkage() &&
3094 G->getGlobal()->hasDefaultVisibility())
3095 Callee = LowerGlobalAddress(Callee, DAG);
3096 else if (isa<ExternalSymbolSDNode>(Callee))
3097 Callee = LowerExternalSymbol(Callee, DAG);
3101 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3102 // From AMD64 ABI document:
3103 // For calls that may call functions that use varargs or stdargs
3104 // (prototype-less calls or calls to functions containing ellipsis (...) in
3105 // the declaration) %al is used as hidden argument to specify the number
3106 // of SSE registers used. The contents of %al do not need to match exactly
3107 // the number of registers, but must be an ubound on the number of SSE
3108 // registers used and is in the range 0 - 8 inclusive.
3110 // Count the number of XMM registers allocated.
3111 static const MCPhysReg XMMArgRegs[] = {
3112 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3113 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3115 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3116 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3117 && "SSE registers cannot be used when SSE is disabled");
3119 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3120 DAG.getConstant(NumXMMRegs, dl,
3124 if (isVarArg && IsMustTail) {
3125 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3126 for (const auto &F : Forwards) {
3127 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3128 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3132 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3133 // don't need this because the eligibility check rejects calls that require
3134 // shuffling arguments passed in memory.
3135 if (!IsSibcall && isTailCall) {
3136 // Force all the incoming stack arguments to be loaded from the stack
3137 // before any new outgoing arguments are stored to the stack, because the
3138 // outgoing stack slots may alias the incoming argument stack slots, and
3139 // the alias isn't otherwise explicit. This is slightly more conservative
3140 // than necessary, because it means that each store effectively depends
3141 // on every argument instead of just those arguments it would clobber.
3142 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3144 SmallVector<SDValue, 8> MemOpChains2;
3147 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3148 CCValAssign &VA = ArgLocs[i];
3151 assert(VA.isMemLoc());
3152 SDValue Arg = OutVals[i];
3153 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3154 // Skip inalloca arguments. They don't require any work.
3155 if (Flags.isInAlloca())
3157 // Create frame index.
3158 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3159 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3160 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3161 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3163 if (Flags.isByVal()) {
3164 // Copy relative to framepointer.
3165 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3166 if (!StackPtr.getNode())
3167 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3168 getPointerTy(DAG.getDataLayout()));
3169 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3172 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3176 // Store relative to framepointer.
3177 MemOpChains2.push_back(
3178 DAG.getStore(ArgChain, dl, Arg, FIN,
3179 MachinePointerInfo::getFixedStack(FI),
3184 if (!MemOpChains2.empty())
3185 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3187 // Store the return address to the appropriate stack slot.
3188 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3189 getPointerTy(DAG.getDataLayout()),
3190 RegInfo->getSlotSize(), FPDiff, dl);
3193 // Build a sequence of copy-to-reg nodes chained together with token chain
3194 // and flag operands which copy the outgoing args into registers.
3196 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3197 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3198 RegsToPass[i].second, InFlag);
3199 InFlag = Chain.getValue(1);
3202 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3203 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3204 // In the 64-bit large code model, we have to make all calls
3205 // through a register, since the call instruction's 32-bit
3206 // pc-relative offset may not be large enough to hold the whole
3208 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3209 // If the callee is a GlobalAddress node (quite common, every direct call
3210 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3212 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3214 // We should use extra load for direct calls to dllimported functions in
3216 const GlobalValue *GV = G->getGlobal();
3217 if (!GV->hasDLLImportStorageClass()) {
3218 unsigned char OpFlags = 0;
3219 bool ExtraLoad = false;
3220 unsigned WrapperKind = ISD::DELETED_NODE;
3222 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3223 // external symbols most go through the PLT in PIC mode. If the symbol
3224 // has hidden or protected visibility, or if it is static or local, then
3225 // we don't need to use the PLT - we can directly call it.
3226 if (Subtarget->isTargetELF() &&
3227 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3228 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3229 OpFlags = X86II::MO_PLT;
3230 } else if (Subtarget->isPICStyleStubAny() &&
3231 !GV->isStrongDefinitionForLinker() &&
3232 (!Subtarget->getTargetTriple().isMacOSX() ||
3233 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3234 // PC-relative references to external symbols should go through $stub,
3235 // unless we're building with the leopard linker or later, which
3236 // automatically synthesizes these stubs.
3237 OpFlags = X86II::MO_DARWIN_STUB;
3238 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3239 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3240 // If the function is marked as non-lazy, generate an indirect call
3241 // which loads from the GOT directly. This avoids runtime overhead
3242 // at the cost of eager binding (and one extra byte of encoding).
3243 OpFlags = X86II::MO_GOTPCREL;
3244 WrapperKind = X86ISD::WrapperRIP;
3248 Callee = DAG.getTargetGlobalAddress(
3249 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3251 // Add a wrapper if needed.
3252 if (WrapperKind != ISD::DELETED_NODE)
3253 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3254 getPointerTy(DAG.getDataLayout()), Callee);
3255 // Add extra indirection if needed.
3257 Callee = DAG.getLoad(
3258 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3259 MachinePointerInfo::getGOT(), false, false, false, 0);
3261 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3262 unsigned char OpFlags = 0;
3264 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3265 // external symbols should go through the PLT.
3266 if (Subtarget->isTargetELF() &&
3267 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3268 OpFlags = X86II::MO_PLT;
3269 } else if (Subtarget->isPICStyleStubAny() &&
3270 (!Subtarget->getTargetTriple().isMacOSX() ||
3271 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3272 // PC-relative references to external symbols should go through $stub,
3273 // unless we're building with the leopard linker or later, which
3274 // automatically synthesizes these stubs.
3275 OpFlags = X86II::MO_DARWIN_STUB;
3278 Callee = DAG.getTargetExternalSymbol(
3279 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3280 } else if (Subtarget->isTarget64BitILP32() &&
3281 Callee->getValueType(0) == MVT::i32) {
3282 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3283 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3286 // Returns a chain & a flag for retval copy to use.
3287 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3288 SmallVector<SDValue, 8> Ops;
3290 if (!IsSibcall && isTailCall) {
3291 Chain = DAG.getCALLSEQ_END(Chain,
3292 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3293 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3294 InFlag = Chain.getValue(1);
3297 Ops.push_back(Chain);
3298 Ops.push_back(Callee);
3301 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3303 // Add argument registers to the end of the list so that they are known live
3305 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3306 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3307 RegsToPass[i].second.getValueType()));
3309 // Add a register mask operand representing the call-preserved registers.
3310 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3311 assert(Mask && "Missing call preserved mask for calling convention");
3313 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3314 // the function clobbers all registers. If an exception is thrown, the runtime
3315 // will not restore CSRs.
3316 // FIXME: Model this more precisely so that we can register allocate across
3317 // the normal edge and spill and fill across the exceptional edge.
3318 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3319 const Function *CallerFn = MF.getFunction();
3320 EHPersonality Pers =
3321 CallerFn->hasPersonalityFn()
3322 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3323 : EHPersonality::Unknown;
3324 if (isMSVCEHPersonality(Pers))
3325 Mask = RegInfo->getNoPreservedMask();
3328 Ops.push_back(DAG.getRegisterMask(Mask));
3330 if (InFlag.getNode())
3331 Ops.push_back(InFlag);
3335 //// If this is the first return lowered for this function, add the regs
3336 //// to the liveout set for the function.
3337 // This isn't right, although it's probably harmless on x86; liveouts
3338 // should be computed from returns not tail calls. Consider a void
3339 // function making a tail call to a function returning int.
3340 MF.getFrameInfo()->setHasTailCall();
3341 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3344 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3345 InFlag = Chain.getValue(1);
3347 // Create the CALLSEQ_END node.
3348 unsigned NumBytesForCalleeToPop;
3349 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3350 DAG.getTarget().Options.GuaranteedTailCallOpt))
3351 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3352 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3353 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3354 SR == StackStructReturn)
3355 // If this is a call to a struct-return function, the callee
3356 // pops the hidden struct pointer, so we have to push it back.
3357 // This is common for Darwin/X86, Linux & Mingw32 targets.
3358 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3359 NumBytesForCalleeToPop = 4;
3361 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3363 // Returns a flag for retval copy to use.
3365 Chain = DAG.getCALLSEQ_END(Chain,
3366 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3367 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3370 InFlag = Chain.getValue(1);
3373 // Handle result values, copying them out of physregs into vregs that we
3375 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3376 Ins, dl, DAG, InVals);
3379 //===----------------------------------------------------------------------===//
3380 // Fast Calling Convention (tail call) implementation
3381 //===----------------------------------------------------------------------===//
3383 // Like std call, callee cleans arguments, convention except that ECX is
3384 // reserved for storing the tail called function address. Only 2 registers are
3385 // free for argument passing (inreg). Tail call optimization is performed
3387 // * tailcallopt is enabled
3388 // * caller/callee are fastcc
3389 // On X86_64 architecture with GOT-style position independent code only local
3390 // (within module) calls are supported at the moment.
3391 // To keep the stack aligned according to platform abi the function
3392 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3393 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3394 // If a tail called function callee has more arguments than the caller the
3395 // caller needs to make sure that there is room to move the RETADDR to. This is
3396 // achieved by reserving an area the size of the argument delta right after the
3397 // original RETADDR, but before the saved framepointer or the spilled registers
3398 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3410 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3413 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3414 SelectionDAG& DAG) const {
3415 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3416 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3417 unsigned StackAlignment = TFI.getStackAlignment();
3418 uint64_t AlignMask = StackAlignment - 1;
3419 int64_t Offset = StackSize;
3420 unsigned SlotSize = RegInfo->getSlotSize();
3421 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3422 // Number smaller than 12 so just add the difference.
3423 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3425 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3426 Offset = ((~AlignMask) & Offset) + StackAlignment +
3427 (StackAlignment-SlotSize);
3432 /// Return true if the given stack call argument is already available in the
3433 /// same position (relatively) of the caller's incoming argument stack.
3435 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3436 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3437 const X86InstrInfo *TII) {
3438 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3440 if (Arg.getOpcode() == ISD::CopyFromReg) {
3441 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3442 if (!TargetRegisterInfo::isVirtualRegister(VR))
3444 MachineInstr *Def = MRI->getVRegDef(VR);
3447 if (!Flags.isByVal()) {
3448 if (!TII->isLoadFromStackSlot(Def, FI))
3451 unsigned Opcode = Def->getOpcode();
3452 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3453 Opcode == X86::LEA64_32r) &&
3454 Def->getOperand(1).isFI()) {
3455 FI = Def->getOperand(1).getIndex();
3456 Bytes = Flags.getByValSize();
3460 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3461 if (Flags.isByVal())
3462 // ByVal argument is passed in as a pointer but it's now being
3463 // dereferenced. e.g.
3464 // define @foo(%struct.X* %A) {
3465 // tail call @bar(%struct.X* byval %A)
3468 SDValue Ptr = Ld->getBasePtr();
3469 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3472 FI = FINode->getIndex();
3473 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3474 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3475 FI = FINode->getIndex();
3476 Bytes = Flags.getByValSize();
3480 assert(FI != INT_MAX);
3481 if (!MFI->isFixedObjectIndex(FI))
3483 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3486 /// Check whether the call is eligible for tail call optimization. Targets
3487 /// that want to do tail call optimization should implement this function.
3489 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3490 CallingConv::ID CalleeCC,
3492 bool isCalleeStructRet,
3493 bool isCallerStructRet,
3495 const SmallVectorImpl<ISD::OutputArg> &Outs,
3496 const SmallVectorImpl<SDValue> &OutVals,
3497 const SmallVectorImpl<ISD::InputArg> &Ins,
3498 SelectionDAG &DAG) const {
3499 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3502 // If -tailcallopt is specified, make fastcc functions tail-callable.
3503 const MachineFunction &MF = DAG.getMachineFunction();
3504 const Function *CallerF = MF.getFunction();
3506 // If the function return type is x86_fp80 and the callee return type is not,
3507 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3508 // perform a tailcall optimization here.
3509 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3512 CallingConv::ID CallerCC = CallerF->getCallingConv();
3513 bool CCMatch = CallerCC == CalleeCC;
3514 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3515 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3517 // Win64 functions have extra shadow space for argument homing. Don't do the
3518 // sibcall if the caller and callee have mismatched expectations for this
3520 if (IsCalleeWin64 != IsCallerWin64)
3523 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3524 if (IsTailCallConvention(CalleeCC) && CCMatch)
3529 // Look for obvious safe cases to perform tail call optimization that do not
3530 // require ABI changes. This is what gcc calls sibcall.
3532 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3533 // emit a special epilogue.
3534 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3535 if (RegInfo->needsStackRealignment(MF))
3538 // Also avoid sibcall optimization if either caller or callee uses struct
3539 // return semantics.
3540 if (isCalleeStructRet || isCallerStructRet)
3543 // An stdcall/thiscall caller is expected to clean up its arguments; the
3544 // callee isn't going to do that.
3545 // FIXME: this is more restrictive than needed. We could produce a tailcall
3546 // when the stack adjustment matches. For example, with a thiscall that takes
3547 // only one argument.
3548 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3549 CallerCC == CallingConv::X86_ThisCall))
3552 // Do not sibcall optimize vararg calls unless all arguments are passed via
3554 if (isVarArg && !Outs.empty()) {
3556 // Optimizing for varargs on Win64 is unlikely to be safe without
3557 // additional testing.
3558 if (IsCalleeWin64 || IsCallerWin64)
3561 SmallVector<CCValAssign, 16> ArgLocs;
3562 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3565 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3566 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3567 if (!ArgLocs[i].isRegLoc())
3571 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3572 // stack. Therefore, if it's not used by the call it is not safe to optimize
3573 // this into a sibcall.
3574 bool Unused = false;
3575 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3582 SmallVector<CCValAssign, 16> RVLocs;
3583 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3585 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3586 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3587 CCValAssign &VA = RVLocs[i];
3588 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3593 // If the calling conventions do not match, then we'd better make sure the
3594 // results are returned in the same way as what the caller expects.
3596 SmallVector<CCValAssign, 16> RVLocs1;
3597 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3599 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3601 SmallVector<CCValAssign, 16> RVLocs2;
3602 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3604 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3606 if (RVLocs1.size() != RVLocs2.size())
3608 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3609 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3611 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3613 if (RVLocs1[i].isRegLoc()) {
3614 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3617 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3623 // If the callee takes no arguments then go on to check the results of the
3625 if (!Outs.empty()) {
3626 // Check if stack adjustment is needed. For now, do not do this if any
3627 // argument is passed on the stack.
3628 SmallVector<CCValAssign, 16> ArgLocs;
3629 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3632 // Allocate shadow area for Win64
3634 CCInfo.AllocateStack(32, 8);
3636 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3637 if (CCInfo.getNextStackOffset()) {
3638 MachineFunction &MF = DAG.getMachineFunction();
3639 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3642 // Check if the arguments are already laid out in the right way as
3643 // the caller's fixed stack objects.
3644 MachineFrameInfo *MFI = MF.getFrameInfo();
3645 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3646 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3647 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3648 CCValAssign &VA = ArgLocs[i];
3649 SDValue Arg = OutVals[i];
3650 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3651 if (VA.getLocInfo() == CCValAssign::Indirect)
3653 if (!VA.isRegLoc()) {
3654 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3661 // If the tailcall address may be in a register, then make sure it's
3662 // possible to register allocate for it. In 32-bit, the call address can
3663 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3664 // callee-saved registers are restored. These happen to be the same
3665 // registers used to pass 'inreg' arguments so watch out for those.
3666 if (!Subtarget->is64Bit() &&
3667 ((!isa<GlobalAddressSDNode>(Callee) &&
3668 !isa<ExternalSymbolSDNode>(Callee)) ||
3669 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3670 unsigned NumInRegs = 0;
3671 // In PIC we need an extra register to formulate the address computation
3673 unsigned MaxInRegs =
3674 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3676 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3677 CCValAssign &VA = ArgLocs[i];
3680 unsigned Reg = VA.getLocReg();
3683 case X86::EAX: case X86::EDX: case X86::ECX:
3684 if (++NumInRegs == MaxInRegs)
3696 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3697 const TargetLibraryInfo *libInfo) const {
3698 return X86::createFastISel(funcInfo, libInfo);
3701 //===----------------------------------------------------------------------===//
3702 // Other Lowering Hooks
3703 //===----------------------------------------------------------------------===//
3705 static bool MayFoldLoad(SDValue Op) {
3706 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3709 static bool MayFoldIntoStore(SDValue Op) {
3710 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3713 static bool isTargetShuffle(unsigned Opcode) {
3715 default: return false;
3716 case X86ISD::BLENDI:
3717 case X86ISD::PSHUFB:
3718 case X86ISD::PSHUFD:
3719 case X86ISD::PSHUFHW:
3720 case X86ISD::PSHUFLW:
3722 case X86ISD::PALIGNR:
3723 case X86ISD::MOVLHPS:
3724 case X86ISD::MOVLHPD:
3725 case X86ISD::MOVHLPS:
3726 case X86ISD::MOVLPS:
3727 case X86ISD::MOVLPD:
3728 case X86ISD::MOVSHDUP:
3729 case X86ISD::MOVSLDUP:
3730 case X86ISD::MOVDDUP:
3733 case X86ISD::UNPCKL:
3734 case X86ISD::UNPCKH:
3735 case X86ISD::VPERMILPI:
3736 case X86ISD::VPERM2X128:
3737 case X86ISD::VPERMI:
3742 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3743 SDValue V1, unsigned TargetMask,
3744 SelectionDAG &DAG) {
3746 default: llvm_unreachable("Unknown x86 shuffle node");
3747 case X86ISD::PSHUFD:
3748 case X86ISD::PSHUFHW:
3749 case X86ISD::PSHUFLW:
3750 case X86ISD::VPERMILPI:
3751 case X86ISD::VPERMI:
3752 return DAG.getNode(Opc, dl, VT, V1,
3753 DAG.getConstant(TargetMask, dl, MVT::i8));
3757 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3758 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3760 default: llvm_unreachable("Unknown x86 shuffle node");
3761 case X86ISD::MOVLHPS:
3762 case X86ISD::MOVLHPD:
3763 case X86ISD::MOVHLPS:
3764 case X86ISD::MOVLPS:
3765 case X86ISD::MOVLPD:
3768 case X86ISD::UNPCKL:
3769 case X86ISD::UNPCKH:
3770 return DAG.getNode(Opc, dl, VT, V1, V2);
3774 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3775 MachineFunction &MF = DAG.getMachineFunction();
3776 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3777 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3778 int ReturnAddrIndex = FuncInfo->getRAIndex();
3780 if (ReturnAddrIndex == 0) {
3781 // Set up a frame object for the return address.
3782 unsigned SlotSize = RegInfo->getSlotSize();
3783 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3786 FuncInfo->setRAIndex(ReturnAddrIndex);
3789 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3792 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3793 bool hasSymbolicDisplacement) {
3794 // Offset should fit into 32 bit immediate field.
3795 if (!isInt<32>(Offset))
3798 // If we don't have a symbolic displacement - we don't have any extra
3800 if (!hasSymbolicDisplacement)
3803 // FIXME: Some tweaks might be needed for medium code model.
3804 if (M != CodeModel::Small && M != CodeModel::Kernel)
3807 // For small code model we assume that latest object is 16MB before end of 31
3808 // bits boundary. We may also accept pretty large negative constants knowing
3809 // that all objects are in the positive half of address space.
3810 if (M == CodeModel::Small && Offset < 16*1024*1024)
3813 // For kernel code model we know that all object resist in the negative half
3814 // of 32bits address space. We may not accept negative offsets, since they may
3815 // be just off and we may accept pretty large positive ones.
3816 if (M == CodeModel::Kernel && Offset >= 0)
3822 /// Determines whether the callee is required to pop its own arguments.
3823 /// Callee pop is necessary to support tail calls.
3824 bool X86::isCalleePop(CallingConv::ID CallingConv,
3825 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3826 switch (CallingConv) {
3829 case CallingConv::X86_StdCall:
3830 case CallingConv::X86_FastCall:
3831 case CallingConv::X86_ThisCall:
3833 case CallingConv::Fast:
3834 case CallingConv::GHC:
3835 case CallingConv::HiPE:
3842 /// \brief Return true if the condition is an unsigned comparison operation.
3843 static bool isX86CCUnsigned(unsigned X86CC) {
3845 default: llvm_unreachable("Invalid integer condition!");
3846 case X86::COND_E: return true;
3847 case X86::COND_G: return false;
3848 case X86::COND_GE: return false;
3849 case X86::COND_L: return false;
3850 case X86::COND_LE: return false;
3851 case X86::COND_NE: return true;
3852 case X86::COND_B: return true;
3853 case X86::COND_A: return true;
3854 case X86::COND_BE: return true;
3855 case X86::COND_AE: return true;
3857 llvm_unreachable("covered switch fell through?!");
3860 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3861 /// condition code, returning the condition code and the LHS/RHS of the
3862 /// comparison to make.
3863 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3864 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3866 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3867 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3868 // X > -1 -> X == 0, jump !sign.
3869 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3870 return X86::COND_NS;
3872 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3873 // X < 0 -> X == 0, jump on sign.
3876 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3878 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3879 return X86::COND_LE;
3883 switch (SetCCOpcode) {
3884 default: llvm_unreachable("Invalid integer condition!");
3885 case ISD::SETEQ: return X86::COND_E;
3886 case ISD::SETGT: return X86::COND_G;
3887 case ISD::SETGE: return X86::COND_GE;
3888 case ISD::SETLT: return X86::COND_L;
3889 case ISD::SETLE: return X86::COND_LE;
3890 case ISD::SETNE: return X86::COND_NE;
3891 case ISD::SETULT: return X86::COND_B;
3892 case ISD::SETUGT: return X86::COND_A;
3893 case ISD::SETULE: return X86::COND_BE;
3894 case ISD::SETUGE: return X86::COND_AE;
3898 // First determine if it is required or is profitable to flip the operands.
3900 // If LHS is a foldable load, but RHS is not, flip the condition.
3901 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3902 !ISD::isNON_EXTLoad(RHS.getNode())) {
3903 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3904 std::swap(LHS, RHS);
3907 switch (SetCCOpcode) {
3913 std::swap(LHS, RHS);
3917 // On a floating point condition, the flags are set as follows:
3919 // 0 | 0 | 0 | X > Y
3920 // 0 | 0 | 1 | X < Y
3921 // 1 | 0 | 0 | X == Y
3922 // 1 | 1 | 1 | unordered
3923 switch (SetCCOpcode) {
3924 default: llvm_unreachable("Condcode should be pre-legalized away");
3926 case ISD::SETEQ: return X86::COND_E;
3927 case ISD::SETOLT: // flipped
3929 case ISD::SETGT: return X86::COND_A;
3930 case ISD::SETOLE: // flipped
3932 case ISD::SETGE: return X86::COND_AE;
3933 case ISD::SETUGT: // flipped
3935 case ISD::SETLT: return X86::COND_B;
3936 case ISD::SETUGE: // flipped
3938 case ISD::SETLE: return X86::COND_BE;
3940 case ISD::SETNE: return X86::COND_NE;
3941 case ISD::SETUO: return X86::COND_P;
3942 case ISD::SETO: return X86::COND_NP;
3944 case ISD::SETUNE: return X86::COND_INVALID;
3948 /// Is there a floating point cmov for the specific X86 condition code?
3949 /// Current x86 isa includes the following FP cmov instructions:
3950 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3951 static bool hasFPCMov(unsigned X86CC) {
3967 /// Returns true if the target can instruction select the
3968 /// specified FP immediate natively. If false, the legalizer will
3969 /// materialize the FP immediate as a load from a constant pool.
3970 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3971 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3972 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3978 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3979 ISD::LoadExtType ExtTy,
3981 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3982 // relocation target a movq or addq instruction: don't let the load shrink.
3983 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3984 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3985 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3986 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3990 /// \brief Returns true if it is beneficial to convert a load of a constant
3991 /// to just the constant itself.
3992 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3994 assert(Ty->isIntegerTy());
3996 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3997 if (BitSize == 0 || BitSize > 64)
4002 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4003 unsigned Index) const {
4004 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4007 return (Index == 0 || Index == ResVT.getVectorNumElements());
4010 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4011 // Speculate cttz only if we can directly use TZCNT.
4012 return Subtarget->hasBMI();
4015 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4016 // Speculate ctlz only if we can directly use LZCNT.
4017 return Subtarget->hasLZCNT();
4020 /// Return true if every element in Mask, beginning
4021 /// from position Pos and ending in Pos+Size is undef.
4022 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4023 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4029 /// Return true if Val is undef or if its value falls within the
4030 /// specified range (L, H].
4031 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4032 return (Val < 0) || (Val >= Low && Val < Hi);
4035 /// Val is either less than zero (undef) or equal to the specified value.
4036 static bool isUndefOrEqual(int Val, int CmpVal) {
4037 return (Val < 0 || Val == CmpVal);
4040 /// Return true if every element in Mask, beginning
4041 /// from position Pos and ending in Pos+Size, falls within the specified
4042 /// sequential range (Low, Low+Size]. or is undef.
4043 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4044 unsigned Pos, unsigned Size, int Low) {
4045 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4046 if (!isUndefOrEqual(Mask[i], Low))
4051 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4052 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4053 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4054 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4055 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4058 // The index should be aligned on a vecWidth-bit boundary.
4060 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4062 MVT VT = N->getSimpleValueType(0);
4063 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4064 bool Result = (Index * ElSize) % vecWidth == 0;
4069 /// Return true if the specified INSERT_SUBVECTOR
4070 /// operand specifies a subvector insert that is suitable for input to
4071 /// insertion of 128 or 256-bit subvectors
4072 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4073 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4074 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4076 // The index should be aligned on a vecWidth-bit boundary.
4078 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4080 MVT VT = N->getSimpleValueType(0);
4081 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4082 bool Result = (Index * ElSize) % vecWidth == 0;
4087 bool X86::isVINSERT128Index(SDNode *N) {
4088 return isVINSERTIndex(N, 128);
4091 bool X86::isVINSERT256Index(SDNode *N) {
4092 return isVINSERTIndex(N, 256);
4095 bool X86::isVEXTRACT128Index(SDNode *N) {
4096 return isVEXTRACTIndex(N, 128);
4099 bool X86::isVEXTRACT256Index(SDNode *N) {
4100 return isVEXTRACTIndex(N, 256);
4103 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4104 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4105 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4106 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4109 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4111 MVT VecVT = N->getOperand(0).getSimpleValueType();
4112 MVT ElVT = VecVT.getVectorElementType();
4114 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4115 return Index / NumElemsPerChunk;
4118 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4119 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4120 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4121 llvm_unreachable("Illegal insert subvector for VINSERT");
4124 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4126 MVT VecVT = N->getSimpleValueType(0);
4127 MVT ElVT = VecVT.getVectorElementType();
4129 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4130 return Index / NumElemsPerChunk;
4133 /// Return the appropriate immediate to extract the specified
4134 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4135 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4136 return getExtractVEXTRACTImmediate(N, 128);
4139 /// Return the appropriate immediate to extract the specified
4140 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4141 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4142 return getExtractVEXTRACTImmediate(N, 256);
4145 /// Return the appropriate immediate to insert at the specified
4146 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4147 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4148 return getInsertVINSERTImmediate(N, 128);
4151 /// Return the appropriate immediate to insert at the specified
4152 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4153 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4154 return getInsertVINSERTImmediate(N, 256);
4157 /// Returns true if Elt is a constant integer zero
4158 static bool isZero(SDValue V) {
4159 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4160 return C && C->isNullValue();
4163 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4164 bool X86::isZeroNode(SDValue Elt) {
4167 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4168 return CFP->getValueAPF().isPosZero();
4172 /// Returns a vector of specified type with all zero elements.
4173 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4174 SelectionDAG &DAG, SDLoc dl) {
4175 assert(VT.isVector() && "Expected a vector type");
4177 // Always build SSE zero vectors as <4 x i32> bitcasted
4178 // to their dest type. This ensures they get CSE'd.
4180 if (VT.is128BitVector()) { // SSE
4181 if (Subtarget->hasSSE2()) { // SSE2
4182 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4183 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4185 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4186 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4188 } else if (VT.is256BitVector()) { // AVX
4189 if (Subtarget->hasInt256()) { // AVX2
4190 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4191 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4192 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4194 // 256-bit logic and arithmetic instructions in AVX are all
4195 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4196 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4197 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4198 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4200 } else if (VT.is512BitVector()) { // AVX-512
4201 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4202 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4203 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4204 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4205 } else if (VT.getScalarType() == MVT::i1) {
4207 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4208 && "Unexpected vector type");
4209 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4210 && "Unexpected vector type");
4211 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4212 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4213 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4215 llvm_unreachable("Unexpected vector type");
4217 return DAG.getBitcast(VT, Vec);
4220 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4221 SelectionDAG &DAG, SDLoc dl,
4222 unsigned vectorWidth) {
4223 assert((vectorWidth == 128 || vectorWidth == 256) &&
4224 "Unsupported vector width");
4225 EVT VT = Vec.getValueType();
4226 EVT ElVT = VT.getVectorElementType();
4227 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4228 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4229 VT.getVectorNumElements()/Factor);
4231 // Extract from UNDEF is UNDEF.
4232 if (Vec.getOpcode() == ISD::UNDEF)
4233 return DAG.getUNDEF(ResultVT);
4235 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4236 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4238 // This is the index of the first element of the vectorWidth-bit chunk
4240 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4243 // If the input is a buildvector just emit a smaller one.
4244 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4245 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4246 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4249 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4250 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4253 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4254 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4255 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4256 /// instructions or a simple subregister reference. Idx is an index in the
4257 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4258 /// lowering EXTRACT_VECTOR_ELT operations easier.
4259 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4260 SelectionDAG &DAG, SDLoc dl) {
4261 assert((Vec.getValueType().is256BitVector() ||
4262 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4263 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4266 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4267 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4268 SelectionDAG &DAG, SDLoc dl) {
4269 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4270 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4273 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4274 unsigned IdxVal, SelectionDAG &DAG,
4275 SDLoc dl, unsigned vectorWidth) {
4276 assert((vectorWidth == 128 || vectorWidth == 256) &&
4277 "Unsupported vector width");
4278 // Inserting UNDEF is Result
4279 if (Vec.getOpcode() == ISD::UNDEF)
4281 EVT VT = Vec.getValueType();
4282 EVT ElVT = VT.getVectorElementType();
4283 EVT ResultVT = Result.getValueType();
4285 // Insert the relevant vectorWidth bits.
4286 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4288 // This is the index of the first element of the vectorWidth-bit chunk
4290 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4293 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4294 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4297 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4298 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4299 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4300 /// simple superregister reference. Idx is an index in the 128 bits
4301 /// we want. It need not be aligned to a 128-bit boundary. That makes
4302 /// lowering INSERT_VECTOR_ELT operations easier.
4303 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4304 SelectionDAG &DAG, SDLoc dl) {
4305 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4307 // For insertion into the zero index (low half) of a 256-bit vector, it is
4308 // more efficient to generate a blend with immediate instead of an insert*128.
4309 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4310 // extend the subvector to the size of the result vector. Make sure that
4311 // we are not recursing on that node by checking for undef here.
4312 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4313 Result.getOpcode() != ISD::UNDEF) {
4314 EVT ResultVT = Result.getValueType();
4315 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4316 SDValue Undef = DAG.getUNDEF(ResultVT);
4317 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4320 // The blend instruction, and therefore its mask, depend on the data type.
4321 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4322 if (ScalarType.isFloatingPoint()) {
4323 // Choose either vblendps (float) or vblendpd (double).
4324 unsigned ScalarSize = ScalarType.getSizeInBits();
4325 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4326 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4327 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4328 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4331 const X86Subtarget &Subtarget =
4332 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4334 // AVX2 is needed for 256-bit integer blend support.
4335 // Integers must be cast to 32-bit because there is only vpblendd;
4336 // vpblendw can't be used for this because it has a handicapped mask.
4338 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4339 // is still more efficient than using the wrong domain vinsertf128 that
4340 // will be created by InsertSubVector().
4341 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4343 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4344 Vec256 = DAG.getBitcast(CastVT, Vec256);
4345 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4346 return DAG.getBitcast(ResultVT, Vec256);
4349 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4352 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4353 SelectionDAG &DAG, SDLoc dl) {
4354 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4355 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4358 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4359 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4360 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4361 /// large BUILD_VECTORS.
4362 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4363 unsigned NumElems, SelectionDAG &DAG,
4365 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4366 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4369 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4370 unsigned NumElems, SelectionDAG &DAG,
4372 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4373 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4376 /// Returns a vector of specified type with all bits set.
4377 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4378 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4379 /// Then bitcast to their original type, ensuring they get CSE'd.
4380 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4382 assert(VT.isVector() && "Expected a vector type");
4384 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4386 if (VT.is256BitVector()) {
4387 if (HasInt256) { // AVX2
4388 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4389 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4391 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4392 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4394 } else if (VT.is128BitVector()) {
4395 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4397 llvm_unreachable("Unexpected vector type");
4399 return DAG.getBitcast(VT, Vec);
4402 /// Returns a vector_shuffle mask for an movs{s|d}, movd
4403 /// operation of specified width.
4404 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4406 unsigned NumElems = VT.getVectorNumElements();
4407 SmallVector<int, 8> Mask;
4408 Mask.push_back(NumElems);
4409 for (unsigned i = 1; i != NumElems; ++i)
4411 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4414 /// Returns a vector_shuffle node for an unpackl operation.
4415 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4417 unsigned NumElems = VT.getVectorNumElements();
4418 SmallVector<int, 8> Mask;
4419 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4421 Mask.push_back(i + NumElems);
4423 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4426 /// Returns a vector_shuffle node for an unpackh operation.
4427 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4429 unsigned NumElems = VT.getVectorNumElements();
4430 SmallVector<int, 8> Mask;
4431 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4432 Mask.push_back(i + Half);
4433 Mask.push_back(i + NumElems + Half);
4435 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4438 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4439 /// This produces a shuffle where the low element of V2 is swizzled into the
4440 /// zero/undef vector, landing at element Idx.
4441 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4442 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4444 const X86Subtarget *Subtarget,
4445 SelectionDAG &DAG) {
4446 MVT VT = V2.getSimpleValueType();
4448 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4449 unsigned NumElems = VT.getVectorNumElements();
4450 SmallVector<int, 16> MaskVec;
4451 for (unsigned i = 0; i != NumElems; ++i)
4452 // If this is the insertion idx, put the low elt of V2 here.
4453 MaskVec.push_back(i == Idx ? NumElems : i);
4454 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4457 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4458 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4459 /// uses one source. Note that this will set IsUnary for shuffles which use a
4460 /// single input multiple times, and in those cases it will
4461 /// adjust the mask to only have indices within that single input.
4462 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4463 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4464 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4465 unsigned NumElems = VT.getVectorNumElements();
4469 bool IsFakeUnary = false;
4470 switch(N->getOpcode()) {
4471 case X86ISD::BLENDI:
4472 ImmN = N->getOperand(N->getNumOperands()-1);
4473 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4476 ImmN = N->getOperand(N->getNumOperands()-1);
4477 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4478 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4480 case X86ISD::UNPCKH:
4481 DecodeUNPCKHMask(VT, Mask);
4482 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4484 case X86ISD::UNPCKL:
4485 DecodeUNPCKLMask(VT, Mask);
4486 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4488 case X86ISD::MOVHLPS:
4489 DecodeMOVHLPSMask(NumElems, Mask);
4490 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4492 case X86ISD::MOVLHPS:
4493 DecodeMOVLHPSMask(NumElems, Mask);
4494 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4496 case X86ISD::PALIGNR:
4497 ImmN = N->getOperand(N->getNumOperands()-1);
4498 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500 case X86ISD::PSHUFD:
4501 case X86ISD::VPERMILPI:
4502 ImmN = N->getOperand(N->getNumOperands()-1);
4503 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4506 case X86ISD::PSHUFHW:
4507 ImmN = N->getOperand(N->getNumOperands()-1);
4508 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4511 case X86ISD::PSHUFLW:
4512 ImmN = N->getOperand(N->getNumOperands()-1);
4513 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516 case X86ISD::PSHUFB: {
4518 SDValue MaskNode = N->getOperand(1);
4519 while (MaskNode->getOpcode() == ISD::BITCAST)
4520 MaskNode = MaskNode->getOperand(0);
4522 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4523 // If we have a build-vector, then things are easy.
4524 EVT VT = MaskNode.getValueType();
4525 assert(VT.isVector() &&
4526 "Can't produce a non-vector with a build_vector!");
4527 if (!VT.isInteger())
4530 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4532 SmallVector<uint64_t, 32> RawMask;
4533 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4534 SDValue Op = MaskNode->getOperand(i);
4535 if (Op->getOpcode() == ISD::UNDEF) {
4536 RawMask.push_back((uint64_t)SM_SentinelUndef);
4539 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4542 APInt MaskElement = CN->getAPIntValue();
4544 // We now have to decode the element which could be any integer size and
4545 // extract each byte of it.
4546 for (int j = 0; j < NumBytesPerElement; ++j) {
4547 // Note that this is x86 and so always little endian: the low byte is
4548 // the first byte of the mask.
4549 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4550 MaskElement = MaskElement.lshr(8);
4553 DecodePSHUFBMask(RawMask, Mask);
4557 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4561 SDValue Ptr = MaskLoad->getBasePtr();
4562 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4563 Ptr->getOpcode() == X86ISD::WrapperRIP)
4564 Ptr = Ptr->getOperand(0);
4566 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4567 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4570 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4571 DecodePSHUFBMask(C, Mask);
4579 case X86ISD::VPERMI:
4580 ImmN = N->getOperand(N->getNumOperands()-1);
4581 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4586 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4588 case X86ISD::VPERM2X128:
4589 ImmN = N->getOperand(N->getNumOperands()-1);
4590 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4591 if (Mask.empty()) return false;
4592 // Mask only contains negative index if an element is zero.
4593 if (std::any_of(Mask.begin(), Mask.end(),
4594 [](int M){ return M == SM_SentinelZero; }))
4597 case X86ISD::MOVSLDUP:
4598 DecodeMOVSLDUPMask(VT, Mask);
4601 case X86ISD::MOVSHDUP:
4602 DecodeMOVSHDUPMask(VT, Mask);
4605 case X86ISD::MOVDDUP:
4606 DecodeMOVDDUPMask(VT, Mask);
4609 case X86ISD::MOVLHPD:
4610 case X86ISD::MOVLPD:
4611 case X86ISD::MOVLPS:
4612 // Not yet implemented
4614 default: llvm_unreachable("unknown target shuffle node");
4617 // If we have a fake unary shuffle, the shuffle mask is spread across two
4618 // inputs that are actually the same node. Re-map the mask to always point
4619 // into the first input.
4622 if (M >= (int)Mask.size())
4628 /// Returns the scalar element that will make up the ith
4629 /// element of the result of the vector shuffle.
4630 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4633 return SDValue(); // Limit search depth.
4635 SDValue V = SDValue(N, 0);
4636 EVT VT = V.getValueType();
4637 unsigned Opcode = V.getOpcode();
4639 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4640 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4641 int Elt = SV->getMaskElt(Index);
4644 return DAG.getUNDEF(VT.getVectorElementType());
4646 unsigned NumElems = VT.getVectorNumElements();
4647 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4648 : SV->getOperand(1);
4649 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4652 // Recurse into target specific vector shuffles to find scalars.
4653 if (isTargetShuffle(Opcode)) {
4654 MVT ShufVT = V.getSimpleValueType();
4655 unsigned NumElems = ShufVT.getVectorNumElements();
4656 SmallVector<int, 16> ShuffleMask;
4659 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4662 int Elt = ShuffleMask[Index];
4664 return DAG.getUNDEF(ShufVT.getVectorElementType());
4666 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4668 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4672 // Actual nodes that may contain scalar elements
4673 if (Opcode == ISD::BITCAST) {
4674 V = V.getOperand(0);
4675 EVT SrcVT = V.getValueType();
4676 unsigned NumElems = VT.getVectorNumElements();
4678 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4682 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4683 return (Index == 0) ? V.getOperand(0)
4684 : DAG.getUNDEF(VT.getVectorElementType());
4686 if (V.getOpcode() == ISD::BUILD_VECTOR)
4687 return V.getOperand(Index);
4692 /// Custom lower build_vector of v16i8.
4693 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4694 unsigned NumNonZero, unsigned NumZero,
4696 const X86Subtarget* Subtarget,
4697 const TargetLowering &TLI) {
4705 // SSE4.1 - use PINSRB to insert each byte directly.
4706 if (Subtarget->hasSSE41()) {
4707 for (unsigned i = 0; i < 16; ++i) {
4708 bool isNonZero = (NonZeros & (1 << i)) != 0;
4712 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4714 V = DAG.getUNDEF(MVT::v16i8);
4717 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4718 MVT::v16i8, V, Op.getOperand(i),
4719 DAG.getIntPtrConstant(i, dl));
4726 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4727 for (unsigned i = 0; i < 16; ++i) {
4728 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4729 if (ThisIsNonZero && First) {
4731 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4733 V = DAG.getUNDEF(MVT::v8i16);
4738 SDValue ThisElt, LastElt;
4739 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4740 if (LastIsNonZero) {
4741 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4742 MVT::i16, Op.getOperand(i-1));
4744 if (ThisIsNonZero) {
4745 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4746 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4747 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4749 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4753 if (ThisElt.getNode())
4754 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4755 DAG.getIntPtrConstant(i/2, dl));
4759 return DAG.getBitcast(MVT::v16i8, V);
4762 /// Custom lower build_vector of v8i16.
4763 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4764 unsigned NumNonZero, unsigned NumZero,
4766 const X86Subtarget* Subtarget,
4767 const TargetLowering &TLI) {
4774 for (unsigned i = 0; i < 8; ++i) {
4775 bool isNonZero = (NonZeros & (1 << i)) != 0;
4779 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4781 V = DAG.getUNDEF(MVT::v8i16);
4784 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4785 MVT::v8i16, V, Op.getOperand(i),
4786 DAG.getIntPtrConstant(i, dl));
4793 /// Custom lower build_vector of v4i32 or v4f32.
4794 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4795 const X86Subtarget *Subtarget,
4796 const TargetLowering &TLI) {
4797 // Find all zeroable elements.
4798 std::bitset<4> Zeroable;
4799 for (int i=0; i < 4; ++i) {
4800 SDValue Elt = Op->getOperand(i);
4801 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4803 assert(Zeroable.size() - Zeroable.count() > 1 &&
4804 "We expect at least two non-zero elements!");
4806 // We only know how to deal with build_vector nodes where elements are either
4807 // zeroable or extract_vector_elt with constant index.
4808 SDValue FirstNonZero;
4809 unsigned FirstNonZeroIdx;
4810 for (unsigned i=0; i < 4; ++i) {
4813 SDValue Elt = Op->getOperand(i);
4814 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4815 !isa<ConstantSDNode>(Elt.getOperand(1)))
4817 // Make sure that this node is extracting from a 128-bit vector.
4818 MVT VT = Elt.getOperand(0).getSimpleValueType();
4819 if (!VT.is128BitVector())
4821 if (!FirstNonZero.getNode()) {
4823 FirstNonZeroIdx = i;
4827 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4828 SDValue V1 = FirstNonZero.getOperand(0);
4829 MVT VT = V1.getSimpleValueType();
4831 // See if this build_vector can be lowered as a blend with zero.
4833 unsigned EltMaskIdx, EltIdx;
4835 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4836 if (Zeroable[EltIdx]) {
4837 // The zero vector will be on the right hand side.
4838 Mask[EltIdx] = EltIdx+4;
4842 Elt = Op->getOperand(EltIdx);
4843 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4844 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4845 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4847 Mask[EltIdx] = EltIdx;
4851 // Let the shuffle legalizer deal with blend operations.
4852 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4853 if (V1.getSimpleValueType() != VT)
4854 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4855 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4858 // See if we can lower this build_vector to a INSERTPS.
4859 if (!Subtarget->hasSSE41())
4862 SDValue V2 = Elt.getOperand(0);
4863 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4866 bool CanFold = true;
4867 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4871 SDValue Current = Op->getOperand(i);
4872 SDValue SrcVector = Current->getOperand(0);
4875 CanFold = SrcVector == V1 &&
4876 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4882 assert(V1.getNode() && "Expected at least two non-zero elements!");
4883 if (V1.getSimpleValueType() != MVT::v4f32)
4884 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4885 if (V2.getSimpleValueType() != MVT::v4f32)
4886 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4888 // Ok, we can emit an INSERTPS instruction.
4889 unsigned ZMask = Zeroable.to_ulong();
4891 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4892 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4894 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4895 DAG.getIntPtrConstant(InsertPSMask, DL));
4896 return DAG.getBitcast(VT, Result);
4899 /// Return a vector logical shift node.
4900 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4901 unsigned NumBits, SelectionDAG &DAG,
4902 const TargetLowering &TLI, SDLoc dl) {
4903 assert(VT.is128BitVector() && "Unknown type for VShift");
4904 MVT ShVT = MVT::v2i64;
4905 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4906 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4907 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4908 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4909 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4910 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4914 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4916 // Check if the scalar load can be widened into a vector load. And if
4917 // the address is "base + cst" see if the cst can be "absorbed" into
4918 // the shuffle mask.
4919 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4920 SDValue Ptr = LD->getBasePtr();
4921 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4923 EVT PVT = LD->getValueType(0);
4924 if (PVT != MVT::i32 && PVT != MVT::f32)
4929 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4930 FI = FINode->getIndex();
4932 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4933 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4934 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4935 Offset = Ptr.getConstantOperandVal(1);
4936 Ptr = Ptr.getOperand(0);
4941 // FIXME: 256-bit vector instructions don't require a strict alignment,
4942 // improve this code to support it better.
4943 unsigned RequiredAlign = VT.getSizeInBits()/8;
4944 SDValue Chain = LD->getChain();
4945 // Make sure the stack object alignment is at least 16 or 32.
4946 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4947 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4948 if (MFI->isFixedObjectIndex(FI)) {
4949 // Can't change the alignment. FIXME: It's possible to compute
4950 // the exact stack offset and reference FI + adjust offset instead.
4951 // If someone *really* cares about this. That's the way to implement it.
4954 MFI->setObjectAlignment(FI, RequiredAlign);
4958 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4959 // Ptr + (Offset & ~15).
4962 if ((Offset % RequiredAlign) & 3)
4964 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4967 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4968 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4971 int EltNo = (Offset - StartOffset) >> 2;
4972 unsigned NumElems = VT.getVectorNumElements();
4974 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4975 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4976 LD->getPointerInfo().getWithOffset(StartOffset),
4977 false, false, false, 0);
4979 SmallVector<int, 8> Mask(NumElems, EltNo);
4981 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4987 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4988 /// elements can be replaced by a single large load which has the same value as
4989 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4991 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4993 /// FIXME: we'd also like to handle the case where the last elements are zero
4994 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4995 /// There's even a handy isZeroNode for that purpose.
4996 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4997 SDLoc &DL, SelectionDAG &DAG,
4998 bool isAfterLegalize) {
4999 unsigned NumElems = Elts.size();
5001 LoadSDNode *LDBase = nullptr;
5002 unsigned LastLoadedElt = -1U;
5004 // For each element in the initializer, see if we've found a load or an undef.
5005 // If we don't find an initial load element, or later load elements are
5006 // non-consecutive, bail out.
5007 for (unsigned i = 0; i < NumElems; ++i) {
5008 SDValue Elt = Elts[i];
5009 // Look through a bitcast.
5010 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5011 Elt = Elt.getOperand(0);
5012 if (!Elt.getNode() ||
5013 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5016 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5018 LDBase = cast<LoadSDNode>(Elt.getNode());
5022 if (Elt.getOpcode() == ISD::UNDEF)
5025 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5026 EVT LdVT = Elt.getValueType();
5027 // Each loaded element must be the correct fractional portion of the
5028 // requested vector load.
5029 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5031 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5036 // If we have found an entire vector of loads and undefs, then return a large
5037 // load of the entire vector width starting at the base pointer. If we found
5038 // consecutive loads for the low half, generate a vzext_load node.
5039 if (LastLoadedElt == NumElems - 1) {
5040 assert(LDBase && "Did not find base load for merging consecutive loads");
5041 EVT EltVT = LDBase->getValueType(0);
5042 // Ensure that the input vector size for the merged loads matches the
5043 // cumulative size of the input elements.
5044 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5047 if (isAfterLegalize &&
5048 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5051 SDValue NewLd = SDValue();
5053 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5054 LDBase->getPointerInfo(), LDBase->isVolatile(),
5055 LDBase->isNonTemporal(), LDBase->isInvariant(),
5056 LDBase->getAlignment());
5058 if (LDBase->hasAnyUseOfValue(1)) {
5059 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5061 SDValue(NewLd.getNode(), 1));
5062 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5063 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5064 SDValue(NewLd.getNode(), 1));
5070 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5071 //of a v4i32 / v4f32. It's probably worth generalizing.
5072 EVT EltVT = VT.getVectorElementType();
5073 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5074 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5075 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5076 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5078 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5079 LDBase->getPointerInfo(),
5080 LDBase->getAlignment(),
5081 false/*isVolatile*/, true/*ReadMem*/,
5084 // Make sure the newly-created LOAD is in the same position as LDBase in
5085 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5086 // update uses of LDBase's output chain to use the TokenFactor.
5087 if (LDBase->hasAnyUseOfValue(1)) {
5088 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5089 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5090 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5091 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5092 SDValue(ResNode.getNode(), 1));
5095 return DAG.getBitcast(VT, ResNode);
5100 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5101 /// to generate a splat value for the following cases:
5102 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5103 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5104 /// a scalar load, or a constant.
5105 /// The VBROADCAST node is returned when a pattern is found,
5106 /// or SDValue() otherwise.
5107 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5108 SelectionDAG &DAG) {
5109 // VBROADCAST requires AVX.
5110 // TODO: Splats could be generated for non-AVX CPUs using SSE
5111 // instructions, but there's less potential gain for only 128-bit vectors.
5112 if (!Subtarget->hasAVX())
5115 MVT VT = Op.getSimpleValueType();
5118 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5119 "Unsupported vector type for broadcast.");
5124 switch (Op.getOpcode()) {
5126 // Unknown pattern found.
5129 case ISD::BUILD_VECTOR: {
5130 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5131 BitVector UndefElements;
5132 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5134 // We need a splat of a single value to use broadcast, and it doesn't
5135 // make any sense if the value is only in one element of the vector.
5136 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5140 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5141 Ld.getOpcode() == ISD::ConstantFP);
5143 // Make sure that all of the users of a non-constant load are from the
5144 // BUILD_VECTOR node.
5145 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5150 case ISD::VECTOR_SHUFFLE: {
5151 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5153 // Shuffles must have a splat mask where the first element is
5155 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5158 SDValue Sc = Op.getOperand(0);
5159 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5160 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5162 if (!Subtarget->hasInt256())
5165 // Use the register form of the broadcast instruction available on AVX2.
5166 if (VT.getSizeInBits() >= 256)
5167 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5168 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5171 Ld = Sc.getOperand(0);
5172 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5173 Ld.getOpcode() == ISD::ConstantFP);
5175 // The scalar_to_vector node and the suspected
5176 // load node must have exactly one user.
5177 // Constants may have multiple users.
5179 // AVX-512 has register version of the broadcast
5180 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5181 Ld.getValueType().getSizeInBits() >= 32;
5182 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5189 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5190 bool IsGE256 = (VT.getSizeInBits() >= 256);
5192 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5193 // instruction to save 8 or more bytes of constant pool data.
5194 // TODO: If multiple splats are generated to load the same constant,
5195 // it may be detrimental to overall size. There needs to be a way to detect
5196 // that condition to know if this is truly a size win.
5197 const Function *F = DAG.getMachineFunction().getFunction();
5198 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5200 // Handle broadcasting a single constant scalar from the constant pool
5202 // On Sandybridge (no AVX2), it is still better to load a constant vector
5203 // from the constant pool and not to broadcast it from a scalar.
5204 // But override that restriction when optimizing for size.
5205 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5206 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5207 EVT CVT = Ld.getValueType();
5208 assert(!CVT.isVector() && "Must not broadcast a vector type");
5210 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5211 // For size optimization, also splat v2f64 and v2i64, and for size opt
5212 // with AVX2, also splat i8 and i16.
5213 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5214 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5215 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5216 const Constant *C = nullptr;
5217 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5218 C = CI->getConstantIntValue();
5219 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5220 C = CF->getConstantFPValue();
5222 assert(C && "Invalid constant type");
5224 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5226 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5227 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5228 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5229 MachinePointerInfo::getConstantPool(),
5230 false, false, false, Alignment);
5232 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5236 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5238 // Handle AVX2 in-register broadcasts.
5239 if (!IsLoad && Subtarget->hasInt256() &&
5240 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5241 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5243 // The scalar source must be a normal load.
5247 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5248 (Subtarget->hasVLX() && ScalarSize == 64))
5249 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5251 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5252 // double since there is no vbroadcastsd xmm
5253 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5254 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5255 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5258 // Unsupported broadcast.
5262 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5263 /// underlying vector and index.
5265 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5267 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5269 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5270 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5273 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5275 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5277 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5278 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5281 // In this case the vector is the extract_subvector expression and the index
5282 // is 2, as specified by the shuffle.
5283 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5284 SDValue ShuffleVec = SVOp->getOperand(0);
5285 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5286 assert(ShuffleVecVT.getVectorElementType() ==
5287 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5289 int ShuffleIdx = SVOp->getMaskElt(Idx);
5290 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5291 ExtractedFromVec = ShuffleVec;
5297 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5298 MVT VT = Op.getSimpleValueType();
5300 // Skip if insert_vec_elt is not supported.
5301 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5302 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5306 unsigned NumElems = Op.getNumOperands();
5310 SmallVector<unsigned, 4> InsertIndices;
5311 SmallVector<int, 8> Mask(NumElems, -1);
5313 for (unsigned i = 0; i != NumElems; ++i) {
5314 unsigned Opc = Op.getOperand(i).getOpcode();
5316 if (Opc == ISD::UNDEF)
5319 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5320 // Quit if more than 1 elements need inserting.
5321 if (InsertIndices.size() > 1)
5324 InsertIndices.push_back(i);
5328 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5329 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5330 // Quit if non-constant index.
5331 if (!isa<ConstantSDNode>(ExtIdx))
5333 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5335 // Quit if extracted from vector of different type.
5336 if (ExtractedFromVec.getValueType() != VT)
5339 if (!VecIn1.getNode())
5340 VecIn1 = ExtractedFromVec;
5341 else if (VecIn1 != ExtractedFromVec) {
5342 if (!VecIn2.getNode())
5343 VecIn2 = ExtractedFromVec;
5344 else if (VecIn2 != ExtractedFromVec)
5345 // Quit if more than 2 vectors to shuffle
5349 if (ExtractedFromVec == VecIn1)
5351 else if (ExtractedFromVec == VecIn2)
5352 Mask[i] = Idx + NumElems;
5355 if (!VecIn1.getNode())
5358 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5359 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5360 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5361 unsigned Idx = InsertIndices[i];
5362 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5363 DAG.getIntPtrConstant(Idx, DL));
5369 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5370 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5371 Op.getScalarValueSizeInBits() == 1 &&
5372 "Can not convert non-constant vector");
5373 uint64_t Immediate = 0;
5374 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5375 SDValue In = Op.getOperand(idx);
5376 if (In.getOpcode() != ISD::UNDEF)
5377 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5381 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5382 return DAG.getConstant(Immediate, dl, VT);
5384 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5386 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5388 MVT VT = Op.getSimpleValueType();
5389 assert((VT.getVectorElementType() == MVT::i1) &&
5390 "Unexpected type in LowerBUILD_VECTORvXi1!");
5393 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5394 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5395 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5396 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5399 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5400 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5401 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5402 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5405 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5406 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5407 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5408 return DAG.getBitcast(VT, Imm);
5409 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5410 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5411 DAG.getIntPtrConstant(0, dl));
5414 // Vector has one or more non-const elements
5415 uint64_t Immediate = 0;
5416 SmallVector<unsigned, 16> NonConstIdx;
5417 bool IsSplat = true;
5418 bool HasConstElts = false;
5420 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5421 SDValue In = Op.getOperand(idx);
5422 if (In.getOpcode() == ISD::UNDEF)
5424 if (!isa<ConstantSDNode>(In))
5425 NonConstIdx.push_back(idx);
5427 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5428 HasConstElts = true;
5432 else if (In != Op.getOperand(SplatIdx))
5436 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5438 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5439 DAG.getConstant(1, dl, VT),
5440 DAG.getConstant(0, dl, VT));
5442 // insert elements one by one
5446 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5447 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5449 else if (HasConstElts)
5450 Imm = DAG.getConstant(0, dl, VT);
5452 Imm = DAG.getUNDEF(VT);
5453 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5454 DstVec = DAG.getBitcast(VT, Imm);
5456 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5457 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5458 DAG.getIntPtrConstant(0, dl));
5461 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5462 unsigned InsertIdx = NonConstIdx[i];
5463 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5464 Op.getOperand(InsertIdx),
5465 DAG.getIntPtrConstant(InsertIdx, dl));
5470 /// \brief Return true if \p N implements a horizontal binop and return the
5471 /// operands for the horizontal binop into V0 and V1.
5473 /// This is a helper function of LowerToHorizontalOp().
5474 /// This function checks that the build_vector \p N in input implements a
5475 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5476 /// operation to match.
5477 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5478 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5479 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5482 /// This function only analyzes elements of \p N whose indices are
5483 /// in range [BaseIdx, LastIdx).
5484 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5486 unsigned BaseIdx, unsigned LastIdx,
5487 SDValue &V0, SDValue &V1) {
5488 EVT VT = N->getValueType(0);
5490 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5491 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5492 "Invalid Vector in input!");
5494 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5495 bool CanFold = true;
5496 unsigned ExpectedVExtractIdx = BaseIdx;
5497 unsigned NumElts = LastIdx - BaseIdx;
5498 V0 = DAG.getUNDEF(VT);
5499 V1 = DAG.getUNDEF(VT);
5501 // Check if N implements a horizontal binop.
5502 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5503 SDValue Op = N->getOperand(i + BaseIdx);
5506 if (Op->getOpcode() == ISD::UNDEF) {
5507 // Update the expected vector extract index.
5508 if (i * 2 == NumElts)
5509 ExpectedVExtractIdx = BaseIdx;
5510 ExpectedVExtractIdx += 2;
5514 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5519 SDValue Op0 = Op.getOperand(0);
5520 SDValue Op1 = Op.getOperand(1);
5522 // Try to match the following pattern:
5523 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5524 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5525 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5526 Op0.getOperand(0) == Op1.getOperand(0) &&
5527 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5528 isa<ConstantSDNode>(Op1.getOperand(1)));
5532 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5533 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5535 if (i * 2 < NumElts) {
5536 if (V0.getOpcode() == ISD::UNDEF) {
5537 V0 = Op0.getOperand(0);
5538 if (V0.getValueType() != VT)
5542 if (V1.getOpcode() == ISD::UNDEF) {
5543 V1 = Op0.getOperand(0);
5544 if (V1.getValueType() != VT)
5547 if (i * 2 == NumElts)
5548 ExpectedVExtractIdx = BaseIdx;
5551 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5552 if (I0 == ExpectedVExtractIdx)
5553 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5554 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5555 // Try to match the following dag sequence:
5556 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5557 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5561 ExpectedVExtractIdx += 2;
5567 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5568 /// a concat_vector.
5570 /// This is a helper function of LowerToHorizontalOp().
5571 /// This function expects two 256-bit vectors called V0 and V1.
5572 /// At first, each vector is split into two separate 128-bit vectors.
5573 /// Then, the resulting 128-bit vectors are used to implement two
5574 /// horizontal binary operations.
5576 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5578 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5579 /// the two new horizontal binop.
5580 /// When Mode is set, the first horizontal binop dag node would take as input
5581 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5582 /// horizontal binop dag node would take as input the lower 128-bit of V1
5583 /// and the upper 128-bit of V1.
5585 /// HADD V0_LO, V0_HI
5586 /// HADD V1_LO, V1_HI
5588 /// Otherwise, the first horizontal binop dag node takes as input the lower
5589 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5590 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5592 /// HADD V0_LO, V1_LO
5593 /// HADD V0_HI, V1_HI
5595 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5596 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5597 /// the upper 128-bits of the result.
5598 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5599 SDLoc DL, SelectionDAG &DAG,
5600 unsigned X86Opcode, bool Mode,
5601 bool isUndefLO, bool isUndefHI) {
5602 EVT VT = V0.getValueType();
5603 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5604 "Invalid nodes in input!");
5606 unsigned NumElts = VT.getVectorNumElements();
5607 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5608 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5609 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5610 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5611 EVT NewVT = V0_LO.getValueType();
5613 SDValue LO = DAG.getUNDEF(NewVT);
5614 SDValue HI = DAG.getUNDEF(NewVT);
5617 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5618 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5619 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5620 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5621 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5623 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5624 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5625 V1_LO->getOpcode() != ISD::UNDEF))
5626 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5628 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5629 V1_HI->getOpcode() != ISD::UNDEF))
5630 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5633 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5636 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5638 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5639 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5640 EVT VT = BV->getValueType(0);
5641 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5642 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5646 unsigned NumElts = VT.getVectorNumElements();
5647 SDValue InVec0 = DAG.getUNDEF(VT);
5648 SDValue InVec1 = DAG.getUNDEF(VT);
5650 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5651 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5653 // Odd-numbered elements in the input build vector are obtained from
5654 // adding two integer/float elements.
5655 // Even-numbered elements in the input build vector are obtained from
5656 // subtracting two integer/float elements.
5657 unsigned ExpectedOpcode = ISD::FSUB;
5658 unsigned NextExpectedOpcode = ISD::FADD;
5659 bool AddFound = false;
5660 bool SubFound = false;
5662 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5663 SDValue Op = BV->getOperand(i);
5665 // Skip 'undef' values.
5666 unsigned Opcode = Op.getOpcode();
5667 if (Opcode == ISD::UNDEF) {
5668 std::swap(ExpectedOpcode, NextExpectedOpcode);
5672 // Early exit if we found an unexpected opcode.
5673 if (Opcode != ExpectedOpcode)
5676 SDValue Op0 = Op.getOperand(0);
5677 SDValue Op1 = Op.getOperand(1);
5679 // Try to match the following pattern:
5680 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5681 // Early exit if we cannot match that sequence.
5682 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5683 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5684 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5685 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5686 Op0.getOperand(1) != Op1.getOperand(1))
5689 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5693 // We found a valid add/sub node. Update the information accordingly.
5699 // Update InVec0 and InVec1.
5700 if (InVec0.getOpcode() == ISD::UNDEF) {
5701 InVec0 = Op0.getOperand(0);
5702 if (InVec0.getValueType() != VT)
5705 if (InVec1.getOpcode() == ISD::UNDEF) {
5706 InVec1 = Op1.getOperand(0);
5707 if (InVec1.getValueType() != VT)
5711 // Make sure that operands in input to each add/sub node always
5712 // come from a same pair of vectors.
5713 if (InVec0 != Op0.getOperand(0)) {
5714 if (ExpectedOpcode == ISD::FSUB)
5717 // FADD is commutable. Try to commute the operands
5718 // and then test again.
5719 std::swap(Op0, Op1);
5720 if (InVec0 != Op0.getOperand(0))
5724 if (InVec1 != Op1.getOperand(0))
5727 // Update the pair of expected opcodes.
5728 std::swap(ExpectedOpcode, NextExpectedOpcode);
5731 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5732 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5733 InVec1.getOpcode() != ISD::UNDEF)
5734 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5739 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5740 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5741 const X86Subtarget *Subtarget,
5742 SelectionDAG &DAG) {
5743 EVT VT = BV->getValueType(0);
5744 unsigned NumElts = VT.getVectorNumElements();
5745 unsigned NumUndefsLO = 0;
5746 unsigned NumUndefsHI = 0;
5747 unsigned Half = NumElts/2;
5749 // Count the number of UNDEF operands in the build_vector in input.
5750 for (unsigned i = 0, e = Half; i != e; ++i)
5751 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5754 for (unsigned i = Half, e = NumElts; i != e; ++i)
5755 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5758 // Early exit if this is either a build_vector of all UNDEFs or all the
5759 // operands but one are UNDEF.
5760 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5764 SDValue InVec0, InVec1;
5765 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5766 // Try to match an SSE3 float HADD/HSUB.
5767 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5768 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5770 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5771 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5772 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5773 // Try to match an SSSE3 integer HADD/HSUB.
5774 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5775 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5777 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5778 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5781 if (!Subtarget->hasAVX())
5784 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5785 // Try to match an AVX horizontal add/sub of packed single/double
5786 // precision floating point values from 256-bit vectors.
5787 SDValue InVec2, InVec3;
5788 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5789 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5790 ((InVec0.getOpcode() == ISD::UNDEF ||
5791 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5792 ((InVec1.getOpcode() == ISD::UNDEF ||
5793 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5794 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5796 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5797 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5798 ((InVec0.getOpcode() == ISD::UNDEF ||
5799 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5800 ((InVec1.getOpcode() == ISD::UNDEF ||
5801 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5802 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5803 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5804 // Try to match an AVX2 horizontal add/sub of signed integers.
5805 SDValue InVec2, InVec3;
5807 bool CanFold = true;
5809 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5810 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5811 ((InVec0.getOpcode() == ISD::UNDEF ||
5812 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5813 ((InVec1.getOpcode() == ISD::UNDEF ||
5814 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5815 X86Opcode = X86ISD::HADD;
5816 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5817 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5818 ((InVec0.getOpcode() == ISD::UNDEF ||
5819 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5820 ((InVec1.getOpcode() == ISD::UNDEF ||
5821 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5822 X86Opcode = X86ISD::HSUB;
5827 // Fold this build_vector into a single horizontal add/sub.
5828 // Do this only if the target has AVX2.
5829 if (Subtarget->hasAVX2())
5830 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5832 // Do not try to expand this build_vector into a pair of horizontal
5833 // add/sub if we can emit a pair of scalar add/sub.
5834 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5837 // Convert this build_vector into a pair of horizontal binop followed by
5839 bool isUndefLO = NumUndefsLO == Half;
5840 bool isUndefHI = NumUndefsHI == Half;
5841 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5842 isUndefLO, isUndefHI);
5846 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5847 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5849 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5850 X86Opcode = X86ISD::HADD;
5851 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5852 X86Opcode = X86ISD::HSUB;
5853 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5854 X86Opcode = X86ISD::FHADD;
5855 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5856 X86Opcode = X86ISD::FHSUB;
5860 // Don't try to expand this build_vector into a pair of horizontal add/sub
5861 // if we can simply emit a pair of scalar add/sub.
5862 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5865 // Convert this build_vector into two horizontal add/sub followed by
5867 bool isUndefLO = NumUndefsLO == Half;
5868 bool isUndefHI = NumUndefsHI == Half;
5869 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5870 isUndefLO, isUndefHI);
5877 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5880 MVT VT = Op.getSimpleValueType();
5881 MVT ExtVT = VT.getVectorElementType();
5882 unsigned NumElems = Op.getNumOperands();
5884 // Generate vectors for predicate vectors.
5885 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5886 return LowerBUILD_VECTORvXi1(Op, DAG);
5888 // Vectors containing all zeros can be matched by pxor and xorps later
5889 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5890 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5891 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5892 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5895 return getZeroVector(VT, Subtarget, DAG, dl);
5898 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5899 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5900 // vpcmpeqd on 256-bit vectors.
5901 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5902 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5905 if (!VT.is512BitVector())
5906 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5909 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5910 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5912 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5913 return HorizontalOp;
5914 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5917 unsigned EVTBits = ExtVT.getSizeInBits();
5919 unsigned NumZero = 0;
5920 unsigned NumNonZero = 0;
5921 unsigned NonZeros = 0;
5922 bool IsAllConstants = true;
5923 SmallSet<SDValue, 8> Values;
5924 for (unsigned i = 0; i < NumElems; ++i) {
5925 SDValue Elt = Op.getOperand(i);
5926 if (Elt.getOpcode() == ISD::UNDEF)
5929 if (Elt.getOpcode() != ISD::Constant &&
5930 Elt.getOpcode() != ISD::ConstantFP)
5931 IsAllConstants = false;
5932 if (X86::isZeroNode(Elt))
5935 NonZeros |= (1 << i);
5940 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5941 if (NumNonZero == 0)
5942 return DAG.getUNDEF(VT);
5944 // Special case for single non-zero, non-undef, element.
5945 if (NumNonZero == 1) {
5946 unsigned Idx = countTrailingZeros(NonZeros);
5947 SDValue Item = Op.getOperand(Idx);
5949 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5950 // the value are obviously zero, truncate the value to i32 and do the
5951 // insertion that way. Only do this if the value is non-constant or if the
5952 // value is a constant being inserted into element 0. It is cheaper to do
5953 // a constant pool load than it is to do a movd + shuffle.
5954 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5955 (!IsAllConstants || Idx == 0)) {
5956 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5958 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5959 EVT VecVT = MVT::v4i32;
5961 // Truncate the value (which may itself be a constant) to i32, and
5962 // convert it to a vector with movd (S2V+shuffle to zero extend).
5963 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5964 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5965 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5966 Item, Idx * 2, true, Subtarget, DAG));
5970 // If we have a constant or non-constant insertion into the low element of
5971 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5972 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5973 // depending on what the source datatype is.
5976 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5978 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5979 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5980 if (VT.is512BitVector()) {
5981 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5982 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5983 Item, DAG.getIntPtrConstant(0, dl));
5985 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5986 "Expected an SSE value type!");
5987 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5988 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5989 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5992 // We can't directly insert an i8 or i16 into a vector, so zero extend
5994 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5995 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5996 if (VT.is256BitVector()) {
5997 if (Subtarget->hasAVX()) {
5998 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5999 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6001 // Without AVX, we need to extend to a 128-bit vector and then
6002 // insert into the 256-bit vector.
6003 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6004 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6005 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6008 assert(VT.is128BitVector() && "Expected an SSE value type!");
6009 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6010 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6012 return DAG.getBitcast(VT, Item);
6016 // Is it a vector logical left shift?
6017 if (NumElems == 2 && Idx == 1 &&
6018 X86::isZeroNode(Op.getOperand(0)) &&
6019 !X86::isZeroNode(Op.getOperand(1))) {
6020 unsigned NumBits = VT.getSizeInBits();
6021 return getVShift(true, VT,
6022 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6023 VT, Op.getOperand(1)),
6024 NumBits/2, DAG, *this, dl);
6027 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6030 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6031 // is a non-constant being inserted into an element other than the low one,
6032 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6033 // movd/movss) to move this into the low element, then shuffle it into
6035 if (EVTBits == 32) {
6036 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6037 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6041 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6042 if (Values.size() == 1) {
6043 if (EVTBits == 32) {
6044 // Instead of a shuffle like this:
6045 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6046 // Check if it's possible to issue this instead.
6047 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6048 unsigned Idx = countTrailingZeros(NonZeros);
6049 SDValue Item = Op.getOperand(Idx);
6050 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6051 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6056 // A vector full of immediates; various special cases are already
6057 // handled, so this is best done with a single constant-pool load.
6061 // For AVX-length vectors, see if we can use a vector load to get all of the
6062 // elements, otherwise build the individual 128-bit pieces and use
6063 // shuffles to put them in place.
6064 if (VT.is256BitVector() || VT.is512BitVector()) {
6065 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6067 // Check for a build vector of consecutive loads.
6068 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6071 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6073 // Build both the lower and upper subvector.
6074 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6075 makeArrayRef(&V[0], NumElems/2));
6076 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6077 makeArrayRef(&V[NumElems / 2], NumElems/2));
6079 // Recreate the wider vector with the lower and upper part.
6080 if (VT.is256BitVector())
6081 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6082 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6085 // Let legalizer expand 2-wide build_vectors.
6086 if (EVTBits == 64) {
6087 if (NumNonZero == 1) {
6088 // One half is zero or undef.
6089 unsigned Idx = countTrailingZeros(NonZeros);
6090 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6091 Op.getOperand(Idx));
6092 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6097 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6098 if (EVTBits == 8 && NumElems == 16)
6099 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6103 if (EVTBits == 16 && NumElems == 8)
6104 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6108 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6109 if (EVTBits == 32 && NumElems == 4)
6110 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6113 // If element VT is == 32 bits, turn it into a number of shuffles.
6114 SmallVector<SDValue, 8> V(NumElems);
6115 if (NumElems == 4 && NumZero > 0) {
6116 for (unsigned i = 0; i < 4; ++i) {
6117 bool isZero = !(NonZeros & (1 << i));
6119 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6121 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6124 for (unsigned i = 0; i < 2; ++i) {
6125 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6128 V[i] = V[i*2]; // Must be a zero vector.
6131 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6134 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6137 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6142 bool Reverse1 = (NonZeros & 0x3) == 2;
6143 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6147 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6148 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6150 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6153 if (Values.size() > 1 && VT.is128BitVector()) {
6154 // Check for a build vector of consecutive loads.
6155 for (unsigned i = 0; i < NumElems; ++i)
6156 V[i] = Op.getOperand(i);
6158 // Check for elements which are consecutive loads.
6159 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6162 // Check for a build vector from mostly shuffle plus few inserting.
6163 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6166 // For SSE 4.1, use insertps to put the high elements into the low element.
6167 if (Subtarget->hasSSE41()) {
6169 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6170 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6172 Result = DAG.getUNDEF(VT);
6174 for (unsigned i = 1; i < NumElems; ++i) {
6175 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6176 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6177 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6182 // Otherwise, expand into a number of unpckl*, start by extending each of
6183 // our (non-undef) elements to the full vector width with the element in the
6184 // bottom slot of the vector (which generates no code for SSE).
6185 for (unsigned i = 0; i < NumElems; ++i) {
6186 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6187 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6189 V[i] = DAG.getUNDEF(VT);
6192 // Next, we iteratively mix elements, e.g. for v4f32:
6193 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6194 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6195 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6196 unsigned EltStride = NumElems >> 1;
6197 while (EltStride != 0) {
6198 for (unsigned i = 0; i < EltStride; ++i) {
6199 // If V[i+EltStride] is undef and this is the first round of mixing,
6200 // then it is safe to just drop this shuffle: V[i] is already in the
6201 // right place, the one element (since it's the first round) being
6202 // inserted as undef can be dropped. This isn't safe for successive
6203 // rounds because they will permute elements within both vectors.
6204 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6205 EltStride == NumElems/2)
6208 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6217 // 256-bit AVX can use the vinsertf128 instruction
6218 // to create 256-bit vectors from two other 128-bit ones.
6219 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6221 MVT ResVT = Op.getSimpleValueType();
6223 assert((ResVT.is256BitVector() ||
6224 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6226 SDValue V1 = Op.getOperand(0);
6227 SDValue V2 = Op.getOperand(1);
6228 unsigned NumElems = ResVT.getVectorNumElements();
6229 if (ResVT.is256BitVector())
6230 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6232 if (Op.getNumOperands() == 4) {
6233 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6234 ResVT.getVectorNumElements()/2);
6235 SDValue V3 = Op.getOperand(2);
6236 SDValue V4 = Op.getOperand(3);
6237 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6238 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6240 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6243 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6244 const X86Subtarget *Subtarget,
6245 SelectionDAG & DAG) {
6247 MVT ResVT = Op.getSimpleValueType();
6248 unsigned NumOfOperands = Op.getNumOperands();
6250 assert(isPowerOf2_32(NumOfOperands) &&
6251 "Unexpected number of operands in CONCAT_VECTORS");
6253 if (NumOfOperands > 2) {
6254 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6255 ResVT.getVectorNumElements()/2);
6256 SmallVector<SDValue, 2> Ops;
6257 for (unsigned i = 0; i < NumOfOperands/2; i++)
6258 Ops.push_back(Op.getOperand(i));
6259 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6261 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6262 Ops.push_back(Op.getOperand(i));
6263 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6264 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6267 SDValue V1 = Op.getOperand(0);
6268 SDValue V2 = Op.getOperand(1);
6269 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6270 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6272 if (IsZeroV1 && IsZeroV2)
6273 return getZeroVector(ResVT, Subtarget, DAG, dl);
6275 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6276 SDValue Undef = DAG.getUNDEF(ResVT);
6277 unsigned NumElems = ResVT.getVectorNumElements();
6278 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6280 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6281 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6285 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6286 // Zero the upper bits of V1
6287 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6288 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6291 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6294 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6295 const X86Subtarget *Subtarget,
6296 SelectionDAG &DAG) {
6297 MVT VT = Op.getSimpleValueType();
6298 if (VT.getVectorElementType() == MVT::i1)
6299 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6301 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6302 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6303 Op.getNumOperands() == 4)));
6305 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6306 // from two other 128-bit ones.
6308 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6309 return LowerAVXCONCAT_VECTORS(Op, DAG);
6313 //===----------------------------------------------------------------------===//
6314 // Vector shuffle lowering
6316 // This is an experimental code path for lowering vector shuffles on x86. It is
6317 // designed to handle arbitrary vector shuffles and blends, gracefully
6318 // degrading performance as necessary. It works hard to recognize idiomatic
6319 // shuffles and lower them to optimal instruction patterns without leaving
6320 // a framework that allows reasonably efficient handling of all vector shuffle
6322 //===----------------------------------------------------------------------===//
6324 /// \brief Tiny helper function to identify a no-op mask.
6326 /// This is a somewhat boring predicate function. It checks whether the mask
6327 /// array input, which is assumed to be a single-input shuffle mask of the kind
6328 /// used by the X86 shuffle instructions (not a fully general
6329 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6330 /// in-place shuffle are 'no-op's.
6331 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6332 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6333 if (Mask[i] != -1 && Mask[i] != i)
6338 /// \brief Helper function to classify a mask as a single-input mask.
6340 /// This isn't a generic single-input test because in the vector shuffle
6341 /// lowering we canonicalize single inputs to be the first input operand. This
6342 /// means we can more quickly test for a single input by only checking whether
6343 /// an input from the second operand exists. We also assume that the size of
6344 /// mask corresponds to the size of the input vectors which isn't true in the
6345 /// fully general case.
6346 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6348 if (M >= (int)Mask.size())
6353 /// \brief Test whether there are elements crossing 128-bit lanes in this
6356 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6357 /// and we routinely test for these.
6358 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6359 int LaneSize = 128 / VT.getScalarSizeInBits();
6360 int Size = Mask.size();
6361 for (int i = 0; i < Size; ++i)
6362 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6367 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6369 /// This checks a shuffle mask to see if it is performing the same
6370 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6371 /// that it is also not lane-crossing. It may however involve a blend from the
6372 /// same lane of a second vector.
6374 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6375 /// non-trivial to compute in the face of undef lanes. The representation is
6376 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6377 /// entries from both V1 and V2 inputs to the wider mask.
6379 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6380 SmallVectorImpl<int> &RepeatedMask) {
6381 int LaneSize = 128 / VT.getScalarSizeInBits();
6382 RepeatedMask.resize(LaneSize, -1);
6383 int Size = Mask.size();
6384 for (int i = 0; i < Size; ++i) {
6387 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6388 // This entry crosses lanes, so there is no way to model this shuffle.
6391 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6392 if (RepeatedMask[i % LaneSize] == -1)
6393 // This is the first non-undef entry in this slot of a 128-bit lane.
6394 RepeatedMask[i % LaneSize] =
6395 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6396 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6397 // Found a mismatch with the repeated mask.
6403 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6406 /// This is a fast way to test a shuffle mask against a fixed pattern:
6408 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6410 /// It returns true if the mask is exactly as wide as the argument list, and
6411 /// each element of the mask is either -1 (signifying undef) or the value given
6412 /// in the argument.
6413 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6414 ArrayRef<int> ExpectedMask) {
6415 if (Mask.size() != ExpectedMask.size())
6418 int Size = Mask.size();
6420 // If the values are build vectors, we can look through them to find
6421 // equivalent inputs that make the shuffles equivalent.
6422 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6423 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6425 for (int i = 0; i < Size; ++i)
6426 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6427 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6428 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6429 if (!MaskBV || !ExpectedBV ||
6430 MaskBV->getOperand(Mask[i] % Size) !=
6431 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6438 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6440 /// This helper function produces an 8-bit shuffle immediate corresponding to
6441 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6442 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6445 /// NB: We rely heavily on "undef" masks preserving the input lane.
6446 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6447 SelectionDAG &DAG) {
6448 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6449 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6450 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6451 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6452 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6455 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6456 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6457 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6458 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6459 return DAG.getConstant(Imm, DL, MVT::i8);
6462 /// \brief Compute whether each element of a shuffle is zeroable.
6464 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6465 /// Either it is an undef element in the shuffle mask, the element of the input
6466 /// referenced is undef, or the element of the input referenced is known to be
6467 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6468 /// as many lanes with this technique as possible to simplify the remaining
6470 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6471 SDValue V1, SDValue V2) {
6472 SmallBitVector Zeroable(Mask.size(), false);
6474 while (V1.getOpcode() == ISD::BITCAST)
6475 V1 = V1->getOperand(0);
6476 while (V2.getOpcode() == ISD::BITCAST)
6477 V2 = V2->getOperand(0);
6479 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6480 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6482 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6484 // Handle the easy cases.
6485 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6490 // If this is an index into a build_vector node (which has the same number
6491 // of elements), dig out the input value and use it.
6492 SDValue V = M < Size ? V1 : V2;
6493 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6496 SDValue Input = V.getOperand(M % Size);
6497 // The UNDEF opcode check really should be dead code here, but not quite
6498 // worth asserting on (it isn't invalid, just unexpected).
6499 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6506 /// \brief Try to emit a bitmask instruction for a shuffle.
6508 /// This handles cases where we can model a blend exactly as a bitmask due to
6509 /// one of the inputs being zeroable.
6510 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6511 SDValue V2, ArrayRef<int> Mask,
6512 SelectionDAG &DAG) {
6513 MVT EltVT = VT.getScalarType();
6514 int NumEltBits = EltVT.getSizeInBits();
6515 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6516 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6517 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6519 if (EltVT.isFloatingPoint()) {
6520 Zero = DAG.getBitcast(EltVT, Zero);
6521 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6523 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6524 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6526 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6529 if (Mask[i] % Size != i)
6530 return SDValue(); // Not a blend.
6532 V = Mask[i] < Size ? V1 : V2;
6533 else if (V != (Mask[i] < Size ? V1 : V2))
6534 return SDValue(); // Can only let one input through the mask.
6536 VMaskOps[i] = AllOnes;
6539 return SDValue(); // No non-zeroable elements!
6541 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6542 V = DAG.getNode(VT.isFloatingPoint()
6543 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6548 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6550 /// This is used as a fallback approach when first class blend instructions are
6551 /// unavailable. Currently it is only suitable for integer vectors, but could
6552 /// be generalized for floating point vectors if desirable.
6553 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6554 SDValue V2, ArrayRef<int> Mask,
6555 SelectionDAG &DAG) {
6556 assert(VT.isInteger() && "Only supports integer vector types!");
6557 MVT EltVT = VT.getScalarType();
6558 int NumEltBits = EltVT.getSizeInBits();
6559 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6560 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6562 SmallVector<SDValue, 16> MaskOps;
6563 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6564 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6565 return SDValue(); // Shuffled input!
6566 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6569 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6570 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6571 // We have to cast V2 around.
6572 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6573 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6574 DAG.getBitcast(MaskVT, V1Mask),
6575 DAG.getBitcast(MaskVT, V2)));
6576 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6579 /// \brief Try to emit a blend instruction for a shuffle.
6581 /// This doesn't do any checks for the availability of instructions for blending
6582 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6583 /// be matched in the backend with the type given. What it does check for is
6584 /// that the shuffle mask is in fact a blend.
6585 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6586 SDValue V2, ArrayRef<int> Mask,
6587 const X86Subtarget *Subtarget,
6588 SelectionDAG &DAG) {
6589 unsigned BlendMask = 0;
6590 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6591 if (Mask[i] >= Size) {
6592 if (Mask[i] != i + Size)
6593 return SDValue(); // Shuffled V2 input!
6594 BlendMask |= 1u << i;
6597 if (Mask[i] >= 0 && Mask[i] != i)
6598 return SDValue(); // Shuffled V1 input!
6600 switch (VT.SimpleTy) {
6605 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6606 DAG.getConstant(BlendMask, DL, MVT::i8));
6610 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6614 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6615 // that instruction.
6616 if (Subtarget->hasAVX2()) {
6617 // Scale the blend by the number of 32-bit dwords per element.
6618 int Scale = VT.getScalarSizeInBits() / 32;
6620 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6621 if (Mask[i] >= Size)
6622 for (int j = 0; j < Scale; ++j)
6623 BlendMask |= 1u << (i * Scale + j);
6625 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6626 V1 = DAG.getBitcast(BlendVT, V1);
6627 V2 = DAG.getBitcast(BlendVT, V2);
6628 return DAG.getBitcast(
6629 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6630 DAG.getConstant(BlendMask, DL, MVT::i8)));
6634 // For integer shuffles we need to expand the mask and cast the inputs to
6635 // v8i16s prior to blending.
6636 int Scale = 8 / VT.getVectorNumElements();
6638 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6639 if (Mask[i] >= Size)
6640 for (int j = 0; j < Scale; ++j)
6641 BlendMask |= 1u << (i * Scale + j);
6643 V1 = DAG.getBitcast(MVT::v8i16, V1);
6644 V2 = DAG.getBitcast(MVT::v8i16, V2);
6645 return DAG.getBitcast(VT,
6646 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6647 DAG.getConstant(BlendMask, DL, MVT::i8)));
6651 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6652 SmallVector<int, 8> RepeatedMask;
6653 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6654 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6655 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6657 for (int i = 0; i < 8; ++i)
6658 if (RepeatedMask[i] >= 16)
6659 BlendMask |= 1u << i;
6660 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6661 DAG.getConstant(BlendMask, DL, MVT::i8));
6667 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6668 "256-bit byte-blends require AVX2 support!");
6670 // Scale the blend by the number of bytes per element.
6671 int Scale = VT.getScalarSizeInBits() / 8;
6673 // This form of blend is always done on bytes. Compute the byte vector
6675 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6677 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6678 // mix of LLVM's code generator and the x86 backend. We tell the code
6679 // generator that boolean values in the elements of an x86 vector register
6680 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6681 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6682 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6683 // of the element (the remaining are ignored) and 0 in that high bit would
6684 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6685 // the LLVM model for boolean values in vector elements gets the relevant
6686 // bit set, it is set backwards and over constrained relative to x86's
6688 SmallVector<SDValue, 32> VSELECTMask;
6689 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6690 for (int j = 0; j < Scale; ++j)
6691 VSELECTMask.push_back(
6692 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6693 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6696 V1 = DAG.getBitcast(BlendVT, V1);
6697 V2 = DAG.getBitcast(BlendVT, V2);
6698 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6699 DAG.getNode(ISD::BUILD_VECTOR, DL,
6700 BlendVT, VSELECTMask),
6705 llvm_unreachable("Not a supported integer vector type!");
6709 /// \brief Try to lower as a blend of elements from two inputs followed by
6710 /// a single-input permutation.
6712 /// This matches the pattern where we can blend elements from two inputs and
6713 /// then reduce the shuffle to a single-input permutation.
6714 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6717 SelectionDAG &DAG) {
6718 // We build up the blend mask while checking whether a blend is a viable way
6719 // to reduce the shuffle.
6720 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6721 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6723 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6727 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6729 if (BlendMask[Mask[i] % Size] == -1)
6730 BlendMask[Mask[i] % Size] = Mask[i];
6731 else if (BlendMask[Mask[i] % Size] != Mask[i])
6732 return SDValue(); // Can't blend in the needed input!
6734 PermuteMask[i] = Mask[i] % Size;
6737 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6738 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6741 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6742 /// blends and permutes.
6744 /// This matches the extremely common pattern for handling combined
6745 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6746 /// operations. It will try to pick the best arrangement of shuffles and
6748 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6752 SelectionDAG &DAG) {
6753 // Shuffle the input elements into the desired positions in V1 and V2 and
6754 // blend them together.
6755 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6756 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6757 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6758 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6759 if (Mask[i] >= 0 && Mask[i] < Size) {
6760 V1Mask[i] = Mask[i];
6762 } else if (Mask[i] >= Size) {
6763 V2Mask[i] = Mask[i] - Size;
6764 BlendMask[i] = i + Size;
6767 // Try to lower with the simpler initial blend strategy unless one of the
6768 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6769 // shuffle may be able to fold with a load or other benefit. However, when
6770 // we'll have to do 2x as many shuffles in order to achieve this, blending
6771 // first is a better strategy.
6772 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6773 if (SDValue BlendPerm =
6774 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6777 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6778 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6779 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6782 /// \brief Try to lower a vector shuffle as a byte rotation.
6784 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6785 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6786 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6787 /// try to generically lower a vector shuffle through such an pattern. It
6788 /// does not check for the profitability of lowering either as PALIGNR or
6789 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6790 /// This matches shuffle vectors that look like:
6792 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6794 /// Essentially it concatenates V1 and V2, shifts right by some number of
6795 /// elements, and takes the low elements as the result. Note that while this is
6796 /// specified as a *right shift* because x86 is little-endian, it is a *left
6797 /// rotate* of the vector lanes.
6798 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6801 const X86Subtarget *Subtarget,
6802 SelectionDAG &DAG) {
6803 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6805 int NumElts = Mask.size();
6806 int NumLanes = VT.getSizeInBits() / 128;
6807 int NumLaneElts = NumElts / NumLanes;
6809 // We need to detect various ways of spelling a rotation:
6810 // [11, 12, 13, 14, 15, 0, 1, 2]
6811 // [-1, 12, 13, 14, -1, -1, 1, -1]
6812 // [-1, -1, -1, -1, -1, -1, 1, 2]
6813 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6814 // [-1, 4, 5, 6, -1, -1, 9, -1]
6815 // [-1, 4, 5, 6, -1, -1, -1, -1]
6818 for (int l = 0; l < NumElts; l += NumLaneElts) {
6819 for (int i = 0; i < NumLaneElts; ++i) {
6820 if (Mask[l + i] == -1)
6822 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6824 // Get the mod-Size index and lane correct it.
6825 int LaneIdx = (Mask[l + i] % NumElts) - l;
6826 // Make sure it was in this lane.
6827 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6830 // Determine where a rotated vector would have started.
6831 int StartIdx = i - LaneIdx;
6833 // The identity rotation isn't interesting, stop.
6836 // If we found the tail of a vector the rotation must be the missing
6837 // front. If we found the head of a vector, it must be how much of the
6839 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6842 Rotation = CandidateRotation;
6843 else if (Rotation != CandidateRotation)
6844 // The rotations don't match, so we can't match this mask.
6847 // Compute which value this mask is pointing at.
6848 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6850 // Compute which of the two target values this index should be assigned
6851 // to. This reflects whether the high elements are remaining or the low
6852 // elements are remaining.
6853 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6855 // Either set up this value if we've not encountered it before, or check
6856 // that it remains consistent.
6859 else if (TargetV != MaskV)
6860 // This may be a rotation, but it pulls from the inputs in some
6861 // unsupported interleaving.
6866 // Check that we successfully analyzed the mask, and normalize the results.
6867 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6868 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6874 // The actual rotate instruction rotates bytes, so we need to scale the
6875 // rotation based on how many bytes are in the vector lane.
6876 int Scale = 16 / NumLaneElts;
6878 // SSSE3 targets can use the palignr instruction.
6879 if (Subtarget->hasSSSE3()) {
6880 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6881 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6882 Lo = DAG.getBitcast(AlignVT, Lo);
6883 Hi = DAG.getBitcast(AlignVT, Hi);
6885 return DAG.getBitcast(
6886 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6887 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6890 assert(VT.getSizeInBits() == 128 &&
6891 "Rotate-based lowering only supports 128-bit lowering!");
6892 assert(Mask.size() <= 16 &&
6893 "Can shuffle at most 16 bytes in a 128-bit vector!");
6895 // Default SSE2 implementation
6896 int LoByteShift = 16 - Rotation * Scale;
6897 int HiByteShift = Rotation * Scale;
6899 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6900 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6901 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6903 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6904 DAG.getConstant(LoByteShift, DL, MVT::i8));
6905 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6906 DAG.getConstant(HiByteShift, DL, MVT::i8));
6907 return DAG.getBitcast(VT,
6908 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6911 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6913 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6914 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6915 /// matches elements from one of the input vectors shuffled to the left or
6916 /// right with zeroable elements 'shifted in'. It handles both the strictly
6917 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6920 /// PSHL : (little-endian) left bit shift.
6921 /// [ zz, 0, zz, 2 ]
6922 /// [ -1, 4, zz, -1 ]
6923 /// PSRL : (little-endian) right bit shift.
6925 /// [ -1, -1, 7, zz]
6926 /// PSLLDQ : (little-endian) left byte shift
6927 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6928 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6929 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6930 /// PSRLDQ : (little-endian) right byte shift
6931 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6932 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6933 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6934 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6935 SDValue V2, ArrayRef<int> Mask,
6936 SelectionDAG &DAG) {
6937 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6939 int Size = Mask.size();
6940 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6942 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6943 for (int i = 0; i < Size; i += Scale)
6944 for (int j = 0; j < Shift; ++j)
6945 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6951 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6952 for (int i = 0; i != Size; i += Scale) {
6953 unsigned Pos = Left ? i + Shift : i;
6954 unsigned Low = Left ? i : i + Shift;
6955 unsigned Len = Scale - Shift;
6956 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6957 Low + (V == V1 ? 0 : Size)))
6961 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6962 bool ByteShift = ShiftEltBits > 64;
6963 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6964 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6965 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6967 // Normalize the scale for byte shifts to still produce an i64 element
6969 Scale = ByteShift ? Scale / 2 : Scale;
6971 // We need to round trip through the appropriate type for the shift.
6972 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6973 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6974 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6975 "Illegal integer vector type");
6976 V = DAG.getBitcast(ShiftVT, V);
6978 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6979 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6980 return DAG.getBitcast(VT, V);
6983 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6984 // keep doubling the size of the integer elements up to that. We can
6985 // then shift the elements of the integer vector by whole multiples of
6986 // their width within the elements of the larger integer vector. Test each
6987 // multiple to see if we can find a match with the moved element indices
6988 // and that the shifted in elements are all zeroable.
6989 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6990 for (int Shift = 1; Shift != Scale; ++Shift)
6991 for (bool Left : {true, false})
6992 if (CheckZeros(Shift, Scale, Left))
6993 for (SDValue V : {V1, V2})
6994 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7001 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7002 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7003 SDValue V2, ArrayRef<int> Mask,
7004 SelectionDAG &DAG) {
7005 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7006 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7008 int Size = Mask.size();
7009 int HalfSize = Size / 2;
7010 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7012 // Upper half must be undefined.
7013 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7016 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7017 // Remainder of lower half result is zero and upper half is all undef.
7018 auto LowerAsEXTRQ = [&]() {
7019 // Determine the extraction length from the part of the
7020 // lower half that isn't zeroable.
7022 for (; Len >= 0; --Len)
7023 if (!Zeroable[Len - 1])
7025 assert(Len > 0 && "Zeroable shuffle mask");
7027 // Attempt to match first Len sequential elements from the lower half.
7030 for (int i = 0; i != Len; ++i) {
7034 SDValue &V = (M < Size ? V1 : V2);
7037 // All mask elements must be in the lower half.
7041 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7052 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7053 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7054 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7055 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7056 DAG.getConstant(BitLen, DL, MVT::i8),
7057 DAG.getConstant(BitIdx, DL, MVT::i8));
7060 if (SDValue ExtrQ = LowerAsEXTRQ())
7063 // INSERTQ: Extract lowest Len elements from lower half of second source and
7064 // insert over first source, starting at Idx.
7065 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7066 auto LowerAsInsertQ = [&]() {
7067 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7070 // Attempt to match first source from mask before insertion point.
7071 if (isUndefInRange(Mask, 0, Idx)) {
7073 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7075 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7081 // Extend the extraction length looking to match both the insertion of
7082 // the second source and the remaining elements of the first.
7083 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7088 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7090 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7096 // Match the remaining elements of the lower half.
7097 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7099 } else if ((!Base || (Base == V1)) &&
7100 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7102 } else if ((!Base || (Base == V2)) &&
7103 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7110 // We may not have a base (first source) - this can safely be undefined.
7112 Base = DAG.getUNDEF(VT);
7114 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7115 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7116 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7117 DAG.getConstant(BitLen, DL, MVT::i8),
7118 DAG.getConstant(BitIdx, DL, MVT::i8));
7125 if (SDValue InsertQ = LowerAsInsertQ())
7131 /// \brief Lower a vector shuffle as a zero or any extension.
7133 /// Given a specific number of elements, element bit width, and extension
7134 /// stride, produce either a zero or any extension based on the available
7135 /// features of the subtarget.
7136 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7137 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7138 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7139 assert(Scale > 1 && "Need a scale to extend.");
7140 int NumElements = VT.getVectorNumElements();
7141 int EltBits = VT.getScalarSizeInBits();
7142 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7143 "Only 8, 16, and 32 bit elements can be extended.");
7144 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7146 // Found a valid zext mask! Try various lowering strategies based on the
7147 // input type and available ISA extensions.
7148 if (Subtarget->hasSSE41()) {
7149 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7150 NumElements / Scale);
7151 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7154 // For any extends we can cheat for larger element sizes and use shuffle
7155 // instructions that can fold with a load and/or copy.
7156 if (AnyExt && EltBits == 32) {
7157 int PSHUFDMask[4] = {0, -1, 1, -1};
7158 return DAG.getBitcast(
7159 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7160 DAG.getBitcast(MVT::v4i32, InputV),
7161 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7163 if (AnyExt && EltBits == 16 && Scale > 2) {
7164 int PSHUFDMask[4] = {0, -1, 0, -1};
7165 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7166 DAG.getBitcast(MVT::v4i32, InputV),
7167 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7168 int PSHUFHWMask[4] = {1, -1, -1, -1};
7169 return DAG.getBitcast(
7170 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7171 DAG.getBitcast(MVT::v8i16, InputV),
7172 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7175 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7177 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7178 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7179 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7181 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7182 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7183 DAG.getConstant(EltBits, DL, MVT::i8),
7184 DAG.getConstant(0, DL, MVT::i8)));
7185 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7186 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7189 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7190 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7191 DAG.getConstant(EltBits, DL, MVT::i8),
7192 DAG.getConstant(EltBits, DL, MVT::i8)));
7193 return DAG.getNode(ISD::BITCAST, DL, VT,
7194 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7197 // If this would require more than 2 unpack instructions to expand, use
7198 // pshufb when available. We can only use more than 2 unpack instructions
7199 // when zero extending i8 elements which also makes it easier to use pshufb.
7200 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7201 assert(NumElements == 16 && "Unexpected byte vector width!");
7202 SDValue PSHUFBMask[16];
7203 for (int i = 0; i < 16; ++i)
7205 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7206 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7207 return DAG.getBitcast(VT,
7208 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7209 DAG.getNode(ISD::BUILD_VECTOR, DL,
7210 MVT::v16i8, PSHUFBMask)));
7213 // Otherwise emit a sequence of unpacks.
7215 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7216 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7217 : getZeroVector(InputVT, Subtarget, DAG, DL);
7218 InputV = DAG.getBitcast(InputVT, InputV);
7219 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7223 } while (Scale > 1);
7224 return DAG.getBitcast(VT, InputV);
7227 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7229 /// This routine will try to do everything in its power to cleverly lower
7230 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7231 /// check for the profitability of this lowering, it tries to aggressively
7232 /// match this pattern. It will use all of the micro-architectural details it
7233 /// can to emit an efficient lowering. It handles both blends with all-zero
7234 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7235 /// masking out later).
7237 /// The reason we have dedicated lowering for zext-style shuffles is that they
7238 /// are both incredibly common and often quite performance sensitive.
7239 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7240 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7241 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7242 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7244 int Bits = VT.getSizeInBits();
7245 int NumElements = VT.getVectorNumElements();
7246 assert(VT.getScalarSizeInBits() <= 32 &&
7247 "Exceeds 32-bit integer zero extension limit");
7248 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7250 // Define a helper function to check a particular ext-scale and lower to it if
7252 auto Lower = [&](int Scale) -> SDValue {
7255 for (int i = 0; i < NumElements; ++i) {
7257 continue; // Valid anywhere but doesn't tell us anything.
7258 if (i % Scale != 0) {
7259 // Each of the extended elements need to be zeroable.
7263 // We no longer are in the anyext case.
7268 // Each of the base elements needs to be consecutive indices into the
7269 // same input vector.
7270 SDValue V = Mask[i] < NumElements ? V1 : V2;
7273 else if (InputV != V)
7274 return SDValue(); // Flip-flopping inputs.
7276 if (Mask[i] % NumElements != i / Scale)
7277 return SDValue(); // Non-consecutive strided elements.
7280 // If we fail to find an input, we have a zero-shuffle which should always
7281 // have already been handled.
7282 // FIXME: Maybe handle this here in case during blending we end up with one?
7286 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7287 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7290 // The widest scale possible for extending is to a 64-bit integer.
7291 assert(Bits % 64 == 0 &&
7292 "The number of bits in a vector must be divisible by 64 on x86!");
7293 int NumExtElements = Bits / 64;
7295 // Each iteration, try extending the elements half as much, but into twice as
7297 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7298 assert(NumElements % NumExtElements == 0 &&
7299 "The input vector size must be divisible by the extended size.");
7300 if (SDValue V = Lower(NumElements / NumExtElements))
7304 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7308 // Returns one of the source operands if the shuffle can be reduced to a
7309 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7310 auto CanZExtLowHalf = [&]() {
7311 for (int i = NumElements / 2; i != NumElements; ++i)
7314 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7316 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7321 if (SDValue V = CanZExtLowHalf()) {
7322 V = DAG.getBitcast(MVT::v2i64, V);
7323 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7324 return DAG.getBitcast(VT, V);
7327 // No viable ext lowering found.
7331 /// \brief Try to get a scalar value for a specific element of a vector.
7333 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7334 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7335 SelectionDAG &DAG) {
7336 MVT VT = V.getSimpleValueType();
7337 MVT EltVT = VT.getVectorElementType();
7338 while (V.getOpcode() == ISD::BITCAST)
7339 V = V.getOperand(0);
7340 // If the bitcasts shift the element size, we can't extract an equivalent
7342 MVT NewVT = V.getSimpleValueType();
7343 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7346 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7347 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7348 // Ensure the scalar operand is the same size as the destination.
7349 // FIXME: Add support for scalar truncation where possible.
7350 SDValue S = V.getOperand(Idx);
7351 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7352 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7358 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7360 /// This is particularly important because the set of instructions varies
7361 /// significantly based on whether the operand is a load or not.
7362 static bool isShuffleFoldableLoad(SDValue V) {
7363 while (V.getOpcode() == ISD::BITCAST)
7364 V = V.getOperand(0);
7366 return ISD::isNON_EXTLoad(V.getNode());
7369 /// \brief Try to lower insertion of a single element into a zero vector.
7371 /// This is a common pattern that we have especially efficient patterns to lower
7372 /// across all subtarget feature sets.
7373 static SDValue lowerVectorShuffleAsElementInsertion(
7374 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7375 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7376 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7378 MVT EltVT = VT.getVectorElementType();
7380 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7381 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7383 bool IsV1Zeroable = true;
7384 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7385 if (i != V2Index && !Zeroable[i]) {
7386 IsV1Zeroable = false;
7390 // Check for a single input from a SCALAR_TO_VECTOR node.
7391 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7392 // all the smarts here sunk into that routine. However, the current
7393 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7394 // vector shuffle lowering is dead.
7395 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7397 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7398 // We need to zext the scalar if it is smaller than an i32.
7399 V2S = DAG.getBitcast(EltVT, V2S);
7400 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7401 // Using zext to expand a narrow element won't work for non-zero
7406 // Zero-extend directly to i32.
7408 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7410 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7411 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7412 EltVT == MVT::i16) {
7413 // Either not inserting from the low element of the input or the input
7414 // element size is too small to use VZEXT_MOVL to clear the high bits.
7418 if (!IsV1Zeroable) {
7419 // If V1 can't be treated as a zero vector we have fewer options to lower
7420 // this. We can't support integer vectors or non-zero targets cheaply, and
7421 // the V1 elements can't be permuted in any way.
7422 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7423 if (!VT.isFloatingPoint() || V2Index != 0)
7425 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7426 V1Mask[V2Index] = -1;
7427 if (!isNoopShuffleMask(V1Mask))
7429 // This is essentially a special case blend operation, but if we have
7430 // general purpose blend operations, they are always faster. Bail and let
7431 // the rest of the lowering handle these as blends.
7432 if (Subtarget->hasSSE41())
7435 // Otherwise, use MOVSD or MOVSS.
7436 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7437 "Only two types of floating point element types to handle!");
7438 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7442 // This lowering only works for the low element with floating point vectors.
7443 if (VT.isFloatingPoint() && V2Index != 0)
7446 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7448 V2 = DAG.getBitcast(VT, V2);
7451 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7452 // the desired position. Otherwise it is more efficient to do a vector
7453 // shift left. We know that we can do a vector shift left because all
7454 // the inputs are zero.
7455 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7456 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7457 V2Shuffle[V2Index] = 0;
7458 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7460 V2 = DAG.getBitcast(MVT::v2i64, V2);
7462 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7463 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7464 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7465 DAG.getDataLayout(), VT)));
7466 V2 = DAG.getBitcast(VT, V2);
7472 /// \brief Try to lower broadcast of a single element.
7474 /// For convenience, this code also bundles all of the subtarget feature set
7475 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7476 /// a convenient way to factor it out.
7477 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7479 const X86Subtarget *Subtarget,
7480 SelectionDAG &DAG) {
7481 if (!Subtarget->hasAVX())
7483 if (VT.isInteger() && !Subtarget->hasAVX2())
7486 // Check that the mask is a broadcast.
7487 int BroadcastIdx = -1;
7489 if (M >= 0 && BroadcastIdx == -1)
7491 else if (M >= 0 && M != BroadcastIdx)
7494 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7495 "a sorted mask where the broadcast "
7498 // Go up the chain of (vector) values to find a scalar load that we can
7499 // combine with the broadcast.
7501 switch (V.getOpcode()) {
7502 case ISD::CONCAT_VECTORS: {
7503 int OperandSize = Mask.size() / V.getNumOperands();
7504 V = V.getOperand(BroadcastIdx / OperandSize);
7505 BroadcastIdx %= OperandSize;
7509 case ISD::INSERT_SUBVECTOR: {
7510 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7511 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7515 int BeginIdx = (int)ConstantIdx->getZExtValue();
7517 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7518 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7519 BroadcastIdx -= BeginIdx;
7530 // Check if this is a broadcast of a scalar. We special case lowering
7531 // for scalars so that we can more effectively fold with loads.
7532 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7533 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7534 V = V.getOperand(BroadcastIdx);
7536 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7537 // Only AVX2 has register broadcasts.
7538 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7540 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7541 // We can't broadcast from a vector register without AVX2, and we can only
7542 // broadcast from the zero-element of a vector register.
7546 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7549 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7550 // INSERTPS when the V1 elements are already in the correct locations
7551 // because otherwise we can just always use two SHUFPS instructions which
7552 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7553 // perform INSERTPS if a single V1 element is out of place and all V2
7554 // elements are zeroable.
7555 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7557 SelectionDAG &DAG) {
7558 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7559 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7560 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7561 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7563 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7566 int V1DstIndex = -1;
7567 int V2DstIndex = -1;
7568 bool V1UsedInPlace = false;
7570 for (int i = 0; i < 4; ++i) {
7571 // Synthesize a zero mask from the zeroable elements (includes undefs).
7577 // Flag if we use any V1 inputs in place.
7579 V1UsedInPlace = true;
7583 // We can only insert a single non-zeroable element.
7584 if (V1DstIndex != -1 || V2DstIndex != -1)
7588 // V1 input out of place for insertion.
7591 // V2 input for insertion.
7596 // Don't bother if we have no (non-zeroable) element for insertion.
7597 if (V1DstIndex == -1 && V2DstIndex == -1)
7600 // Determine element insertion src/dst indices. The src index is from the
7601 // start of the inserted vector, not the start of the concatenated vector.
7602 unsigned V2SrcIndex = 0;
7603 if (V1DstIndex != -1) {
7604 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7605 // and don't use the original V2 at all.
7606 V2SrcIndex = Mask[V1DstIndex];
7607 V2DstIndex = V1DstIndex;
7610 V2SrcIndex = Mask[V2DstIndex] - 4;
7613 // If no V1 inputs are used in place, then the result is created only from
7614 // the zero mask and the V2 insertion - so remove V1 dependency.
7616 V1 = DAG.getUNDEF(MVT::v4f32);
7618 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7619 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7621 // Insert the V2 element into the desired position.
7623 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7624 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7627 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7628 /// UNPCK instruction.
7630 /// This specifically targets cases where we end up with alternating between
7631 /// the two inputs, and so can permute them into something that feeds a single
7632 /// UNPCK instruction. Note that this routine only targets integer vectors
7633 /// because for floating point vectors we have a generalized SHUFPS lowering
7634 /// strategy that handles everything that doesn't *exactly* match an unpack,
7635 /// making this clever lowering unnecessary.
7636 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7637 SDValue V2, ArrayRef<int> Mask,
7638 SelectionDAG &DAG) {
7639 assert(!VT.isFloatingPoint() &&
7640 "This routine only supports integer vectors.");
7641 assert(!isSingleInputShuffleMask(Mask) &&
7642 "This routine should only be used when blending two inputs.");
7643 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7645 int Size = Mask.size();
7647 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7648 return M >= 0 && M % Size < Size / 2;
7650 int NumHiInputs = std::count_if(
7651 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7653 bool UnpackLo = NumLoInputs >= NumHiInputs;
7655 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7656 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7657 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7659 for (int i = 0; i < Size; ++i) {
7663 // Each element of the unpack contains Scale elements from this mask.
7664 int UnpackIdx = i / Scale;
7666 // We only handle the case where V1 feeds the first slots of the unpack.
7667 // We rely on canonicalization to ensure this is the case.
7668 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7671 // Setup the mask for this input. The indexing is tricky as we have to
7672 // handle the unpack stride.
7673 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7674 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7678 // If we will have to shuffle both inputs to use the unpack, check whether
7679 // we can just unpack first and shuffle the result. If so, skip this unpack.
7680 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7681 !isNoopShuffleMask(V2Mask))
7684 // Shuffle the inputs into place.
7685 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7686 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7688 // Cast the inputs to the type we will use to unpack them.
7689 V1 = DAG.getBitcast(UnpackVT, V1);
7690 V2 = DAG.getBitcast(UnpackVT, V2);
7692 // Unpack the inputs and cast the result back to the desired type.
7693 return DAG.getBitcast(
7694 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7698 // We try each unpack from the largest to the smallest to try and find one
7699 // that fits this mask.
7700 int OrigNumElements = VT.getVectorNumElements();
7701 int OrigScalarSize = VT.getScalarSizeInBits();
7702 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7703 int Scale = ScalarSize / OrigScalarSize;
7704 int NumElements = OrigNumElements / Scale;
7705 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7706 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7710 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7712 if (NumLoInputs == 0 || NumHiInputs == 0) {
7713 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7714 "We have to have *some* inputs!");
7715 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7717 // FIXME: We could consider the total complexity of the permute of each
7718 // possible unpacking. Or at the least we should consider how many
7719 // half-crossings are created.
7720 // FIXME: We could consider commuting the unpacks.
7722 SmallVector<int, 32> PermMask;
7723 PermMask.assign(Size, -1);
7724 for (int i = 0; i < Size; ++i) {
7728 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7731 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7733 return DAG.getVectorShuffle(
7734 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7736 DAG.getUNDEF(VT), PermMask);
7742 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7744 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7745 /// support for floating point shuffles but not integer shuffles. These
7746 /// instructions will incur a domain crossing penalty on some chips though so
7747 /// it is better to avoid lowering through this for integer vectors where
7749 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7750 const X86Subtarget *Subtarget,
7751 SelectionDAG &DAG) {
7753 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7754 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7755 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7756 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7757 ArrayRef<int> Mask = SVOp->getMask();
7758 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7760 if (isSingleInputShuffleMask(Mask)) {
7761 // Use low duplicate instructions for masks that match their pattern.
7762 if (Subtarget->hasSSE3())
7763 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7764 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7766 // Straight shuffle of a single input vector. Simulate this by using the
7767 // single input as both of the "inputs" to this instruction..
7768 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7770 if (Subtarget->hasAVX()) {
7771 // If we have AVX, we can use VPERMILPS which will allow folding a load
7772 // into the shuffle.
7773 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7774 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7777 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7778 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7780 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7781 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7783 // If we have a single input, insert that into V1 if we can do so cheaply.
7784 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7785 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7786 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7788 // Try inverting the insertion since for v2 masks it is easy to do and we
7789 // can't reliably sort the mask one way or the other.
7790 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7791 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7792 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7793 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7797 // Try to use one of the special instruction patterns to handle two common
7798 // blend patterns if a zero-blend above didn't work.
7799 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7800 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7801 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7802 // We can either use a special instruction to load over the low double or
7803 // to move just the low double.
7805 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7807 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7809 if (Subtarget->hasSSE41())
7810 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7814 // Use dedicated unpack instructions for masks that match their pattern.
7815 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7816 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7817 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7818 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7820 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7821 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7822 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7825 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7827 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7828 /// the integer unit to minimize domain crossing penalties. However, for blends
7829 /// it falls back to the floating point shuffle operation with appropriate bit
7831 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7832 const X86Subtarget *Subtarget,
7833 SelectionDAG &DAG) {
7835 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7836 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7837 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7838 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7839 ArrayRef<int> Mask = SVOp->getMask();
7840 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7842 if (isSingleInputShuffleMask(Mask)) {
7843 // Check for being able to broadcast a single element.
7844 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7845 Mask, Subtarget, DAG))
7848 // Straight shuffle of a single input vector. For everything from SSE2
7849 // onward this has a single fast instruction with no scary immediates.
7850 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7851 V1 = DAG.getBitcast(MVT::v4i32, V1);
7852 int WidenedMask[4] = {
7853 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7854 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7855 return DAG.getBitcast(
7857 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7858 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7860 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7861 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7862 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7863 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7865 // If we have a blend of two PACKUS operations an the blend aligns with the
7866 // low and half halves, we can just merge the PACKUS operations. This is
7867 // particularly important as it lets us merge shuffles that this routine itself
7869 auto GetPackNode = [](SDValue V) {
7870 while (V.getOpcode() == ISD::BITCAST)
7871 V = V.getOperand(0);
7873 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7875 if (SDValue V1Pack = GetPackNode(V1))
7876 if (SDValue V2Pack = GetPackNode(V2))
7877 return DAG.getBitcast(MVT::v2i64,
7878 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7879 Mask[0] == 0 ? V1Pack.getOperand(0)
7880 : V1Pack.getOperand(1),
7881 Mask[1] == 2 ? V2Pack.getOperand(0)
7882 : V2Pack.getOperand(1)));
7884 // Try to use shift instructions.
7886 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7889 // When loading a scalar and then shuffling it into a vector we can often do
7890 // the insertion cheaply.
7891 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7892 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7894 // Try inverting the insertion since for v2 masks it is easy to do and we
7895 // can't reliably sort the mask one way or the other.
7896 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7897 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7898 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7901 // We have different paths for blend lowering, but they all must use the
7902 // *exact* same predicate.
7903 bool IsBlendSupported = Subtarget->hasSSE41();
7904 if (IsBlendSupported)
7905 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7909 // Use dedicated unpack instructions for masks that match their pattern.
7910 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7911 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7912 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7913 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7915 // Try to use byte rotation instructions.
7916 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7917 if (Subtarget->hasSSSE3())
7918 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7919 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7922 // If we have direct support for blends, we should lower by decomposing into
7923 // a permute. That will be faster than the domain cross.
7924 if (IsBlendSupported)
7925 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7928 // We implement this with SHUFPD which is pretty lame because it will likely
7929 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7930 // However, all the alternatives are still more cycles and newer chips don't
7931 // have this problem. It would be really nice if x86 had better shuffles here.
7932 V1 = DAG.getBitcast(MVT::v2f64, V1);
7933 V2 = DAG.getBitcast(MVT::v2f64, V2);
7934 return DAG.getBitcast(MVT::v2i64,
7935 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7938 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7940 /// This is used to disable more specialized lowerings when the shufps lowering
7941 /// will happen to be efficient.
7942 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7943 // This routine only handles 128-bit shufps.
7944 assert(Mask.size() == 4 && "Unsupported mask size!");
7946 // To lower with a single SHUFPS we need to have the low half and high half
7947 // each requiring a single input.
7948 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7950 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7956 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7958 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7959 /// It makes no assumptions about whether this is the *best* lowering, it simply
7961 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7962 ArrayRef<int> Mask, SDValue V1,
7963 SDValue V2, SelectionDAG &DAG) {
7964 SDValue LowV = V1, HighV = V2;
7965 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7968 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7970 if (NumV2Elements == 1) {
7972 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7975 // Compute the index adjacent to V2Index and in the same half by toggling
7977 int V2AdjIndex = V2Index ^ 1;
7979 if (Mask[V2AdjIndex] == -1) {
7980 // Handles all the cases where we have a single V2 element and an undef.
7981 // This will only ever happen in the high lanes because we commute the
7982 // vector otherwise.
7984 std::swap(LowV, HighV);
7985 NewMask[V2Index] -= 4;
7987 // Handle the case where the V2 element ends up adjacent to a V1 element.
7988 // To make this work, blend them together as the first step.
7989 int V1Index = V2AdjIndex;
7990 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7991 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7992 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7994 // Now proceed to reconstruct the final blend as we have the necessary
7995 // high or low half formed.
8002 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8003 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8005 } else if (NumV2Elements == 2) {
8006 if (Mask[0] < 4 && Mask[1] < 4) {
8007 // Handle the easy case where we have V1 in the low lanes and V2 in the
8011 } else if (Mask[2] < 4 && Mask[3] < 4) {
8012 // We also handle the reversed case because this utility may get called
8013 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8014 // arrange things in the right direction.
8020 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8021 // trying to place elements directly, just blend them and set up the final
8022 // shuffle to place them.
8024 // The first two blend mask elements are for V1, the second two are for
8026 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8027 Mask[2] < 4 ? Mask[2] : Mask[3],
8028 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8029 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8030 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8031 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8033 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8036 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8037 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8038 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8039 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8042 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8043 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8046 /// \brief Lower 4-lane 32-bit floating point shuffles.
8048 /// Uses instructions exclusively from the floating point unit to minimize
8049 /// domain crossing penalties, as these are sufficient to implement all v4f32
8051 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8052 const X86Subtarget *Subtarget,
8053 SelectionDAG &DAG) {
8055 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8056 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8057 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8058 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8059 ArrayRef<int> Mask = SVOp->getMask();
8060 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8063 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8065 if (NumV2Elements == 0) {
8066 // Check for being able to broadcast a single element.
8067 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8068 Mask, Subtarget, DAG))
8071 // Use even/odd duplicate instructions for masks that match their pattern.
8072 if (Subtarget->hasSSE3()) {
8073 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8074 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8075 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8076 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8079 if (Subtarget->hasAVX()) {
8080 // If we have AVX, we can use VPERMILPS which will allow folding a load
8081 // into the shuffle.
8082 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8083 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8086 // Otherwise, use a straight shuffle of a single input vector. We pass the
8087 // input vector to both operands to simulate this with a SHUFPS.
8088 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8089 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8092 // There are special ways we can lower some single-element blends. However, we
8093 // have custom ways we can lower more complex single-element blends below that
8094 // we defer to if both this and BLENDPS fail to match, so restrict this to
8095 // when the V2 input is targeting element 0 of the mask -- that is the fast
8097 if (NumV2Elements == 1 && Mask[0] >= 4)
8098 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8099 Mask, Subtarget, DAG))
8102 if (Subtarget->hasSSE41()) {
8103 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8107 // Use INSERTPS if we can complete the shuffle efficiently.
8108 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8111 if (!isSingleSHUFPSMask(Mask))
8112 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8113 DL, MVT::v4f32, V1, V2, Mask, DAG))
8117 // Use dedicated unpack instructions for masks that match their pattern.
8118 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8119 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8120 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8121 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8122 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8123 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8124 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8125 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8127 // Otherwise fall back to a SHUFPS lowering strategy.
8128 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8131 /// \brief Lower 4-lane i32 vector shuffles.
8133 /// We try to handle these with integer-domain shuffles where we can, but for
8134 /// blends we use the floating point domain blend instructions.
8135 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8136 const X86Subtarget *Subtarget,
8137 SelectionDAG &DAG) {
8139 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8140 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8141 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8142 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8143 ArrayRef<int> Mask = SVOp->getMask();
8144 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8146 // Whenever we can lower this as a zext, that instruction is strictly faster
8147 // than any alternative. It also allows us to fold memory operands into the
8148 // shuffle in many cases.
8149 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8150 Mask, Subtarget, DAG))
8154 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8156 if (NumV2Elements == 0) {
8157 // Check for being able to broadcast a single element.
8158 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8159 Mask, Subtarget, DAG))
8162 // Straight shuffle of a single input vector. For everything from SSE2
8163 // onward this has a single fast instruction with no scary immediates.
8164 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8165 // but we aren't actually going to use the UNPCK instruction because doing
8166 // so prevents folding a load into this instruction or making a copy.
8167 const int UnpackLoMask[] = {0, 0, 1, 1};
8168 const int UnpackHiMask[] = {2, 2, 3, 3};
8169 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8170 Mask = UnpackLoMask;
8171 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8172 Mask = UnpackHiMask;
8174 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8175 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8178 // Try to use shift instructions.
8180 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8183 // There are special ways we can lower some single-element blends.
8184 if (NumV2Elements == 1)
8185 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8186 Mask, Subtarget, DAG))
8189 // We have different paths for blend lowering, but they all must use the
8190 // *exact* same predicate.
8191 bool IsBlendSupported = Subtarget->hasSSE41();
8192 if (IsBlendSupported)
8193 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8197 if (SDValue Masked =
8198 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8201 // Use dedicated unpack instructions for masks that match their pattern.
8202 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8203 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8204 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8205 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8206 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8207 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8208 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8209 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8211 // Try to use byte rotation instructions.
8212 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8213 if (Subtarget->hasSSSE3())
8214 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8215 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8218 // If we have direct support for blends, we should lower by decomposing into
8219 // a permute. That will be faster than the domain cross.
8220 if (IsBlendSupported)
8221 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8224 // Try to lower by permuting the inputs into an unpack instruction.
8225 if (SDValue Unpack =
8226 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8229 // We implement this with SHUFPS because it can blend from two vectors.
8230 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8231 // up the inputs, bypassing domain shift penalties that we would encur if we
8232 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8234 return DAG.getBitcast(
8236 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8237 DAG.getBitcast(MVT::v4f32, V2), Mask));
8240 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8241 /// shuffle lowering, and the most complex part.
8243 /// The lowering strategy is to try to form pairs of input lanes which are
8244 /// targeted at the same half of the final vector, and then use a dword shuffle
8245 /// to place them onto the right half, and finally unpack the paired lanes into
8246 /// their final position.
8248 /// The exact breakdown of how to form these dword pairs and align them on the
8249 /// correct sides is really tricky. See the comments within the function for
8250 /// more of the details.
8252 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8253 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8254 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8255 /// vector, form the analogous 128-bit 8-element Mask.
8256 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8257 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8258 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8259 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8260 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8262 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8263 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8264 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8266 SmallVector<int, 4> LoInputs;
8267 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8268 [](int M) { return M >= 0; });
8269 std::sort(LoInputs.begin(), LoInputs.end());
8270 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8271 SmallVector<int, 4> HiInputs;
8272 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8273 [](int M) { return M >= 0; });
8274 std::sort(HiInputs.begin(), HiInputs.end());
8275 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8277 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8278 int NumHToL = LoInputs.size() - NumLToL;
8280 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8281 int NumHToH = HiInputs.size() - NumLToH;
8282 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8283 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8284 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8285 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8287 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8288 // such inputs we can swap two of the dwords across the half mark and end up
8289 // with <=2 inputs to each half in each half. Once there, we can fall through
8290 // to the generic code below. For example:
8292 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8293 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8295 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8296 // and an existing 2-into-2 on the other half. In this case we may have to
8297 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8298 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8299 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8300 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8301 // half than the one we target for fixing) will be fixed when we re-enter this
8302 // path. We will also combine away any sequence of PSHUFD instructions that
8303 // result into a single instruction. Here is an example of the tricky case:
8305 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8306 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8308 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8310 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8311 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8313 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8314 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8316 // The result is fine to be handled by the generic logic.
8317 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8318 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8319 int AOffset, int BOffset) {
8320 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8321 "Must call this with A having 3 or 1 inputs from the A half.");
8322 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8323 "Must call this with B having 1 or 3 inputs from the B half.");
8324 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8325 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8327 // Compute the index of dword with only one word among the three inputs in
8328 // a half by taking the sum of the half with three inputs and subtracting
8329 // the sum of the actual three inputs. The difference is the remaining
8332 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8333 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8334 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8335 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8336 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8337 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8338 int TripleNonInputIdx =
8339 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8340 TripleDWord = TripleNonInputIdx / 2;
8342 // We use xor with one to compute the adjacent DWord to whichever one the
8344 OneInputDWord = (OneInput / 2) ^ 1;
8346 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8347 // and BToA inputs. If there is also such a problem with the BToB and AToB
8348 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8349 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8350 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8351 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8352 // Compute how many inputs will be flipped by swapping these DWords. We
8354 // to balance this to ensure we don't form a 3-1 shuffle in the other
8356 int NumFlippedAToBInputs =
8357 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8358 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8359 int NumFlippedBToBInputs =
8360 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8361 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8362 if ((NumFlippedAToBInputs == 1 &&
8363 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8364 (NumFlippedBToBInputs == 1 &&
8365 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8366 // We choose whether to fix the A half or B half based on whether that
8367 // half has zero flipped inputs. At zero, we may not be able to fix it
8368 // with that half. We also bias towards fixing the B half because that
8369 // will more commonly be the high half, and we have to bias one way.
8370 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8371 ArrayRef<int> Inputs) {
8372 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8373 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8374 PinnedIdx ^ 1) != Inputs.end();
8375 // Determine whether the free index is in the flipped dword or the
8376 // unflipped dword based on where the pinned index is. We use this bit
8377 // in an xor to conditionally select the adjacent dword.
8378 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8379 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8380 FixFreeIdx) != Inputs.end();
8381 if (IsFixIdxInput == IsFixFreeIdxInput)
8383 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8384 FixFreeIdx) != Inputs.end();
8385 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8386 "We need to be changing the number of flipped inputs!");
8387 int PSHUFHalfMask[] = {0, 1, 2, 3};
8388 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8389 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8391 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8394 if (M != -1 && M == FixIdx)
8396 else if (M != -1 && M == FixFreeIdx)
8399 if (NumFlippedBToBInputs != 0) {
8401 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8402 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8404 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8406 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8407 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8412 int PSHUFDMask[] = {0, 1, 2, 3};
8413 PSHUFDMask[ADWord] = BDWord;
8414 PSHUFDMask[BDWord] = ADWord;
8417 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8418 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8420 // Adjust the mask to match the new locations of A and B.
8422 if (M != -1 && M/2 == ADWord)
8423 M = 2 * BDWord + M % 2;
8424 else if (M != -1 && M/2 == BDWord)
8425 M = 2 * ADWord + M % 2;
8427 // Recurse back into this routine to re-compute state now that this isn't
8428 // a 3 and 1 problem.
8429 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8432 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8433 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8434 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8435 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8437 // At this point there are at most two inputs to the low and high halves from
8438 // each half. That means the inputs can always be grouped into dwords and
8439 // those dwords can then be moved to the correct half with a dword shuffle.
8440 // We use at most one low and one high word shuffle to collect these paired
8441 // inputs into dwords, and finally a dword shuffle to place them.
8442 int PSHUFLMask[4] = {-1, -1, -1, -1};
8443 int PSHUFHMask[4] = {-1, -1, -1, -1};
8444 int PSHUFDMask[4] = {-1, -1, -1, -1};
8446 // First fix the masks for all the inputs that are staying in their
8447 // original halves. This will then dictate the targets of the cross-half
8449 auto fixInPlaceInputs =
8450 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8451 MutableArrayRef<int> SourceHalfMask,
8452 MutableArrayRef<int> HalfMask, int HalfOffset) {
8453 if (InPlaceInputs.empty())
8455 if (InPlaceInputs.size() == 1) {
8456 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8457 InPlaceInputs[0] - HalfOffset;
8458 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8461 if (IncomingInputs.empty()) {
8462 // Just fix all of the in place inputs.
8463 for (int Input : InPlaceInputs) {
8464 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8465 PSHUFDMask[Input / 2] = Input / 2;
8470 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8471 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8472 InPlaceInputs[0] - HalfOffset;
8473 // Put the second input next to the first so that they are packed into
8474 // a dword. We find the adjacent index by toggling the low bit.
8475 int AdjIndex = InPlaceInputs[0] ^ 1;
8476 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8477 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8478 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8480 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8481 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8483 // Now gather the cross-half inputs and place them into a free dword of
8484 // their target half.
8485 // FIXME: This operation could almost certainly be simplified dramatically to
8486 // look more like the 3-1 fixing operation.
8487 auto moveInputsToRightHalf = [&PSHUFDMask](
8488 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8489 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8490 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8492 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8493 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8495 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8497 int LowWord = Word & ~1;
8498 int HighWord = Word | 1;
8499 return isWordClobbered(SourceHalfMask, LowWord) ||
8500 isWordClobbered(SourceHalfMask, HighWord);
8503 if (IncomingInputs.empty())
8506 if (ExistingInputs.empty()) {
8507 // Map any dwords with inputs from them into the right half.
8508 for (int Input : IncomingInputs) {
8509 // If the source half mask maps over the inputs, turn those into
8510 // swaps and use the swapped lane.
8511 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8512 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8513 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8514 Input - SourceOffset;
8515 // We have to swap the uses in our half mask in one sweep.
8516 for (int &M : HalfMask)
8517 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8519 else if (M == Input)
8520 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8522 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8523 Input - SourceOffset &&
8524 "Previous placement doesn't match!");
8526 // Note that this correctly re-maps both when we do a swap and when
8527 // we observe the other side of the swap above. We rely on that to
8528 // avoid swapping the members of the input list directly.
8529 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8532 // Map the input's dword into the correct half.
8533 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8534 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8536 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8538 "Previous placement doesn't match!");
8541 // And just directly shift any other-half mask elements to be same-half
8542 // as we will have mirrored the dword containing the element into the
8543 // same position within that half.
8544 for (int &M : HalfMask)
8545 if (M >= SourceOffset && M < SourceOffset + 4) {
8546 M = M - SourceOffset + DestOffset;
8547 assert(M >= 0 && "This should never wrap below zero!");
8552 // Ensure we have the input in a viable dword of its current half. This
8553 // is particularly tricky because the original position may be clobbered
8554 // by inputs being moved and *staying* in that half.
8555 if (IncomingInputs.size() == 1) {
8556 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8557 int InputFixed = std::find(std::begin(SourceHalfMask),
8558 std::end(SourceHalfMask), -1) -
8559 std::begin(SourceHalfMask) + SourceOffset;
8560 SourceHalfMask[InputFixed - SourceOffset] =
8561 IncomingInputs[0] - SourceOffset;
8562 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8564 IncomingInputs[0] = InputFixed;
8566 } else if (IncomingInputs.size() == 2) {
8567 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8568 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8569 // We have two non-adjacent or clobbered inputs we need to extract from
8570 // the source half. To do this, we need to map them into some adjacent
8571 // dword slot in the source mask.
8572 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8573 IncomingInputs[1] - SourceOffset};
8575 // If there is a free slot in the source half mask adjacent to one of
8576 // the inputs, place the other input in it. We use (Index XOR 1) to
8577 // compute an adjacent index.
8578 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8579 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8580 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8581 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8582 InputsFixed[1] = InputsFixed[0] ^ 1;
8583 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8584 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8585 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8586 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8587 InputsFixed[0] = InputsFixed[1] ^ 1;
8588 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8589 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8590 // The two inputs are in the same DWord but it is clobbered and the
8591 // adjacent DWord isn't used at all. Move both inputs to the free
8593 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8594 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8595 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8596 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8598 // The only way we hit this point is if there is no clobbering
8599 // (because there are no off-half inputs to this half) and there is no
8600 // free slot adjacent to one of the inputs. In this case, we have to
8601 // swap an input with a non-input.
8602 for (int i = 0; i < 4; ++i)
8603 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8604 "We can't handle any clobbers here!");
8605 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8606 "Cannot have adjacent inputs here!");
8608 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8609 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8611 // We also have to update the final source mask in this case because
8612 // it may need to undo the above swap.
8613 for (int &M : FinalSourceHalfMask)
8614 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8615 M = InputsFixed[1] + SourceOffset;
8616 else if (M == InputsFixed[1] + SourceOffset)
8617 M = (InputsFixed[0] ^ 1) + SourceOffset;
8619 InputsFixed[1] = InputsFixed[0] ^ 1;
8622 // Point everything at the fixed inputs.
8623 for (int &M : HalfMask)
8624 if (M == IncomingInputs[0])
8625 M = InputsFixed[0] + SourceOffset;
8626 else if (M == IncomingInputs[1])
8627 M = InputsFixed[1] + SourceOffset;
8629 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8630 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8633 llvm_unreachable("Unhandled input size!");
8636 // Now hoist the DWord down to the right half.
8637 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8638 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8639 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8640 for (int &M : HalfMask)
8641 for (int Input : IncomingInputs)
8643 M = FreeDWord * 2 + Input % 2;
8645 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8646 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8647 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8648 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8650 // Now enact all the shuffles we've computed to move the inputs into their
8652 if (!isNoopShuffleMask(PSHUFLMask))
8653 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8654 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8655 if (!isNoopShuffleMask(PSHUFHMask))
8656 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8657 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8658 if (!isNoopShuffleMask(PSHUFDMask))
8661 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8662 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8664 // At this point, each half should contain all its inputs, and we can then
8665 // just shuffle them into their final position.
8666 assert(std::count_if(LoMask.begin(), LoMask.end(),
8667 [](int M) { return M >= 4; }) == 0 &&
8668 "Failed to lift all the high half inputs to the low mask!");
8669 assert(std::count_if(HiMask.begin(), HiMask.end(),
8670 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8671 "Failed to lift all the low half inputs to the high mask!");
8673 // Do a half shuffle for the low mask.
8674 if (!isNoopShuffleMask(LoMask))
8675 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8676 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8678 // Do a half shuffle with the high mask after shifting its values down.
8679 for (int &M : HiMask)
8682 if (!isNoopShuffleMask(HiMask))
8683 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8684 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8689 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8690 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8691 SDValue V2, ArrayRef<int> Mask,
8692 SelectionDAG &DAG, bool &V1InUse,
8694 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8700 int Size = Mask.size();
8701 int Scale = 16 / Size;
8702 for (int i = 0; i < 16; ++i) {
8703 if (Mask[i / Scale] == -1) {
8704 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8706 const int ZeroMask = 0x80;
8707 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8709 int V2Idx = Mask[i / Scale] < Size
8711 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8712 if (Zeroable[i / Scale])
8713 V1Idx = V2Idx = ZeroMask;
8714 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8715 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8716 V1InUse |= (ZeroMask != V1Idx);
8717 V2InUse |= (ZeroMask != V2Idx);
8722 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8723 DAG.getBitcast(MVT::v16i8, V1),
8724 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8726 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8727 DAG.getBitcast(MVT::v16i8, V2),
8728 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8730 // If we need shuffled inputs from both, blend the two.
8732 if (V1InUse && V2InUse)
8733 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8735 V = V1InUse ? V1 : V2;
8737 // Cast the result back to the correct type.
8738 return DAG.getBitcast(VT, V);
8741 /// \brief Generic lowering of 8-lane i16 shuffles.
8743 /// This handles both single-input shuffles and combined shuffle/blends with
8744 /// two inputs. The single input shuffles are immediately delegated to
8745 /// a dedicated lowering routine.
8747 /// The blends are lowered in one of three fundamental ways. If there are few
8748 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8749 /// of the input is significantly cheaper when lowered as an interleaving of
8750 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8751 /// halves of the inputs separately (making them have relatively few inputs)
8752 /// and then concatenate them.
8753 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8754 const X86Subtarget *Subtarget,
8755 SelectionDAG &DAG) {
8757 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8758 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8759 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8760 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8761 ArrayRef<int> OrigMask = SVOp->getMask();
8762 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8763 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8764 MutableArrayRef<int> Mask(MaskStorage);
8766 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8768 // Whenever we can lower this as a zext, that instruction is strictly faster
8769 // than any alternative.
8770 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8771 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8774 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8776 auto isV2 = [](int M) { return M >= 8; };
8778 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8780 if (NumV2Inputs == 0) {
8781 // Check for being able to broadcast a single element.
8782 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8783 Mask, Subtarget, DAG))
8786 // Try to use shift instructions.
8788 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8791 // Use dedicated unpack instructions for masks that match their pattern.
8792 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8793 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8794 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8795 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8797 // Try to use byte rotation instructions.
8798 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8799 Mask, Subtarget, DAG))
8802 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8806 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8807 "All single-input shuffles should be canonicalized to be V1-input "
8810 // Try to use shift instructions.
8812 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8815 // See if we can use SSE4A Extraction / Insertion.
8816 if (Subtarget->hasSSE4A())
8817 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8820 // There are special ways we can lower some single-element blends.
8821 if (NumV2Inputs == 1)
8822 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8823 Mask, Subtarget, DAG))
8826 // We have different paths for blend lowering, but they all must use the
8827 // *exact* same predicate.
8828 bool IsBlendSupported = Subtarget->hasSSE41();
8829 if (IsBlendSupported)
8830 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8834 if (SDValue Masked =
8835 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8838 // Use dedicated unpack instructions for masks that match their pattern.
8839 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8840 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8841 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8842 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8844 // Try to use byte rotation instructions.
8845 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8846 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8849 if (SDValue BitBlend =
8850 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8853 if (SDValue Unpack =
8854 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8857 // If we can't directly blend but can use PSHUFB, that will be better as it
8858 // can both shuffle and set up the inefficient blend.
8859 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8860 bool V1InUse, V2InUse;
8861 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8865 // We can always bit-blend if we have to so the fallback strategy is to
8866 // decompose into single-input permutes and blends.
8867 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8871 /// \brief Check whether a compaction lowering can be done by dropping even
8872 /// elements and compute how many times even elements must be dropped.
8874 /// This handles shuffles which take every Nth element where N is a power of
8875 /// two. Example shuffle masks:
8877 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8878 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8879 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8880 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8881 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8882 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8884 /// Any of these lanes can of course be undef.
8886 /// This routine only supports N <= 3.
8887 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8890 /// \returns N above, or the number of times even elements must be dropped if
8891 /// there is such a number. Otherwise returns zero.
8892 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8893 // Figure out whether we're looping over two inputs or just one.
8894 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8896 // The modulus for the shuffle vector entries is based on whether this is
8897 // a single input or not.
8898 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8899 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8900 "We should only be called with masks with a power-of-2 size!");
8902 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8904 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8905 // and 2^3 simultaneously. This is because we may have ambiguity with
8906 // partially undef inputs.
8907 bool ViableForN[3] = {true, true, true};
8909 for (int i = 0, e = Mask.size(); i < e; ++i) {
8910 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8915 bool IsAnyViable = false;
8916 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8917 if (ViableForN[j]) {
8920 // The shuffle mask must be equal to (i * 2^N) % M.
8921 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8924 ViableForN[j] = false;
8926 // Early exit if we exhaust the possible powers of two.
8931 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8935 // Return 0 as there is no viable power of two.
8939 /// \brief Generic lowering of v16i8 shuffles.
8941 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8942 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8943 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8944 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8946 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8947 const X86Subtarget *Subtarget,
8948 SelectionDAG &DAG) {
8950 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8951 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8952 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8953 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8954 ArrayRef<int> Mask = SVOp->getMask();
8955 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8957 // Try to use shift instructions.
8959 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8962 // Try to use byte rotation instructions.
8963 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8964 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8967 // Try to use a zext lowering.
8968 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8969 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8972 // See if we can use SSE4A Extraction / Insertion.
8973 if (Subtarget->hasSSE4A())
8974 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8978 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8980 // For single-input shuffles, there are some nicer lowering tricks we can use.
8981 if (NumV2Elements == 0) {
8982 // Check for being able to broadcast a single element.
8983 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8984 Mask, Subtarget, DAG))
8987 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8988 // Notably, this handles splat and partial-splat shuffles more efficiently.
8989 // However, it only makes sense if the pre-duplication shuffle simplifies
8990 // things significantly. Currently, this means we need to be able to
8991 // express the pre-duplication shuffle as an i16 shuffle.
8993 // FIXME: We should check for other patterns which can be widened into an
8994 // i16 shuffle as well.
8995 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8996 for (int i = 0; i < 16; i += 2)
8997 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9002 auto tryToWidenViaDuplication = [&]() -> SDValue {
9003 if (!canWidenViaDuplication(Mask))
9005 SmallVector<int, 4> LoInputs;
9006 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9007 [](int M) { return M >= 0 && M < 8; });
9008 std::sort(LoInputs.begin(), LoInputs.end());
9009 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9011 SmallVector<int, 4> HiInputs;
9012 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9013 [](int M) { return M >= 8; });
9014 std::sort(HiInputs.begin(), HiInputs.end());
9015 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9018 bool TargetLo = LoInputs.size() >= HiInputs.size();
9019 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9020 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9022 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9023 SmallDenseMap<int, int, 8> LaneMap;
9024 for (int I : InPlaceInputs) {
9025 PreDupI16Shuffle[I/2] = I/2;
9028 int j = TargetLo ? 0 : 4, je = j + 4;
9029 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9030 // Check if j is already a shuffle of this input. This happens when
9031 // there are two adjacent bytes after we move the low one.
9032 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9033 // If we haven't yet mapped the input, search for a slot into which
9035 while (j < je && PreDupI16Shuffle[j] != -1)
9039 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9042 // Map this input with the i16 shuffle.
9043 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9046 // Update the lane map based on the mapping we ended up with.
9047 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9049 V1 = DAG.getBitcast(
9051 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9052 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9054 // Unpack the bytes to form the i16s that will be shuffled into place.
9055 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9056 MVT::v16i8, V1, V1);
9058 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9059 for (int i = 0; i < 16; ++i)
9060 if (Mask[i] != -1) {
9061 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9062 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9063 if (PostDupI16Shuffle[i / 2] == -1)
9064 PostDupI16Shuffle[i / 2] = MappedMask;
9066 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9067 "Conflicting entrties in the original shuffle!");
9069 return DAG.getBitcast(
9071 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9072 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9074 if (SDValue V = tryToWidenViaDuplication())
9078 // Use dedicated unpack instructions for masks that match their pattern.
9079 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9080 0, 16, 1, 17, 2, 18, 3, 19,
9082 4, 20, 5, 21, 6, 22, 7, 23}))
9083 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9084 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9085 8, 24, 9, 25, 10, 26, 11, 27,
9087 12, 28, 13, 29, 14, 30, 15, 31}))
9088 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9090 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9091 // with PSHUFB. It is important to do this before we attempt to generate any
9092 // blends but after all of the single-input lowerings. If the single input
9093 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9094 // want to preserve that and we can DAG combine any longer sequences into
9095 // a PSHUFB in the end. But once we start blending from multiple inputs,
9096 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9097 // and there are *very* few patterns that would actually be faster than the
9098 // PSHUFB approach because of its ability to zero lanes.
9100 // FIXME: The only exceptions to the above are blends which are exact
9101 // interleavings with direct instructions supporting them. We currently don't
9102 // handle those well here.
9103 if (Subtarget->hasSSSE3()) {
9104 bool V1InUse = false;
9105 bool V2InUse = false;
9107 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9108 DAG, V1InUse, V2InUse);
9110 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9111 // do so. This avoids using them to handle blends-with-zero which is
9112 // important as a single pshufb is significantly faster for that.
9113 if (V1InUse && V2InUse) {
9114 if (Subtarget->hasSSE41())
9115 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9116 Mask, Subtarget, DAG))
9119 // We can use an unpack to do the blending rather than an or in some
9120 // cases. Even though the or may be (very minorly) more efficient, we
9121 // preference this lowering because there are common cases where part of
9122 // the complexity of the shuffles goes away when we do the final blend as
9124 // FIXME: It might be worth trying to detect if the unpack-feeding
9125 // shuffles will both be pshufb, in which case we shouldn't bother with
9127 if (SDValue Unpack =
9128 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9135 // There are special ways we can lower some single-element blends.
9136 if (NumV2Elements == 1)
9137 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9138 Mask, Subtarget, DAG))
9141 if (SDValue BitBlend =
9142 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9145 // Check whether a compaction lowering can be done. This handles shuffles
9146 // which take every Nth element for some even N. See the helper function for
9149 // We special case these as they can be particularly efficiently handled with
9150 // the PACKUSB instruction on x86 and they show up in common patterns of
9151 // rearranging bytes to truncate wide elements.
9152 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9153 // NumEvenDrops is the power of two stride of the elements. Another way of
9154 // thinking about it is that we need to drop the even elements this many
9155 // times to get the original input.
9156 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9158 // First we need to zero all the dropped bytes.
9159 assert(NumEvenDrops <= 3 &&
9160 "No support for dropping even elements more than 3 times.");
9161 // We use the mask type to pick which bytes are preserved based on how many
9162 // elements are dropped.
9163 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9164 SDValue ByteClearMask = DAG.getBitcast(
9165 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9166 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9168 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9170 // Now pack things back together.
9171 V1 = DAG.getBitcast(MVT::v8i16, V1);
9172 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9173 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9174 for (int i = 1; i < NumEvenDrops; ++i) {
9175 Result = DAG.getBitcast(MVT::v8i16, Result);
9176 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9182 // Handle multi-input cases by blending single-input shuffles.
9183 if (NumV2Elements > 0)
9184 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9187 // The fallback path for single-input shuffles widens this into two v8i16
9188 // vectors with unpacks, shuffles those, and then pulls them back together
9192 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9193 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9194 for (int i = 0; i < 16; ++i)
9196 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9198 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9200 SDValue VLoHalf, VHiHalf;
9201 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9202 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9204 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9205 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9206 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9207 [](int M) { return M >= 0 && M % 2 == 1; })) {
9208 // Use a mask to drop the high bytes.
9209 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9210 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9211 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9213 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9214 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9216 // Squash the masks to point directly into VLoHalf.
9217 for (int &M : LoBlendMask)
9220 for (int &M : HiBlendMask)
9224 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9225 // VHiHalf so that we can blend them as i16s.
9226 VLoHalf = DAG.getBitcast(
9227 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9228 VHiHalf = DAG.getBitcast(
9229 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9232 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9233 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9235 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9238 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9240 /// This routine breaks down the specific type of 128-bit shuffle and
9241 /// dispatches to the lowering routines accordingly.
9242 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9243 MVT VT, const X86Subtarget *Subtarget,
9244 SelectionDAG &DAG) {
9245 switch (VT.SimpleTy) {
9247 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9249 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9251 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9253 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9255 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9257 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9260 llvm_unreachable("Unimplemented!");
9264 /// \brief Helper function to test whether a shuffle mask could be
9265 /// simplified by widening the elements being shuffled.
9267 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9268 /// leaves it in an unspecified state.
9270 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9271 /// shuffle masks. The latter have the special property of a '-2' representing
9272 /// a zero-ed lane of a vector.
9273 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9274 SmallVectorImpl<int> &WidenedMask) {
9275 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9276 // If both elements are undef, its trivial.
9277 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9278 WidenedMask.push_back(SM_SentinelUndef);
9282 // Check for an undef mask and a mask value properly aligned to fit with
9283 // a pair of values. If we find such a case, use the non-undef mask's value.
9284 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9285 WidenedMask.push_back(Mask[i + 1] / 2);
9288 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9289 WidenedMask.push_back(Mask[i] / 2);
9293 // When zeroing, we need to spread the zeroing across both lanes to widen.
9294 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9295 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9296 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9297 WidenedMask.push_back(SM_SentinelZero);
9303 // Finally check if the two mask values are adjacent and aligned with
9305 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9306 WidenedMask.push_back(Mask[i] / 2);
9310 // Otherwise we can't safely widen the elements used in this shuffle.
9313 assert(WidenedMask.size() == Mask.size() / 2 &&
9314 "Incorrect size of mask after widening the elements!");
9319 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9321 /// This routine just extracts two subvectors, shuffles them independently, and
9322 /// then concatenates them back together. This should work effectively with all
9323 /// AVX vector shuffle types.
9324 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9325 SDValue V2, ArrayRef<int> Mask,
9326 SelectionDAG &DAG) {
9327 assert(VT.getSizeInBits() >= 256 &&
9328 "Only for 256-bit or wider vector shuffles!");
9329 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9330 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9332 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9333 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9335 int NumElements = VT.getVectorNumElements();
9336 int SplitNumElements = NumElements / 2;
9337 MVT ScalarVT = VT.getScalarType();
9338 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9340 // Rather than splitting build-vectors, just build two narrower build
9341 // vectors. This helps shuffling with splats and zeros.
9342 auto SplitVector = [&](SDValue V) {
9343 while (V.getOpcode() == ISD::BITCAST)
9344 V = V->getOperand(0);
9346 MVT OrigVT = V.getSimpleValueType();
9347 int OrigNumElements = OrigVT.getVectorNumElements();
9348 int OrigSplitNumElements = OrigNumElements / 2;
9349 MVT OrigScalarVT = OrigVT.getScalarType();
9350 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9354 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9356 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9357 DAG.getIntPtrConstant(0, DL));
9358 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9359 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9362 SmallVector<SDValue, 16> LoOps, HiOps;
9363 for (int i = 0; i < OrigSplitNumElements; ++i) {
9364 LoOps.push_back(BV->getOperand(i));
9365 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9367 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9368 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9370 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9371 DAG.getBitcast(SplitVT, HiV));
9374 SDValue LoV1, HiV1, LoV2, HiV2;
9375 std::tie(LoV1, HiV1) = SplitVector(V1);
9376 std::tie(LoV2, HiV2) = SplitVector(V2);
9378 // Now create two 4-way blends of these half-width vectors.
9379 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9380 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9381 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9382 for (int i = 0; i < SplitNumElements; ++i) {
9383 int M = HalfMask[i];
9384 if (M >= NumElements) {
9385 if (M >= NumElements + SplitNumElements)
9389 V2BlendMask.push_back(M - NumElements);
9390 V1BlendMask.push_back(-1);
9391 BlendMask.push_back(SplitNumElements + i);
9392 } else if (M >= 0) {
9393 if (M >= SplitNumElements)
9397 V2BlendMask.push_back(-1);
9398 V1BlendMask.push_back(M);
9399 BlendMask.push_back(i);
9401 V2BlendMask.push_back(-1);
9402 V1BlendMask.push_back(-1);
9403 BlendMask.push_back(-1);
9407 // Because the lowering happens after all combining takes place, we need to
9408 // manually combine these blend masks as much as possible so that we create
9409 // a minimal number of high-level vector shuffle nodes.
9411 // First try just blending the halves of V1 or V2.
9412 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9413 return DAG.getUNDEF(SplitVT);
9414 if (!UseLoV2 && !UseHiV2)
9415 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9416 if (!UseLoV1 && !UseHiV1)
9417 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9419 SDValue V1Blend, V2Blend;
9420 if (UseLoV1 && UseHiV1) {
9422 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9424 // We only use half of V1 so map the usage down into the final blend mask.
9425 V1Blend = UseLoV1 ? LoV1 : HiV1;
9426 for (int i = 0; i < SplitNumElements; ++i)
9427 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9428 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9430 if (UseLoV2 && UseHiV2) {
9432 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9434 // We only use half of V2 so map the usage down into the final blend mask.
9435 V2Blend = UseLoV2 ? LoV2 : HiV2;
9436 for (int i = 0; i < SplitNumElements; ++i)
9437 if (BlendMask[i] >= SplitNumElements)
9438 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9440 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9442 SDValue Lo = HalfBlend(LoMask);
9443 SDValue Hi = HalfBlend(HiMask);
9444 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9447 /// \brief Either split a vector in halves or decompose the shuffles and the
9450 /// This is provided as a good fallback for many lowerings of non-single-input
9451 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9452 /// between splitting the shuffle into 128-bit components and stitching those
9453 /// back together vs. extracting the single-input shuffles and blending those
9455 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9456 SDValue V2, ArrayRef<int> Mask,
9457 SelectionDAG &DAG) {
9458 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9459 "lower single-input shuffles as it "
9460 "could then recurse on itself.");
9461 int Size = Mask.size();
9463 // If this can be modeled as a broadcast of two elements followed by a blend,
9464 // prefer that lowering. This is especially important because broadcasts can
9465 // often fold with memory operands.
9466 auto DoBothBroadcast = [&] {
9467 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9470 if (V2BroadcastIdx == -1)
9471 V2BroadcastIdx = M - Size;
9472 else if (M - Size != V2BroadcastIdx)
9474 } else if (M >= 0) {
9475 if (V1BroadcastIdx == -1)
9477 else if (M != V1BroadcastIdx)
9482 if (DoBothBroadcast())
9483 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9486 // If the inputs all stem from a single 128-bit lane of each input, then we
9487 // split them rather than blending because the split will decompose to
9488 // unusually few instructions.
9489 int LaneCount = VT.getSizeInBits() / 128;
9490 int LaneSize = Size / LaneCount;
9491 SmallBitVector LaneInputs[2];
9492 LaneInputs[0].resize(LaneCount, false);
9493 LaneInputs[1].resize(LaneCount, false);
9494 for (int i = 0; i < Size; ++i)
9496 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9497 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9498 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9500 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9501 // that the decomposed single-input shuffles don't end up here.
9502 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9505 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9506 /// a permutation and blend of those lanes.
9508 /// This essentially blends the out-of-lane inputs to each lane into the lane
9509 /// from a permuted copy of the vector. This lowering strategy results in four
9510 /// instructions in the worst case for a single-input cross lane shuffle which
9511 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9512 /// of. Special cases for each particular shuffle pattern should be handled
9513 /// prior to trying this lowering.
9514 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9515 SDValue V1, SDValue V2,
9517 SelectionDAG &DAG) {
9518 // FIXME: This should probably be generalized for 512-bit vectors as well.
9519 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9520 int LaneSize = Mask.size() / 2;
9522 // If there are only inputs from one 128-bit lane, splitting will in fact be
9523 // less expensive. The flags track whether the given lane contains an element
9524 // that crosses to another lane.
9525 bool LaneCrossing[2] = {false, false};
9526 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9527 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9528 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9529 if (!LaneCrossing[0] || !LaneCrossing[1])
9530 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9532 if (isSingleInputShuffleMask(Mask)) {
9533 SmallVector<int, 32> FlippedBlendMask;
9534 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9535 FlippedBlendMask.push_back(
9536 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9538 : Mask[i] % LaneSize +
9539 (i / LaneSize) * LaneSize + Size));
9541 // Flip the vector, and blend the results which should now be in-lane. The
9542 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9543 // 5 for the high source. The value 3 selects the high half of source 2 and
9544 // the value 2 selects the low half of source 2. We only use source 2 to
9545 // allow folding it into a memory operand.
9546 unsigned PERMMask = 3 | 2 << 4;
9547 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9548 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9549 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9552 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9553 // will be handled by the above logic and a blend of the results, much like
9554 // other patterns in AVX.
9555 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9558 /// \brief Handle lowering 2-lane 128-bit shuffles.
9559 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9560 SDValue V2, ArrayRef<int> Mask,
9561 const X86Subtarget *Subtarget,
9562 SelectionDAG &DAG) {
9563 // TODO: If minimizing size and one of the inputs is a zero vector and the
9564 // the zero vector has only one use, we could use a VPERM2X128 to save the
9565 // instruction bytes needed to explicitly generate the zero vector.
9567 // Blends are faster and handle all the non-lane-crossing cases.
9568 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9572 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9573 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9575 // If either input operand is a zero vector, use VPERM2X128 because its mask
9576 // allows us to replace the zero input with an implicit zero.
9577 if (!IsV1Zero && !IsV2Zero) {
9578 // Check for patterns which can be matched with a single insert of a 128-bit
9580 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9581 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9582 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9583 VT.getVectorNumElements() / 2);
9584 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9585 DAG.getIntPtrConstant(0, DL));
9586 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9587 OnlyUsesV1 ? V1 : V2,
9588 DAG.getIntPtrConstant(0, DL));
9589 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9593 // Otherwise form a 128-bit permutation. After accounting for undefs,
9594 // convert the 64-bit shuffle mask selection values into 128-bit
9595 // selection bits by dividing the indexes by 2 and shifting into positions
9596 // defined by a vperm2*128 instruction's immediate control byte.
9598 // The immediate permute control byte looks like this:
9599 // [1:0] - select 128 bits from sources for low half of destination
9601 // [3] - zero low half of destination
9602 // [5:4] - select 128 bits from sources for high half of destination
9604 // [7] - zero high half of destination
9606 int MaskLO = Mask[0];
9607 if (MaskLO == SM_SentinelUndef)
9608 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9610 int MaskHI = Mask[2];
9611 if (MaskHI == SM_SentinelUndef)
9612 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9614 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9616 // If either input is a zero vector, replace it with an undef input.
9617 // Shuffle mask values < 4 are selecting elements of V1.
9618 // Shuffle mask values >= 4 are selecting elements of V2.
9619 // Adjust each half of the permute mask by clearing the half that was
9620 // selecting the zero vector and setting the zero mask bit.
9622 V1 = DAG.getUNDEF(VT);
9624 PermMask = (PermMask & 0xf0) | 0x08;
9626 PermMask = (PermMask & 0x0f) | 0x80;
9629 V2 = DAG.getUNDEF(VT);
9631 PermMask = (PermMask & 0xf0) | 0x08;
9633 PermMask = (PermMask & 0x0f) | 0x80;
9636 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9637 DAG.getConstant(PermMask, DL, MVT::i8));
9640 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9641 /// shuffling each lane.
9643 /// This will only succeed when the result of fixing the 128-bit lanes results
9644 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9645 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9646 /// the lane crosses early and then use simpler shuffles within each lane.
9648 /// FIXME: It might be worthwhile at some point to support this without
9649 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9650 /// in x86 only floating point has interesting non-repeating shuffles, and even
9651 /// those are still *marginally* more expensive.
9652 static SDValue lowerVectorShuffleByMerging128BitLanes(
9653 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9654 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9655 assert(!isSingleInputShuffleMask(Mask) &&
9656 "This is only useful with multiple inputs.");
9658 int Size = Mask.size();
9659 int LaneSize = 128 / VT.getScalarSizeInBits();
9660 int NumLanes = Size / LaneSize;
9661 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9663 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9664 // check whether the in-128-bit lane shuffles share a repeating pattern.
9665 SmallVector<int, 4> Lanes;
9666 Lanes.resize(NumLanes, -1);
9667 SmallVector<int, 4> InLaneMask;
9668 InLaneMask.resize(LaneSize, -1);
9669 for (int i = 0; i < Size; ++i) {
9673 int j = i / LaneSize;
9676 // First entry we've seen for this lane.
9677 Lanes[j] = Mask[i] / LaneSize;
9678 } else if (Lanes[j] != Mask[i] / LaneSize) {
9679 // This doesn't match the lane selected previously!
9683 // Check that within each lane we have a consistent shuffle mask.
9684 int k = i % LaneSize;
9685 if (InLaneMask[k] < 0) {
9686 InLaneMask[k] = Mask[i] % LaneSize;
9687 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9688 // This doesn't fit a repeating in-lane mask.
9693 // First shuffle the lanes into place.
9694 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9695 VT.getSizeInBits() / 64);
9696 SmallVector<int, 8> LaneMask;
9697 LaneMask.resize(NumLanes * 2, -1);
9698 for (int i = 0; i < NumLanes; ++i)
9699 if (Lanes[i] >= 0) {
9700 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9701 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9704 V1 = DAG.getBitcast(LaneVT, V1);
9705 V2 = DAG.getBitcast(LaneVT, V2);
9706 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9708 // Cast it back to the type we actually want.
9709 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9711 // Now do a simple shuffle that isn't lane crossing.
9712 SmallVector<int, 8> NewMask;
9713 NewMask.resize(Size, -1);
9714 for (int i = 0; i < Size; ++i)
9716 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9717 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9718 "Must not introduce lane crosses at this point!");
9720 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9723 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9726 /// This returns true if the elements from a particular input are already in the
9727 /// slot required by the given mask and require no permutation.
9728 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9729 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9730 int Size = Mask.size();
9731 for (int i = 0; i < Size; ++i)
9732 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9738 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9739 ArrayRef<int> Mask, SDValue V1,
9740 SDValue V2, SelectionDAG &DAG) {
9742 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9743 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9744 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9745 int NumElts = VT.getVectorNumElements();
9746 bool ShufpdMask = true;
9747 bool CommutableMask = true;
9748 unsigned Immediate = 0;
9749 for (int i = 0; i < NumElts; ++i) {
9752 int Val = (i & 6) + NumElts * (i & 1);
9753 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9754 if (Mask[i] < Val || Mask[i] > Val + 1)
9756 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9757 CommutableMask = false;
9758 Immediate |= (Mask[i] % 2) << i;
9761 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9762 DAG.getConstant(Immediate, DL, MVT::i8));
9764 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9765 DAG.getConstant(Immediate, DL, MVT::i8));
9769 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9771 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9772 /// isn't available.
9773 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9774 const X86Subtarget *Subtarget,
9775 SelectionDAG &DAG) {
9777 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9778 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9779 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9780 ArrayRef<int> Mask = SVOp->getMask();
9781 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9783 SmallVector<int, 4> WidenedMask;
9784 if (canWidenShuffleElements(Mask, WidenedMask))
9785 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9788 if (isSingleInputShuffleMask(Mask)) {
9789 // Check for being able to broadcast a single element.
9790 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9791 Mask, Subtarget, DAG))
9794 // Use low duplicate instructions for masks that match their pattern.
9795 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9796 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9798 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9799 // Non-half-crossing single input shuffles can be lowerid with an
9800 // interleaved permutation.
9801 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9802 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9803 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9804 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9807 // With AVX2 we have direct support for this permutation.
9808 if (Subtarget->hasAVX2())
9809 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9810 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9812 // Otherwise, fall back.
9813 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9817 // X86 has dedicated unpack instructions that can handle specific blend
9818 // operations: UNPCKH and UNPCKL.
9819 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9820 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9821 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9822 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9823 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9824 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9825 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9826 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9828 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9832 // Check if the blend happens to exactly fit that of SHUFPD.
9834 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9837 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9838 // shuffle. However, if we have AVX2 and either inputs are already in place,
9839 // we will be able to shuffle even across lanes the other input in a single
9840 // instruction so skip this pattern.
9841 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9842 isShuffleMaskInputInPlace(1, Mask))))
9843 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9844 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9847 // If we have AVX2 then we always want to lower with a blend because an v4 we
9848 // can fully permute the elements.
9849 if (Subtarget->hasAVX2())
9850 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9853 // Otherwise fall back on generic lowering.
9854 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9857 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9859 /// This routine is only called when we have AVX2 and thus a reasonable
9860 /// instruction set for v4i64 shuffling..
9861 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9862 const X86Subtarget *Subtarget,
9863 SelectionDAG &DAG) {
9865 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9866 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9867 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9868 ArrayRef<int> Mask = SVOp->getMask();
9869 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9870 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9872 SmallVector<int, 4> WidenedMask;
9873 if (canWidenShuffleElements(Mask, WidenedMask))
9874 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9877 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9881 // Check for being able to broadcast a single element.
9882 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9883 Mask, Subtarget, DAG))
9886 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9887 // use lower latency instructions that will operate on both 128-bit lanes.
9888 SmallVector<int, 2> RepeatedMask;
9889 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9890 if (isSingleInputShuffleMask(Mask)) {
9891 int PSHUFDMask[] = {-1, -1, -1, -1};
9892 for (int i = 0; i < 2; ++i)
9893 if (RepeatedMask[i] >= 0) {
9894 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9895 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9897 return DAG.getBitcast(
9899 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9900 DAG.getBitcast(MVT::v8i32, V1),
9901 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9905 // AVX2 provides a direct instruction for permuting a single input across
9907 if (isSingleInputShuffleMask(Mask))
9908 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9909 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9911 // Try to use shift instructions.
9913 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9916 // Use dedicated unpack instructions for masks that match their pattern.
9917 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9918 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9919 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9920 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9921 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9922 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9923 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9924 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9926 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9927 // shuffle. However, if we have AVX2 and either inputs are already in place,
9928 // we will be able to shuffle even across lanes the other input in a single
9929 // instruction so skip this pattern.
9930 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9931 isShuffleMaskInputInPlace(1, Mask))))
9932 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9933 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9936 // Otherwise fall back on generic blend lowering.
9937 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9941 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9943 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9944 /// isn't available.
9945 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9946 const X86Subtarget *Subtarget,
9947 SelectionDAG &DAG) {
9949 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9950 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9951 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9952 ArrayRef<int> Mask = SVOp->getMask();
9953 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9955 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9959 // Check for being able to broadcast a single element.
9960 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9961 Mask, Subtarget, DAG))
9964 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9965 // options to efficiently lower the shuffle.
9966 SmallVector<int, 4> RepeatedMask;
9967 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9968 assert(RepeatedMask.size() == 4 &&
9969 "Repeated masks must be half the mask width!");
9971 // Use even/odd duplicate instructions for masks that match their pattern.
9972 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9973 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9974 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9975 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9977 if (isSingleInputShuffleMask(Mask))
9978 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9979 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9981 // Use dedicated unpack instructions for masks that match their pattern.
9982 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9983 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9984 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9985 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9986 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9987 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9988 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9989 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9991 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9992 // have already handled any direct blends. We also need to squash the
9993 // repeated mask into a simulated v4f32 mask.
9994 for (int i = 0; i < 4; ++i)
9995 if (RepeatedMask[i] >= 8)
9996 RepeatedMask[i] -= 4;
9997 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10000 // If we have a single input shuffle with different shuffle patterns in the
10001 // two 128-bit lanes use the variable mask to VPERMILPS.
10002 if (isSingleInputShuffleMask(Mask)) {
10003 SDValue VPermMask[8];
10004 for (int i = 0; i < 8; ++i)
10005 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10006 : DAG.getConstant(Mask[i], DL, MVT::i32);
10007 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10008 return DAG.getNode(
10009 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10010 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10012 if (Subtarget->hasAVX2())
10013 return DAG.getNode(
10014 X86ISD::VPERMV, DL, MVT::v8f32,
10015 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10016 MVT::v8i32, VPermMask)),
10019 // Otherwise, fall back.
10020 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10024 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10026 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10027 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10030 // If we have AVX2 then we always want to lower with a blend because at v8 we
10031 // can fully permute the elements.
10032 if (Subtarget->hasAVX2())
10033 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10036 // Otherwise fall back on generic lowering.
10037 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10040 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10042 /// This routine is only called when we have AVX2 and thus a reasonable
10043 /// instruction set for v8i32 shuffling..
10044 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10045 const X86Subtarget *Subtarget,
10046 SelectionDAG &DAG) {
10048 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10049 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10050 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10051 ArrayRef<int> Mask = SVOp->getMask();
10052 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10053 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10055 // Whenever we can lower this as a zext, that instruction is strictly faster
10056 // than any alternative. It also allows us to fold memory operands into the
10057 // shuffle in many cases.
10058 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10059 Mask, Subtarget, DAG))
10062 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10066 // Check for being able to broadcast a single element.
10067 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10068 Mask, Subtarget, DAG))
10071 // If the shuffle mask is repeated in each 128-bit lane we can use more
10072 // efficient instructions that mirror the shuffles across the two 128-bit
10074 SmallVector<int, 4> RepeatedMask;
10075 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10076 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10077 if (isSingleInputShuffleMask(Mask))
10078 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10079 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10081 // Use dedicated unpack instructions for masks that match their pattern.
10082 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10083 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10084 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10085 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10086 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10087 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10088 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10089 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10092 // Try to use shift instructions.
10093 if (SDValue Shift =
10094 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10097 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10098 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10101 // If the shuffle patterns aren't repeated but it is a single input, directly
10102 // generate a cross-lane VPERMD instruction.
10103 if (isSingleInputShuffleMask(Mask)) {
10104 SDValue VPermMask[8];
10105 for (int i = 0; i < 8; ++i)
10106 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10107 : DAG.getConstant(Mask[i], DL, MVT::i32);
10108 return DAG.getNode(
10109 X86ISD::VPERMV, DL, MVT::v8i32,
10110 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10113 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10115 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10116 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10119 // Otherwise fall back on generic blend lowering.
10120 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10124 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10126 /// This routine is only called when we have AVX2 and thus a reasonable
10127 /// instruction set for v16i16 shuffling..
10128 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10129 const X86Subtarget *Subtarget,
10130 SelectionDAG &DAG) {
10132 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10133 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10134 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10135 ArrayRef<int> Mask = SVOp->getMask();
10136 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10137 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10139 // Whenever we can lower this as a zext, that instruction is strictly faster
10140 // than any alternative. It also allows us to fold memory operands into the
10141 // shuffle in many cases.
10142 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10143 Mask, Subtarget, DAG))
10146 // Check for being able to broadcast a single element.
10147 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10148 Mask, Subtarget, DAG))
10151 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10155 // Use dedicated unpack instructions for masks that match their pattern.
10156 if (isShuffleEquivalent(V1, V2, Mask,
10157 {// First 128-bit lane:
10158 0, 16, 1, 17, 2, 18, 3, 19,
10159 // Second 128-bit lane:
10160 8, 24, 9, 25, 10, 26, 11, 27}))
10161 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10162 if (isShuffleEquivalent(V1, V2, Mask,
10163 {// First 128-bit lane:
10164 4, 20, 5, 21, 6, 22, 7, 23,
10165 // Second 128-bit lane:
10166 12, 28, 13, 29, 14, 30, 15, 31}))
10167 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10169 // Try to use shift instructions.
10170 if (SDValue Shift =
10171 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10174 // Try to use byte rotation instructions.
10175 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10176 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10179 if (isSingleInputShuffleMask(Mask)) {
10180 // There are no generalized cross-lane shuffle operations available on i16
10182 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10183 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10186 SmallVector<int, 8> RepeatedMask;
10187 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10188 // As this is a single-input shuffle, the repeated mask should be
10189 // a strictly valid v8i16 mask that we can pass through to the v8i16
10190 // lowering to handle even the v16 case.
10191 return lowerV8I16GeneralSingleInputVectorShuffle(
10192 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10195 SDValue PSHUFBMask[32];
10196 for (int i = 0; i < 16; ++i) {
10197 if (Mask[i] == -1) {
10198 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10202 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10203 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10204 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10205 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10207 return DAG.getBitcast(MVT::v16i16,
10208 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10209 DAG.getBitcast(MVT::v32i8, V1),
10210 DAG.getNode(ISD::BUILD_VECTOR, DL,
10211 MVT::v32i8, PSHUFBMask)));
10214 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10216 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10217 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10220 // Otherwise fall back on generic lowering.
10221 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10224 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10226 /// This routine is only called when we have AVX2 and thus a reasonable
10227 /// instruction set for v32i8 shuffling..
10228 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10229 const X86Subtarget *Subtarget,
10230 SelectionDAG &DAG) {
10232 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10233 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10234 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10235 ArrayRef<int> Mask = SVOp->getMask();
10236 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10237 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10239 // Whenever we can lower this as a zext, that instruction is strictly faster
10240 // than any alternative. It also allows us to fold memory operands into the
10241 // shuffle in many cases.
10242 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10243 Mask, Subtarget, DAG))
10246 // Check for being able to broadcast a single element.
10247 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10248 Mask, Subtarget, DAG))
10251 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10255 // Use dedicated unpack instructions for masks that match their pattern.
10256 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10258 if (isShuffleEquivalent(
10260 {// First 128-bit lane:
10261 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10262 // Second 128-bit lane:
10263 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10264 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10265 if (isShuffleEquivalent(
10267 {// First 128-bit lane:
10268 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10269 // Second 128-bit lane:
10270 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10271 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10273 // Try to use shift instructions.
10274 if (SDValue Shift =
10275 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10278 // Try to use byte rotation instructions.
10279 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10280 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10283 if (isSingleInputShuffleMask(Mask)) {
10284 // There are no generalized cross-lane shuffle operations available on i8
10286 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10287 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10290 SDValue PSHUFBMask[32];
10291 for (int i = 0; i < 32; ++i)
10294 ? DAG.getUNDEF(MVT::i8)
10295 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10298 return DAG.getNode(
10299 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10300 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10303 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10305 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10306 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10309 // Otherwise fall back on generic lowering.
10310 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10313 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10315 /// This routine either breaks down the specific type of a 256-bit x86 vector
10316 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10317 /// together based on the available instructions.
10318 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10319 MVT VT, const X86Subtarget *Subtarget,
10320 SelectionDAG &DAG) {
10322 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10323 ArrayRef<int> Mask = SVOp->getMask();
10325 // If we have a single input to the zero element, insert that into V1 if we
10326 // can do so cheaply.
10327 int NumElts = VT.getVectorNumElements();
10328 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10329 return M >= NumElts;
10332 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10333 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10334 DL, VT, V1, V2, Mask, Subtarget, DAG))
10337 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10338 // check for those subtargets here and avoid much of the subtarget querying in
10339 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10340 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10341 // floating point types there eventually, just immediately cast everything to
10342 // a float and operate entirely in that domain.
10343 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10344 int ElementBits = VT.getScalarSizeInBits();
10345 if (ElementBits < 32)
10346 // No floating point type available, decompose into 128-bit vectors.
10347 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10349 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10350 VT.getVectorNumElements());
10351 V1 = DAG.getBitcast(FpVT, V1);
10352 V2 = DAG.getBitcast(FpVT, V2);
10353 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10356 switch (VT.SimpleTy) {
10358 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10360 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10362 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10364 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10366 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10368 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10371 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10375 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10376 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10377 const X86Subtarget *Subtarget,
10378 SelectionDAG &DAG) {
10380 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10381 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10382 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10383 ArrayRef<int> Mask = SVOp->getMask();
10384 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10386 // X86 has dedicated unpack instructions that can handle specific blend
10387 // operations: UNPCKH and UNPCKL.
10388 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10389 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10390 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10391 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10393 // FIXME: Implement direct support for this type!
10394 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10397 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10398 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10399 const X86Subtarget *Subtarget,
10400 SelectionDAG &DAG) {
10402 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10403 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10404 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10405 ArrayRef<int> Mask = SVOp->getMask();
10406 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10408 // Use dedicated unpack instructions for masks that match their pattern.
10409 if (isShuffleEquivalent(V1, V2, Mask,
10410 {// First 128-bit lane.
10411 0, 16, 1, 17, 4, 20, 5, 21,
10412 // Second 128-bit lane.
10413 8, 24, 9, 25, 12, 28, 13, 29}))
10414 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10415 if (isShuffleEquivalent(V1, V2, Mask,
10416 {// First 128-bit lane.
10417 2, 18, 3, 19, 6, 22, 7, 23,
10418 // Second 128-bit lane.
10419 10, 26, 11, 27, 14, 30, 15, 31}))
10420 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10422 // FIXME: Implement direct support for this type!
10423 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10426 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10427 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10428 const X86Subtarget *Subtarget,
10429 SelectionDAG &DAG) {
10431 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10432 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10433 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10434 ArrayRef<int> Mask = SVOp->getMask();
10435 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10437 // X86 has dedicated unpack instructions that can handle specific blend
10438 // operations: UNPCKH and UNPCKL.
10439 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10440 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10441 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10442 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10444 // FIXME: Implement direct support for this type!
10445 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10448 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10449 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10450 const X86Subtarget *Subtarget,
10451 SelectionDAG &DAG) {
10453 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10454 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10455 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10456 ArrayRef<int> Mask = SVOp->getMask();
10457 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10459 // Use dedicated unpack instructions for masks that match their pattern.
10460 if (isShuffleEquivalent(V1, V2, Mask,
10461 {// First 128-bit lane.
10462 0, 16, 1, 17, 4, 20, 5, 21,
10463 // Second 128-bit lane.
10464 8, 24, 9, 25, 12, 28, 13, 29}))
10465 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10466 if (isShuffleEquivalent(V1, V2, Mask,
10467 {// First 128-bit lane.
10468 2, 18, 3, 19, 6, 22, 7, 23,
10469 // Second 128-bit lane.
10470 10, 26, 11, 27, 14, 30, 15, 31}))
10471 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10473 // FIXME: Implement direct support for this type!
10474 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10477 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10478 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10479 const X86Subtarget *Subtarget,
10480 SelectionDAG &DAG) {
10482 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10483 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10484 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10485 ArrayRef<int> Mask = SVOp->getMask();
10486 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10487 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10489 // FIXME: Implement direct support for this type!
10490 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10493 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10494 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10495 const X86Subtarget *Subtarget,
10496 SelectionDAG &DAG) {
10498 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10499 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10500 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10501 ArrayRef<int> Mask = SVOp->getMask();
10502 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10503 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10505 // FIXME: Implement direct support for this type!
10506 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10509 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10511 /// This routine either breaks down the specific type of a 512-bit x86 vector
10512 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10513 /// together based on the available instructions.
10514 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10515 MVT VT, const X86Subtarget *Subtarget,
10516 SelectionDAG &DAG) {
10518 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10519 ArrayRef<int> Mask = SVOp->getMask();
10520 assert(Subtarget->hasAVX512() &&
10521 "Cannot lower 512-bit vectors w/ basic ISA!");
10523 // Check for being able to broadcast a single element.
10524 if (SDValue Broadcast =
10525 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10528 // Dispatch to each element type for lowering. If we don't have supprot for
10529 // specific element type shuffles at 512 bits, immediately split them and
10530 // lower them. Each lowering routine of a given type is allowed to assume that
10531 // the requisite ISA extensions for that element type are available.
10532 switch (VT.SimpleTy) {
10534 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10536 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10538 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10540 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10542 if (Subtarget->hasBWI())
10543 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10546 if (Subtarget->hasBWI())
10547 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10551 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10554 // Otherwise fall back on splitting.
10555 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10558 /// \brief Top-level lowering for x86 vector shuffles.
10560 /// This handles decomposition, canonicalization, and lowering of all x86
10561 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10562 /// above in helper routines. The canonicalization attempts to widen shuffles
10563 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10564 /// s.t. only one of the two inputs needs to be tested, etc.
10565 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10566 SelectionDAG &DAG) {
10567 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10568 ArrayRef<int> Mask = SVOp->getMask();
10569 SDValue V1 = Op.getOperand(0);
10570 SDValue V2 = Op.getOperand(1);
10571 MVT VT = Op.getSimpleValueType();
10572 int NumElements = VT.getVectorNumElements();
10575 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10577 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10578 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10579 if (V1IsUndef && V2IsUndef)
10580 return DAG.getUNDEF(VT);
10582 // When we create a shuffle node we put the UNDEF node to second operand,
10583 // but in some cases the first operand may be transformed to UNDEF.
10584 // In this case we should just commute the node.
10586 return DAG.getCommutedVectorShuffle(*SVOp);
10588 // Check for non-undef masks pointing at an undef vector and make the masks
10589 // undef as well. This makes it easier to match the shuffle based solely on
10593 if (M >= NumElements) {
10594 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10595 for (int &M : NewMask)
10596 if (M >= NumElements)
10598 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10601 // We actually see shuffles that are entirely re-arrangements of a set of
10602 // zero inputs. This mostly happens while decomposing complex shuffles into
10603 // simple ones. Directly lower these as a buildvector of zeros.
10604 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10605 if (Zeroable.all())
10606 return getZeroVector(VT, Subtarget, DAG, dl);
10608 // Try to collapse shuffles into using a vector type with fewer elements but
10609 // wider element types. We cap this to not form integers or floating point
10610 // elements wider than 64 bits, but it might be interesting to form i128
10611 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10612 SmallVector<int, 16> WidenedMask;
10613 if (VT.getScalarSizeInBits() < 64 &&
10614 canWidenShuffleElements(Mask, WidenedMask)) {
10615 MVT NewEltVT = VT.isFloatingPoint()
10616 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10617 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10618 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10619 // Make sure that the new vector type is legal. For example, v2f64 isn't
10621 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10622 V1 = DAG.getBitcast(NewVT, V1);
10623 V2 = DAG.getBitcast(NewVT, V2);
10624 return DAG.getBitcast(
10625 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10629 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10630 for (int M : SVOp->getMask())
10632 ++NumUndefElements;
10633 else if (M < NumElements)
10638 // Commute the shuffle as needed such that more elements come from V1 than
10639 // V2. This allows us to match the shuffle pattern strictly on how many
10640 // elements come from V1 without handling the symmetric cases.
10641 if (NumV2Elements > NumV1Elements)
10642 return DAG.getCommutedVectorShuffle(*SVOp);
10644 // When the number of V1 and V2 elements are the same, try to minimize the
10645 // number of uses of V2 in the low half of the vector. When that is tied,
10646 // ensure that the sum of indices for V1 is equal to or lower than the sum
10647 // indices for V2. When those are equal, try to ensure that the number of odd
10648 // indices for V1 is lower than the number of odd indices for V2.
10649 if (NumV1Elements == NumV2Elements) {
10650 int LowV1Elements = 0, LowV2Elements = 0;
10651 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10652 if (M >= NumElements)
10656 if (LowV2Elements > LowV1Elements) {
10657 return DAG.getCommutedVectorShuffle(*SVOp);
10658 } else if (LowV2Elements == LowV1Elements) {
10659 int SumV1Indices = 0, SumV2Indices = 0;
10660 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10661 if (SVOp->getMask()[i] >= NumElements)
10663 else if (SVOp->getMask()[i] >= 0)
10665 if (SumV2Indices < SumV1Indices) {
10666 return DAG.getCommutedVectorShuffle(*SVOp);
10667 } else if (SumV2Indices == SumV1Indices) {
10668 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10669 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10670 if (SVOp->getMask()[i] >= NumElements)
10671 NumV2OddIndices += i % 2;
10672 else if (SVOp->getMask()[i] >= 0)
10673 NumV1OddIndices += i % 2;
10674 if (NumV2OddIndices < NumV1OddIndices)
10675 return DAG.getCommutedVectorShuffle(*SVOp);
10680 // For each vector width, delegate to a specialized lowering routine.
10681 if (VT.getSizeInBits() == 128)
10682 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10684 if (VT.getSizeInBits() == 256)
10685 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10687 // Force AVX-512 vectors to be scalarized for now.
10688 // FIXME: Implement AVX-512 support!
10689 if (VT.getSizeInBits() == 512)
10690 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10692 llvm_unreachable("Unimplemented!");
10695 // This function assumes its argument is a BUILD_VECTOR of constants or
10696 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10698 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10699 unsigned &MaskValue) {
10701 unsigned NumElems = BuildVector->getNumOperands();
10702 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10703 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10704 unsigned NumElemsInLane = NumElems / NumLanes;
10706 // Blend for v16i16 should be symetric for the both lanes.
10707 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10708 SDValue EltCond = BuildVector->getOperand(i);
10709 SDValue SndLaneEltCond =
10710 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10712 int Lane1Cond = -1, Lane2Cond = -1;
10713 if (isa<ConstantSDNode>(EltCond))
10714 Lane1Cond = !isZero(EltCond);
10715 if (isa<ConstantSDNode>(SndLaneEltCond))
10716 Lane2Cond = !isZero(SndLaneEltCond);
10718 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10719 // Lane1Cond != 0, means we want the first argument.
10720 // Lane1Cond == 0, means we want the second argument.
10721 // The encoding of this argument is 0 for the first argument, 1
10722 // for the second. Therefore, invert the condition.
10723 MaskValue |= !Lane1Cond << i;
10724 else if (Lane1Cond < 0)
10725 MaskValue |= !Lane2Cond << i;
10732 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10733 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10734 const X86Subtarget *Subtarget,
10735 SelectionDAG &DAG) {
10736 SDValue Cond = Op.getOperand(0);
10737 SDValue LHS = Op.getOperand(1);
10738 SDValue RHS = Op.getOperand(2);
10740 MVT VT = Op.getSimpleValueType();
10742 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10744 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10746 // Only non-legal VSELECTs reach this lowering, convert those into generic
10747 // shuffles and re-use the shuffle lowering path for blends.
10748 SmallVector<int, 32> Mask;
10749 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10750 SDValue CondElt = CondBV->getOperand(i);
10752 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10754 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10757 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10758 // A vselect where all conditions and data are constants can be optimized into
10759 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10760 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10761 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10762 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10765 // Try to lower this to a blend-style vector shuffle. This can handle all
10766 // constant condition cases.
10767 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10770 // Variable blends are only legal from SSE4.1 onward.
10771 if (!Subtarget->hasSSE41())
10774 // Only some types will be legal on some subtargets. If we can emit a legal
10775 // VSELECT-matching blend, return Op, and but if we need to expand, return
10777 switch (Op.getSimpleValueType().SimpleTy) {
10779 // Most of the vector types have blends past SSE4.1.
10783 // The byte blends for AVX vectors were introduced only in AVX2.
10784 if (Subtarget->hasAVX2())
10791 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10792 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10795 // FIXME: We should custom lower this by fixing the condition and using i8
10801 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10802 MVT VT = Op.getSimpleValueType();
10805 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10808 if (VT.getSizeInBits() == 8) {
10809 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10810 Op.getOperand(0), Op.getOperand(1));
10811 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10812 DAG.getValueType(VT));
10813 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10816 if (VT.getSizeInBits() == 16) {
10817 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10818 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10820 return DAG.getNode(
10821 ISD::TRUNCATE, dl, MVT::i16,
10822 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10823 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10824 Op.getOperand(1)));
10825 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10826 Op.getOperand(0), Op.getOperand(1));
10827 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10828 DAG.getValueType(VT));
10829 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10832 if (VT == MVT::f32) {
10833 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10834 // the result back to FR32 register. It's only worth matching if the
10835 // result has a single use which is a store or a bitcast to i32. And in
10836 // the case of a store, it's not worth it if the index is a constant 0,
10837 // because a MOVSSmr can be used instead, which is smaller and faster.
10838 if (!Op.hasOneUse())
10840 SDNode *User = *Op.getNode()->use_begin();
10841 if ((User->getOpcode() != ISD::STORE ||
10842 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10843 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10844 (User->getOpcode() != ISD::BITCAST ||
10845 User->getValueType(0) != MVT::i32))
10847 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10848 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10850 return DAG.getBitcast(MVT::f32, Extract);
10853 if (VT == MVT::i32 || VT == MVT::i64) {
10854 // ExtractPS/pextrq works with constant index.
10855 if (isa<ConstantSDNode>(Op.getOperand(1)))
10861 /// Extract one bit from mask vector, like v16i1 or v8i1.
10862 /// AVX-512 feature.
10864 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10865 SDValue Vec = Op.getOperand(0);
10867 MVT VecVT = Vec.getSimpleValueType();
10868 SDValue Idx = Op.getOperand(1);
10869 MVT EltVT = Op.getSimpleValueType();
10871 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10872 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10873 "Unexpected vector type in ExtractBitFromMaskVector");
10875 // variable index can't be handled in mask registers,
10876 // extend vector to VR512
10877 if (!isa<ConstantSDNode>(Idx)) {
10878 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10879 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10880 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10881 ExtVT.getVectorElementType(), Ext, Idx);
10882 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10885 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10886 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10887 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10888 rc = getRegClassFor(MVT::v16i1);
10889 unsigned MaxSift = rc->getSize()*8 - 1;
10890 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10891 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10892 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10893 DAG.getConstant(MaxSift, dl, MVT::i8));
10894 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10895 DAG.getIntPtrConstant(0, dl));
10899 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10900 SelectionDAG &DAG) const {
10902 SDValue Vec = Op.getOperand(0);
10903 MVT VecVT = Vec.getSimpleValueType();
10904 SDValue Idx = Op.getOperand(1);
10906 if (Op.getSimpleValueType() == MVT::i1)
10907 return ExtractBitFromMaskVector(Op, DAG);
10909 if (!isa<ConstantSDNode>(Idx)) {
10910 if (VecVT.is512BitVector() ||
10911 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10912 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10915 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10916 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10917 MaskEltVT.getSizeInBits());
10919 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10920 auto PtrVT = getPointerTy(DAG.getDataLayout());
10921 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10922 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10923 DAG.getConstant(0, dl, PtrVT));
10924 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10925 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10926 DAG.getConstant(0, dl, PtrVT));
10931 // If this is a 256-bit vector result, first extract the 128-bit vector and
10932 // then extract the element from the 128-bit vector.
10933 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10935 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10936 // Get the 128-bit vector.
10937 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10938 MVT EltVT = VecVT.getVectorElementType();
10940 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10942 //if (IdxVal >= NumElems/2)
10943 // IdxVal -= NumElems/2;
10944 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10945 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10946 DAG.getConstant(IdxVal, dl, MVT::i32));
10949 assert(VecVT.is128BitVector() && "Unexpected vector length");
10951 if (Subtarget->hasSSE41())
10952 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10955 MVT VT = Op.getSimpleValueType();
10956 // TODO: handle v16i8.
10957 if (VT.getSizeInBits() == 16) {
10958 SDValue Vec = Op.getOperand(0);
10959 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10961 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10962 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10963 DAG.getBitcast(MVT::v4i32, Vec),
10964 Op.getOperand(1)));
10965 // Transform it so it match pextrw which produces a 32-bit result.
10966 MVT EltVT = MVT::i32;
10967 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10968 Op.getOperand(0), Op.getOperand(1));
10969 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10970 DAG.getValueType(VT));
10971 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10974 if (VT.getSizeInBits() == 32) {
10975 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10979 // SHUFPS the element to the lowest double word, then movss.
10980 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10981 MVT VVT = Op.getOperand(0).getSimpleValueType();
10982 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10983 DAG.getUNDEF(VVT), Mask);
10984 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10985 DAG.getIntPtrConstant(0, dl));
10988 if (VT.getSizeInBits() == 64) {
10989 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10990 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10991 // to match extract_elt for f64.
10992 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10996 // UNPCKHPD the element to the lowest double word, then movsd.
10997 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10998 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10999 int Mask[2] = { 1, -1 };
11000 MVT VVT = Op.getOperand(0).getSimpleValueType();
11001 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11002 DAG.getUNDEF(VVT), Mask);
11003 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11004 DAG.getIntPtrConstant(0, dl));
11010 /// Insert one bit to mask vector, like v16i1 or v8i1.
11011 /// AVX-512 feature.
11013 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11015 SDValue Vec = Op.getOperand(0);
11016 SDValue Elt = Op.getOperand(1);
11017 SDValue Idx = Op.getOperand(2);
11018 MVT VecVT = Vec.getSimpleValueType();
11020 if (!isa<ConstantSDNode>(Idx)) {
11021 // Non constant index. Extend source and destination,
11022 // insert element and then truncate the result.
11023 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11024 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11025 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11026 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11027 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11028 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11031 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11032 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11034 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11035 DAG.getConstant(IdxVal, dl, MVT::i8));
11036 if (Vec.getOpcode() == ISD::UNDEF)
11038 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11041 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11042 SelectionDAG &DAG) const {
11043 MVT VT = Op.getSimpleValueType();
11044 MVT EltVT = VT.getVectorElementType();
11046 if (EltVT == MVT::i1)
11047 return InsertBitToMaskVector(Op, DAG);
11050 SDValue N0 = Op.getOperand(0);
11051 SDValue N1 = Op.getOperand(1);
11052 SDValue N2 = Op.getOperand(2);
11053 if (!isa<ConstantSDNode>(N2))
11055 auto *N2C = cast<ConstantSDNode>(N2);
11056 unsigned IdxVal = N2C->getZExtValue();
11058 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11059 // into that, and then insert the subvector back into the result.
11060 if (VT.is256BitVector() || VT.is512BitVector()) {
11061 // With a 256-bit vector, we can insert into the zero element efficiently
11062 // using a blend if we have AVX or AVX2 and the right data type.
11063 if (VT.is256BitVector() && IdxVal == 0) {
11064 // TODO: It is worthwhile to cast integer to floating point and back
11065 // and incur a domain crossing penalty if that's what we'll end up
11066 // doing anyway after extracting to a 128-bit vector.
11067 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11068 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11069 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11070 N2 = DAG.getIntPtrConstant(1, dl);
11071 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11075 // Get the desired 128-bit vector chunk.
11076 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11078 // Insert the element into the desired chunk.
11079 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11080 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11082 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11083 DAG.getConstant(IdxIn128, dl, MVT::i32));
11085 // Insert the changed part back into the bigger vector
11086 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11088 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11090 if (Subtarget->hasSSE41()) {
11091 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11093 if (VT == MVT::v8i16) {
11094 Opc = X86ISD::PINSRW;
11096 assert(VT == MVT::v16i8);
11097 Opc = X86ISD::PINSRB;
11100 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11102 if (N1.getValueType() != MVT::i32)
11103 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11104 if (N2.getValueType() != MVT::i32)
11105 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11106 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11109 if (EltVT == MVT::f32) {
11110 // Bits [7:6] of the constant are the source select. This will always be
11111 // zero here. The DAG Combiner may combine an extract_elt index into
11112 // these bits. For example (insert (extract, 3), 2) could be matched by
11113 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11114 // Bits [5:4] of the constant are the destination select. This is the
11115 // value of the incoming immediate.
11116 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11117 // combine either bitwise AND or insert of float 0.0 to set these bits.
11119 const Function *F = DAG.getMachineFunction().getFunction();
11120 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11121 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11122 // If this is an insertion of 32-bits into the low 32-bits of
11123 // a vector, we prefer to generate a blend with immediate rather
11124 // than an insertps. Blends are simpler operations in hardware and so
11125 // will always have equal or better performance than insertps.
11126 // But if optimizing for size and there's a load folding opportunity,
11127 // generate insertps because blendps does not have a 32-bit memory
11129 N2 = DAG.getIntPtrConstant(1, dl);
11130 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11131 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11133 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11134 // Create this as a scalar to vector..
11135 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11136 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11139 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11140 // PINSR* works with constant index.
11145 if (EltVT == MVT::i8)
11148 if (EltVT.getSizeInBits() == 16) {
11149 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11150 // as its second argument.
11151 if (N1.getValueType() != MVT::i32)
11152 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11153 if (N2.getValueType() != MVT::i32)
11154 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11155 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11160 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11162 MVT OpVT = Op.getSimpleValueType();
11164 // If this is a 256-bit vector result, first insert into a 128-bit
11165 // vector and then insert into the 256-bit vector.
11166 if (!OpVT.is128BitVector()) {
11167 // Insert into a 128-bit vector.
11168 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11169 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11170 OpVT.getVectorNumElements() / SizeFactor);
11172 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11174 // Insert the 128-bit vector.
11175 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11178 if (OpVT == MVT::v1i64 &&
11179 Op.getOperand(0).getValueType() == MVT::i64)
11180 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11182 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11183 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11184 return DAG.getBitcast(
11185 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11188 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11189 // a simple subregister reference or explicit instructions to grab
11190 // upper bits of a vector.
11191 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11192 SelectionDAG &DAG) {
11194 SDValue In = Op.getOperand(0);
11195 SDValue Idx = Op.getOperand(1);
11196 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11197 MVT ResVT = Op.getSimpleValueType();
11198 MVT InVT = In.getSimpleValueType();
11200 if (Subtarget->hasFp256()) {
11201 if (ResVT.is128BitVector() &&
11202 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11203 isa<ConstantSDNode>(Idx)) {
11204 return Extract128BitVector(In, IdxVal, DAG, dl);
11206 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11207 isa<ConstantSDNode>(Idx)) {
11208 return Extract256BitVector(In, IdxVal, DAG, dl);
11214 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11215 // simple superregister reference or explicit instructions to insert
11216 // the upper bits of a vector.
11217 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11218 SelectionDAG &DAG) {
11219 if (!Subtarget->hasAVX())
11223 SDValue Vec = Op.getOperand(0);
11224 SDValue SubVec = Op.getOperand(1);
11225 SDValue Idx = Op.getOperand(2);
11227 if (!isa<ConstantSDNode>(Idx))
11230 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11231 MVT OpVT = Op.getSimpleValueType();
11232 MVT SubVecVT = SubVec.getSimpleValueType();
11234 // Fold two 16-byte subvector loads into one 32-byte load:
11235 // (insert_subvector (insert_subvector undef, (load addr), 0),
11236 // (load addr + 16), Elts/2)
11238 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11239 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11240 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11241 !Subtarget->isUnalignedMem32Slow()) {
11242 SDValue SubVec2 = Vec.getOperand(1);
11243 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11244 if (Idx2->getZExtValue() == 0) {
11245 SDValue Ops[] = { SubVec2, SubVec };
11246 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11252 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11253 SubVecVT.is128BitVector())
11254 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11256 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11257 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11259 if (OpVT.getVectorElementType() == MVT::i1) {
11260 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11262 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11263 SDValue Undef = DAG.getUNDEF(OpVT);
11264 unsigned NumElems = OpVT.getVectorNumElements();
11265 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11267 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11268 // Zero upper bits of the Vec
11269 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11270 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11272 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11274 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11275 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11278 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11280 // Zero upper bits of the Vec2
11281 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11282 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11283 // Zero lower bits of the Vec
11284 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11285 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11286 // Merge them together
11287 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11293 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11294 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11295 // one of the above mentioned nodes. It has to be wrapped because otherwise
11296 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11297 // be used to form addressing mode. These wrapped nodes will be selected
11300 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11301 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11303 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11304 // global base reg.
11305 unsigned char OpFlag = 0;
11306 unsigned WrapperKind = X86ISD::Wrapper;
11307 CodeModel::Model M = DAG.getTarget().getCodeModel();
11309 if (Subtarget->isPICStyleRIPRel() &&
11310 (M == CodeModel::Small || M == CodeModel::Kernel))
11311 WrapperKind = X86ISD::WrapperRIP;
11312 else if (Subtarget->isPICStyleGOT())
11313 OpFlag = X86II::MO_GOTOFF;
11314 else if (Subtarget->isPICStyleStubPIC())
11315 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11317 auto PtrVT = getPointerTy(DAG.getDataLayout());
11318 SDValue Result = DAG.getTargetConstantPool(
11319 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11321 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11322 // With PIC, the address is actually $g + Offset.
11325 DAG.getNode(ISD::ADD, DL, PtrVT,
11326 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11332 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11333 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11335 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11336 // global base reg.
11337 unsigned char OpFlag = 0;
11338 unsigned WrapperKind = X86ISD::Wrapper;
11339 CodeModel::Model M = DAG.getTarget().getCodeModel();
11341 if (Subtarget->isPICStyleRIPRel() &&
11342 (M == CodeModel::Small || M == CodeModel::Kernel))
11343 WrapperKind = X86ISD::WrapperRIP;
11344 else if (Subtarget->isPICStyleGOT())
11345 OpFlag = X86II::MO_GOTOFF;
11346 else if (Subtarget->isPICStyleStubPIC())
11347 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11349 auto PtrVT = getPointerTy(DAG.getDataLayout());
11350 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11352 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11354 // With PIC, the address is actually $g + Offset.
11357 DAG.getNode(ISD::ADD, DL, PtrVT,
11358 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11364 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11365 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11367 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11368 // global base reg.
11369 unsigned char OpFlag = 0;
11370 unsigned WrapperKind = X86ISD::Wrapper;
11371 CodeModel::Model M = DAG.getTarget().getCodeModel();
11373 if (Subtarget->isPICStyleRIPRel() &&
11374 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11375 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11376 OpFlag = X86II::MO_GOTPCREL;
11377 WrapperKind = X86ISD::WrapperRIP;
11378 } else if (Subtarget->isPICStyleGOT()) {
11379 OpFlag = X86II::MO_GOT;
11380 } else if (Subtarget->isPICStyleStubPIC()) {
11381 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11382 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11383 OpFlag = X86II::MO_DARWIN_NONLAZY;
11386 auto PtrVT = getPointerTy(DAG.getDataLayout());
11387 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11390 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11392 // With PIC, the address is actually $g + Offset.
11393 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11394 !Subtarget->is64Bit()) {
11396 DAG.getNode(ISD::ADD, DL, PtrVT,
11397 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11400 // For symbols that require a load from a stub to get the address, emit the
11402 if (isGlobalStubReference(OpFlag))
11403 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11404 MachinePointerInfo::getGOT(), false, false, false, 0);
11410 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11411 // Create the TargetBlockAddressAddress node.
11412 unsigned char OpFlags =
11413 Subtarget->ClassifyBlockAddressReference();
11414 CodeModel::Model M = DAG.getTarget().getCodeModel();
11415 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11416 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11418 auto PtrVT = getPointerTy(DAG.getDataLayout());
11419 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11421 if (Subtarget->isPICStyleRIPRel() &&
11422 (M == CodeModel::Small || M == CodeModel::Kernel))
11423 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11425 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11427 // With PIC, the address is actually $g + Offset.
11428 if (isGlobalRelativeToPICBase(OpFlags)) {
11429 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11430 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11437 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11438 int64_t Offset, SelectionDAG &DAG) const {
11439 // Create the TargetGlobalAddress node, folding in the constant
11440 // offset if it is legal.
11441 unsigned char OpFlags =
11442 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11443 CodeModel::Model M = DAG.getTarget().getCodeModel();
11444 auto PtrVT = getPointerTy(DAG.getDataLayout());
11446 if (OpFlags == X86II::MO_NO_FLAG &&
11447 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11448 // A direct static reference to a global.
11449 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11452 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11455 if (Subtarget->isPICStyleRIPRel() &&
11456 (M == CodeModel::Small || M == CodeModel::Kernel))
11457 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11459 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11461 // With PIC, the address is actually $g + Offset.
11462 if (isGlobalRelativeToPICBase(OpFlags)) {
11463 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11464 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11467 // For globals that require a load from a stub to get the address, emit the
11469 if (isGlobalStubReference(OpFlags))
11470 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11471 MachinePointerInfo::getGOT(), false, false, false, 0);
11473 // If there was a non-zero offset that we didn't fold, create an explicit
11474 // addition for it.
11476 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11477 DAG.getConstant(Offset, dl, PtrVT));
11483 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11484 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11485 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11486 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11490 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11491 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11492 unsigned char OperandFlags, bool LocalDynamic = false) {
11493 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11494 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11496 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11497 GA->getValueType(0),
11501 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11505 SDValue Ops[] = { Chain, TGA, *InFlag };
11506 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11508 SDValue Ops[] = { Chain, TGA };
11509 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11512 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11513 MFI->setAdjustsStack(true);
11514 MFI->setHasCalls(true);
11516 SDValue Flag = Chain.getValue(1);
11517 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11520 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11522 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11525 SDLoc dl(GA); // ? function entry point might be better
11526 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11527 DAG.getNode(X86ISD::GlobalBaseReg,
11528 SDLoc(), PtrVT), InFlag);
11529 InFlag = Chain.getValue(1);
11531 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11534 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11536 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11538 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11539 X86::RAX, X86II::MO_TLSGD);
11542 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11548 // Get the start address of the TLS block for this module.
11549 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11550 .getInfo<X86MachineFunctionInfo>();
11551 MFI->incNumLocalDynamicTLSAccesses();
11555 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11556 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11559 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11560 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11561 InFlag = Chain.getValue(1);
11562 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11563 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11566 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11570 unsigned char OperandFlags = X86II::MO_DTPOFF;
11571 unsigned WrapperKind = X86ISD::Wrapper;
11572 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11573 GA->getValueType(0),
11574 GA->getOffset(), OperandFlags);
11575 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11577 // Add x@dtpoff with the base.
11578 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11581 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11582 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11583 const EVT PtrVT, TLSModel::Model model,
11584 bool is64Bit, bool isPIC) {
11587 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11588 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11589 is64Bit ? 257 : 256));
11591 SDValue ThreadPointer =
11592 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11593 MachinePointerInfo(Ptr), false, false, false, 0);
11595 unsigned char OperandFlags = 0;
11596 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11598 unsigned WrapperKind = X86ISD::Wrapper;
11599 if (model == TLSModel::LocalExec) {
11600 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11601 } else if (model == TLSModel::InitialExec) {
11603 OperandFlags = X86II::MO_GOTTPOFF;
11604 WrapperKind = X86ISD::WrapperRIP;
11606 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11609 llvm_unreachable("Unexpected model");
11612 // emit "addl x@ntpoff,%eax" (local exec)
11613 // or "addl x@indntpoff,%eax" (initial exec)
11614 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11616 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11617 GA->getOffset(), OperandFlags);
11618 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11620 if (model == TLSModel::InitialExec) {
11621 if (isPIC && !is64Bit) {
11622 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11623 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11627 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11628 MachinePointerInfo::getGOT(), false, false, false, 0);
11631 // The address of the thread local variable is the add of the thread
11632 // pointer with the offset of the variable.
11633 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11637 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11639 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11640 const GlobalValue *GV = GA->getGlobal();
11641 auto PtrVT = getPointerTy(DAG.getDataLayout());
11643 if (Subtarget->isTargetELF()) {
11644 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11646 case TLSModel::GeneralDynamic:
11647 if (Subtarget->is64Bit())
11648 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11649 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11650 case TLSModel::LocalDynamic:
11651 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11652 Subtarget->is64Bit());
11653 case TLSModel::InitialExec:
11654 case TLSModel::LocalExec:
11655 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11656 DAG.getTarget().getRelocationModel() ==
11659 llvm_unreachable("Unknown TLS model.");
11662 if (Subtarget->isTargetDarwin()) {
11663 // Darwin only has one model of TLS. Lower to that.
11664 unsigned char OpFlag = 0;
11665 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11666 X86ISD::WrapperRIP : X86ISD::Wrapper;
11668 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11669 // global base reg.
11670 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11671 !Subtarget->is64Bit();
11673 OpFlag = X86II::MO_TLVP_PIC_BASE;
11675 OpFlag = X86II::MO_TLVP;
11677 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11678 GA->getValueType(0),
11679 GA->getOffset(), OpFlag);
11680 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11682 // With PIC32, the address is actually $g + Offset.
11684 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11685 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11688 // Lowering the machine isd will make sure everything is in the right
11690 SDValue Chain = DAG.getEntryNode();
11691 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11692 SDValue Args[] = { Chain, Offset };
11693 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11695 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11696 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11697 MFI->setAdjustsStack(true);
11699 // And our return value (tls address) is in the standard call return value
11701 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11702 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11705 if (Subtarget->isTargetKnownWindowsMSVC() ||
11706 Subtarget->isTargetWindowsGNU()) {
11707 // Just use the implicit TLS architecture
11708 // Need to generate someting similar to:
11709 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11711 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11712 // mov rcx, qword [rdx+rcx*8]
11713 // mov eax, .tls$:tlsvar
11714 // [rax+rcx] contains the address
11715 // Windows 64bit: gs:0x58
11716 // Windows 32bit: fs:__tls_array
11719 SDValue Chain = DAG.getEntryNode();
11721 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11722 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11723 // use its literal value of 0x2C.
11724 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11725 ? Type::getInt8PtrTy(*DAG.getContext(),
11727 : Type::getInt32PtrTy(*DAG.getContext(),
11730 SDValue TlsArray = Subtarget->is64Bit()
11731 ? DAG.getIntPtrConstant(0x58, dl)
11732 : (Subtarget->isTargetWindowsGNU()
11733 ? DAG.getIntPtrConstant(0x2C, dl)
11734 : DAG.getExternalSymbol("_tls_array", PtrVT));
11736 SDValue ThreadPointer =
11737 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11741 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11742 res = ThreadPointer;
11744 // Load the _tls_index variable
11745 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11746 if (Subtarget->is64Bit())
11747 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11748 MachinePointerInfo(), MVT::i32, false, false,
11751 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11754 auto &DL = DAG.getDataLayout();
11756 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11757 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11759 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11762 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11765 // Get the offset of start of .tls section
11766 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11767 GA->getValueType(0),
11768 GA->getOffset(), X86II::MO_SECREL);
11769 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11771 // The address of the thread local variable is the add of the thread
11772 // pointer with the offset of the variable.
11773 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11776 llvm_unreachable("TLS not implemented for this target.");
11779 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11780 /// and take a 2 x i32 value to shift plus a shift amount.
11781 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11782 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11783 MVT VT = Op.getSimpleValueType();
11784 unsigned VTBits = VT.getSizeInBits();
11786 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11787 SDValue ShOpLo = Op.getOperand(0);
11788 SDValue ShOpHi = Op.getOperand(1);
11789 SDValue ShAmt = Op.getOperand(2);
11790 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11791 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11793 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11794 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11795 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11796 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11797 : DAG.getConstant(0, dl, VT);
11799 SDValue Tmp2, Tmp3;
11800 if (Op.getOpcode() == ISD::SHL_PARTS) {
11801 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11802 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11804 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11805 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11808 // If the shift amount is larger or equal than the width of a part we can't
11809 // rely on the results of shld/shrd. Insert a test and select the appropriate
11810 // values for large shift amounts.
11811 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11812 DAG.getConstant(VTBits, dl, MVT::i8));
11813 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11814 AndNode, DAG.getConstant(0, dl, MVT::i8));
11817 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11818 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11819 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11821 if (Op.getOpcode() == ISD::SHL_PARTS) {
11822 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11823 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11825 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11826 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11829 SDValue Ops[2] = { Lo, Hi };
11830 return DAG.getMergeValues(Ops, dl);
11833 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11834 SelectionDAG &DAG) const {
11835 SDValue Src = Op.getOperand(0);
11836 MVT SrcVT = Src.getSimpleValueType();
11837 MVT VT = Op.getSimpleValueType();
11840 if (SrcVT.isVector()) {
11841 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11842 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11843 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11844 DAG.getUNDEF(SrcVT)));
11846 if (SrcVT.getVectorElementType() == MVT::i1) {
11847 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11848 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11849 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11854 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11855 "Unknown SINT_TO_FP to lower!");
11857 // These are really Legal; return the operand so the caller accepts it as
11859 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11861 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11862 Subtarget->is64Bit()) {
11866 unsigned Size = SrcVT.getSizeInBits()/8;
11867 MachineFunction &MF = DAG.getMachineFunction();
11868 auto PtrVT = getPointerTy(MF.getDataLayout());
11869 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11870 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11871 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11873 MachinePointerInfo::getFixedStack(SSFI),
11875 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11878 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11880 SelectionDAG &DAG) const {
11884 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11886 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11888 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11890 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11892 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11893 MachineMemOperand *MMO;
11895 int SSFI = FI->getIndex();
11897 DAG.getMachineFunction()
11898 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11899 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11901 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11902 StackSlot = StackSlot.getOperand(1);
11904 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11905 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11907 Tys, Ops, SrcVT, MMO);
11910 Chain = Result.getValue(1);
11911 SDValue InFlag = Result.getValue(2);
11913 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11914 // shouldn't be necessary except that RFP cannot be live across
11915 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11916 MachineFunction &MF = DAG.getMachineFunction();
11917 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11918 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11919 auto PtrVT = getPointerTy(MF.getDataLayout());
11920 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11921 Tys = DAG.getVTList(MVT::Other);
11923 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11925 MachineMemOperand *MMO =
11926 DAG.getMachineFunction()
11927 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11928 MachineMemOperand::MOStore, SSFISize, SSFISize);
11930 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11931 Ops, Op.getValueType(), MMO);
11932 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11933 MachinePointerInfo::getFixedStack(SSFI),
11934 false, false, false, 0);
11940 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11941 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11942 SelectionDAG &DAG) const {
11943 // This algorithm is not obvious. Here it is what we're trying to output:
11946 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11947 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11949 haddpd %xmm0, %xmm0
11951 pshufd $0x4e, %xmm0, %xmm1
11957 LLVMContext *Context = DAG.getContext();
11959 // Build some magic constants.
11960 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11961 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11962 auto PtrVT = getPointerTy(DAG.getDataLayout());
11963 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11965 SmallVector<Constant*,2> CV1;
11967 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11968 APInt(64, 0x4330000000000000ULL))));
11970 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11971 APInt(64, 0x4530000000000000ULL))));
11972 Constant *C1 = ConstantVector::get(CV1);
11973 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11975 // Load the 64-bit value into an XMM register.
11976 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11978 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11979 MachinePointerInfo::getConstantPool(),
11980 false, false, false, 16);
11982 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11984 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11985 MachinePointerInfo::getConstantPool(),
11986 false, false, false, 16);
11987 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11988 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11991 if (Subtarget->hasSSE3()) {
11992 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11993 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11995 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11996 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11998 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11999 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12002 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12003 DAG.getIntPtrConstant(0, dl));
12006 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12007 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12008 SelectionDAG &DAG) const {
12010 // FP constant to bias correct the final result.
12011 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12014 // Load the 32-bit value into an XMM register.
12015 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12018 // Zero out the upper parts of the register.
12019 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12021 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12022 DAG.getBitcast(MVT::v2f64, Load),
12023 DAG.getIntPtrConstant(0, dl));
12025 // Or the load with the bias.
12026 SDValue Or = DAG.getNode(
12027 ISD::OR, dl, MVT::v2i64,
12028 DAG.getBitcast(MVT::v2i64,
12029 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12030 DAG.getBitcast(MVT::v2i64,
12031 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12033 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12034 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12036 // Subtract the bias.
12037 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12039 // Handle final rounding.
12040 EVT DestVT = Op.getValueType();
12042 if (DestVT.bitsLT(MVT::f64))
12043 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12044 DAG.getIntPtrConstant(0, dl));
12045 if (DestVT.bitsGT(MVT::f64))
12046 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12048 // Handle final rounding.
12052 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12053 const X86Subtarget &Subtarget) {
12054 // The algorithm is the following:
12055 // #ifdef __SSE4_1__
12056 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12057 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12058 // (uint4) 0x53000000, 0xaa);
12060 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12061 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12063 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12064 // return (float4) lo + fhi;
12067 SDValue V = Op->getOperand(0);
12068 EVT VecIntVT = V.getValueType();
12069 bool Is128 = VecIntVT == MVT::v4i32;
12070 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12071 // If we convert to something else than the supported type, e.g., to v4f64,
12073 if (VecFloatVT != Op->getValueType(0))
12076 unsigned NumElts = VecIntVT.getVectorNumElements();
12077 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12078 "Unsupported custom type");
12079 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12081 // In the #idef/#else code, we have in common:
12082 // - The vector of constants:
12088 // Create the splat vector for 0x4b000000.
12089 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12090 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12091 CstLow, CstLow, CstLow, CstLow};
12092 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12093 makeArrayRef(&CstLowArray[0], NumElts));
12094 // Create the splat vector for 0x53000000.
12095 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12096 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12097 CstHigh, CstHigh, CstHigh, CstHigh};
12098 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12099 makeArrayRef(&CstHighArray[0], NumElts));
12101 // Create the right shift.
12102 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12103 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12104 CstShift, CstShift, CstShift, CstShift};
12105 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12106 makeArrayRef(&CstShiftArray[0], NumElts));
12107 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12110 if (Subtarget.hasSSE41()) {
12111 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12112 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12113 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12114 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12115 // Low will be bitcasted right away, so do not bother bitcasting back to its
12117 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12118 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12119 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12120 // (uint4) 0x53000000, 0xaa);
12121 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12122 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12123 // High will be bitcasted right away, so do not bother bitcasting back to
12124 // its original type.
12125 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12126 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12128 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12129 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12130 CstMask, CstMask, CstMask);
12131 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12132 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12133 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12135 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12136 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12139 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12140 SDValue CstFAdd = DAG.getConstantFP(
12141 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12142 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12143 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12144 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12145 makeArrayRef(&CstFAddArray[0], NumElts));
12147 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12148 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12150 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12151 // return (float4) lo + fhi;
12152 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12153 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12156 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12157 SelectionDAG &DAG) const {
12158 SDValue N0 = Op.getOperand(0);
12159 MVT SVT = N0.getSimpleValueType();
12162 switch (SVT.SimpleTy) {
12164 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12169 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12170 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12171 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12175 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12178 if (Subtarget->hasAVX512())
12179 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12180 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12182 llvm_unreachable(nullptr);
12185 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12186 SelectionDAG &DAG) const {
12187 SDValue N0 = Op.getOperand(0);
12189 auto PtrVT = getPointerTy(DAG.getDataLayout());
12191 if (Op.getValueType().isVector())
12192 return lowerUINT_TO_FP_vec(Op, DAG);
12194 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12195 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12196 // the optimization here.
12197 if (DAG.SignBitIsZero(N0))
12198 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12200 MVT SrcVT = N0.getSimpleValueType();
12201 MVT DstVT = Op.getSimpleValueType();
12202 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12203 return LowerUINT_TO_FP_i64(Op, DAG);
12204 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12205 return LowerUINT_TO_FP_i32(Op, DAG);
12206 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12209 // Make a 64-bit buffer, and use it to build an FILD.
12210 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12211 if (SrcVT == MVT::i32) {
12212 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12213 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12214 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12215 StackSlot, MachinePointerInfo(),
12217 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12218 OffsetSlot, MachinePointerInfo(),
12220 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12224 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12225 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12226 StackSlot, MachinePointerInfo(),
12228 // For i64 source, we need to add the appropriate power of 2 if the input
12229 // was negative. This is the same as the optimization in
12230 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12231 // we must be careful to do the computation in x87 extended precision, not
12232 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12233 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12234 MachineMemOperand *MMO =
12235 DAG.getMachineFunction()
12236 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12237 MachineMemOperand::MOLoad, 8, 8);
12239 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12240 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12241 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12244 APInt FF(32, 0x5F800000ULL);
12246 // Check whether the sign bit is set.
12247 SDValue SignSet = DAG.getSetCC(
12248 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12249 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12251 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12252 SDValue FudgePtr = DAG.getConstantPool(
12253 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12255 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12256 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12257 SDValue Four = DAG.getIntPtrConstant(4, dl);
12258 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12260 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12262 // Load the value out, extending it from f32 to f80.
12263 // FIXME: Avoid the extend by constructing the right constant pool?
12264 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12265 FudgePtr, MachinePointerInfo::getConstantPool(),
12266 MVT::f32, false, false, false, 4);
12267 // Extend everything to 80 bits to force it to be done on x87.
12268 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12269 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12270 DAG.getIntPtrConstant(0, dl));
12273 std::pair<SDValue,SDValue>
12274 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12275 bool IsSigned, bool IsReplace) const {
12278 EVT DstTy = Op.getValueType();
12279 auto PtrVT = getPointerTy(DAG.getDataLayout());
12281 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12282 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12286 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12287 DstTy.getSimpleVT() >= MVT::i16 &&
12288 "Unknown FP_TO_INT to lower!");
12290 // These are really Legal.
12291 if (DstTy == MVT::i32 &&
12292 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12293 return std::make_pair(SDValue(), SDValue());
12294 if (Subtarget->is64Bit() &&
12295 DstTy == MVT::i64 &&
12296 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12297 return std::make_pair(SDValue(), SDValue());
12299 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12300 // stack slot, or into the FTOL runtime function.
12301 MachineFunction &MF = DAG.getMachineFunction();
12302 unsigned MemSize = DstTy.getSizeInBits()/8;
12303 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12304 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12307 if (!IsSigned && isIntegerTypeFTOL(DstTy))
12308 Opc = X86ISD::WIN_FTOL;
12310 switch (DstTy.getSimpleVT().SimpleTy) {
12311 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12312 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12313 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12314 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12317 SDValue Chain = DAG.getEntryNode();
12318 SDValue Value = Op.getOperand(0);
12319 EVT TheVT = Op.getOperand(0).getValueType();
12320 // FIXME This causes a redundant load/store if the SSE-class value is already
12321 // in memory, such as if it is on the callstack.
12322 if (isScalarFPTypeInSSEReg(TheVT)) {
12323 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12324 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12325 MachinePointerInfo::getFixedStack(SSFI),
12327 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12329 Chain, StackSlot, DAG.getValueType(TheVT)
12332 MachineMemOperand *MMO =
12333 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12334 MachineMemOperand::MOLoad, MemSize, MemSize);
12335 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12336 Chain = Value.getValue(1);
12337 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12338 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12341 MachineMemOperand *MMO =
12342 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12343 MachineMemOperand::MOStore, MemSize, MemSize);
12345 if (Opc != X86ISD::WIN_FTOL) {
12346 // Build the FP_TO_INT*_IN_MEM
12347 SDValue Ops[] = { Chain, Value, StackSlot };
12348 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12350 return std::make_pair(FIST, StackSlot);
12352 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12353 DAG.getVTList(MVT::Other, MVT::Glue),
12355 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12356 MVT::i32, ftol.getValue(1));
12357 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12358 MVT::i32, eax.getValue(2));
12359 SDValue Ops[] = { eax, edx };
12360 SDValue pair = IsReplace
12361 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12362 : DAG.getMergeValues(Ops, DL);
12363 return std::make_pair(pair, SDValue());
12367 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12368 const X86Subtarget *Subtarget) {
12369 MVT VT = Op->getSimpleValueType(0);
12370 SDValue In = Op->getOperand(0);
12371 MVT InVT = In.getSimpleValueType();
12374 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12375 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12377 // Optimize vectors in AVX mode:
12380 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12381 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12382 // Concat upper and lower parts.
12385 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12386 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12387 // Concat upper and lower parts.
12390 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12391 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12392 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12395 if (Subtarget->hasInt256())
12396 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12398 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12399 SDValue Undef = DAG.getUNDEF(InVT);
12400 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12401 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12402 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12404 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12405 VT.getVectorNumElements()/2);
12407 OpLo = DAG.getBitcast(HVT, OpLo);
12408 OpHi = DAG.getBitcast(HVT, OpHi);
12410 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12413 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12414 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12415 MVT VT = Op->getSimpleValueType(0);
12416 SDValue In = Op->getOperand(0);
12417 MVT InVT = In.getSimpleValueType();
12419 unsigned int NumElts = VT.getVectorNumElements();
12420 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12423 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12424 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12426 assert(InVT.getVectorElementType() == MVT::i1);
12427 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12429 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12431 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12433 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12434 if (VT.is512BitVector())
12436 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12439 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12440 SelectionDAG &DAG) {
12441 if (Subtarget->hasFp256())
12442 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12448 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12449 SelectionDAG &DAG) {
12451 MVT VT = Op.getSimpleValueType();
12452 SDValue In = Op.getOperand(0);
12453 MVT SVT = In.getSimpleValueType();
12455 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12456 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12458 if (Subtarget->hasFp256())
12459 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12462 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12463 VT.getVectorNumElements() != SVT.getVectorNumElements());
12467 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12469 MVT VT = Op.getSimpleValueType();
12470 SDValue In = Op.getOperand(0);
12471 MVT InVT = In.getSimpleValueType();
12473 if (VT == MVT::i1) {
12474 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12475 "Invalid scalar TRUNCATE operation");
12476 if (InVT.getSizeInBits() >= 32)
12478 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12479 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12481 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12482 "Invalid TRUNCATE operation");
12484 // move vector to mask - truncate solution for SKX
12485 if (VT.getVectorElementType() == MVT::i1) {
12486 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12487 Subtarget->hasBWI())
12488 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12489 if ((InVT.is256BitVector() || InVT.is128BitVector())
12490 && InVT.getScalarSizeInBits() <= 16 &&
12491 Subtarget->hasBWI() && Subtarget->hasVLX())
12492 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12493 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12494 Subtarget->hasDQI())
12495 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12496 if ((InVT.is256BitVector() || InVT.is128BitVector())
12497 && InVT.getScalarSizeInBits() >= 32 &&
12498 Subtarget->hasDQI() && Subtarget->hasVLX())
12499 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12502 if (VT.getVectorElementType() == MVT::i1) {
12503 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12504 unsigned NumElts = InVT.getVectorNumElements();
12505 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12506 if (InVT.getSizeInBits() < 512) {
12507 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12508 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12513 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12514 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12515 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12518 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12519 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12520 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12521 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12523 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12524 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12525 if (Subtarget->hasInt256()) {
12526 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12527 In = DAG.getBitcast(MVT::v8i32, In);
12528 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12530 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12531 DAG.getIntPtrConstant(0, DL));
12534 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12535 DAG.getIntPtrConstant(0, DL));
12536 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12537 DAG.getIntPtrConstant(2, DL));
12538 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12539 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12540 static const int ShufMask[] = {0, 2, 4, 6};
12541 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12544 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12545 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12546 if (Subtarget->hasInt256()) {
12547 In = DAG.getBitcast(MVT::v32i8, In);
12549 SmallVector<SDValue,32> pshufbMask;
12550 for (unsigned i = 0; i < 2; ++i) {
12551 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12552 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12553 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12554 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12555 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12556 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12557 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12558 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12559 for (unsigned j = 0; j < 8; ++j)
12560 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12562 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12563 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12564 In = DAG.getBitcast(MVT::v4i64, In);
12566 static const int ShufMask[] = {0, 2, -1, -1};
12567 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12569 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12570 DAG.getIntPtrConstant(0, DL));
12571 return DAG.getBitcast(VT, In);
12574 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12575 DAG.getIntPtrConstant(0, DL));
12577 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12578 DAG.getIntPtrConstant(4, DL));
12580 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12581 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12583 // The PSHUFB mask:
12584 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12585 -1, -1, -1, -1, -1, -1, -1, -1};
12587 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12588 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12589 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12591 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12592 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12594 // The MOVLHPS Mask:
12595 static const int ShufMask2[] = {0, 1, 4, 5};
12596 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12597 return DAG.getBitcast(MVT::v8i16, res);
12600 // Handle truncation of V256 to V128 using shuffles.
12601 if (!VT.is128BitVector() || !InVT.is256BitVector())
12604 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12606 unsigned NumElems = VT.getVectorNumElements();
12607 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12609 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12610 // Prepare truncation shuffle mask
12611 for (unsigned i = 0; i != NumElems; ++i)
12612 MaskVec[i] = i * 2;
12613 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12614 DAG.getUNDEF(NVT), &MaskVec[0]);
12615 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12616 DAG.getIntPtrConstant(0, DL));
12619 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12620 SelectionDAG &DAG) const {
12621 assert(!Op.getSimpleValueType().isVector());
12623 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12624 /*IsSigned=*/ true, /*IsReplace=*/ false);
12625 SDValue FIST = Vals.first, StackSlot = Vals.second;
12626 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12627 if (!FIST.getNode()) return Op;
12629 if (StackSlot.getNode())
12630 // Load the result.
12631 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12632 FIST, StackSlot, MachinePointerInfo(),
12633 false, false, false, 0);
12635 // The node is the result.
12639 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12640 SelectionDAG &DAG) const {
12641 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12642 /*IsSigned=*/ false, /*IsReplace=*/ false);
12643 SDValue FIST = Vals.first, StackSlot = Vals.second;
12644 assert(FIST.getNode() && "Unexpected failure");
12646 if (StackSlot.getNode())
12647 // Load the result.
12648 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12649 FIST, StackSlot, MachinePointerInfo(),
12650 false, false, false, 0);
12652 // The node is the result.
12656 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12658 MVT VT = Op.getSimpleValueType();
12659 SDValue In = Op.getOperand(0);
12660 MVT SVT = In.getSimpleValueType();
12662 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12664 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12665 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12666 In, DAG.getUNDEF(SVT)));
12669 /// The only differences between FABS and FNEG are the mask and the logic op.
12670 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12671 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12672 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12673 "Wrong opcode for lowering FABS or FNEG.");
12675 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12677 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12678 // into an FNABS. We'll lower the FABS after that if it is still in use.
12680 for (SDNode *User : Op->uses())
12681 if (User->getOpcode() == ISD::FNEG)
12684 SDValue Op0 = Op.getOperand(0);
12685 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12688 MVT VT = Op.getSimpleValueType();
12689 // Assume scalar op for initialization; update for vector if needed.
12690 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12691 // generate a 16-byte vector constant and logic op even for the scalar case.
12692 // Using a 16-byte mask allows folding the load of the mask with
12693 // the logic op, so it can save (~4 bytes) on code size.
12695 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12696 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12697 // decide if we should generate a 16-byte constant mask when we only need 4 or
12698 // 8 bytes for the scalar case.
12699 if (VT.isVector()) {
12700 EltVT = VT.getVectorElementType();
12701 NumElts = VT.getVectorNumElements();
12704 unsigned EltBits = EltVT.getSizeInBits();
12705 LLVMContext *Context = DAG.getContext();
12706 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12708 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12709 Constant *C = ConstantInt::get(*Context, MaskElt);
12710 C = ConstantVector::getSplat(NumElts, C);
12711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12712 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12713 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12714 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12715 MachinePointerInfo::getConstantPool(),
12716 false, false, false, Alignment);
12718 if (VT.isVector()) {
12719 // For a vector, cast operands to a vector type, perform the logic op,
12720 // and cast the result back to the original value type.
12721 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12722 SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12723 SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12724 : DAG.getBitcast(VecVT, Op0);
12725 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12726 return DAG.getBitcast(VT,
12727 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12730 // If not vector, then scalar.
12731 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12732 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12733 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12736 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12738 LLVMContext *Context = DAG.getContext();
12739 SDValue Op0 = Op.getOperand(0);
12740 SDValue Op1 = Op.getOperand(1);
12742 MVT VT = Op.getSimpleValueType();
12743 MVT SrcVT = Op1.getSimpleValueType();
12745 // If second operand is smaller, extend it first.
12746 if (SrcVT.bitsLT(VT)) {
12747 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12750 // And if it is bigger, shrink it first.
12751 if (SrcVT.bitsGT(VT)) {
12752 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12756 // At this point the operands and the result should have the same
12757 // type, and that won't be f80 since that is not custom lowered.
12759 const fltSemantics &Sem =
12760 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12761 const unsigned SizeInBits = VT.getSizeInBits();
12763 SmallVector<Constant *, 4> CV(
12764 VT == MVT::f64 ? 2 : 4,
12765 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12767 // First, clear all bits but the sign bit from the second operand (sign).
12768 CV[0] = ConstantFP::get(*Context,
12769 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12770 Constant *C = ConstantVector::get(CV);
12771 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12772 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12773 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12774 MachinePointerInfo::getConstantPool(),
12775 false, false, false, 16);
12776 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12778 // Next, clear the sign bit from the first operand (magnitude).
12779 // If it's a constant, we can clear it here.
12780 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12781 APFloat APF = Op0CN->getValueAPF();
12782 // If the magnitude is a positive zero, the sign bit alone is enough.
12783 if (APF.isPosZero())
12786 CV[0] = ConstantFP::get(*Context, APF);
12788 CV[0] = ConstantFP::get(
12790 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12792 C = ConstantVector::get(CV);
12793 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12794 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12795 MachinePointerInfo::getConstantPool(),
12796 false, false, false, 16);
12797 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12798 if (!isa<ConstantFPSDNode>(Op0))
12799 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12801 // OR the magnitude value with the sign bit.
12802 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12805 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12806 SDValue N0 = Op.getOperand(0);
12808 MVT VT = Op.getSimpleValueType();
12810 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12811 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12812 DAG.getConstant(1, dl, VT));
12813 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12816 // Check whether an OR'd tree is PTEST-able.
12817 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12818 SelectionDAG &DAG) {
12819 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12821 if (!Subtarget->hasSSE41())
12824 if (!Op->hasOneUse())
12827 SDNode *N = Op.getNode();
12830 SmallVector<SDValue, 8> Opnds;
12831 DenseMap<SDValue, unsigned> VecInMap;
12832 SmallVector<SDValue, 8> VecIns;
12833 EVT VT = MVT::Other;
12835 // Recognize a special case where a vector is casted into wide integer to
12837 Opnds.push_back(N->getOperand(0));
12838 Opnds.push_back(N->getOperand(1));
12840 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12841 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12842 // BFS traverse all OR'd operands.
12843 if (I->getOpcode() == ISD::OR) {
12844 Opnds.push_back(I->getOperand(0));
12845 Opnds.push_back(I->getOperand(1));
12846 // Re-evaluate the number of nodes to be traversed.
12847 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12851 // Quit if a non-EXTRACT_VECTOR_ELT
12852 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12855 // Quit if without a constant index.
12856 SDValue Idx = I->getOperand(1);
12857 if (!isa<ConstantSDNode>(Idx))
12860 SDValue ExtractedFromVec = I->getOperand(0);
12861 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12862 if (M == VecInMap.end()) {
12863 VT = ExtractedFromVec.getValueType();
12864 // Quit if not 128/256-bit vector.
12865 if (!VT.is128BitVector() && !VT.is256BitVector())
12867 // Quit if not the same type.
12868 if (VecInMap.begin() != VecInMap.end() &&
12869 VT != VecInMap.begin()->first.getValueType())
12871 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12872 VecIns.push_back(ExtractedFromVec);
12874 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12877 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12878 "Not extracted from 128-/256-bit vector.");
12880 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12882 for (DenseMap<SDValue, unsigned>::const_iterator
12883 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12884 // Quit if not all elements are used.
12885 if (I->second != FullMask)
12889 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12891 // Cast all vectors into TestVT for PTEST.
12892 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12893 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12895 // If more than one full vectors are evaluated, OR them first before PTEST.
12896 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12897 // Each iteration will OR 2 nodes and append the result until there is only
12898 // 1 node left, i.e. the final OR'd value of all vectors.
12899 SDValue LHS = VecIns[Slot];
12900 SDValue RHS = VecIns[Slot + 1];
12901 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12904 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12905 VecIns.back(), VecIns.back());
12908 /// \brief return true if \c Op has a use that doesn't just read flags.
12909 static bool hasNonFlagsUse(SDValue Op) {
12910 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12912 SDNode *User = *UI;
12913 unsigned UOpNo = UI.getOperandNo();
12914 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12915 // Look pass truncate.
12916 UOpNo = User->use_begin().getOperandNo();
12917 User = *User->use_begin();
12920 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12921 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12927 /// Emit nodes that will be selected as "test Op0,Op0", or something
12929 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12930 SelectionDAG &DAG) const {
12931 if (Op.getValueType() == MVT::i1) {
12932 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12933 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12934 DAG.getConstant(0, dl, MVT::i8));
12936 // CF and OF aren't always set the way we want. Determine which
12937 // of these we need.
12938 bool NeedCF = false;
12939 bool NeedOF = false;
12942 case X86::COND_A: case X86::COND_AE:
12943 case X86::COND_B: case X86::COND_BE:
12946 case X86::COND_G: case X86::COND_GE:
12947 case X86::COND_L: case X86::COND_LE:
12948 case X86::COND_O: case X86::COND_NO: {
12949 // Check if we really need to set the
12950 // Overflow flag. If NoSignedWrap is present
12951 // that is not actually needed.
12952 switch (Op->getOpcode()) {
12957 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12958 if (BinNode->Flags.hasNoSignedWrap())
12968 // See if we can use the EFLAGS value from the operand instead of
12969 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12970 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12971 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12972 // Emit a CMP with 0, which is the TEST pattern.
12973 //if (Op.getValueType() == MVT::i1)
12974 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12975 // DAG.getConstant(0, MVT::i1));
12976 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12977 DAG.getConstant(0, dl, Op.getValueType()));
12979 unsigned Opcode = 0;
12980 unsigned NumOperands = 0;
12982 // Truncate operations may prevent the merge of the SETCC instruction
12983 // and the arithmetic instruction before it. Attempt to truncate the operands
12984 // of the arithmetic instruction and use a reduced bit-width instruction.
12985 bool NeedTruncation = false;
12986 SDValue ArithOp = Op;
12987 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12988 SDValue Arith = Op->getOperand(0);
12989 // Both the trunc and the arithmetic op need to have one user each.
12990 if (Arith->hasOneUse())
12991 switch (Arith.getOpcode()) {
12998 NeedTruncation = true;
13004 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13005 // which may be the result of a CAST. We use the variable 'Op', which is the
13006 // non-casted variable when we check for possible users.
13007 switch (ArithOp.getOpcode()) {
13009 // Due to an isel shortcoming, be conservative if this add is likely to be
13010 // selected as part of a load-modify-store instruction. When the root node
13011 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13012 // uses of other nodes in the match, such as the ADD in this case. This
13013 // leads to the ADD being left around and reselected, with the result being
13014 // two adds in the output. Alas, even if none our users are stores, that
13015 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13016 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13017 // climbing the DAG back to the root, and it doesn't seem to be worth the
13019 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13020 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13021 if (UI->getOpcode() != ISD::CopyToReg &&
13022 UI->getOpcode() != ISD::SETCC &&
13023 UI->getOpcode() != ISD::STORE)
13026 if (ConstantSDNode *C =
13027 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13028 // An add of one will be selected as an INC.
13029 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13030 Opcode = X86ISD::INC;
13035 // An add of negative one (subtract of one) will be selected as a DEC.
13036 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13037 Opcode = X86ISD::DEC;
13043 // Otherwise use a regular EFLAGS-setting add.
13044 Opcode = X86ISD::ADD;
13049 // If we have a constant logical shift that's only used in a comparison
13050 // against zero turn it into an equivalent AND. This allows turning it into
13051 // a TEST instruction later.
13052 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13053 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13054 EVT VT = Op.getValueType();
13055 unsigned BitWidth = VT.getSizeInBits();
13056 unsigned ShAmt = Op->getConstantOperandVal(1);
13057 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13059 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13060 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13061 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13062 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13064 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13065 DAG.getConstant(Mask, dl, VT));
13066 DAG.ReplaceAllUsesWith(Op, New);
13072 // If the primary and result isn't used, don't bother using X86ISD::AND,
13073 // because a TEST instruction will be better.
13074 if (!hasNonFlagsUse(Op))
13080 // Due to the ISEL shortcoming noted above, be conservative if this op is
13081 // likely to be selected as part of a load-modify-store instruction.
13082 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13083 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13084 if (UI->getOpcode() == ISD::STORE)
13087 // Otherwise use a regular EFLAGS-setting instruction.
13088 switch (ArithOp.getOpcode()) {
13089 default: llvm_unreachable("unexpected operator!");
13090 case ISD::SUB: Opcode = X86ISD::SUB; break;
13091 case ISD::XOR: Opcode = X86ISD::XOR; break;
13092 case ISD::AND: Opcode = X86ISD::AND; break;
13094 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13095 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13096 if (EFLAGS.getNode())
13099 Opcode = X86ISD::OR;
13113 return SDValue(Op.getNode(), 1);
13119 // If we found that truncation is beneficial, perform the truncation and
13121 if (NeedTruncation) {
13122 EVT VT = Op.getValueType();
13123 SDValue WideVal = Op->getOperand(0);
13124 EVT WideVT = WideVal.getValueType();
13125 unsigned ConvertedOp = 0;
13126 // Use a target machine opcode to prevent further DAGCombine
13127 // optimizations that may separate the arithmetic operations
13128 // from the setcc node.
13129 switch (WideVal.getOpcode()) {
13131 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13132 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13133 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13134 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13135 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13140 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13141 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13142 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13143 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13149 // Emit a CMP with 0, which is the TEST pattern.
13150 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13151 DAG.getConstant(0, dl, Op.getValueType()));
13153 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13154 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13156 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13157 DAG.ReplaceAllUsesWith(Op, New);
13158 return SDValue(New.getNode(), 1);
13161 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13163 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13164 SDLoc dl, SelectionDAG &DAG) const {
13165 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13166 if (C->getAPIntValue() == 0)
13167 return EmitTest(Op0, X86CC, dl, DAG);
13169 if (Op0.getValueType() == MVT::i1)
13170 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13173 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13174 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13175 // Do the comparison at i32 if it's smaller, besides the Atom case.
13176 // This avoids subregister aliasing issues. Keep the smaller reference
13177 // if we're optimizing for size, however, as that'll allow better folding
13178 // of memory operations.
13179 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13180 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13181 Attribute::MinSize) &&
13182 !Subtarget->isAtom()) {
13183 unsigned ExtendOp =
13184 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13185 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13186 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13188 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13189 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13190 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13192 return SDValue(Sub.getNode(), 1);
13194 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13197 /// Convert a comparison if required by the subtarget.
13198 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13199 SelectionDAG &DAG) const {
13200 // If the subtarget does not support the FUCOMI instruction, floating-point
13201 // comparisons have to be converted.
13202 if (Subtarget->hasCMov() ||
13203 Cmp.getOpcode() != X86ISD::CMP ||
13204 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13205 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13208 // The instruction selector will select an FUCOM instruction instead of
13209 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13210 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13211 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13213 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13214 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13215 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13216 DAG.getConstant(8, dl, MVT::i8));
13217 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13218 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13221 /// The minimum architected relative accuracy is 2^-12. We need one
13222 /// Newton-Raphson step to have a good float result (24 bits of precision).
13223 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13224 DAGCombinerInfo &DCI,
13225 unsigned &RefinementSteps,
13226 bool &UseOneConstNR) const {
13227 EVT VT = Op.getValueType();
13228 const char *RecipOp;
13230 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13231 // TODO: Add support for AVX512 (v16f32).
13232 // It is likely not profitable to do this for f64 because a double-precision
13233 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13234 // instructions: convert to single, rsqrtss, convert back to double, refine
13235 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13236 // along with FMA, this could be a throughput win.
13237 if (VT == MVT::f32 && Subtarget->hasSSE1())
13239 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13240 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13241 RecipOp = "vec-sqrtf";
13245 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13246 if (!Recips.isEnabled(RecipOp))
13249 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13250 UseOneConstNR = false;
13251 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13254 /// The minimum architected relative accuracy is 2^-12. We need one
13255 /// Newton-Raphson step to have a good float result (24 bits of precision).
13256 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13257 DAGCombinerInfo &DCI,
13258 unsigned &RefinementSteps) const {
13259 EVT VT = Op.getValueType();
13260 const char *RecipOp;
13262 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13263 // TODO: Add support for AVX512 (v16f32).
13264 // It is likely not profitable to do this for f64 because a double-precision
13265 // reciprocal estimate with refinement on x86 prior to FMA requires
13266 // 15 instructions: convert to single, rcpss, convert back to double, refine
13267 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13268 // along with FMA, this could be a throughput win.
13269 if (VT == MVT::f32 && Subtarget->hasSSE1())
13271 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13272 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13273 RecipOp = "vec-divf";
13277 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13278 if (!Recips.isEnabled(RecipOp))
13281 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13282 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13285 /// If we have at least two divisions that use the same divisor, convert to
13286 /// multplication by a reciprocal. This may need to be adjusted for a given
13287 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13288 /// This is because we still need one division to calculate the reciprocal and
13289 /// then we need two multiplies by that reciprocal as replacements for the
13290 /// original divisions.
13291 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13292 return NumUsers > 1;
13295 static bool isAllOnes(SDValue V) {
13296 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13297 return C && C->isAllOnesValue();
13300 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13301 /// if it's possible.
13302 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13303 SDLoc dl, SelectionDAG &DAG) const {
13304 SDValue Op0 = And.getOperand(0);
13305 SDValue Op1 = And.getOperand(1);
13306 if (Op0.getOpcode() == ISD::TRUNCATE)
13307 Op0 = Op0.getOperand(0);
13308 if (Op1.getOpcode() == ISD::TRUNCATE)
13309 Op1 = Op1.getOperand(0);
13312 if (Op1.getOpcode() == ISD::SHL)
13313 std::swap(Op0, Op1);
13314 if (Op0.getOpcode() == ISD::SHL) {
13315 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13316 if (And00C->getZExtValue() == 1) {
13317 // If we looked past a truncate, check that it's only truncating away
13319 unsigned BitWidth = Op0.getValueSizeInBits();
13320 unsigned AndBitWidth = And.getValueSizeInBits();
13321 if (BitWidth > AndBitWidth) {
13323 DAG.computeKnownBits(Op0, Zeros, Ones);
13324 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13328 RHS = Op0.getOperand(1);
13330 } else if (Op1.getOpcode() == ISD::Constant) {
13331 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13332 uint64_t AndRHSVal = AndRHS->getZExtValue();
13333 SDValue AndLHS = Op0;
13335 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13336 LHS = AndLHS.getOperand(0);
13337 RHS = AndLHS.getOperand(1);
13340 // Use BT if the immediate can't be encoded in a TEST instruction.
13341 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13343 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13347 if (LHS.getNode()) {
13348 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13349 // instruction. Since the shift amount is in-range-or-undefined, we know
13350 // that doing a bittest on the i32 value is ok. We extend to i32 because
13351 // the encoding for the i16 version is larger than the i32 version.
13352 // Also promote i16 to i32 for performance / code size reason.
13353 if (LHS.getValueType() == MVT::i8 ||
13354 LHS.getValueType() == MVT::i16)
13355 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13357 // If the operand types disagree, extend the shift amount to match. Since
13358 // BT ignores high bits (like shifts) we can use anyextend.
13359 if (LHS.getValueType() != RHS.getValueType())
13360 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13362 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13363 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13364 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13365 DAG.getConstant(Cond, dl, MVT::i8), BT);
13371 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13373 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13378 // SSE Condition code mapping:
13387 switch (SetCCOpcode) {
13388 default: llvm_unreachable("Unexpected SETCC condition");
13390 case ISD::SETEQ: SSECC = 0; break;
13392 case ISD::SETGT: Swap = true; // Fallthrough
13394 case ISD::SETOLT: SSECC = 1; break;
13396 case ISD::SETGE: Swap = true; // Fallthrough
13398 case ISD::SETOLE: SSECC = 2; break;
13399 case ISD::SETUO: SSECC = 3; break;
13401 case ISD::SETNE: SSECC = 4; break;
13402 case ISD::SETULE: Swap = true; // Fallthrough
13403 case ISD::SETUGE: SSECC = 5; break;
13404 case ISD::SETULT: Swap = true; // Fallthrough
13405 case ISD::SETUGT: SSECC = 6; break;
13406 case ISD::SETO: SSECC = 7; break;
13408 case ISD::SETONE: SSECC = 8; break;
13411 std::swap(Op0, Op1);
13416 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13417 // ones, and then concatenate the result back.
13418 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13419 MVT VT = Op.getSimpleValueType();
13421 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13422 "Unsupported value type for operation");
13424 unsigned NumElems = VT.getVectorNumElements();
13426 SDValue CC = Op.getOperand(2);
13428 // Extract the LHS vectors
13429 SDValue LHS = Op.getOperand(0);
13430 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13431 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13433 // Extract the RHS vectors
13434 SDValue RHS = Op.getOperand(1);
13435 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13436 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13438 // Issue the operation on the smaller types and concatenate the result back
13439 MVT EltVT = VT.getVectorElementType();
13440 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13441 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13442 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13443 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13446 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13447 SDValue Op0 = Op.getOperand(0);
13448 SDValue Op1 = Op.getOperand(1);
13449 SDValue CC = Op.getOperand(2);
13450 MVT VT = Op.getSimpleValueType();
13453 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13454 "Unexpected type for boolean compare operation");
13455 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13456 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13457 DAG.getConstant(-1, dl, VT));
13458 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13459 DAG.getConstant(-1, dl, VT));
13460 switch (SetCCOpcode) {
13461 default: llvm_unreachable("Unexpected SETCC condition");
13463 // (x == y) -> ~(x ^ y)
13464 return DAG.getNode(ISD::XOR, dl, VT,
13465 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13466 DAG.getConstant(-1, dl, VT));
13468 // (x != y) -> (x ^ y)
13469 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13472 // (x > y) -> (x & ~y)
13473 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13476 // (x < y) -> (~x & y)
13477 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13480 // (x <= y) -> (~x | y)
13481 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13484 // (x >=y) -> (x | ~y)
13485 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13489 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13490 const X86Subtarget *Subtarget) {
13491 SDValue Op0 = Op.getOperand(0);
13492 SDValue Op1 = Op.getOperand(1);
13493 SDValue CC = Op.getOperand(2);
13494 MVT VT = Op.getSimpleValueType();
13497 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13498 Op.getValueType().getScalarType() == MVT::i1 &&
13499 "Cannot set masked compare for this operation");
13501 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13503 bool Unsigned = false;
13506 switch (SetCCOpcode) {
13507 default: llvm_unreachable("Unexpected SETCC condition");
13508 case ISD::SETNE: SSECC = 4; break;
13509 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13510 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13511 case ISD::SETLT: Swap = true; //fall-through
13512 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13513 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13514 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13515 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13516 case ISD::SETULE: Unsigned = true; //fall-through
13517 case ISD::SETLE: SSECC = 2; break;
13521 std::swap(Op0, Op1);
13523 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13524 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13525 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13526 DAG.getConstant(SSECC, dl, MVT::i8));
13529 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13530 /// operand \p Op1. If non-trivial (for example because it's not constant)
13531 /// return an empty value.
13532 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13534 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13538 MVT VT = Op1.getSimpleValueType();
13539 MVT EVT = VT.getVectorElementType();
13540 unsigned n = VT.getVectorNumElements();
13541 SmallVector<SDValue, 8> ULTOp1;
13543 for (unsigned i = 0; i < n; ++i) {
13544 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13545 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13548 // Avoid underflow.
13549 APInt Val = Elt->getAPIntValue();
13553 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13556 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13559 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13560 SelectionDAG &DAG) {
13561 SDValue Op0 = Op.getOperand(0);
13562 SDValue Op1 = Op.getOperand(1);
13563 SDValue CC = Op.getOperand(2);
13564 MVT VT = Op.getSimpleValueType();
13565 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13566 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13571 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13572 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13575 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13576 unsigned Opc = X86ISD::CMPP;
13577 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13578 assert(VT.getVectorNumElements() <= 16);
13579 Opc = X86ISD::CMPM;
13581 // In the two special cases we can't handle, emit two comparisons.
13584 unsigned CombineOpc;
13585 if (SetCCOpcode == ISD::SETUEQ) {
13586 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13588 assert(SetCCOpcode == ISD::SETONE);
13589 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13592 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13593 DAG.getConstant(CC0, dl, MVT::i8));
13594 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13595 DAG.getConstant(CC1, dl, MVT::i8));
13596 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13598 // Handle all other FP comparisons here.
13599 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13600 DAG.getConstant(SSECC, dl, MVT::i8));
13603 // Break 256-bit integer vector compare into smaller ones.
13604 if (VT.is256BitVector() && !Subtarget->hasInt256())
13605 return Lower256IntVSETCC(Op, DAG);
13607 EVT OpVT = Op1.getValueType();
13608 if (OpVT.getVectorElementType() == MVT::i1)
13609 return LowerBoolVSETCC_AVX512(Op, DAG);
13611 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13612 if (Subtarget->hasAVX512()) {
13613 if (Op1.getValueType().is512BitVector() ||
13614 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13615 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13616 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13618 // In AVX-512 architecture setcc returns mask with i1 elements,
13619 // But there is no compare instruction for i8 and i16 elements in KNL.
13620 // We are not talking about 512-bit operands in this case, these
13621 // types are illegal.
13623 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13624 OpVT.getVectorElementType().getSizeInBits() >= 8))
13625 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13626 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13629 // We are handling one of the integer comparisons here. Since SSE only has
13630 // GT and EQ comparisons for integer, swapping operands and multiple
13631 // operations may be required for some comparisons.
13633 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13634 bool Subus = false;
13636 switch (SetCCOpcode) {
13637 default: llvm_unreachable("Unexpected SETCC condition");
13638 case ISD::SETNE: Invert = true;
13639 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13640 case ISD::SETLT: Swap = true;
13641 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13642 case ISD::SETGE: Swap = true;
13643 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13644 Invert = true; break;
13645 case ISD::SETULT: Swap = true;
13646 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13647 FlipSigns = true; break;
13648 case ISD::SETUGE: Swap = true;
13649 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13650 FlipSigns = true; Invert = true; break;
13653 // Special case: Use min/max operations for SETULE/SETUGE
13654 MVT VET = VT.getVectorElementType();
13656 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13657 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13660 switch (SetCCOpcode) {
13662 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13663 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13666 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13669 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13670 if (!MinMax && hasSubus) {
13671 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13673 // t = psubus Op0, Op1
13674 // pcmpeq t, <0..0>
13675 switch (SetCCOpcode) {
13677 case ISD::SETULT: {
13678 // If the comparison is against a constant we can turn this into a
13679 // setule. With psubus, setule does not require a swap. This is
13680 // beneficial because the constant in the register is no longer
13681 // destructed as the destination so it can be hoisted out of a loop.
13682 // Only do this pre-AVX since vpcmp* is no longer destructive.
13683 if (Subtarget->hasAVX())
13685 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13686 if (ULEOp1.getNode()) {
13688 Subus = true; Invert = false; Swap = false;
13692 // Psubus is better than flip-sign because it requires no inversion.
13693 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13694 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13698 Opc = X86ISD::SUBUS;
13704 std::swap(Op0, Op1);
13706 // Check that the operation in question is available (most are plain SSE2,
13707 // but PCMPGTQ and PCMPEQQ have different requirements).
13708 if (VT == MVT::v2i64) {
13709 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13710 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13712 // First cast everything to the right type.
13713 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13714 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13716 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13717 // bits of the inputs before performing those operations. The lower
13718 // compare is always unsigned.
13721 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13723 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13724 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13725 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13726 Sign, Zero, Sign, Zero);
13728 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13729 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13731 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13732 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13733 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13735 // Create masks for only the low parts/high parts of the 64 bit integers.
13736 static const int MaskHi[] = { 1, 1, 3, 3 };
13737 static const int MaskLo[] = { 0, 0, 2, 2 };
13738 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13739 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13740 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13742 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13743 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13746 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13748 return DAG.getBitcast(VT, Result);
13751 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13752 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13753 // pcmpeqd + pshufd + pand.
13754 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13756 // First cast everything to the right type.
13757 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13758 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13761 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13763 // Make sure the lower and upper halves are both all-ones.
13764 static const int Mask[] = { 1, 0, 3, 2 };
13765 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13766 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13769 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13771 return DAG.getBitcast(VT, Result);
13775 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13776 // bits of the inputs before performing those operations.
13778 EVT EltVT = VT.getVectorElementType();
13779 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13781 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13782 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13785 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13787 // If the logical-not of the result is required, perform that now.
13789 Result = DAG.getNOT(dl, Result, VT);
13792 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13795 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13796 getZeroVector(VT, Subtarget, DAG, dl));
13801 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13803 MVT VT = Op.getSimpleValueType();
13805 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13807 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13808 && "SetCC type must be 8-bit or 1-bit integer");
13809 SDValue Op0 = Op.getOperand(0);
13810 SDValue Op1 = Op.getOperand(1);
13812 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13814 // Optimize to BT if possible.
13815 // Lower (X & (1 << N)) == 0 to BT(X, N).
13816 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13817 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13818 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13819 Op1.getOpcode() == ISD::Constant &&
13820 cast<ConstantSDNode>(Op1)->isNullValue() &&
13821 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13822 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13823 if (NewSetCC.getNode()) {
13825 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13830 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13832 if (Op1.getOpcode() == ISD::Constant &&
13833 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13834 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13835 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13837 // If the input is a setcc, then reuse the input setcc or use a new one with
13838 // the inverted condition.
13839 if (Op0.getOpcode() == X86ISD::SETCC) {
13840 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13841 bool Invert = (CC == ISD::SETNE) ^
13842 cast<ConstantSDNode>(Op1)->isNullValue();
13846 CCode = X86::GetOppositeBranchCondition(CCode);
13847 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13848 DAG.getConstant(CCode, dl, MVT::i8),
13849 Op0.getOperand(1));
13851 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13855 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13856 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13857 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13859 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13860 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13863 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13864 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13865 if (X86CC == X86::COND_INVALID)
13868 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13869 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13870 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13871 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13873 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13877 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13878 static bool isX86LogicalCmp(SDValue Op) {
13879 unsigned Opc = Op.getNode()->getOpcode();
13880 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13881 Opc == X86ISD::SAHF)
13883 if (Op.getResNo() == 1 &&
13884 (Opc == X86ISD::ADD ||
13885 Opc == X86ISD::SUB ||
13886 Opc == X86ISD::ADC ||
13887 Opc == X86ISD::SBB ||
13888 Opc == X86ISD::SMUL ||
13889 Opc == X86ISD::UMUL ||
13890 Opc == X86ISD::INC ||
13891 Opc == X86ISD::DEC ||
13892 Opc == X86ISD::OR ||
13893 Opc == X86ISD::XOR ||
13894 Opc == X86ISD::AND))
13897 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13903 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13904 if (V.getOpcode() != ISD::TRUNCATE)
13907 SDValue VOp0 = V.getOperand(0);
13908 unsigned InBits = VOp0.getValueSizeInBits();
13909 unsigned Bits = V.getValueSizeInBits();
13910 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13913 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13914 bool addTest = true;
13915 SDValue Cond = Op.getOperand(0);
13916 SDValue Op1 = Op.getOperand(1);
13917 SDValue Op2 = Op.getOperand(2);
13919 EVT VT = Op1.getValueType();
13922 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13923 // are available or VBLENDV if AVX is available.
13924 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13925 if (Cond.getOpcode() == ISD::SETCC &&
13926 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13927 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13928 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13929 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13930 int SSECC = translateX86FSETCC(
13931 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13934 if (Subtarget->hasAVX512()) {
13935 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13936 DAG.getConstant(SSECC, DL, MVT::i8));
13937 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13940 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13941 DAG.getConstant(SSECC, DL, MVT::i8));
13943 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13944 // of 3 logic instructions for size savings and potentially speed.
13945 // Unfortunately, there is no scalar form of VBLENDV.
13947 // If either operand is a constant, don't try this. We can expect to
13948 // optimize away at least one of the logic instructions later in that
13949 // case, so that sequence would be faster than a variable blend.
13951 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13952 // uses XMM0 as the selection register. That may need just as many
13953 // instructions as the AND/ANDN/OR sequence due to register moves, so
13956 if (Subtarget->hasAVX() &&
13957 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13959 // Convert to vectors, do a VSELECT, and convert back to scalar.
13960 // All of the conversions should be optimized away.
13962 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13963 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13964 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13965 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13967 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13968 VCmp = DAG.getBitcast(VCmpVT, VCmp);
13970 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13972 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13973 VSel, DAG.getIntPtrConstant(0, DL));
13975 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13976 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13977 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13981 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13983 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13984 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
13985 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13986 Op1Scalar = Op1.getOperand(0);
13988 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13989 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
13990 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13991 Op2Scalar = Op2.getOperand(0);
13992 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13993 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13994 Op1Scalar.getValueType(),
13995 Cond, Op1Scalar, Op2Scalar);
13996 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13997 return DAG.getBitcast(VT, newSelect);
13998 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13999 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14000 DAG.getIntPtrConstant(0, DL));
14004 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14005 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14006 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14007 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14008 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14009 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14010 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14012 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14015 if (Cond.getOpcode() == ISD::SETCC) {
14016 SDValue NewCond = LowerSETCC(Cond, DAG);
14017 if (NewCond.getNode())
14021 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14022 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14023 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14024 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14025 if (Cond.getOpcode() == X86ISD::SETCC &&
14026 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14027 isZero(Cond.getOperand(1).getOperand(1))) {
14028 SDValue Cmp = Cond.getOperand(1);
14030 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14032 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14033 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14034 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14036 SDValue CmpOp0 = Cmp.getOperand(0);
14037 // Apply further optimizations for special cases
14038 // (select (x != 0), -1, 0) -> neg & sbb
14039 // (select (x == 0), 0, -1) -> neg & sbb
14040 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14041 if (YC->isNullValue() &&
14042 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14043 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14044 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14045 DAG.getConstant(0, DL,
14046 CmpOp0.getValueType()),
14048 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14049 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14050 SDValue(Neg.getNode(), 1));
14054 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14055 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14056 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14058 SDValue Res = // Res = 0 or -1.
14059 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14060 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14062 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14063 Res = DAG.getNOT(DL, Res, Res.getValueType());
14065 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14066 if (!N2C || !N2C->isNullValue())
14067 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14072 // Look past (and (setcc_carry (cmp ...)), 1).
14073 if (Cond.getOpcode() == ISD::AND &&
14074 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14075 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14076 if (C && C->getAPIntValue() == 1)
14077 Cond = Cond.getOperand(0);
14080 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14081 // setting operand in place of the X86ISD::SETCC.
14082 unsigned CondOpcode = Cond.getOpcode();
14083 if (CondOpcode == X86ISD::SETCC ||
14084 CondOpcode == X86ISD::SETCC_CARRY) {
14085 CC = Cond.getOperand(0);
14087 SDValue Cmp = Cond.getOperand(1);
14088 unsigned Opc = Cmp.getOpcode();
14089 MVT VT = Op.getSimpleValueType();
14091 bool IllegalFPCMov = false;
14092 if (VT.isFloatingPoint() && !VT.isVector() &&
14093 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14094 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14096 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14097 Opc == X86ISD::BT) { // FIXME
14101 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14102 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14103 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14104 Cond.getOperand(0).getValueType() != MVT::i8)) {
14105 SDValue LHS = Cond.getOperand(0);
14106 SDValue RHS = Cond.getOperand(1);
14107 unsigned X86Opcode;
14110 switch (CondOpcode) {
14111 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14112 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14113 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14114 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14115 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14116 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14117 default: llvm_unreachable("unexpected overflowing operator");
14119 if (CondOpcode == ISD::UMULO)
14120 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14123 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14125 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14127 if (CondOpcode == ISD::UMULO)
14128 Cond = X86Op.getValue(2);
14130 Cond = X86Op.getValue(1);
14132 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14137 // Look past the truncate if the high bits are known zero.
14138 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14139 Cond = Cond.getOperand(0);
14141 // We know the result of AND is compared against zero. Try to match
14143 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14144 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14145 if (NewSetCC.getNode()) {
14146 CC = NewSetCC.getOperand(0);
14147 Cond = NewSetCC.getOperand(1);
14154 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14155 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14158 // a < b ? -1 : 0 -> RES = ~setcc_carry
14159 // a < b ? 0 : -1 -> RES = setcc_carry
14160 // a >= b ? -1 : 0 -> RES = setcc_carry
14161 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14162 if (Cond.getOpcode() == X86ISD::SUB) {
14163 Cond = ConvertCmpIfNecessary(Cond, DAG);
14164 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14166 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14167 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14168 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14169 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14171 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14172 return DAG.getNOT(DL, Res, Res.getValueType());
14177 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14178 // widen the cmov and push the truncate through. This avoids introducing a new
14179 // branch during isel and doesn't add any extensions.
14180 if (Op.getValueType() == MVT::i8 &&
14181 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14182 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14183 if (T1.getValueType() == T2.getValueType() &&
14184 // Blacklist CopyFromReg to avoid partial register stalls.
14185 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14186 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14187 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14188 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14192 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14193 // condition is true.
14194 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14195 SDValue Ops[] = { Op2, Op1, CC, Cond };
14196 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14199 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14200 const X86Subtarget *Subtarget,
14201 SelectionDAG &DAG) {
14202 MVT VT = Op->getSimpleValueType(0);
14203 SDValue In = Op->getOperand(0);
14204 MVT InVT = In.getSimpleValueType();
14205 MVT VTElt = VT.getVectorElementType();
14206 MVT InVTElt = InVT.getVectorElementType();
14210 if ((InVTElt == MVT::i1) &&
14211 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14212 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14214 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14215 VTElt.getSizeInBits() <= 16)) ||
14217 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14218 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14220 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14221 VTElt.getSizeInBits() >= 32))))
14222 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14224 unsigned int NumElts = VT.getVectorNumElements();
14226 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14229 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14230 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14231 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14232 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14235 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14236 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14238 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14241 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14243 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14244 if (VT.is512BitVector())
14246 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14249 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14250 const X86Subtarget *Subtarget,
14251 SelectionDAG &DAG) {
14252 SDValue In = Op->getOperand(0);
14253 MVT VT = Op->getSimpleValueType(0);
14254 MVT InVT = In.getSimpleValueType();
14255 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14257 MVT InSVT = InVT.getScalarType();
14258 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14260 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14262 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14267 // SSE41 targets can use the pmovsx* instructions directly.
14268 if (Subtarget->hasSSE41())
14269 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14271 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14275 // As SRAI is only available on i16/i32 types, we expand only up to i32
14276 // and handle i64 separately.
14277 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14278 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14279 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14280 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14281 Curr = DAG.getBitcast(CurrVT, Curr);
14284 SDValue SignExt = Curr;
14285 if (CurrVT != InVT) {
14286 unsigned SignExtShift =
14287 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14288 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14289 DAG.getConstant(SignExtShift, dl, MVT::i8));
14295 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14296 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14297 DAG.getConstant(31, dl, MVT::i8));
14298 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14299 return DAG.getBitcast(VT, Ext);
14305 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14306 SelectionDAG &DAG) {
14307 MVT VT = Op->getSimpleValueType(0);
14308 SDValue In = Op->getOperand(0);
14309 MVT InVT = In.getSimpleValueType();
14312 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14313 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14315 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14316 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14317 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14320 if (Subtarget->hasInt256())
14321 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14323 // Optimize vectors in AVX mode
14324 // Sign extend v8i16 to v8i32 and
14327 // Divide input vector into two parts
14328 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14329 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14330 // concat the vectors to original VT
14332 unsigned NumElems = InVT.getVectorNumElements();
14333 SDValue Undef = DAG.getUNDEF(InVT);
14335 SmallVector<int,8> ShufMask1(NumElems, -1);
14336 for (unsigned i = 0; i != NumElems/2; ++i)
14339 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14341 SmallVector<int,8> ShufMask2(NumElems, -1);
14342 for (unsigned i = 0; i != NumElems/2; ++i)
14343 ShufMask2[i] = i + NumElems/2;
14345 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14347 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14348 VT.getVectorNumElements()/2);
14350 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14351 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14353 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14356 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14357 // may emit an illegal shuffle but the expansion is still better than scalar
14358 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14359 // we'll emit a shuffle and a arithmetic shift.
14360 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14361 // TODO: It is possible to support ZExt by zeroing the undef values during
14362 // the shuffle phase or after the shuffle.
14363 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14364 SelectionDAG &DAG) {
14365 MVT RegVT = Op.getSimpleValueType();
14366 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14367 assert(RegVT.isInteger() &&
14368 "We only custom lower integer vector sext loads.");
14370 // Nothing useful we can do without SSE2 shuffles.
14371 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14373 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14375 EVT MemVT = Ld->getMemoryVT();
14376 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14377 unsigned RegSz = RegVT.getSizeInBits();
14379 ISD::LoadExtType Ext = Ld->getExtensionType();
14381 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14382 && "Only anyext and sext are currently implemented.");
14383 assert(MemVT != RegVT && "Cannot extend to the same type");
14384 assert(MemVT.isVector() && "Must load a vector from memory");
14386 unsigned NumElems = RegVT.getVectorNumElements();
14387 unsigned MemSz = MemVT.getSizeInBits();
14388 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14390 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14391 // The only way in which we have a legal 256-bit vector result but not the
14392 // integer 256-bit operations needed to directly lower a sextload is if we
14393 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14394 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14395 // correctly legalized. We do this late to allow the canonical form of
14396 // sextload to persist throughout the rest of the DAG combiner -- it wants
14397 // to fold together any extensions it can, and so will fuse a sign_extend
14398 // of an sextload into a sextload targeting a wider value.
14400 if (MemSz == 128) {
14401 // Just switch this to a normal load.
14402 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14403 "it must be a legal 128-bit vector "
14405 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14406 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14407 Ld->isInvariant(), Ld->getAlignment());
14409 assert(MemSz < 128 &&
14410 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14411 // Do an sext load to a 128-bit vector type. We want to use the same
14412 // number of elements, but elements half as wide. This will end up being
14413 // recursively lowered by this routine, but will succeed as we definitely
14414 // have all the necessary features if we're using AVX1.
14416 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14417 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14419 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14420 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14421 Ld->isNonTemporal(), Ld->isInvariant(),
14422 Ld->getAlignment());
14425 // Replace chain users with the new chain.
14426 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14427 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14429 // Finally, do a normal sign-extend to the desired register.
14430 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14433 // All sizes must be a power of two.
14434 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14435 "Non-power-of-two elements are not custom lowered!");
14437 // Attempt to load the original value using scalar loads.
14438 // Find the largest scalar type that divides the total loaded size.
14439 MVT SclrLoadTy = MVT::i8;
14440 for (MVT Tp : MVT::integer_valuetypes()) {
14441 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14446 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14447 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14449 SclrLoadTy = MVT::f64;
14451 // Calculate the number of scalar loads that we need to perform
14452 // in order to load our vector from memory.
14453 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14455 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14456 "Can only lower sext loads with a single scalar load!");
14458 unsigned loadRegZize = RegSz;
14459 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14462 // Represent our vector as a sequence of elements which are the
14463 // largest scalar that we can load.
14464 EVT LoadUnitVecVT = EVT::getVectorVT(
14465 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14467 // Represent the data using the same element type that is stored in
14468 // memory. In practice, we ''widen'' MemVT.
14470 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14471 loadRegZize / MemVT.getScalarType().getSizeInBits());
14473 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14474 "Invalid vector type");
14476 // We can't shuffle using an illegal type.
14477 assert(TLI.isTypeLegal(WideVecVT) &&
14478 "We only lower types that form legal widened vector types");
14480 SmallVector<SDValue, 8> Chains;
14481 SDValue Ptr = Ld->getBasePtr();
14482 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14483 TLI.getPointerTy(DAG.getDataLayout()));
14484 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14486 for (unsigned i = 0; i < NumLoads; ++i) {
14487 // Perform a single load.
14488 SDValue ScalarLoad =
14489 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14490 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14491 Ld->getAlignment());
14492 Chains.push_back(ScalarLoad.getValue(1));
14493 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14494 // another round of DAGCombining.
14496 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14498 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14499 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14501 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14504 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14506 // Bitcast the loaded value to a vector of the original element type, in
14507 // the size of the target vector type.
14508 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14509 unsigned SizeRatio = RegSz / MemSz;
14511 if (Ext == ISD::SEXTLOAD) {
14512 // If we have SSE4.1, we can directly emit a VSEXT node.
14513 if (Subtarget->hasSSE41()) {
14514 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14515 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14519 // Otherwise we'll shuffle the small elements in the high bits of the
14520 // larger type and perform an arithmetic shift. If the shift is not legal
14521 // it's better to scalarize.
14522 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14523 "We can't implement a sext load without an arithmetic right shift!");
14525 // Redistribute the loaded elements into the different locations.
14526 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14527 for (unsigned i = 0; i != NumElems; ++i)
14528 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14530 SDValue Shuff = DAG.getVectorShuffle(
14531 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14533 Shuff = DAG.getBitcast(RegVT, Shuff);
14535 // Build the arithmetic shift.
14536 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14537 MemVT.getVectorElementType().getSizeInBits();
14539 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14540 DAG.getConstant(Amt, dl, RegVT));
14542 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14546 // Redistribute the loaded elements into the different locations.
14547 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14548 for (unsigned i = 0; i != NumElems; ++i)
14549 ShuffleVec[i * SizeRatio] = i;
14551 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14552 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14554 // Bitcast to the requested type.
14555 Shuff = DAG.getBitcast(RegVT, Shuff);
14556 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14560 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14561 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14562 // from the AND / OR.
14563 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14564 Opc = Op.getOpcode();
14565 if (Opc != ISD::OR && Opc != ISD::AND)
14567 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14568 Op.getOperand(0).hasOneUse() &&
14569 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14570 Op.getOperand(1).hasOneUse());
14573 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14574 // 1 and that the SETCC node has a single use.
14575 static bool isXor1OfSetCC(SDValue Op) {
14576 if (Op.getOpcode() != ISD::XOR)
14578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14579 if (N1C && N1C->getAPIntValue() == 1) {
14580 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14581 Op.getOperand(0).hasOneUse();
14586 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14587 bool addTest = true;
14588 SDValue Chain = Op.getOperand(0);
14589 SDValue Cond = Op.getOperand(1);
14590 SDValue Dest = Op.getOperand(2);
14593 bool Inverted = false;
14595 if (Cond.getOpcode() == ISD::SETCC) {
14596 // Check for setcc([su]{add,sub,mul}o == 0).
14597 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14598 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14599 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14600 Cond.getOperand(0).getResNo() == 1 &&
14601 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14602 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14603 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14604 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14605 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14606 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14608 Cond = Cond.getOperand(0);
14610 SDValue NewCond = LowerSETCC(Cond, DAG);
14611 if (NewCond.getNode())
14616 // FIXME: LowerXALUO doesn't handle these!!
14617 else if (Cond.getOpcode() == X86ISD::ADD ||
14618 Cond.getOpcode() == X86ISD::SUB ||
14619 Cond.getOpcode() == X86ISD::SMUL ||
14620 Cond.getOpcode() == X86ISD::UMUL)
14621 Cond = LowerXALUO(Cond, DAG);
14624 // Look pass (and (setcc_carry (cmp ...)), 1).
14625 if (Cond.getOpcode() == ISD::AND &&
14626 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14627 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14628 if (C && C->getAPIntValue() == 1)
14629 Cond = Cond.getOperand(0);
14632 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14633 // setting operand in place of the X86ISD::SETCC.
14634 unsigned CondOpcode = Cond.getOpcode();
14635 if (CondOpcode == X86ISD::SETCC ||
14636 CondOpcode == X86ISD::SETCC_CARRY) {
14637 CC = Cond.getOperand(0);
14639 SDValue Cmp = Cond.getOperand(1);
14640 unsigned Opc = Cmp.getOpcode();
14641 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14642 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14646 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14650 // These can only come from an arithmetic instruction with overflow,
14651 // e.g. SADDO, UADDO.
14652 Cond = Cond.getNode()->getOperand(1);
14658 CondOpcode = Cond.getOpcode();
14659 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14660 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14661 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14662 Cond.getOperand(0).getValueType() != MVT::i8)) {
14663 SDValue LHS = Cond.getOperand(0);
14664 SDValue RHS = Cond.getOperand(1);
14665 unsigned X86Opcode;
14668 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14669 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14671 switch (CondOpcode) {
14672 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14674 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14676 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14679 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14680 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14682 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14684 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14687 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14688 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14689 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14690 default: llvm_unreachable("unexpected overflowing operator");
14693 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14694 if (CondOpcode == ISD::UMULO)
14695 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14698 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14700 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14702 if (CondOpcode == ISD::UMULO)
14703 Cond = X86Op.getValue(2);
14705 Cond = X86Op.getValue(1);
14707 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14711 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14712 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14713 if (CondOpc == ISD::OR) {
14714 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14715 // two branches instead of an explicit OR instruction with a
14717 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14718 isX86LogicalCmp(Cmp)) {
14719 CC = Cond.getOperand(0).getOperand(0);
14720 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14721 Chain, Dest, CC, Cmp);
14722 CC = Cond.getOperand(1).getOperand(0);
14726 } else { // ISD::AND
14727 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14728 // two branches instead of an explicit AND instruction with a
14729 // separate test. However, we only do this if this block doesn't
14730 // have a fall-through edge, because this requires an explicit
14731 // jmp when the condition is false.
14732 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14733 isX86LogicalCmp(Cmp) &&
14734 Op.getNode()->hasOneUse()) {
14735 X86::CondCode CCode =
14736 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14737 CCode = X86::GetOppositeBranchCondition(CCode);
14738 CC = DAG.getConstant(CCode, dl, MVT::i8);
14739 SDNode *User = *Op.getNode()->use_begin();
14740 // Look for an unconditional branch following this conditional branch.
14741 // We need this because we need to reverse the successors in order
14742 // to implement FCMP_OEQ.
14743 if (User->getOpcode() == ISD::BR) {
14744 SDValue FalseBB = User->getOperand(1);
14746 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14747 assert(NewBR == User);
14751 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14752 Chain, Dest, CC, Cmp);
14753 X86::CondCode CCode =
14754 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14755 CCode = X86::GetOppositeBranchCondition(CCode);
14756 CC = DAG.getConstant(CCode, dl, MVT::i8);
14762 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14763 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14764 // It should be transformed during dag combiner except when the condition
14765 // is set by a arithmetics with overflow node.
14766 X86::CondCode CCode =
14767 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14768 CCode = X86::GetOppositeBranchCondition(CCode);
14769 CC = DAG.getConstant(CCode, dl, MVT::i8);
14770 Cond = Cond.getOperand(0).getOperand(1);
14772 } else if (Cond.getOpcode() == ISD::SETCC &&
14773 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14774 // For FCMP_OEQ, we can emit
14775 // two branches instead of an explicit AND instruction with a
14776 // separate test. However, we only do this if this block doesn't
14777 // have a fall-through edge, because this requires an explicit
14778 // jmp when the condition is false.
14779 if (Op.getNode()->hasOneUse()) {
14780 SDNode *User = *Op.getNode()->use_begin();
14781 // Look for an unconditional branch following this conditional branch.
14782 // We need this because we need to reverse the successors in order
14783 // to implement FCMP_OEQ.
14784 if (User->getOpcode() == ISD::BR) {
14785 SDValue FalseBB = User->getOperand(1);
14787 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14788 assert(NewBR == User);
14792 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14793 Cond.getOperand(0), Cond.getOperand(1));
14794 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14795 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14796 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14797 Chain, Dest, CC, Cmp);
14798 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14803 } else if (Cond.getOpcode() == ISD::SETCC &&
14804 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14805 // For FCMP_UNE, we can emit
14806 // two branches instead of an explicit AND instruction with a
14807 // separate test. However, we only do this if this block doesn't
14808 // have a fall-through edge, because this requires an explicit
14809 // jmp when the condition is false.
14810 if (Op.getNode()->hasOneUse()) {
14811 SDNode *User = *Op.getNode()->use_begin();
14812 // Look for an unconditional branch following this conditional branch.
14813 // We need this because we need to reverse the successors in order
14814 // to implement FCMP_UNE.
14815 if (User->getOpcode() == ISD::BR) {
14816 SDValue FalseBB = User->getOperand(1);
14818 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14819 assert(NewBR == User);
14822 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14823 Cond.getOperand(0), Cond.getOperand(1));
14824 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14825 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14826 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14827 Chain, Dest, CC, Cmp);
14828 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14838 // Look pass the truncate if the high bits are known zero.
14839 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14840 Cond = Cond.getOperand(0);
14842 // We know the result of AND is compared against zero. Try to match
14844 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14845 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14846 if (NewSetCC.getNode()) {
14847 CC = NewSetCC.getOperand(0);
14848 Cond = NewSetCC.getOperand(1);
14855 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14856 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14857 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14859 Cond = ConvertCmpIfNecessary(Cond, DAG);
14860 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14861 Chain, Dest, CC, Cond);
14864 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14865 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14866 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14867 // that the guard pages used by the OS virtual memory manager are allocated in
14868 // correct sequence.
14870 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14871 SelectionDAG &DAG) const {
14872 MachineFunction &MF = DAG.getMachineFunction();
14873 bool SplitStack = MF.shouldSplitStack();
14874 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14879 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14880 SDNode* Node = Op.getNode();
14882 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14883 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14884 " not tell us which reg is the stack pointer!");
14885 EVT VT = Node->getValueType(0);
14886 SDValue Tmp1 = SDValue(Node, 0);
14887 SDValue Tmp2 = SDValue(Node, 1);
14888 SDValue Tmp3 = Node->getOperand(2);
14889 SDValue Chain = Tmp1.getOperand(0);
14891 // Chain the dynamic stack allocation so that it doesn't modify the stack
14892 // pointer when other instructions are using the stack.
14893 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14896 SDValue Size = Tmp2.getOperand(1);
14897 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14898 Chain = SP.getValue(1);
14899 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14900 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14901 unsigned StackAlign = TFI.getStackAlignment();
14902 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14903 if (Align > StackAlign)
14904 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14905 DAG.getConstant(-(uint64_t)Align, dl, VT));
14906 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14908 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14909 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14912 SDValue Ops[2] = { Tmp1, Tmp2 };
14913 return DAG.getMergeValues(Ops, dl);
14917 SDValue Chain = Op.getOperand(0);
14918 SDValue Size = Op.getOperand(1);
14919 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14920 EVT VT = Op.getNode()->getValueType(0);
14922 bool Is64Bit = Subtarget->is64Bit();
14923 MVT SPTy = getPointerTy(DAG.getDataLayout());
14926 MachineRegisterInfo &MRI = MF.getRegInfo();
14929 // The 64 bit implementation of segmented stacks needs to clobber both r10
14930 // r11. This makes it impossible to use it along with nested parameters.
14931 const Function *F = MF.getFunction();
14933 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14935 if (I->hasNestAttr())
14936 report_fatal_error("Cannot use segmented stacks with functions that "
14937 "have nested arguments.");
14940 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14941 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14942 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14943 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14944 DAG.getRegister(Vreg, SPTy));
14945 SDValue Ops1[2] = { Value, Chain };
14946 return DAG.getMergeValues(Ops1, dl);
14949 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14951 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14952 Flag = Chain.getValue(1);
14953 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14955 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14957 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14958 unsigned SPReg = RegInfo->getStackRegister();
14959 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14960 Chain = SP.getValue(1);
14963 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14964 DAG.getConstant(-(uint64_t)Align, dl, VT));
14965 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14968 SDValue Ops1[2] = { SP, Chain };
14969 return DAG.getMergeValues(Ops1, dl);
14973 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14974 MachineFunction &MF = DAG.getMachineFunction();
14975 auto PtrVT = getPointerTy(MF.getDataLayout());
14976 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14978 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14981 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14982 // vastart just stores the address of the VarArgsFrameIndex slot into the
14983 // memory location argument.
14984 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14985 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14986 MachinePointerInfo(SV), false, false, 0);
14990 // gp_offset (0 - 6 * 8)
14991 // fp_offset (48 - 48 + 8 * 16)
14992 // overflow_arg_area (point to parameters coming in memory).
14994 SmallVector<SDValue, 8> MemOps;
14995 SDValue FIN = Op.getOperand(1);
14997 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14998 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15000 FIN, MachinePointerInfo(SV), false, false, 0);
15001 MemOps.push_back(Store);
15004 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15005 Store = DAG.getStore(Op.getOperand(0), DL,
15006 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15008 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15009 MemOps.push_back(Store);
15011 // Store ptr to overflow_arg_area
15012 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15013 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15014 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15015 MachinePointerInfo(SV, 8),
15017 MemOps.push_back(Store);
15019 // Store ptr to reg_save_area.
15020 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15021 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15022 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15023 MachinePointerInfo(SV, 16), false, false, 0);
15024 MemOps.push_back(Store);
15025 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15028 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15029 assert(Subtarget->is64Bit() &&
15030 "LowerVAARG only handles 64-bit va_arg!");
15031 assert((Subtarget->isTargetLinux() ||
15032 Subtarget->isTargetDarwin()) &&
15033 "Unhandled target in LowerVAARG");
15034 assert(Op.getNode()->getNumOperands() == 4);
15035 SDValue Chain = Op.getOperand(0);
15036 SDValue SrcPtr = Op.getOperand(1);
15037 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15038 unsigned Align = Op.getConstantOperandVal(3);
15041 EVT ArgVT = Op.getNode()->getValueType(0);
15042 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15043 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15046 // Decide which area this value should be read from.
15047 // TODO: Implement the AMD64 ABI in its entirety. This simple
15048 // selection mechanism works only for the basic types.
15049 if (ArgVT == MVT::f80) {
15050 llvm_unreachable("va_arg for f80 not yet implemented");
15051 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15052 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15053 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15054 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15056 llvm_unreachable("Unhandled argument type in LowerVAARG");
15059 if (ArgMode == 2) {
15060 // Sanity Check: Make sure using fp_offset makes sense.
15061 assert(!Subtarget->useSoftFloat() &&
15062 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15063 Attribute::NoImplicitFloat)) &&
15064 Subtarget->hasSSE1());
15067 // Insert VAARG_64 node into the DAG
15068 // VAARG_64 returns two values: Variable Argument Address, Chain
15069 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15070 DAG.getConstant(ArgMode, dl, MVT::i8),
15071 DAG.getConstant(Align, dl, MVT::i32)};
15072 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15073 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15074 VTs, InstOps, MVT::i64,
15075 MachinePointerInfo(SV),
15077 /*Volatile=*/false,
15079 /*WriteMem=*/true);
15080 Chain = VAARG.getValue(1);
15082 // Load the next argument and return it
15083 return DAG.getLoad(ArgVT, dl,
15086 MachinePointerInfo(),
15087 false, false, false, 0);
15090 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15091 SelectionDAG &DAG) {
15092 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15093 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15094 SDValue Chain = Op.getOperand(0);
15095 SDValue DstPtr = Op.getOperand(1);
15096 SDValue SrcPtr = Op.getOperand(2);
15097 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15098 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15101 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15102 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15104 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15107 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15108 // amount is a constant. Takes immediate version of shift as input.
15109 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15110 SDValue SrcOp, uint64_t ShiftAmt,
15111 SelectionDAG &DAG) {
15112 MVT ElementType = VT.getVectorElementType();
15114 // Fold this packed shift into its first operand if ShiftAmt is 0.
15118 // Check for ShiftAmt >= element width
15119 if (ShiftAmt >= ElementType.getSizeInBits()) {
15120 if (Opc == X86ISD::VSRAI)
15121 ShiftAmt = ElementType.getSizeInBits() - 1;
15123 return DAG.getConstant(0, dl, VT);
15126 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15127 && "Unknown target vector shift-by-constant node");
15129 // Fold this packed vector shift into a build vector if SrcOp is a
15130 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15131 if (VT == SrcOp.getSimpleValueType() &&
15132 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15133 SmallVector<SDValue, 8> Elts;
15134 unsigned NumElts = SrcOp->getNumOperands();
15135 ConstantSDNode *ND;
15138 default: llvm_unreachable(nullptr);
15139 case X86ISD::VSHLI:
15140 for (unsigned i=0; i!=NumElts; ++i) {
15141 SDValue CurrentOp = SrcOp->getOperand(i);
15142 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15143 Elts.push_back(CurrentOp);
15146 ND = cast<ConstantSDNode>(CurrentOp);
15147 const APInt &C = ND->getAPIntValue();
15148 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15151 case X86ISD::VSRLI:
15152 for (unsigned i=0; i!=NumElts; ++i) {
15153 SDValue CurrentOp = SrcOp->getOperand(i);
15154 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15155 Elts.push_back(CurrentOp);
15158 ND = cast<ConstantSDNode>(CurrentOp);
15159 const APInt &C = ND->getAPIntValue();
15160 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15163 case X86ISD::VSRAI:
15164 for (unsigned i=0; i!=NumElts; ++i) {
15165 SDValue CurrentOp = SrcOp->getOperand(i);
15166 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15167 Elts.push_back(CurrentOp);
15170 ND = cast<ConstantSDNode>(CurrentOp);
15171 const APInt &C = ND->getAPIntValue();
15172 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15177 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15180 return DAG.getNode(Opc, dl, VT, SrcOp,
15181 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15184 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15185 // may or may not be a constant. Takes immediate version of shift as input.
15186 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15187 SDValue SrcOp, SDValue ShAmt,
15188 SelectionDAG &DAG) {
15189 MVT SVT = ShAmt.getSimpleValueType();
15190 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15192 // Catch shift-by-constant.
15193 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15194 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15195 CShAmt->getZExtValue(), DAG);
15197 // Change opcode to non-immediate version
15199 default: llvm_unreachable("Unknown target vector shift node");
15200 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15201 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15202 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15205 const X86Subtarget &Subtarget =
15206 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15207 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15208 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15209 // Let the shuffle legalizer expand this shift amount node.
15210 SDValue Op0 = ShAmt.getOperand(0);
15211 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15212 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15214 // Need to build a vector containing shift amount.
15215 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15216 SmallVector<SDValue, 4> ShOps;
15217 ShOps.push_back(ShAmt);
15218 if (SVT == MVT::i32) {
15219 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15220 ShOps.push_back(DAG.getUNDEF(SVT));
15222 ShOps.push_back(DAG.getUNDEF(SVT));
15224 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15225 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15228 // The return type has to be a 128-bit type with the same element
15229 // type as the input type.
15230 MVT EltVT = VT.getVectorElementType();
15231 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15233 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15234 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15237 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15238 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15239 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15240 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15241 SDValue PreservedSrc,
15242 const X86Subtarget *Subtarget,
15243 SelectionDAG &DAG) {
15244 EVT VT = Op.getValueType();
15245 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15246 MVT::i1, VT.getVectorNumElements());
15247 SDValue VMask = SDValue();
15248 unsigned OpcodeSelect = ISD::VSELECT;
15251 assert(MaskVT.isSimple() && "invalid mask type");
15253 if (isAllOnes(Mask))
15256 if (MaskVT.bitsGT(Mask.getValueType())) {
15257 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15258 MaskVT.getSizeInBits());
15259 VMask = DAG.getBitcast(MaskVT,
15260 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15262 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15263 Mask.getValueType().getSizeInBits());
15264 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15265 // are extracted by EXTRACT_SUBVECTOR.
15266 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15267 DAG.getBitcast(BitcastVT, Mask),
15268 DAG.getIntPtrConstant(0, dl));
15271 switch (Op.getOpcode()) {
15273 case X86ISD::PCMPEQM:
15274 case X86ISD::PCMPGTM:
15276 case X86ISD::CMPMU:
15277 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15278 case X86ISD::VTRUNC:
15279 case X86ISD::VTRUNCS:
15280 case X86ISD::VTRUNCUS:
15281 // We can't use ISD::VSELECT here because it is not always "Legal"
15282 // for the destination type. For example vpmovqb require only AVX512
15283 // and vselect that can operate on byte element type require BWI
15284 OpcodeSelect = X86ISD::SELECT;
15287 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15288 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15289 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15292 /// \brief Creates an SDNode for a predicated scalar operation.
15293 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15294 /// The mask is comming as MVT::i8 and it should be truncated
15295 /// to MVT::i1 while lowering masking intrinsics.
15296 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15297 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15298 /// a scalar instruction.
15299 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15300 SDValue PreservedSrc,
15301 const X86Subtarget *Subtarget,
15302 SelectionDAG &DAG) {
15303 if (isAllOnes(Mask))
15306 EVT VT = Op.getValueType();
15308 // The mask should be of type MVT::i1
15309 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15311 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15312 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15313 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15316 static int getSEHRegistrationNodeSize(const Function *Fn) {
15317 if (!Fn->hasPersonalityFn())
15318 report_fatal_error(
15319 "querying registration node size for function without personality");
15320 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15321 // WinEHStatePass for the full struct definition.
15322 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15323 case EHPersonality::MSVC_X86SEH: return 24;
15324 case EHPersonality::MSVC_CXX: return 16;
15327 report_fatal_error("can only recover FP for MSVC EH personality functions");
15330 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15331 /// function or when returning to a parent frame after catching an exception, we
15332 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15333 /// Here's the math:
15334 /// RegNodeBase = EntryEBP - RegNodeSize
15335 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15336 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15337 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15338 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15339 SDValue EntryEBP) {
15340 MachineFunction &MF = DAG.getMachineFunction();
15343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15344 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15346 // It's possible that the parent function no longer has a personality function
15347 // if the exceptional code was optimized away, in which case we just return
15348 // the incoming EBP.
15349 if (!Fn->hasPersonalityFn())
15352 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15354 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15356 MCSymbol *OffsetSym =
15357 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15358 GlobalValue::getRealLinkageName(Fn->getName()));
15359 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15360 SDValue RegNodeFrameOffset =
15361 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15363 // RegNodeBase = EntryEBP - RegNodeSize
15364 // ParentFP = RegNodeBase - RegNodeFrameOffset
15365 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15366 DAG.getConstant(RegNodeSize, dl, PtrVT));
15367 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15370 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15371 SelectionDAG &DAG) {
15373 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15374 EVT VT = Op.getValueType();
15375 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15377 switch(IntrData->Type) {
15378 case INTR_TYPE_1OP:
15379 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15380 case INTR_TYPE_2OP:
15381 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15383 case INTR_TYPE_3OP:
15384 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15385 Op.getOperand(2), Op.getOperand(3));
15386 case INTR_TYPE_4OP:
15387 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15388 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15389 case INTR_TYPE_1OP_MASK_RM: {
15390 SDValue Src = Op.getOperand(1);
15391 SDValue PassThru = Op.getOperand(2);
15392 SDValue Mask = Op.getOperand(3);
15393 SDValue RoundingMode;
15394 // We allways add rounding mode to the Node.
15395 // If the rounding mode is not specified, we add the
15396 // "current direction" mode.
15397 if (Op.getNumOperands() == 4)
15399 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15401 RoundingMode = Op.getOperand(4);
15402 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15403 if (IntrWithRoundingModeOpcode != 0)
15404 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15405 X86::STATIC_ROUNDING::CUR_DIRECTION)
15406 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15407 dl, Op.getValueType(), Src, RoundingMode),
15408 Mask, PassThru, Subtarget, DAG);
15409 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15411 Mask, PassThru, Subtarget, DAG);
15413 case INTR_TYPE_1OP_MASK: {
15414 SDValue Src = Op.getOperand(1);
15415 SDValue PassThru = Op.getOperand(2);
15416 SDValue Mask = Op.getOperand(3);
15417 // We add rounding mode to the Node when
15418 // - RM Opcode is specified and
15419 // - RM is not "current direction".
15420 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15421 if (IntrWithRoundingModeOpcode != 0) {
15422 SDValue Rnd = Op.getOperand(4);
15423 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15424 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15425 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15426 dl, Op.getValueType(),
15428 Mask, PassThru, Subtarget, DAG);
15431 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15432 Mask, PassThru, Subtarget, DAG);
15434 case INTR_TYPE_SCALAR_MASK_RM: {
15435 SDValue Src1 = Op.getOperand(1);
15436 SDValue Src2 = Op.getOperand(2);
15437 SDValue Src0 = Op.getOperand(3);
15438 SDValue Mask = Op.getOperand(4);
15439 // There are 2 kinds of intrinsics in this group:
15440 // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15441 // (2) With rounding mode and sae - 7 operands.
15442 if (Op.getNumOperands() == 6) {
15443 SDValue Sae = Op.getOperand(5);
15444 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15445 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15447 Mask, Src0, Subtarget, DAG);
15449 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15450 SDValue RoundingMode = Op.getOperand(5);
15451 SDValue Sae = Op.getOperand(6);
15452 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15453 RoundingMode, Sae),
15454 Mask, Src0, Subtarget, DAG);
15456 case INTR_TYPE_2OP_MASK: {
15457 SDValue Src1 = Op.getOperand(1);
15458 SDValue Src2 = Op.getOperand(2);
15459 SDValue PassThru = Op.getOperand(3);
15460 SDValue Mask = Op.getOperand(4);
15461 // We specify 2 possible opcodes for intrinsics with rounding modes.
15462 // First, we check if the intrinsic may have non-default rounding mode,
15463 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15464 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15465 if (IntrWithRoundingModeOpcode != 0) {
15466 SDValue Rnd = Op.getOperand(5);
15467 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15468 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15469 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15470 dl, Op.getValueType(),
15472 Mask, PassThru, Subtarget, DAG);
15475 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15477 Mask, PassThru, Subtarget, DAG);
15479 case INTR_TYPE_2OP_MASK_RM: {
15480 SDValue Src1 = Op.getOperand(1);
15481 SDValue Src2 = Op.getOperand(2);
15482 SDValue PassThru = Op.getOperand(3);
15483 SDValue Mask = Op.getOperand(4);
15484 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15485 // First, we check if the intrinsic have rounding mode (6 operands),
15486 // if not, we set rounding mode to "current".
15488 if (Op.getNumOperands() == 6)
15489 Rnd = Op.getOperand(5);
15491 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15492 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15494 Mask, PassThru, Subtarget, DAG);
15496 case INTR_TYPE_3OP_MASK_RM: {
15497 SDValue Src1 = Op.getOperand(1);
15498 SDValue Src2 = Op.getOperand(2);
15499 SDValue Imm = Op.getOperand(3);
15500 SDValue PassThru = Op.getOperand(4);
15501 SDValue Mask = Op.getOperand(5);
15502 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15503 // First, we check if the intrinsic have rounding mode (7 operands),
15504 // if not, we set rounding mode to "current".
15506 if (Op.getNumOperands() == 7)
15507 Rnd = Op.getOperand(6);
15509 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15510 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15511 Src1, Src2, Imm, Rnd),
15512 Mask, PassThru, Subtarget, DAG);
15514 case INTR_TYPE_3OP_MASK: {
15515 SDValue Src1 = Op.getOperand(1);
15516 SDValue Src2 = Op.getOperand(2);
15517 SDValue Src3 = Op.getOperand(3);
15518 SDValue PassThru = Op.getOperand(4);
15519 SDValue Mask = Op.getOperand(5);
15520 // We specify 2 possible opcodes for intrinsics with rounding modes.
15521 // First, we check if the intrinsic may have non-default rounding mode,
15522 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15523 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15524 if (IntrWithRoundingModeOpcode != 0) {
15525 SDValue Rnd = Op.getOperand(6);
15526 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15527 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15528 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15529 dl, Op.getValueType(),
15530 Src1, Src2, Src3, Rnd),
15531 Mask, PassThru, Subtarget, DAG);
15534 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15536 Mask, PassThru, Subtarget, DAG);
15538 case VPERM_3OP_MASKZ:
15539 case VPERM_3OP_MASK:
15542 case FMA_OP_MASK: {
15543 SDValue Src1 = Op.getOperand(1);
15544 SDValue Src2 = Op.getOperand(2);
15545 SDValue Src3 = Op.getOperand(3);
15546 SDValue Mask = Op.getOperand(4);
15547 EVT VT = Op.getValueType();
15548 SDValue PassThru = SDValue();
15550 // set PassThru element
15551 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15552 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15553 else if (IntrData->Type == FMA_OP_MASK3)
15558 // We specify 2 possible opcodes for intrinsics with rounding modes.
15559 // First, we check if the intrinsic may have non-default rounding mode,
15560 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15561 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15562 if (IntrWithRoundingModeOpcode != 0) {
15563 SDValue Rnd = Op.getOperand(5);
15564 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15565 X86::STATIC_ROUNDING::CUR_DIRECTION)
15566 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15567 dl, Op.getValueType(),
15568 Src1, Src2, Src3, Rnd),
15569 Mask, PassThru, Subtarget, DAG);
15571 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15572 dl, Op.getValueType(),
15574 Mask, PassThru, Subtarget, DAG);
15577 case CMP_MASK_CC: {
15578 // Comparison intrinsics with masks.
15579 // Example of transformation:
15580 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15581 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15583 // (v8i1 (insert_subvector undef,
15584 // (v2i1 (and (PCMPEQM %a, %b),
15585 // (extract_subvector
15586 // (v8i1 (bitcast %mask)), 0))), 0))))
15587 EVT VT = Op.getOperand(1).getValueType();
15588 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15589 VT.getVectorNumElements());
15590 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15591 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15592 Mask.getValueType().getSizeInBits());
15594 if (IntrData->Type == CMP_MASK_CC) {
15595 SDValue CC = Op.getOperand(3);
15596 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15597 // We specify 2 possible opcodes for intrinsics with rounding modes.
15598 // First, we check if the intrinsic may have non-default rounding mode,
15599 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15600 if (IntrData->Opc1 != 0) {
15601 SDValue Rnd = Op.getOperand(5);
15602 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15603 X86::STATIC_ROUNDING::CUR_DIRECTION)
15604 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15605 Op.getOperand(2), CC, Rnd);
15607 //default rounding mode
15609 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15610 Op.getOperand(2), CC);
15613 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15614 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15617 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15618 DAG.getTargetConstant(0, dl,
15621 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15622 DAG.getUNDEF(BitcastVT), CmpMask,
15623 DAG.getIntPtrConstant(0, dl));
15624 return DAG.getBitcast(Op.getValueType(), Res);
15626 case COMI: { // Comparison intrinsics
15627 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15628 SDValue LHS = Op.getOperand(1);
15629 SDValue RHS = Op.getOperand(2);
15630 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15631 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15632 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15633 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15634 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15635 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15638 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15639 Op.getOperand(1), Op.getOperand(2), DAG);
15641 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15642 Op.getSimpleValueType(),
15644 Op.getOperand(2), DAG),
15645 Op.getOperand(4), Op.getOperand(3), Subtarget,
15647 case COMPRESS_EXPAND_IN_REG: {
15648 SDValue Mask = Op.getOperand(3);
15649 SDValue DataToCompress = Op.getOperand(1);
15650 SDValue PassThru = Op.getOperand(2);
15651 if (isAllOnes(Mask)) // return data as is
15652 return Op.getOperand(1);
15654 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15656 Mask, PassThru, Subtarget, DAG);
15659 SDValue Mask = Op.getOperand(3);
15660 EVT VT = Op.getValueType();
15661 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15662 VT.getVectorNumElements());
15663 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15664 Mask.getValueType().getSizeInBits());
15666 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15667 DAG.getBitcast(BitcastVT, Mask),
15668 DAG.getIntPtrConstant(0, dl));
15669 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15678 default: return SDValue(); // Don't custom lower most intrinsics.
15680 case Intrinsic::x86_avx2_permd:
15681 case Intrinsic::x86_avx2_permps:
15682 // Operands intentionally swapped. Mask is last operand to intrinsic,
15683 // but second operand for node/instruction.
15684 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15685 Op.getOperand(2), Op.getOperand(1));
15687 // ptest and testp intrinsics. The intrinsic these come from are designed to
15688 // return an integer value, not just an instruction so lower it to the ptest
15689 // or testp pattern and a setcc for the result.
15690 case Intrinsic::x86_sse41_ptestz:
15691 case Intrinsic::x86_sse41_ptestc:
15692 case Intrinsic::x86_sse41_ptestnzc:
15693 case Intrinsic::x86_avx_ptestz_256:
15694 case Intrinsic::x86_avx_ptestc_256:
15695 case Intrinsic::x86_avx_ptestnzc_256:
15696 case Intrinsic::x86_avx_vtestz_ps:
15697 case Intrinsic::x86_avx_vtestc_ps:
15698 case Intrinsic::x86_avx_vtestnzc_ps:
15699 case Intrinsic::x86_avx_vtestz_pd:
15700 case Intrinsic::x86_avx_vtestc_pd:
15701 case Intrinsic::x86_avx_vtestnzc_pd:
15702 case Intrinsic::x86_avx_vtestz_ps_256:
15703 case Intrinsic::x86_avx_vtestc_ps_256:
15704 case Intrinsic::x86_avx_vtestnzc_ps_256:
15705 case Intrinsic::x86_avx_vtestz_pd_256:
15706 case Intrinsic::x86_avx_vtestc_pd_256:
15707 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15708 bool IsTestPacked = false;
15711 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15712 case Intrinsic::x86_avx_vtestz_ps:
15713 case Intrinsic::x86_avx_vtestz_pd:
15714 case Intrinsic::x86_avx_vtestz_ps_256:
15715 case Intrinsic::x86_avx_vtestz_pd_256:
15716 IsTestPacked = true; // Fallthrough
15717 case Intrinsic::x86_sse41_ptestz:
15718 case Intrinsic::x86_avx_ptestz_256:
15720 X86CC = X86::COND_E;
15722 case Intrinsic::x86_avx_vtestc_ps:
15723 case Intrinsic::x86_avx_vtestc_pd:
15724 case Intrinsic::x86_avx_vtestc_ps_256:
15725 case Intrinsic::x86_avx_vtestc_pd_256:
15726 IsTestPacked = true; // Fallthrough
15727 case Intrinsic::x86_sse41_ptestc:
15728 case Intrinsic::x86_avx_ptestc_256:
15730 X86CC = X86::COND_B;
15732 case Intrinsic::x86_avx_vtestnzc_ps:
15733 case Intrinsic::x86_avx_vtestnzc_pd:
15734 case Intrinsic::x86_avx_vtestnzc_ps_256:
15735 case Intrinsic::x86_avx_vtestnzc_pd_256:
15736 IsTestPacked = true; // Fallthrough
15737 case Intrinsic::x86_sse41_ptestnzc:
15738 case Intrinsic::x86_avx_ptestnzc_256:
15740 X86CC = X86::COND_A;
15744 SDValue LHS = Op.getOperand(1);
15745 SDValue RHS = Op.getOperand(2);
15746 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15747 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15748 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15749 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15750 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15752 case Intrinsic::x86_avx512_kortestz_w:
15753 case Intrinsic::x86_avx512_kortestc_w: {
15754 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15755 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15756 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15757 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15758 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15759 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15760 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15763 case Intrinsic::x86_sse42_pcmpistria128:
15764 case Intrinsic::x86_sse42_pcmpestria128:
15765 case Intrinsic::x86_sse42_pcmpistric128:
15766 case Intrinsic::x86_sse42_pcmpestric128:
15767 case Intrinsic::x86_sse42_pcmpistrio128:
15768 case Intrinsic::x86_sse42_pcmpestrio128:
15769 case Intrinsic::x86_sse42_pcmpistris128:
15770 case Intrinsic::x86_sse42_pcmpestris128:
15771 case Intrinsic::x86_sse42_pcmpistriz128:
15772 case Intrinsic::x86_sse42_pcmpestriz128: {
15776 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15777 case Intrinsic::x86_sse42_pcmpistria128:
15778 Opcode = X86ISD::PCMPISTRI;
15779 X86CC = X86::COND_A;
15781 case Intrinsic::x86_sse42_pcmpestria128:
15782 Opcode = X86ISD::PCMPESTRI;
15783 X86CC = X86::COND_A;
15785 case Intrinsic::x86_sse42_pcmpistric128:
15786 Opcode = X86ISD::PCMPISTRI;
15787 X86CC = X86::COND_B;
15789 case Intrinsic::x86_sse42_pcmpestric128:
15790 Opcode = X86ISD::PCMPESTRI;
15791 X86CC = X86::COND_B;
15793 case Intrinsic::x86_sse42_pcmpistrio128:
15794 Opcode = X86ISD::PCMPISTRI;
15795 X86CC = X86::COND_O;
15797 case Intrinsic::x86_sse42_pcmpestrio128:
15798 Opcode = X86ISD::PCMPESTRI;
15799 X86CC = X86::COND_O;
15801 case Intrinsic::x86_sse42_pcmpistris128:
15802 Opcode = X86ISD::PCMPISTRI;
15803 X86CC = X86::COND_S;
15805 case Intrinsic::x86_sse42_pcmpestris128:
15806 Opcode = X86ISD::PCMPESTRI;
15807 X86CC = X86::COND_S;
15809 case Intrinsic::x86_sse42_pcmpistriz128:
15810 Opcode = X86ISD::PCMPISTRI;
15811 X86CC = X86::COND_E;
15813 case Intrinsic::x86_sse42_pcmpestriz128:
15814 Opcode = X86ISD::PCMPESTRI;
15815 X86CC = X86::COND_E;
15818 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15819 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15820 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15821 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15822 DAG.getConstant(X86CC, dl, MVT::i8),
15823 SDValue(PCMP.getNode(), 1));
15824 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15827 case Intrinsic::x86_sse42_pcmpistri128:
15828 case Intrinsic::x86_sse42_pcmpestri128: {
15830 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15831 Opcode = X86ISD::PCMPISTRI;
15833 Opcode = X86ISD::PCMPESTRI;
15835 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15836 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15837 return DAG.getNode(Opcode, dl, VTs, NewOps);
15840 case Intrinsic::x86_seh_lsda: {
15841 // Compute the symbol for the LSDA. We know it'll get emitted later.
15842 MachineFunction &MF = DAG.getMachineFunction();
15843 SDValue Op1 = Op.getOperand(1);
15844 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15845 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15846 GlobalValue::getRealLinkageName(Fn->getName()));
15848 // Generate a simple absolute symbol reference. This intrinsic is only
15849 // supported on 32-bit Windows, which isn't PIC.
15850 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15851 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15854 case Intrinsic::x86_seh_recoverfp: {
15855 SDValue FnOp = Op.getOperand(1);
15856 SDValue IncomingFPOp = Op.getOperand(2);
15857 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15858 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15860 report_fatal_error(
15861 "llvm.x86.seh.recoverfp must take a function as the first argument");
15862 return recoverFramePointer(DAG, Fn, IncomingFPOp);
15865 case Intrinsic::localaddress: {
15866 // Returns one of the stack, base, or frame pointer registers, depending on
15867 // which is used to reference local variables.
15868 MachineFunction &MF = DAG.getMachineFunction();
15869 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15871 if (RegInfo->hasBasePointer(MF))
15872 Reg = RegInfo->getBaseRegister();
15873 else // This function handles the SP or FP case.
15874 Reg = RegInfo->getPtrSizedFrameRegister(MF);
15875 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15880 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15881 SDValue Src, SDValue Mask, SDValue Base,
15882 SDValue Index, SDValue ScaleOp, SDValue Chain,
15883 const X86Subtarget * Subtarget) {
15885 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15887 llvm_unreachable("Invalid scale type");
15888 unsigned ScaleVal = C->getZExtValue();
15889 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15890 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15892 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15893 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15894 Index.getSimpleValueType().getVectorNumElements());
15896 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15898 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15900 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15901 Mask.getValueType().getSizeInBits());
15903 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15904 // are extracted by EXTRACT_SUBVECTOR.
15905 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15906 DAG.getBitcast(BitcastVT, Mask),
15907 DAG.getIntPtrConstant(0, dl));
15909 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15910 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15911 SDValue Segment = DAG.getRegister(0, MVT::i32);
15912 if (Src.getOpcode() == ISD::UNDEF)
15913 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15914 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15915 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15916 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15917 return DAG.getMergeValues(RetOps, dl);
15920 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15921 SDValue Src, SDValue Mask, SDValue Base,
15922 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15924 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15926 llvm_unreachable("Invalid scale type");
15927 unsigned ScaleVal = C->getZExtValue();
15928 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15929 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15931 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15932 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15933 SDValue Segment = DAG.getRegister(0, MVT::i32);
15934 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15935 Index.getSimpleValueType().getVectorNumElements());
15937 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15939 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15941 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15942 Mask.getValueType().getSizeInBits());
15944 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15945 // are extracted by EXTRACT_SUBVECTOR.
15946 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15947 DAG.getBitcast(BitcastVT, Mask),
15948 DAG.getIntPtrConstant(0, dl));
15950 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15951 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15952 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15953 return SDValue(Res, 1);
15956 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15957 SDValue Mask, SDValue Base, SDValue Index,
15958 SDValue ScaleOp, SDValue Chain) {
15960 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15961 assert(C && "Invalid scale type");
15962 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15963 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15964 SDValue Segment = DAG.getRegister(0, MVT::i32);
15966 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15968 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15970 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15972 MaskInReg = DAG.getBitcast(MaskVT, Mask);
15973 //SDVTList VTs = DAG.getVTList(MVT::Other);
15974 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15975 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15976 return SDValue(Res, 0);
15979 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15980 // read performance monitor counters (x86_rdpmc).
15981 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15982 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15983 SmallVectorImpl<SDValue> &Results) {
15984 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15985 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15988 // The ECX register is used to select the index of the performance counter
15990 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15992 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15994 // Reads the content of a 64-bit performance counter and returns it in the
15995 // registers EDX:EAX.
15996 if (Subtarget->is64Bit()) {
15997 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15998 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16001 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16002 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16005 Chain = HI.getValue(1);
16007 if (Subtarget->is64Bit()) {
16008 // The EAX register is loaded with the low-order 32 bits. The EDX register
16009 // is loaded with the supported high-order bits of the counter.
16010 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16011 DAG.getConstant(32, DL, MVT::i8));
16012 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16013 Results.push_back(Chain);
16017 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16018 SDValue Ops[] = { LO, HI };
16019 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16020 Results.push_back(Pair);
16021 Results.push_back(Chain);
16024 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16025 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16026 // also used to custom lower READCYCLECOUNTER nodes.
16027 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16028 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16029 SmallVectorImpl<SDValue> &Results) {
16030 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16031 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16034 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16035 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16036 // and the EAX register is loaded with the low-order 32 bits.
16037 if (Subtarget->is64Bit()) {
16038 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16039 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16042 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16043 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16046 SDValue Chain = HI.getValue(1);
16048 if (Opcode == X86ISD::RDTSCP_DAG) {
16049 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16051 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16052 // the ECX register. Add 'ecx' explicitly to the chain.
16053 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16055 // Explicitly store the content of ECX at the location passed in input
16056 // to the 'rdtscp' intrinsic.
16057 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16058 MachinePointerInfo(), false, false, 0);
16061 if (Subtarget->is64Bit()) {
16062 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16063 // the EAX register is loaded with the low-order 32 bits.
16064 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16065 DAG.getConstant(32, DL, MVT::i8));
16066 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16067 Results.push_back(Chain);
16071 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16072 SDValue Ops[] = { LO, HI };
16073 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16074 Results.push_back(Pair);
16075 Results.push_back(Chain);
16078 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16079 SelectionDAG &DAG) {
16080 SmallVector<SDValue, 2> Results;
16082 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16084 return DAG.getMergeValues(Results, DL);
16087 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16088 SelectionDAG &DAG) {
16089 MachineFunction &MF = DAG.getMachineFunction();
16090 const Function *Fn = MF.getFunction();
16092 SDValue Chain = Op.getOperand(0);
16094 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16095 "using llvm.x86.seh.restoreframe requires a frame pointer");
16097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16098 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16100 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16101 unsigned FrameReg =
16102 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16103 unsigned SPReg = RegInfo->getStackRegister();
16104 unsigned SlotSize = RegInfo->getSlotSize();
16106 // Get incoming EBP.
16107 SDValue IncomingEBP =
16108 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16110 // SP is saved in the first field of every registration node, so load
16111 // [EBP-RegNodeSize] into SP.
16112 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16113 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16114 DAG.getConstant(-RegNodeSize, dl, VT));
16116 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16117 false, VT.getScalarSizeInBits() / 8);
16118 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16120 if (!RegInfo->needsStackRealignment(MF)) {
16121 // Adjust EBP to point back to the original frame position.
16122 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16123 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16125 assert(RegInfo->hasBasePointer(MF) &&
16126 "functions with Win32 EH must use frame or base pointer register");
16128 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16129 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16130 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16132 // Reload the spilled EBP value, now that the stack and base pointers are
16134 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16135 X86FI->setHasSEHFramePtrSave(true);
16136 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16137 X86FI->setSEHFramePtrSaveIndex(FI);
16138 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16139 MachinePointerInfo(), false, false, false,
16140 VT.getScalarSizeInBits() / 8);
16141 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16147 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16148 /// return truncate Store/MaskedStore Node
16149 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16153 SDValue Mask = Op.getOperand(4);
16154 SDValue DataToTruncate = Op.getOperand(3);
16155 SDValue Addr = Op.getOperand(2);
16156 SDValue Chain = Op.getOperand(0);
16158 EVT VT = DataToTruncate.getValueType();
16159 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16160 ElementType, VT.getVectorNumElements());
16162 if (isAllOnes(Mask)) // return just a truncate store
16163 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16164 MachinePointerInfo(), SVT, false, false,
16165 SVT.getScalarSizeInBits()/8);
16167 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16168 MVT::i1, VT.getVectorNumElements());
16169 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16170 Mask.getValueType().getSizeInBits());
16171 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16172 // are extracted by EXTRACT_SUBVECTOR.
16173 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16174 DAG.getBitcast(BitcastVT, Mask),
16175 DAG.getIntPtrConstant(0, dl));
16177 MachineMemOperand *MMO = DAG.getMachineFunction().
16178 getMachineMemOperand(MachinePointerInfo(),
16179 MachineMemOperand::MOStore, SVT.getStoreSize(),
16180 SVT.getScalarSizeInBits()/8);
16182 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16183 VMask, SVT, MMO, true);
16186 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16187 SelectionDAG &DAG) {
16188 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16190 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16192 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16193 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16198 switch(IntrData->Type) {
16200 llvm_unreachable("Unknown Intrinsic Type");
16204 // Emit the node with the right value type.
16205 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16206 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16208 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16209 // Otherwise return the value from Rand, which is always 0, casted to i32.
16210 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16211 DAG.getConstant(1, dl, Op->getValueType(1)),
16212 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16213 SDValue(Result.getNode(), 1) };
16214 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16215 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16218 // Return { result, isValid, chain }.
16219 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16220 SDValue(Result.getNode(), 2));
16223 //gather(v1, mask, index, base, scale);
16224 SDValue Chain = Op.getOperand(0);
16225 SDValue Src = Op.getOperand(2);
16226 SDValue Base = Op.getOperand(3);
16227 SDValue Index = Op.getOperand(4);
16228 SDValue Mask = Op.getOperand(5);
16229 SDValue Scale = Op.getOperand(6);
16230 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16234 //scatter(base, mask, index, v1, scale);
16235 SDValue Chain = Op.getOperand(0);
16236 SDValue Base = Op.getOperand(2);
16237 SDValue Mask = Op.getOperand(3);
16238 SDValue Index = Op.getOperand(4);
16239 SDValue Src = Op.getOperand(5);
16240 SDValue Scale = Op.getOperand(6);
16241 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16245 SDValue Hint = Op.getOperand(6);
16246 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16247 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16248 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16249 SDValue Chain = Op.getOperand(0);
16250 SDValue Mask = Op.getOperand(2);
16251 SDValue Index = Op.getOperand(3);
16252 SDValue Base = Op.getOperand(4);
16253 SDValue Scale = Op.getOperand(5);
16254 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16256 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16258 SmallVector<SDValue, 2> Results;
16259 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16261 return DAG.getMergeValues(Results, dl);
16263 // Read Performance Monitoring Counters.
16265 SmallVector<SDValue, 2> Results;
16266 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16267 return DAG.getMergeValues(Results, dl);
16269 // XTEST intrinsics.
16271 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16272 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16273 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16274 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16276 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16277 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16278 Ret, SDValue(InTrans.getNode(), 1));
16282 SmallVector<SDValue, 2> Results;
16283 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16284 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16285 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16286 DAG.getConstant(-1, dl, MVT::i8));
16287 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16288 Op.getOperand(4), GenCF.getValue(1));
16289 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16290 Op.getOperand(5), MachinePointerInfo(),
16292 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16293 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16295 Results.push_back(SetCC);
16296 Results.push_back(Store);
16297 return DAG.getMergeValues(Results, dl);
16299 case COMPRESS_TO_MEM: {
16301 SDValue Mask = Op.getOperand(4);
16302 SDValue DataToCompress = Op.getOperand(3);
16303 SDValue Addr = Op.getOperand(2);
16304 SDValue Chain = Op.getOperand(0);
16306 EVT VT = DataToCompress.getValueType();
16307 if (isAllOnes(Mask)) // return just a store
16308 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16309 MachinePointerInfo(), false, false,
16310 VT.getScalarSizeInBits()/8);
16312 SDValue Compressed =
16313 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16314 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16315 return DAG.getStore(Chain, dl, Compressed, Addr,
16316 MachinePointerInfo(), false, false,
16317 VT.getScalarSizeInBits()/8);
16319 case TRUNCATE_TO_MEM_VI8:
16320 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16321 case TRUNCATE_TO_MEM_VI16:
16322 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16323 case TRUNCATE_TO_MEM_VI32:
16324 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16325 case EXPAND_FROM_MEM: {
16327 SDValue Mask = Op.getOperand(4);
16328 SDValue PassThru = Op.getOperand(3);
16329 SDValue Addr = Op.getOperand(2);
16330 SDValue Chain = Op.getOperand(0);
16331 EVT VT = Op.getValueType();
16333 if (isAllOnes(Mask)) // return just a load
16334 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16335 false, VT.getScalarSizeInBits()/8);
16337 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16338 false, false, false,
16339 VT.getScalarSizeInBits()/8);
16341 SDValue Results[] = {
16342 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16343 Mask, PassThru, Subtarget, DAG), Chain};
16344 return DAG.getMergeValues(Results, dl);
16349 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16350 SelectionDAG &DAG) const {
16351 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16352 MFI->setReturnAddressIsTaken(true);
16354 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16357 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16359 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16362 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16363 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16364 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16365 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16366 DAG.getNode(ISD::ADD, dl, PtrVT,
16367 FrameAddr, Offset),
16368 MachinePointerInfo(), false, false, false, 0);
16371 // Just load the return address.
16372 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16373 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16374 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16377 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16378 MachineFunction &MF = DAG.getMachineFunction();
16379 MachineFrameInfo *MFI = MF.getFrameInfo();
16380 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16381 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16382 EVT VT = Op.getValueType();
16384 MFI->setFrameAddressIsTaken(true);
16386 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16387 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16388 // is not possible to crawl up the stack without looking at the unwind codes
16390 int FrameAddrIndex = FuncInfo->getFAIndex();
16391 if (!FrameAddrIndex) {
16392 // Set up a frame object for the return address.
16393 unsigned SlotSize = RegInfo->getSlotSize();
16394 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16395 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16396 FuncInfo->setFAIndex(FrameAddrIndex);
16398 return DAG.getFrameIndex(FrameAddrIndex, VT);
16401 unsigned FrameReg =
16402 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16403 SDLoc dl(Op); // FIXME probably not meaningful
16404 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16405 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16406 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16407 "Invalid Frame Register!");
16408 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16410 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16411 MachinePointerInfo(),
16412 false, false, false, 0);
16416 // FIXME? Maybe this could be a TableGen attribute on some registers and
16417 // this table could be generated automatically from RegInfo.
16418 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16419 SelectionDAG &DAG) const {
16420 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16421 const MachineFunction &MF = DAG.getMachineFunction();
16423 unsigned Reg = StringSwitch<unsigned>(RegName)
16424 .Case("esp", X86::ESP)
16425 .Case("rsp", X86::RSP)
16426 .Case("ebp", X86::EBP)
16427 .Case("rbp", X86::RBP)
16430 if (Reg == X86::EBP || Reg == X86::RBP) {
16431 if (!TFI.hasFP(MF))
16432 report_fatal_error("register " + StringRef(RegName) +
16433 " is allocatable: function has no frame pointer");
16436 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16437 unsigned FrameReg =
16438 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16439 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16440 "Invalid Frame Register!");
16448 report_fatal_error("Invalid register name global variable");
16451 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16452 SelectionDAG &DAG) const {
16453 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16454 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16457 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16458 SDValue Chain = Op.getOperand(0);
16459 SDValue Offset = Op.getOperand(1);
16460 SDValue Handler = Op.getOperand(2);
16463 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16464 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16465 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16466 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16467 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16468 "Invalid Frame Register!");
16469 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16470 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16472 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16473 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16475 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16476 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16478 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16480 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16481 DAG.getRegister(StoreAddrReg, PtrVT));
16484 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16485 SelectionDAG &DAG) const {
16487 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16488 DAG.getVTList(MVT::i32, MVT::Other),
16489 Op.getOperand(0), Op.getOperand(1));
16492 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16493 SelectionDAG &DAG) const {
16495 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16496 Op.getOperand(0), Op.getOperand(1));
16499 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16500 return Op.getOperand(0);
16503 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16504 SelectionDAG &DAG) const {
16505 SDValue Root = Op.getOperand(0);
16506 SDValue Trmp = Op.getOperand(1); // trampoline
16507 SDValue FPtr = Op.getOperand(2); // nested function
16508 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16511 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16512 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16514 if (Subtarget->is64Bit()) {
16515 SDValue OutChains[6];
16517 // Large code-model.
16518 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16519 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16521 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16522 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16524 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16526 // Load the pointer to the nested function into R11.
16527 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16528 SDValue Addr = Trmp;
16529 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16530 Addr, MachinePointerInfo(TrmpAddr),
16533 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16534 DAG.getConstant(2, dl, MVT::i64));
16535 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16536 MachinePointerInfo(TrmpAddr, 2),
16539 // Load the 'nest' parameter value into R10.
16540 // R10 is specified in X86CallingConv.td
16541 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16542 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16543 DAG.getConstant(10, dl, MVT::i64));
16544 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16545 Addr, MachinePointerInfo(TrmpAddr, 10),
16548 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16549 DAG.getConstant(12, dl, MVT::i64));
16550 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16551 MachinePointerInfo(TrmpAddr, 12),
16554 // Jump to the nested function.
16555 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16556 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16557 DAG.getConstant(20, dl, MVT::i64));
16558 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16559 Addr, MachinePointerInfo(TrmpAddr, 20),
16562 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16563 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16564 DAG.getConstant(22, dl, MVT::i64));
16565 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16566 Addr, MachinePointerInfo(TrmpAddr, 22),
16569 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16571 const Function *Func =
16572 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16573 CallingConv::ID CC = Func->getCallingConv();
16578 llvm_unreachable("Unsupported calling convention");
16579 case CallingConv::C:
16580 case CallingConv::X86_StdCall: {
16581 // Pass 'nest' parameter in ECX.
16582 // Must be kept in sync with X86CallingConv.td
16583 NestReg = X86::ECX;
16585 // Check that ECX wasn't needed by an 'inreg' parameter.
16586 FunctionType *FTy = Func->getFunctionType();
16587 const AttributeSet &Attrs = Func->getAttributes();
16589 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16590 unsigned InRegCount = 0;
16593 for (FunctionType::param_iterator I = FTy->param_begin(),
16594 E = FTy->param_end(); I != E; ++I, ++Idx)
16595 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16596 auto &DL = DAG.getDataLayout();
16597 // FIXME: should only count parameters that are lowered to integers.
16598 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16601 if (InRegCount > 2) {
16602 report_fatal_error("Nest register in use - reduce number of inreg"
16608 case CallingConv::X86_FastCall:
16609 case CallingConv::X86_ThisCall:
16610 case CallingConv::Fast:
16611 // Pass 'nest' parameter in EAX.
16612 // Must be kept in sync with X86CallingConv.td
16613 NestReg = X86::EAX;
16617 SDValue OutChains[4];
16618 SDValue Addr, Disp;
16620 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16621 DAG.getConstant(10, dl, MVT::i32));
16622 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16624 // This is storing the opcode for MOV32ri.
16625 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16626 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16627 OutChains[0] = DAG.getStore(Root, dl,
16628 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16629 Trmp, MachinePointerInfo(TrmpAddr),
16632 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16633 DAG.getConstant(1, dl, MVT::i32));
16634 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16635 MachinePointerInfo(TrmpAddr, 1),
16638 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16639 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16640 DAG.getConstant(5, dl, MVT::i32));
16641 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16642 Addr, MachinePointerInfo(TrmpAddr, 5),
16645 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16646 DAG.getConstant(6, dl, MVT::i32));
16647 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16648 MachinePointerInfo(TrmpAddr, 6),
16651 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16655 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16656 SelectionDAG &DAG) const {
16658 The rounding mode is in bits 11:10 of FPSR, and has the following
16660 00 Round to nearest
16665 FLT_ROUNDS, on the other hand, expects the following:
16672 To perform the conversion, we do:
16673 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16676 MachineFunction &MF = DAG.getMachineFunction();
16677 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16678 unsigned StackAlignment = TFI.getStackAlignment();
16679 MVT VT = Op.getSimpleValueType();
16682 // Save FP Control Word to stack slot
16683 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16684 SDValue StackSlot =
16685 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16687 MachineMemOperand *MMO =
16688 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16689 MachineMemOperand::MOStore, 2, 2);
16691 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16692 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16693 DAG.getVTList(MVT::Other),
16694 Ops, MVT::i16, MMO);
16696 // Load FP Control Word from stack slot
16697 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16698 MachinePointerInfo(), false, false, false, 0);
16700 // Transform as necessary
16702 DAG.getNode(ISD::SRL, DL, MVT::i16,
16703 DAG.getNode(ISD::AND, DL, MVT::i16,
16704 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16705 DAG.getConstant(11, DL, MVT::i8));
16707 DAG.getNode(ISD::SRL, DL, MVT::i16,
16708 DAG.getNode(ISD::AND, DL, MVT::i16,
16709 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16710 DAG.getConstant(9, DL, MVT::i8));
16713 DAG.getNode(ISD::AND, DL, MVT::i16,
16714 DAG.getNode(ISD::ADD, DL, MVT::i16,
16715 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16716 DAG.getConstant(1, DL, MVT::i16)),
16717 DAG.getConstant(3, DL, MVT::i16));
16719 return DAG.getNode((VT.getSizeInBits() < 16 ?
16720 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16723 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16724 MVT VT = Op.getSimpleValueType();
16726 unsigned NumBits = VT.getSizeInBits();
16729 Op = Op.getOperand(0);
16730 if (VT == MVT::i8) {
16731 // Zero extend to i32 since there is not an i8 bsr.
16733 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16736 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16737 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16738 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16740 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16743 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16744 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16747 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16749 // Finally xor with NumBits-1.
16750 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16751 DAG.getConstant(NumBits - 1, dl, OpVT));
16754 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16758 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16759 MVT VT = Op.getSimpleValueType();
16761 unsigned NumBits = VT.getSizeInBits();
16764 Op = Op.getOperand(0);
16765 if (VT == MVT::i8) {
16766 // Zero extend to i32 since there is not an i8 bsr.
16768 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16771 // Issue a bsr (scan bits in reverse).
16772 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16773 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16775 // And xor with NumBits-1.
16776 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16777 DAG.getConstant(NumBits - 1, dl, OpVT));
16780 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16784 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16785 MVT VT = Op.getSimpleValueType();
16786 unsigned NumBits = VT.getSizeInBits();
16788 Op = Op.getOperand(0);
16790 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16791 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16792 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16794 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16797 DAG.getConstant(NumBits, dl, VT),
16798 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16801 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16804 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16805 // ones, and then concatenate the result back.
16806 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16807 MVT VT = Op.getSimpleValueType();
16809 assert(VT.is256BitVector() && VT.isInteger() &&
16810 "Unsupported value type for operation");
16812 unsigned NumElems = VT.getVectorNumElements();
16815 // Extract the LHS vectors
16816 SDValue LHS = Op.getOperand(0);
16817 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16818 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16820 // Extract the RHS vectors
16821 SDValue RHS = Op.getOperand(1);
16822 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16823 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16825 MVT EltVT = VT.getVectorElementType();
16826 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16828 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16829 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16830 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16833 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16834 if (Op.getValueType() == MVT::i1)
16835 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16836 Op.getOperand(0), Op.getOperand(1));
16837 assert(Op.getSimpleValueType().is256BitVector() &&
16838 Op.getSimpleValueType().isInteger() &&
16839 "Only handle AVX 256-bit vector integer operation");
16840 return Lower256IntArith(Op, DAG);
16843 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16844 if (Op.getValueType() == MVT::i1)
16845 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16846 Op.getOperand(0), Op.getOperand(1));
16847 assert(Op.getSimpleValueType().is256BitVector() &&
16848 Op.getSimpleValueType().isInteger() &&
16849 "Only handle AVX 256-bit vector integer operation");
16850 return Lower256IntArith(Op, DAG);
16853 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16854 SelectionDAG &DAG) {
16856 MVT VT = Op.getSimpleValueType();
16859 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16861 // Decompose 256-bit ops into smaller 128-bit ops.
16862 if (VT.is256BitVector() && !Subtarget->hasInt256())
16863 return Lower256IntArith(Op, DAG);
16865 SDValue A = Op.getOperand(0);
16866 SDValue B = Op.getOperand(1);
16868 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16869 // pairs, multiply and truncate.
16870 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16871 if (Subtarget->hasInt256()) {
16872 if (VT == MVT::v32i8) {
16873 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16874 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16875 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16876 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16877 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16878 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16879 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16880 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16881 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16882 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16885 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16886 return DAG.getNode(
16887 ISD::TRUNCATE, dl, VT,
16888 DAG.getNode(ISD::MUL, dl, ExVT,
16889 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16890 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16893 assert(VT == MVT::v16i8 &&
16894 "Pre-AVX2 support only supports v16i8 multiplication");
16895 MVT ExVT = MVT::v8i16;
16897 // Extract the lo parts and sign extend to i16
16899 if (Subtarget->hasSSE41()) {
16900 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16901 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16903 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16904 -1, 4, -1, 5, -1, 6, -1, 7};
16905 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16906 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16907 ALo = DAG.getBitcast(ExVT, ALo);
16908 BLo = DAG.getBitcast(ExVT, BLo);
16909 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16910 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16913 // Extract the hi parts and sign extend to i16
16915 if (Subtarget->hasSSE41()) {
16916 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16917 -1, -1, -1, -1, -1, -1, -1, -1};
16918 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16919 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16920 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16921 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16923 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16924 -1, 12, -1, 13, -1, 14, -1, 15};
16925 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16926 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16927 AHi = DAG.getBitcast(ExVT, AHi);
16928 BHi = DAG.getBitcast(ExVT, BHi);
16929 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16930 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16933 // Multiply, mask the lower 8bits of the lo/hi results and pack
16934 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16935 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16936 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16937 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16938 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16941 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16942 if (VT == MVT::v4i32) {
16943 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16944 "Should not custom lower when pmuldq is available!");
16946 // Extract the odd parts.
16947 static const int UnpackMask[] = { 1, -1, 3, -1 };
16948 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16949 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16951 // Multiply the even parts.
16952 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16953 // Now multiply odd parts.
16954 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16956 Evens = DAG.getBitcast(VT, Evens);
16957 Odds = DAG.getBitcast(VT, Odds);
16959 // Merge the two vectors back together with a shuffle. This expands into 2
16961 static const int ShufMask[] = { 0, 4, 2, 6 };
16962 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16965 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16966 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16968 // Ahi = psrlqi(a, 32);
16969 // Bhi = psrlqi(b, 32);
16971 // AloBlo = pmuludq(a, b);
16972 // AloBhi = pmuludq(a, Bhi);
16973 // AhiBlo = pmuludq(Ahi, b);
16975 // AloBhi = psllqi(AloBhi, 32);
16976 // AhiBlo = psllqi(AhiBlo, 32);
16977 // return AloBlo + AloBhi + AhiBlo;
16979 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16980 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16982 SDValue AhiBlo = Ahi;
16983 SDValue AloBhi = Bhi;
16984 // Bit cast to 32-bit vectors for MULUDQ
16985 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16986 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16987 A = DAG.getBitcast(MulVT, A);
16988 B = DAG.getBitcast(MulVT, B);
16989 Ahi = DAG.getBitcast(MulVT, Ahi);
16990 Bhi = DAG.getBitcast(MulVT, Bhi);
16992 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16993 // After shifting right const values the result may be all-zero.
16994 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16995 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16996 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16998 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16999 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17000 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17003 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17004 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17007 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17008 assert(Subtarget->isTargetWin64() && "Unexpected target");
17009 EVT VT = Op.getValueType();
17010 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17011 "Unexpected return type for lowering");
17015 switch (Op->getOpcode()) {
17016 default: llvm_unreachable("Unexpected request for libcall!");
17017 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17018 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17019 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17020 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17021 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17022 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17026 SDValue InChain = DAG.getEntryNode();
17028 TargetLowering::ArgListTy Args;
17029 TargetLowering::ArgListEntry Entry;
17030 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17031 EVT ArgVT = Op->getOperand(i).getValueType();
17032 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17033 "Unexpected argument type for lowering");
17034 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17035 Entry.Node = StackPtr;
17036 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17038 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17039 Entry.Ty = PointerType::get(ArgTy,0);
17040 Entry.isSExt = false;
17041 Entry.isZExt = false;
17042 Args.push_back(Entry);
17045 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17046 getPointerTy(DAG.getDataLayout()));
17048 TargetLowering::CallLoweringInfo CLI(DAG);
17049 CLI.setDebugLoc(dl).setChain(InChain)
17050 .setCallee(getLibcallCallingConv(LC),
17051 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17052 Callee, std::move(Args), 0)
17053 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17055 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17056 return DAG.getBitcast(VT, CallInfo.first);
17059 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17060 SelectionDAG &DAG) {
17061 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17062 EVT VT = Op0.getValueType();
17065 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17066 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17068 // PMULxD operations multiply each even value (starting at 0) of LHS with
17069 // the related value of RHS and produce a widen result.
17070 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17071 // => <2 x i64> <ae|cg>
17073 // In other word, to have all the results, we need to perform two PMULxD:
17074 // 1. one with the even values.
17075 // 2. one with the odd values.
17076 // To achieve #2, with need to place the odd values at an even position.
17078 // Place the odd value at an even position (basically, shift all values 1
17079 // step to the left):
17080 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17081 // <a|b|c|d> => <b|undef|d|undef>
17082 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17083 // <e|f|g|h> => <f|undef|h|undef>
17084 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17086 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17088 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17089 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17091 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17092 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17093 // => <2 x i64> <ae|cg>
17094 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17095 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17096 // => <2 x i64> <bf|dh>
17097 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17099 // Shuffle it back into the right order.
17100 SDValue Highs, Lows;
17101 if (VT == MVT::v8i32) {
17102 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17103 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17104 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17105 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17107 const int HighMask[] = {1, 5, 3, 7};
17108 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17109 const int LowMask[] = {0, 4, 2, 6};
17110 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17113 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17114 // unsigned multiply.
17115 if (IsSigned && !Subtarget->hasSSE41()) {
17116 SDValue ShAmt = DAG.getConstant(
17118 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17119 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17120 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17121 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17122 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17124 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17125 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17128 // The first result of MUL_LOHI is actually the low value, followed by the
17130 SDValue Ops[] = {Lows, Highs};
17131 return DAG.getMergeValues(Ops, dl);
17134 // Return true if the required (according to Opcode) shift-imm form is natively
17135 // supported by the Subtarget
17136 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17138 if (VT.getScalarSizeInBits() < 16)
17141 if (VT.is512BitVector() &&
17142 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17145 bool LShift = VT.is128BitVector() ||
17146 (VT.is256BitVector() && Subtarget->hasInt256());
17148 bool AShift = LShift && (Subtarget->hasVLX() ||
17149 (VT != MVT::v2i64 && VT != MVT::v4i64));
17150 return (Opcode == ISD::SRA) ? AShift : LShift;
17153 // The shift amount is a variable, but it is the same for all vector lanes.
17154 // These instructions are defined together with shift-immediate.
17156 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17158 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17161 // Return true if the required (according to Opcode) variable-shift form is
17162 // natively supported by the Subtarget
17163 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17166 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17169 // vXi16 supported only on AVX-512, BWI
17170 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17173 if (VT.is512BitVector() || Subtarget->hasVLX())
17176 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17177 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17178 return (Opcode == ISD::SRA) ? AShift : LShift;
17181 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17182 const X86Subtarget *Subtarget) {
17183 MVT VT = Op.getSimpleValueType();
17185 SDValue R = Op.getOperand(0);
17186 SDValue Amt = Op.getOperand(1);
17188 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17189 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17191 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17192 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17193 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17194 SDValue Ex = DAG.getBitcast(ExVT, R);
17196 if (ShiftAmt >= 32) {
17197 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17199 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17200 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17201 ShiftAmt - 32, DAG);
17202 if (VT == MVT::v2i64)
17203 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17204 if (VT == MVT::v4i64)
17205 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17206 {9, 1, 11, 3, 13, 5, 15, 7});
17208 // SRA upper i32, SHL whole i64 and select lower i32.
17209 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17212 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17213 Lower = DAG.getBitcast(ExVT, Lower);
17214 if (VT == MVT::v2i64)
17215 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17216 if (VT == MVT::v4i64)
17217 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17218 {8, 1, 10, 3, 12, 5, 14, 7});
17220 return DAG.getBitcast(VT, Ex);
17223 // Optimize shl/srl/sra with constant shift amount.
17224 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17225 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17226 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17228 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17229 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17231 // i64 SRA needs to be performed as partial shifts.
17232 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17233 Op.getOpcode() == ISD::SRA)
17234 return ArithmeticShiftRight64(ShiftAmt);
17236 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17237 unsigned NumElts = VT.getVectorNumElements();
17238 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17240 if (Op.getOpcode() == ISD::SHL) {
17241 // Simple i8 add case
17243 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17245 // Make a large shift.
17246 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17248 SHL = DAG.getBitcast(VT, SHL);
17249 // Zero out the rightmost bits.
17250 SmallVector<SDValue, 32> V(
17251 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17252 return DAG.getNode(ISD::AND, dl, VT, SHL,
17253 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17255 if (Op.getOpcode() == ISD::SRL) {
17256 // Make a large shift.
17257 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17259 SRL = DAG.getBitcast(VT, SRL);
17260 // Zero out the leftmost bits.
17261 SmallVector<SDValue, 32> V(
17262 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17263 return DAG.getNode(ISD::AND, dl, VT, SRL,
17264 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17266 if (Op.getOpcode() == ISD::SRA) {
17267 if (ShiftAmt == 7) {
17268 // R s>> 7 === R s< 0
17269 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17270 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17273 // R s>> a === ((R u>> a) ^ m) - m
17274 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17275 SmallVector<SDValue, 32> V(NumElts,
17276 DAG.getConstant(128 >> ShiftAmt, dl,
17278 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17279 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17280 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17283 llvm_unreachable("Unknown shift opcode.");
17288 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17289 if (!Subtarget->is64Bit() &&
17290 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17291 Amt.getOpcode() == ISD::BITCAST &&
17292 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17293 Amt = Amt.getOperand(0);
17294 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17295 VT.getVectorNumElements();
17296 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17297 uint64_t ShiftAmt = 0;
17298 for (unsigned i = 0; i != Ratio; ++i) {
17299 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17303 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17305 // Check remaining shift amounts.
17306 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17307 uint64_t ShAmt = 0;
17308 for (unsigned j = 0; j != Ratio; ++j) {
17309 ConstantSDNode *C =
17310 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17314 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17316 if (ShAmt != ShiftAmt)
17320 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17321 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17323 if (Op.getOpcode() == ISD::SRA)
17324 return ArithmeticShiftRight64(ShiftAmt);
17330 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17331 const X86Subtarget* Subtarget) {
17332 MVT VT = Op.getSimpleValueType();
17334 SDValue R = Op.getOperand(0);
17335 SDValue Amt = Op.getOperand(1);
17337 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17338 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17340 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17341 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17343 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17345 EVT EltVT = VT.getVectorElementType();
17347 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17348 // Check if this build_vector node is doing a splat.
17349 // If so, then set BaseShAmt equal to the splat value.
17350 BaseShAmt = BV->getSplatValue();
17351 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17352 BaseShAmt = SDValue();
17354 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17355 Amt = Amt.getOperand(0);
17357 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17358 if (SVN && SVN->isSplat()) {
17359 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17360 SDValue InVec = Amt.getOperand(0);
17361 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17362 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17363 "Unexpected shuffle index found!");
17364 BaseShAmt = InVec.getOperand(SplatIdx);
17365 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17366 if (ConstantSDNode *C =
17367 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17368 if (C->getZExtValue() == SplatIdx)
17369 BaseShAmt = InVec.getOperand(1);
17374 // Avoid introducing an extract element from a shuffle.
17375 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17376 DAG.getIntPtrConstant(SplatIdx, dl));
17380 if (BaseShAmt.getNode()) {
17381 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17382 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17383 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17384 else if (EltVT.bitsLT(MVT::i32))
17385 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17387 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17391 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17392 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17393 Amt.getOpcode() == ISD::BITCAST &&
17394 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17395 Amt = Amt.getOperand(0);
17396 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17397 VT.getVectorNumElements();
17398 std::vector<SDValue> Vals(Ratio);
17399 for (unsigned i = 0; i != Ratio; ++i)
17400 Vals[i] = Amt.getOperand(i);
17401 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17402 for (unsigned j = 0; j != Ratio; ++j)
17403 if (Vals[j] != Amt.getOperand(i + j))
17407 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17408 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17413 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17414 SelectionDAG &DAG) {
17415 MVT VT = Op.getSimpleValueType();
17417 SDValue R = Op.getOperand(0);
17418 SDValue Amt = Op.getOperand(1);
17420 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17421 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17423 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17426 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17429 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17432 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17433 // shifts per-lane and then shuffle the partial results back together.
17434 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17435 // Splat the shift amounts so the scalar shifts above will catch it.
17436 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17437 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17438 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17439 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17440 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17443 // If possible, lower this packed shift into a vector multiply instead of
17444 // expanding it into a sequence of scalar shifts.
17445 // Do this only if the vector shift count is a constant build_vector.
17446 if (Op.getOpcode() == ISD::SHL &&
17447 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17448 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17449 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17450 SmallVector<SDValue, 8> Elts;
17451 EVT SVT = VT.getScalarType();
17452 unsigned SVTBits = SVT.getSizeInBits();
17453 const APInt &One = APInt(SVTBits, 1);
17454 unsigned NumElems = VT.getVectorNumElements();
17456 for (unsigned i=0; i !=NumElems; ++i) {
17457 SDValue Op = Amt->getOperand(i);
17458 if (Op->getOpcode() == ISD::UNDEF) {
17459 Elts.push_back(Op);
17463 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17464 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17465 uint64_t ShAmt = C.getZExtValue();
17466 if (ShAmt >= SVTBits) {
17467 Elts.push_back(DAG.getUNDEF(SVT));
17470 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17472 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17473 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17476 // Lower SHL with variable shift amount.
17477 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17478 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17480 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17481 DAG.getConstant(0x3f800000U, dl, VT));
17482 Op = DAG.getBitcast(MVT::v4f32, Op);
17483 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17484 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17487 // If possible, lower this shift as a sequence of two shifts by
17488 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17490 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17492 // Could be rewritten as:
17493 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17495 // The advantage is that the two shifts from the example would be
17496 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17497 // the vector shift into four scalar shifts plus four pairs of vector
17499 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17500 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17501 unsigned TargetOpcode = X86ISD::MOVSS;
17502 bool CanBeSimplified;
17503 // The splat value for the first packed shift (the 'X' from the example).
17504 SDValue Amt1 = Amt->getOperand(0);
17505 // The splat value for the second packed shift (the 'Y' from the example).
17506 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17507 Amt->getOperand(2);
17509 // See if it is possible to replace this node with a sequence of
17510 // two shifts followed by a MOVSS/MOVSD
17511 if (VT == MVT::v4i32) {
17512 // Check if it is legal to use a MOVSS.
17513 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17514 Amt2 == Amt->getOperand(3);
17515 if (!CanBeSimplified) {
17516 // Otherwise, check if we can still simplify this node using a MOVSD.
17517 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17518 Amt->getOperand(2) == Amt->getOperand(3);
17519 TargetOpcode = X86ISD::MOVSD;
17520 Amt2 = Amt->getOperand(2);
17523 // Do similar checks for the case where the machine value type
17525 CanBeSimplified = Amt1 == Amt->getOperand(1);
17526 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17527 CanBeSimplified = Amt2 == Amt->getOperand(i);
17529 if (!CanBeSimplified) {
17530 TargetOpcode = X86ISD::MOVSD;
17531 CanBeSimplified = true;
17532 Amt2 = Amt->getOperand(4);
17533 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17534 CanBeSimplified = Amt1 == Amt->getOperand(i);
17535 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17536 CanBeSimplified = Amt2 == Amt->getOperand(j);
17540 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17541 isa<ConstantSDNode>(Amt2)) {
17542 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17543 EVT CastVT = MVT::v4i32;
17545 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17546 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17548 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17549 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17550 if (TargetOpcode == X86ISD::MOVSD)
17551 CastVT = MVT::v2i64;
17552 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17553 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17554 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17556 return DAG.getBitcast(VT, Result);
17560 // v4i32 Non Uniform Shifts.
17561 // If the shift amount is constant we can shift each lane using the SSE2
17562 // immediate shifts, else we need to zero-extend each lane to the lower i64
17563 // and shift using the SSE2 variable shifts.
17564 // The separate results can then be blended together.
17565 if (VT == MVT::v4i32) {
17566 unsigned Opc = Op.getOpcode();
17567 SDValue Amt0, Amt1, Amt2, Amt3;
17568 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17569 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17570 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17571 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17572 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17574 // ISD::SHL is handled above but we include it here for completeness.
17577 llvm_unreachable("Unknown target vector shift node");
17579 Opc = X86ISD::VSHL;
17582 Opc = X86ISD::VSRL;
17585 Opc = X86ISD::VSRA;
17588 // The SSE2 shifts use the lower i64 as the same shift amount for
17589 // all lanes and the upper i64 is ignored. These shuffle masks
17590 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17591 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17592 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17593 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17594 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17595 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17598 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17599 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17600 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17601 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17602 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17603 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17604 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17607 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17608 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17609 unsigned ShiftOpcode = Op->getOpcode();
17611 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17612 // On SSE41 targets we make use of the fact that VSELECT lowers
17613 // to PBLENDVB which selects bytes based just on the sign bit.
17614 if (Subtarget->hasSSE41()) {
17615 V0 = DAG.getBitcast(VT, V0);
17616 V1 = DAG.getBitcast(VT, V1);
17617 Sel = DAG.getBitcast(VT, Sel);
17618 return DAG.getBitcast(SelVT,
17619 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17621 // On pre-SSE41 targets we test for the sign bit by comparing to
17622 // zero - a negative value will set all bits of the lanes to true
17623 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17624 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17625 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17626 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17629 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17630 // We can safely do this using i16 shifts as we're only interested in
17631 // the 3 lower bits of each byte.
17632 Amt = DAG.getBitcast(ExtVT, Amt);
17633 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17634 Amt = DAG.getBitcast(VT, Amt);
17636 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17637 // r = VSELECT(r, shift(r, 4), a);
17639 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17640 R = SignBitSelect(VT, Amt, M, R);
17643 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17645 // r = VSELECT(r, shift(r, 2), a);
17646 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17647 R = SignBitSelect(VT, Amt, M, R);
17650 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17652 // return VSELECT(r, shift(r, 1), a);
17653 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17654 R = SignBitSelect(VT, Amt, M, R);
17658 if (Op->getOpcode() == ISD::SRA) {
17659 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17660 // so we can correctly sign extend. We don't care what happens to the
17662 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17663 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17664 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17665 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17666 ALo = DAG.getBitcast(ExtVT, ALo);
17667 AHi = DAG.getBitcast(ExtVT, AHi);
17668 RLo = DAG.getBitcast(ExtVT, RLo);
17669 RHi = DAG.getBitcast(ExtVT, RHi);
17671 // r = VSELECT(r, shift(r, 4), a);
17672 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17673 DAG.getConstant(4, dl, ExtVT));
17674 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17675 DAG.getConstant(4, dl, ExtVT));
17676 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17677 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17680 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17681 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17683 // r = VSELECT(r, shift(r, 2), a);
17684 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17685 DAG.getConstant(2, dl, ExtVT));
17686 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17687 DAG.getConstant(2, dl, ExtVT));
17688 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17689 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17692 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17693 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17695 // r = VSELECT(r, shift(r, 1), a);
17696 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17697 DAG.getConstant(1, dl, ExtVT));
17698 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17699 DAG.getConstant(1, dl, ExtVT));
17700 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17701 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17703 // Logical shift the result back to the lower byte, leaving a zero upper
17705 // meaning that we can safely pack with PACKUSWB.
17707 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17709 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17710 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17714 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17715 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17716 // solution better.
17717 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17718 MVT ExtVT = MVT::v8i32;
17720 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17721 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17722 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17723 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17724 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17727 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17728 MVT ExtVT = MVT::v8i32;
17729 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17730 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17731 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17732 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17733 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17734 ALo = DAG.getBitcast(ExtVT, ALo);
17735 AHi = DAG.getBitcast(ExtVT, AHi);
17736 RLo = DAG.getBitcast(ExtVT, RLo);
17737 RHi = DAG.getBitcast(ExtVT, RHi);
17738 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17739 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17740 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17741 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17742 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17745 if (VT == MVT::v8i16) {
17746 unsigned ShiftOpcode = Op->getOpcode();
17748 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17749 // On SSE41 targets we make use of the fact that VSELECT lowers
17750 // to PBLENDVB which selects bytes based just on the sign bit.
17751 if (Subtarget->hasSSE41()) {
17752 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17753 V0 = DAG.getBitcast(ExtVT, V0);
17754 V1 = DAG.getBitcast(ExtVT, V1);
17755 Sel = DAG.getBitcast(ExtVT, Sel);
17756 return DAG.getBitcast(
17757 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17759 // On pre-SSE41 targets we splat the sign bit - a negative value will
17760 // set all bits of the lanes to true and VSELECT uses that in
17761 // its OR(AND(V0,C),AND(V1,~C)) lowering.
17763 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17764 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17767 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17768 if (Subtarget->hasSSE41()) {
17769 // On SSE41 targets we need to replicate the shift mask in both
17770 // bytes for PBLENDVB.
17773 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17774 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17776 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17779 // r = VSELECT(r, shift(r, 8), a);
17780 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17781 R = SignBitSelect(Amt, M, R);
17784 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17786 // r = VSELECT(r, shift(r, 4), a);
17787 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17788 R = SignBitSelect(Amt, M, R);
17791 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17793 // r = VSELECT(r, shift(r, 2), a);
17794 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17795 R = SignBitSelect(Amt, M, R);
17798 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17800 // return VSELECT(r, shift(r, 1), a);
17801 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17802 R = SignBitSelect(Amt, M, R);
17806 // Decompose 256-bit shifts into smaller 128-bit shifts.
17807 if (VT.is256BitVector()) {
17808 unsigned NumElems = VT.getVectorNumElements();
17809 MVT EltVT = VT.getVectorElementType();
17810 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17812 // Extract the two vectors
17813 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17814 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17816 // Recreate the shift amount vectors
17817 SDValue Amt1, Amt2;
17818 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17819 // Constant shift amount
17820 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17821 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17822 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17824 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17825 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17827 // Variable shift amount
17828 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17829 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17832 // Issue new vector shifts for the smaller types
17833 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17834 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17836 // Concatenate the result back
17837 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17843 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17844 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17845 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17846 // looks for this combo and may remove the "setcc" instruction if the "setcc"
17847 // has only one use.
17848 SDNode *N = Op.getNode();
17849 SDValue LHS = N->getOperand(0);
17850 SDValue RHS = N->getOperand(1);
17851 unsigned BaseOp = 0;
17854 switch (Op.getOpcode()) {
17855 default: llvm_unreachable("Unknown ovf instruction!");
17857 // A subtract of one will be selected as a INC. Note that INC doesn't
17858 // set CF, so we can't do this for UADDO.
17859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17861 BaseOp = X86ISD::INC;
17862 Cond = X86::COND_O;
17865 BaseOp = X86ISD::ADD;
17866 Cond = X86::COND_O;
17869 BaseOp = X86ISD::ADD;
17870 Cond = X86::COND_B;
17873 // A subtract of one will be selected as a DEC. Note that DEC doesn't
17874 // set CF, so we can't do this for USUBO.
17875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17877 BaseOp = X86ISD::DEC;
17878 Cond = X86::COND_O;
17881 BaseOp = X86ISD::SUB;
17882 Cond = X86::COND_O;
17885 BaseOp = X86ISD::SUB;
17886 Cond = X86::COND_B;
17889 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17890 Cond = X86::COND_O;
17892 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17893 if (N->getValueType(0) == MVT::i8) {
17894 BaseOp = X86ISD::UMUL8;
17895 Cond = X86::COND_O;
17898 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17900 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17903 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17904 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17905 SDValue(Sum.getNode(), 2));
17907 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17911 // Also sets EFLAGS.
17912 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17913 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17916 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17917 DAG.getConstant(Cond, DL, MVT::i32),
17918 SDValue(Sum.getNode(), 1));
17920 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17923 /// Returns true if the operand type is exactly twice the native width, and
17924 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17925 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17926 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17927 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17928 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17931 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17932 else if (OpWidth == 128)
17933 return Subtarget->hasCmpxchg16b();
17938 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17939 return needsCmpXchgNb(SI->getValueOperand()->getType());
17942 // Note: this turns large loads into lock cmpxchg8b/16b.
17943 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17944 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17945 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17946 return needsCmpXchgNb(PTy->getElementType());
17949 TargetLoweringBase::AtomicRMWExpansionKind
17950 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17951 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17952 const Type *MemType = AI->getType();
17954 // If the operand is too big, we must see if cmpxchg8/16b is available
17955 // and default to library calls otherwise.
17956 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17957 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17958 : AtomicRMWExpansionKind::None;
17961 AtomicRMWInst::BinOp Op = AI->getOperation();
17964 llvm_unreachable("Unknown atomic operation");
17965 case AtomicRMWInst::Xchg:
17966 case AtomicRMWInst::Add:
17967 case AtomicRMWInst::Sub:
17968 // It's better to use xadd, xsub or xchg for these in all cases.
17969 return AtomicRMWExpansionKind::None;
17970 case AtomicRMWInst::Or:
17971 case AtomicRMWInst::And:
17972 case AtomicRMWInst::Xor:
17973 // If the atomicrmw's result isn't actually used, we can just add a "lock"
17974 // prefix to a normal instruction for these operations.
17975 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17976 : AtomicRMWExpansionKind::None;
17977 case AtomicRMWInst::Nand:
17978 case AtomicRMWInst::Max:
17979 case AtomicRMWInst::Min:
17980 case AtomicRMWInst::UMax:
17981 case AtomicRMWInst::UMin:
17982 // These always require a non-trivial set of data operations on x86. We must
17983 // use a cmpxchg loop.
17984 return AtomicRMWExpansionKind::CmpXChg;
17988 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17989 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17990 // no-sse2). There isn't any reason to disable it if the target processor
17992 return Subtarget.hasSSE2() || Subtarget.is64Bit();
17996 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17997 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17998 const Type *MemType = AI->getType();
17999 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18000 // there is no benefit in turning such RMWs into loads, and it is actually
18001 // harmful as it introduces a mfence.
18002 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18005 auto Builder = IRBuilder<>(AI);
18006 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18007 auto SynchScope = AI->getSynchScope();
18008 // We must restrict the ordering to avoid generating loads with Release or
18009 // ReleaseAcquire orderings.
18010 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18011 auto Ptr = AI->getPointerOperand();
18013 // Before the load we need a fence. Here is an example lifted from
18014 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18017 // x.store(1, relaxed);
18018 // r1 = y.fetch_add(0, release);
18020 // y.fetch_add(42, acquire);
18021 // r2 = x.load(relaxed);
18022 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18023 // lowered to just a load without a fence. A mfence flushes the store buffer,
18024 // making the optimization clearly correct.
18025 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18026 // otherwise, we might be able to be more agressive on relaxed idempotent
18027 // rmw. In practice, they do not look useful, so we don't try to be
18028 // especially clever.
18029 if (SynchScope == SingleThread)
18030 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18031 // the IR level, so we must wrap it in an intrinsic.
18034 if (!hasMFENCE(*Subtarget))
18035 // FIXME: it might make sense to use a locked operation here but on a
18036 // different cache-line to prevent cache-line bouncing. In practice it
18037 // is probably a small win, and x86 processors without mfence are rare
18038 // enough that we do not bother.
18042 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18043 Builder.CreateCall(MFence, {});
18045 // Finally we can emit the atomic load.
18046 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18047 AI->getType()->getPrimitiveSizeInBits());
18048 Loaded->setAtomic(Order, SynchScope);
18049 AI->replaceAllUsesWith(Loaded);
18050 AI->eraseFromParent();
18054 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18055 SelectionDAG &DAG) {
18057 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18058 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18059 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18060 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18062 // The only fence that needs an instruction is a sequentially-consistent
18063 // cross-thread fence.
18064 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18065 if (hasMFENCE(*Subtarget))
18066 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18068 SDValue Chain = Op.getOperand(0);
18069 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18071 DAG.getRegister(X86::ESP, MVT::i32), // Base
18072 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18073 DAG.getRegister(0, MVT::i32), // Index
18074 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18075 DAG.getRegister(0, MVT::i32), // Segment.
18079 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18080 return SDValue(Res, 0);
18083 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18084 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18087 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18088 SelectionDAG &DAG) {
18089 MVT T = Op.getSimpleValueType();
18093 switch(T.SimpleTy) {
18094 default: llvm_unreachable("Invalid value type!");
18095 case MVT::i8: Reg = X86::AL; size = 1; break;
18096 case MVT::i16: Reg = X86::AX; size = 2; break;
18097 case MVT::i32: Reg = X86::EAX; size = 4; break;
18099 assert(Subtarget->is64Bit() && "Node not type legal!");
18100 Reg = X86::RAX; size = 8;
18103 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18104 Op.getOperand(2), SDValue());
18105 SDValue Ops[] = { cpIn.getValue(0),
18108 DAG.getTargetConstant(size, DL, MVT::i8),
18109 cpIn.getValue(1) };
18110 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18111 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18112 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18116 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18117 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18118 MVT::i32, cpOut.getValue(2));
18119 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18120 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18123 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18124 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18125 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18129 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18130 SelectionDAG &DAG) {
18131 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18132 MVT DstVT = Op.getSimpleValueType();
18134 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18135 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18136 if (DstVT != MVT::f64)
18137 // This conversion needs to be expanded.
18140 SDValue InVec = Op->getOperand(0);
18142 unsigned NumElts = SrcVT.getVectorNumElements();
18143 EVT SVT = SrcVT.getVectorElementType();
18145 // Widen the vector in input in the case of MVT::v2i32.
18146 // Example: from MVT::v2i32 to MVT::v4i32.
18147 SmallVector<SDValue, 16> Elts;
18148 for (unsigned i = 0, e = NumElts; i != e; ++i)
18149 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18150 DAG.getIntPtrConstant(i, dl)));
18152 // Explicitly mark the extra elements as Undef.
18153 Elts.append(NumElts, DAG.getUNDEF(SVT));
18155 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18156 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18157 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18158 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18159 DAG.getIntPtrConstant(0, dl));
18162 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18163 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18164 assert((DstVT == MVT::i64 ||
18165 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18166 "Unexpected custom BITCAST");
18167 // i64 <=> MMX conversions are Legal.
18168 if (SrcVT==MVT::i64 && DstVT.isVector())
18170 if (DstVT==MVT::i64 && SrcVT.isVector())
18172 // MMX <=> MMX conversions are Legal.
18173 if (SrcVT.isVector() && DstVT.isVector())
18175 // All other conversions need to be expanded.
18179 /// Compute the horizontal sum of bytes in V for the elements of VT.
18181 /// Requires V to be a byte vector and VT to be an integer vector type with
18182 /// wider elements than V's type. The width of the elements of VT determines
18183 /// how many bytes of V are summed horizontally to produce each element of the
18185 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18186 const X86Subtarget *Subtarget,
18187 SelectionDAG &DAG) {
18189 MVT ByteVecVT = V.getSimpleValueType();
18190 MVT EltVT = VT.getVectorElementType();
18191 int NumElts = VT.getVectorNumElements();
18192 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18193 "Expected value to have byte element type.");
18194 assert(EltVT != MVT::i8 &&
18195 "Horizontal byte sum only makes sense for wider elements!");
18196 unsigned VecSize = VT.getSizeInBits();
18197 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18199 // PSADBW instruction horizontally add all bytes and leave the result in i64
18200 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18201 if (EltVT == MVT::i64) {
18202 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18203 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18204 return DAG.getBitcast(VT, V);
18207 if (EltVT == MVT::i32) {
18208 // We unpack the low half and high half into i32s interleaved with zeros so
18209 // that we can use PSADBW to horizontally sum them. The most useful part of
18210 // this is that it lines up the results of two PSADBW instructions to be
18211 // two v2i64 vectors which concatenated are the 4 population counts. We can
18212 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18213 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18214 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18215 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18217 // Do the horizontal sums into two v2i64s.
18218 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18219 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18220 DAG.getBitcast(ByteVecVT, Low), Zeros);
18221 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18222 DAG.getBitcast(ByteVecVT, High), Zeros);
18224 // Merge them together.
18225 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18226 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18227 DAG.getBitcast(ShortVecVT, Low),
18228 DAG.getBitcast(ShortVecVT, High));
18230 return DAG.getBitcast(VT, V);
18233 // The only element type left is i16.
18234 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18236 // To obtain pop count for each i16 element starting from the pop count for
18237 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18238 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18239 // directly supported.
18240 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18241 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18242 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18243 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18244 DAG.getBitcast(ByteVecVT, V));
18245 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18248 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18249 const X86Subtarget *Subtarget,
18250 SelectionDAG &DAG) {
18251 MVT VT = Op.getSimpleValueType();
18252 MVT EltVT = VT.getVectorElementType();
18253 unsigned VecSize = VT.getSizeInBits();
18255 // Implement a lookup table in register by using an algorithm based on:
18256 // http://wm.ite.pl/articles/sse-popcount.html
18258 // The general idea is that every lower byte nibble in the input vector is an
18259 // index into a in-register pre-computed pop count table. We then split up the
18260 // input vector in two new ones: (1) a vector with only the shifted-right
18261 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18262 // masked out higher ones) for each byte. PSHUB is used separately with both
18263 // to index the in-register table. Next, both are added and the result is a
18264 // i8 vector where each element contains the pop count for input byte.
18266 // To obtain the pop count for elements != i8, we follow up with the same
18267 // approach and use additional tricks as described below.
18269 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18270 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18271 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18272 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18274 int NumByteElts = VecSize / 8;
18275 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18276 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18277 SmallVector<SDValue, 16> LUTVec;
18278 for (int i = 0; i < NumByteElts; ++i)
18279 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18280 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18281 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18282 DAG.getConstant(0x0F, DL, MVT::i8));
18283 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18286 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18287 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18288 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18291 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18293 // The input vector is used as the shuffle mask that index elements into the
18294 // LUT. After counting low and high nibbles, add the vector to obtain the
18295 // final pop count per i8 element.
18296 SDValue HighPopCnt =
18297 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18298 SDValue LowPopCnt =
18299 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18300 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18302 if (EltVT == MVT::i8)
18305 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18308 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18309 const X86Subtarget *Subtarget,
18310 SelectionDAG &DAG) {
18311 MVT VT = Op.getSimpleValueType();
18312 assert(VT.is128BitVector() &&
18313 "Only 128-bit vector bitmath lowering supported.");
18315 int VecSize = VT.getSizeInBits();
18316 MVT EltVT = VT.getVectorElementType();
18317 int Len = EltVT.getSizeInBits();
18319 // This is the vectorized version of the "best" algorithm from
18320 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18321 // with a minor tweak to use a series of adds + shifts instead of vector
18322 // multiplications. Implemented for all integer vector types. We only use
18323 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18324 // much faster, even faster than using native popcnt instructions.
18326 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18327 MVT VT = V.getSimpleValueType();
18328 SmallVector<SDValue, 32> Shifters(
18329 VT.getVectorNumElements(),
18330 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18331 return DAG.getNode(OpCode, DL, VT, V,
18332 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18334 auto GetMask = [&](SDValue V, APInt Mask) {
18335 MVT VT = V.getSimpleValueType();
18336 SmallVector<SDValue, 32> Masks(
18337 VT.getVectorNumElements(),
18338 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18339 return DAG.getNode(ISD::AND, DL, VT, V,
18340 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18343 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18344 // x86, so set the SRL type to have elements at least i16 wide. This is
18345 // correct because all of our SRLs are followed immediately by a mask anyways
18346 // that handles any bits that sneak into the high bits of the byte elements.
18347 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18351 // v = v - ((v >> 1) & 0x55555555...)
18353 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18354 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18355 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18357 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18358 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18359 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18360 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18361 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18363 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18364 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18365 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18366 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18368 // At this point, V contains the byte-wise population count, and we are
18369 // merely doing a horizontal sum if necessary to get the wider element
18371 if (EltVT == MVT::i8)
18374 return LowerHorizontalByteSum(
18375 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18379 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18380 SelectionDAG &DAG) {
18381 MVT VT = Op.getSimpleValueType();
18382 // FIXME: Need to add AVX-512 support here!
18383 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18384 "Unknown CTPOP type to handle");
18385 SDLoc DL(Op.getNode());
18386 SDValue Op0 = Op.getOperand(0);
18388 if (!Subtarget->hasSSSE3()) {
18389 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18390 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18391 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18394 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18395 unsigned NumElems = VT.getVectorNumElements();
18397 // Extract each 128-bit vector, compute pop count and concat the result.
18398 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18399 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18401 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18402 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18403 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18406 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18409 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18410 SelectionDAG &DAG) {
18411 assert(Op.getValueType().isVector() &&
18412 "We only do custom lowering for vector population count.");
18413 return LowerVectorCTPOP(Op, Subtarget, DAG);
18416 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18417 SDNode *Node = Op.getNode();
18419 EVT T = Node->getValueType(0);
18420 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18421 DAG.getConstant(0, dl, T), Node->getOperand(2));
18422 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18423 cast<AtomicSDNode>(Node)->getMemoryVT(),
18424 Node->getOperand(0),
18425 Node->getOperand(1), negOp,
18426 cast<AtomicSDNode>(Node)->getMemOperand(),
18427 cast<AtomicSDNode>(Node)->getOrdering(),
18428 cast<AtomicSDNode>(Node)->getSynchScope());
18431 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18432 SDNode *Node = Op.getNode();
18434 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18436 // Convert seq_cst store -> xchg
18437 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18438 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18439 // (The only way to get a 16-byte store is cmpxchg16b)
18440 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18441 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18442 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18443 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18444 cast<AtomicSDNode>(Node)->getMemoryVT(),
18445 Node->getOperand(0),
18446 Node->getOperand(1), Node->getOperand(2),
18447 cast<AtomicSDNode>(Node)->getMemOperand(),
18448 cast<AtomicSDNode>(Node)->getOrdering(),
18449 cast<AtomicSDNode>(Node)->getSynchScope());
18450 return Swap.getValue(1);
18452 // Other atomic stores have a simple pattern.
18456 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18457 EVT VT = Op.getNode()->getSimpleValueType(0);
18459 // Let legalize expand this if it isn't a legal type yet.
18460 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18463 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18466 bool ExtraOp = false;
18467 switch (Op.getOpcode()) {
18468 default: llvm_unreachable("Invalid code");
18469 case ISD::ADDC: Opc = X86ISD::ADD; break;
18470 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18471 case ISD::SUBC: Opc = X86ISD::SUB; break;
18472 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18476 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18478 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18479 Op.getOperand(1), Op.getOperand(2));
18482 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18483 SelectionDAG &DAG) {
18484 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18486 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18487 // which returns the values as { float, float } (in XMM0) or
18488 // { double, double } (which is returned in XMM0, XMM1).
18490 SDValue Arg = Op.getOperand(0);
18491 EVT ArgVT = Arg.getValueType();
18492 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18494 TargetLowering::ArgListTy Args;
18495 TargetLowering::ArgListEntry Entry;
18499 Entry.isSExt = false;
18500 Entry.isZExt = false;
18501 Args.push_back(Entry);
18503 bool isF64 = ArgVT == MVT::f64;
18504 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18505 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18506 // the results are returned via SRet in memory.
18507 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18508 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18510 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18512 Type *RetTy = isF64
18513 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18514 : (Type*)VectorType::get(ArgTy, 4);
18516 TargetLowering::CallLoweringInfo CLI(DAG);
18517 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18518 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18520 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18523 // Returned in xmm0 and xmm1.
18524 return CallResult.first;
18526 // Returned in bits 0:31 and 32:64 xmm0.
18527 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18528 CallResult.first, DAG.getIntPtrConstant(0, dl));
18529 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18530 CallResult.first, DAG.getIntPtrConstant(1, dl));
18531 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18532 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18535 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18536 SelectionDAG &DAG) {
18537 assert(Subtarget->hasAVX512() &&
18538 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18540 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18541 EVT VT = N->getValue().getValueType();
18542 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18545 // X86 scatter kills mask register, so its type should be added to
18546 // the list of return values
18547 if (N->getNumValues() == 1) {
18548 SDValue Index = N->getIndex();
18549 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18550 !Index.getValueType().is512BitVector())
18551 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18553 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18554 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18555 N->getOperand(3), Index };
18557 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18558 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18559 return SDValue(NewScatter.getNode(), 0);
18564 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18565 SelectionDAG &DAG) {
18566 assert(Subtarget->hasAVX512() &&
18567 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18569 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18570 EVT VT = Op.getValueType();
18571 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18574 SDValue Index = N->getIndex();
18575 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18576 !Index.getValueType().is512BitVector()) {
18577 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18578 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18579 N->getOperand(3), Index };
18580 DAG.UpdateNodeOperands(N, Ops);
18585 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18586 SelectionDAG &DAG) const {
18587 // TODO: Eventually, the lowering of these nodes should be informed by or
18588 // deferred to the GC strategy for the function in which they appear. For
18589 // now, however, they must be lowered to something. Since they are logically
18590 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18591 // require special handling for these nodes), lower them as literal NOOPs for
18593 SmallVector<SDValue, 2> Ops;
18595 Ops.push_back(Op.getOperand(0));
18596 if (Op->getGluedNode())
18597 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18600 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18601 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18606 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18607 SelectionDAG &DAG) const {
18608 // TODO: Eventually, the lowering of these nodes should be informed by or
18609 // deferred to the GC strategy for the function in which they appear. For
18610 // now, however, they must be lowered to something. Since they are logically
18611 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18612 // require special handling for these nodes), lower them as literal NOOPs for
18614 SmallVector<SDValue, 2> Ops;
18616 Ops.push_back(Op.getOperand(0));
18617 if (Op->getGluedNode())
18618 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18621 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18622 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18627 /// LowerOperation - Provide custom lowering hooks for some operations.
18629 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18630 switch (Op.getOpcode()) {
18631 default: llvm_unreachable("Should not custom lower this!");
18632 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18633 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18634 return LowerCMP_SWAP(Op, Subtarget, DAG);
18635 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18636 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18637 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18638 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18639 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18640 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18641 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18642 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18643 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18644 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18645 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18646 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18647 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18648 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18649 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18650 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18651 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18652 case ISD::SHL_PARTS:
18653 case ISD::SRA_PARTS:
18654 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18655 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18656 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18657 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18658 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18659 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18660 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18661 case ISD::SIGN_EXTEND_VECTOR_INREG:
18662 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18663 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18664 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18665 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18666 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18668 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18669 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18670 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18671 case ISD::SETCC: return LowerSETCC(Op, DAG);
18672 case ISD::SELECT: return LowerSELECT(Op, DAG);
18673 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18674 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18675 case ISD::VASTART: return LowerVASTART(Op, DAG);
18676 case ISD::VAARG: return LowerVAARG(Op, DAG);
18677 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18678 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18679 case ISD::INTRINSIC_VOID:
18680 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18681 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18682 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18683 case ISD::FRAME_TO_ARGS_OFFSET:
18684 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18685 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18686 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18687 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18688 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18689 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18690 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18691 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18692 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18693 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18694 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18695 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18696 case ISD::UMUL_LOHI:
18697 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18700 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18706 case ISD::UMULO: return LowerXALUO(Op, DAG);
18707 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18708 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18712 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18713 case ISD::ADD: return LowerADD(Op, DAG);
18714 case ISD::SUB: return LowerSUB(Op, DAG);
18715 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18716 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18717 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18718 case ISD::GC_TRANSITION_START:
18719 return LowerGC_TRANSITION_START(Op, DAG);
18720 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18724 /// ReplaceNodeResults - Replace a node with an illegal result type
18725 /// with a new node built out of custom code.
18726 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18727 SmallVectorImpl<SDValue>&Results,
18728 SelectionDAG &DAG) const {
18730 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18731 switch (N->getOpcode()) {
18733 llvm_unreachable("Do not know how to custom type legalize this operation!");
18734 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18735 case X86ISD::FMINC:
18737 case X86ISD::FMAXC:
18738 case X86ISD::FMAX: {
18739 EVT VT = N->getValueType(0);
18740 if (VT != MVT::v2f32)
18741 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18742 SDValue UNDEF = DAG.getUNDEF(VT);
18743 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18744 N->getOperand(0), UNDEF);
18745 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18746 N->getOperand(1), UNDEF);
18747 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18750 case ISD::SIGN_EXTEND_INREG:
18755 // We don't want to expand or promote these.
18762 case ISD::UDIVREM: {
18763 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18764 Results.push_back(V);
18767 case ISD::FP_TO_SINT:
18768 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
18769 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18770 if (N->getOperand(0).getValueType() == MVT::f16)
18773 case ISD::FP_TO_UINT: {
18774 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18776 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18779 std::pair<SDValue,SDValue> Vals =
18780 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18781 SDValue FIST = Vals.first, StackSlot = Vals.second;
18782 if (FIST.getNode()) {
18783 EVT VT = N->getValueType(0);
18784 // Return a load from the stack slot.
18785 if (StackSlot.getNode())
18786 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18787 MachinePointerInfo(),
18788 false, false, false, 0));
18790 Results.push_back(FIST);
18794 case ISD::UINT_TO_FP: {
18795 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18796 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18797 N->getValueType(0) != MVT::v2f32)
18799 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18801 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18803 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18804 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18805 DAG.getBitcast(MVT::v2i64, VBias));
18806 Or = DAG.getBitcast(MVT::v2f64, Or);
18807 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18808 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18811 case ISD::FP_ROUND: {
18812 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18814 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18815 Results.push_back(V);
18818 case ISD::FP_EXTEND: {
18819 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18820 // No other ValueType for FP_EXTEND should reach this point.
18821 assert(N->getValueType(0) == MVT::v2f32 &&
18822 "Do not know how to legalize this Node");
18825 case ISD::INTRINSIC_W_CHAIN: {
18826 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18828 default : llvm_unreachable("Do not know how to custom type "
18829 "legalize this intrinsic operation!");
18830 case Intrinsic::x86_rdtsc:
18831 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18833 case Intrinsic::x86_rdtscp:
18834 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18836 case Intrinsic::x86_rdpmc:
18837 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18840 case ISD::READCYCLECOUNTER: {
18841 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18844 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18845 EVT T = N->getValueType(0);
18846 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18847 bool Regs64bit = T == MVT::i128;
18848 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18849 SDValue cpInL, cpInH;
18850 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18851 DAG.getConstant(0, dl, HalfT));
18852 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18853 DAG.getConstant(1, dl, HalfT));
18854 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18855 Regs64bit ? X86::RAX : X86::EAX,
18857 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18858 Regs64bit ? X86::RDX : X86::EDX,
18859 cpInH, cpInL.getValue(1));
18860 SDValue swapInL, swapInH;
18861 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18862 DAG.getConstant(0, dl, HalfT));
18863 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18864 DAG.getConstant(1, dl, HalfT));
18865 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18866 Regs64bit ? X86::RBX : X86::EBX,
18867 swapInL, cpInH.getValue(1));
18868 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18869 Regs64bit ? X86::RCX : X86::ECX,
18870 swapInH, swapInL.getValue(1));
18871 SDValue Ops[] = { swapInH.getValue(0),
18873 swapInH.getValue(1) };
18874 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18875 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18876 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18877 X86ISD::LCMPXCHG8_DAG;
18878 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18879 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18880 Regs64bit ? X86::RAX : X86::EAX,
18881 HalfT, Result.getValue(1));
18882 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18883 Regs64bit ? X86::RDX : X86::EDX,
18884 HalfT, cpOutL.getValue(2));
18885 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18887 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18888 MVT::i32, cpOutH.getValue(2));
18890 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18891 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18892 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18894 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18895 Results.push_back(Success);
18896 Results.push_back(EFLAGS.getValue(1));
18899 case ISD::ATOMIC_SWAP:
18900 case ISD::ATOMIC_LOAD_ADD:
18901 case ISD::ATOMIC_LOAD_SUB:
18902 case ISD::ATOMIC_LOAD_AND:
18903 case ISD::ATOMIC_LOAD_OR:
18904 case ISD::ATOMIC_LOAD_XOR:
18905 case ISD::ATOMIC_LOAD_NAND:
18906 case ISD::ATOMIC_LOAD_MIN:
18907 case ISD::ATOMIC_LOAD_MAX:
18908 case ISD::ATOMIC_LOAD_UMIN:
18909 case ISD::ATOMIC_LOAD_UMAX:
18910 case ISD::ATOMIC_LOAD: {
18911 // Delegate to generic TypeLegalization. Situations we can really handle
18912 // should have already been dealt with by AtomicExpandPass.cpp.
18915 case ISD::BITCAST: {
18916 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18917 EVT DstVT = N->getValueType(0);
18918 EVT SrcVT = N->getOperand(0)->getValueType(0);
18920 if (SrcVT != MVT::f64 ||
18921 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18924 unsigned NumElts = DstVT.getVectorNumElements();
18925 EVT SVT = DstVT.getVectorElementType();
18926 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18927 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18928 MVT::v2f64, N->getOperand(0));
18929 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18931 if (ExperimentalVectorWideningLegalization) {
18932 // If we are legalizing vectors by widening, we already have the desired
18933 // legal vector type, just return it.
18934 Results.push_back(ToVecInt);
18938 SmallVector<SDValue, 8> Elts;
18939 for (unsigned i = 0, e = NumElts; i != e; ++i)
18940 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18941 ToVecInt, DAG.getIntPtrConstant(i, dl)));
18943 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18948 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18949 switch ((X86ISD::NodeType)Opcode) {
18950 case X86ISD::FIRST_NUMBER: break;
18951 case X86ISD::BSF: return "X86ISD::BSF";
18952 case X86ISD::BSR: return "X86ISD::BSR";
18953 case X86ISD::SHLD: return "X86ISD::SHLD";
18954 case X86ISD::SHRD: return "X86ISD::SHRD";
18955 case X86ISD::FAND: return "X86ISD::FAND";
18956 case X86ISD::FANDN: return "X86ISD::FANDN";
18957 case X86ISD::FOR: return "X86ISD::FOR";
18958 case X86ISD::FXOR: return "X86ISD::FXOR";
18959 case X86ISD::FILD: return "X86ISD::FILD";
18960 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
18961 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18962 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18963 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18964 case X86ISD::FLD: return "X86ISD::FLD";
18965 case X86ISD::FST: return "X86ISD::FST";
18966 case X86ISD::CALL: return "X86ISD::CALL";
18967 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
18968 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
18969 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
18970 case X86ISD::BT: return "X86ISD::BT";
18971 case X86ISD::CMP: return "X86ISD::CMP";
18972 case X86ISD::COMI: return "X86ISD::COMI";
18973 case X86ISD::UCOMI: return "X86ISD::UCOMI";
18974 case X86ISD::CMPM: return "X86ISD::CMPM";
18975 case X86ISD::CMPMU: return "X86ISD::CMPMU";
18976 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
18977 case X86ISD::SETCC: return "X86ISD::SETCC";
18978 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
18979 case X86ISD::FSETCC: return "X86ISD::FSETCC";
18980 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
18981 case X86ISD::CMOV: return "X86ISD::CMOV";
18982 case X86ISD::BRCOND: return "X86ISD::BRCOND";
18983 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
18984 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
18985 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
18986 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
18987 case X86ISD::Wrapper: return "X86ISD::Wrapper";
18988 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
18989 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
18990 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
18991 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
18992 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
18993 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
18994 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
18995 case X86ISD::PINSRB: return "X86ISD::PINSRB";
18996 case X86ISD::PINSRW: return "X86ISD::PINSRW";
18997 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
18998 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
18999 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19000 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19001 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19002 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19003 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19004 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19005 case X86ISD::HADD: return "X86ISD::HADD";
19006 case X86ISD::HSUB: return "X86ISD::HSUB";
19007 case X86ISD::FHADD: return "X86ISD::FHADD";
19008 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19009 case X86ISD::ABS: return "X86ISD::ABS";
19010 case X86ISD::FMAX: return "X86ISD::FMAX";
19011 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19012 case X86ISD::FMIN: return "X86ISD::FMIN";
19013 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19014 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19015 case X86ISD::FMINC: return "X86ISD::FMINC";
19016 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19017 case X86ISD::FRCP: return "X86ISD::FRCP";
19018 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19019 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19020 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19021 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19022 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19023 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19024 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19025 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19026 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19027 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19028 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19029 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19030 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19031 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19032 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19033 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19034 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19035 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19036 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19037 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19038 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19039 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19040 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19041 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19042 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19043 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19044 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19045 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19046 case X86ISD::VSHL: return "X86ISD::VSHL";
19047 case X86ISD::VSRL: return "X86ISD::VSRL";
19048 case X86ISD::VSRA: return "X86ISD::VSRA";
19049 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19050 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19051 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19052 case X86ISD::CMPP: return "X86ISD::CMPP";
19053 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19054 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19055 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19056 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19057 case X86ISD::ADD: return "X86ISD::ADD";
19058 case X86ISD::SUB: return "X86ISD::SUB";
19059 case X86ISD::ADC: return "X86ISD::ADC";
19060 case X86ISD::SBB: return "X86ISD::SBB";
19061 case X86ISD::SMUL: return "X86ISD::SMUL";
19062 case X86ISD::UMUL: return "X86ISD::UMUL";
19063 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19064 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19065 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19066 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19067 case X86ISD::INC: return "X86ISD::INC";
19068 case X86ISD::DEC: return "X86ISD::DEC";
19069 case X86ISD::OR: return "X86ISD::OR";
19070 case X86ISD::XOR: return "X86ISD::XOR";
19071 case X86ISD::AND: return "X86ISD::AND";
19072 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19073 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19074 case X86ISD::PTEST: return "X86ISD::PTEST";
19075 case X86ISD::TESTP: return "X86ISD::TESTP";
19076 case X86ISD::TESTM: return "X86ISD::TESTM";
19077 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19078 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19079 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19080 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19081 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19082 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19083 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19084 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19085 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19086 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19087 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19088 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19089 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19090 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19091 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19092 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19093 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19094 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19095 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19096 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19097 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19098 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19099 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19100 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19101 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19102 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19103 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19104 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19105 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19106 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19107 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19108 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19109 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19110 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19111 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19112 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19113 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19114 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19115 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19116 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19117 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19118 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19119 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19120 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19121 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19122 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19123 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
19124 case X86ISD::SAHF: return "X86ISD::SAHF";
19125 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19126 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19127 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19128 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19129 case X86ISD::FMADD: return "X86ISD::FMADD";
19130 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19131 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19132 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19133 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19134 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19135 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19136 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19137 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19138 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19139 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19140 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19141 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19142 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19143 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19144 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19145 case X86ISD::XTEST: return "X86ISD::XTEST";
19146 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19147 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19148 case X86ISD::SELECT: return "X86ISD::SELECT";
19149 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19150 case X86ISD::RCP28: return "X86ISD::RCP28";
19151 case X86ISD::EXP2: return "X86ISD::EXP2";
19152 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19153 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19154 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19155 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19156 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19157 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19158 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19159 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19160 case X86ISD::ADDS: return "X86ISD::ADDS";
19161 case X86ISD::SUBS: return "X86ISD::SUBS";
19162 case X86ISD::AVG: return "X86ISD::AVG";
19163 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19164 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19165 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19166 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19167 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19172 // isLegalAddressingMode - Return true if the addressing mode represented
19173 // by AM is legal for this target, for a load/store of the specified type.
19174 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19175 const AddrMode &AM, Type *Ty,
19176 unsigned AS) const {
19177 // X86 supports extremely general addressing modes.
19178 CodeModel::Model M = getTargetMachine().getCodeModel();
19179 Reloc::Model R = getTargetMachine().getRelocationModel();
19181 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19182 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19187 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19189 // If a reference to this global requires an extra load, we can't fold it.
19190 if (isGlobalStubReference(GVFlags))
19193 // If BaseGV requires a register for the PIC base, we cannot also have a
19194 // BaseReg specified.
19195 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19198 // If lower 4G is not available, then we must use rip-relative addressing.
19199 if ((M != CodeModel::Small || R != Reloc::Static) &&
19200 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19204 switch (AM.Scale) {
19210 // These scales always work.
19215 // These scales are formed with basereg+scalereg. Only accept if there is
19220 default: // Other stuff never works.
19227 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19228 unsigned Bits = Ty->getScalarSizeInBits();
19230 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19231 // particularly cheaper than those without.
19235 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19236 // variable shifts just as cheap as scalar ones.
19237 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19240 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19241 // fully general vector.
19245 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19246 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19248 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19249 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19250 return NumBits1 > NumBits2;
19253 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19254 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19257 if (!isTypeLegal(EVT::getEVT(Ty1)))
19260 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19262 // Assuming the caller doesn't have a zeroext or signext return parameter,
19263 // truncation all the way down to i1 is valid.
19267 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19268 return isInt<32>(Imm);
19271 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19272 // Can also use sub to handle negated immediates.
19273 return isInt<32>(Imm);
19276 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19277 if (!VT1.isInteger() || !VT2.isInteger())
19279 unsigned NumBits1 = VT1.getSizeInBits();
19280 unsigned NumBits2 = VT2.getSizeInBits();
19281 return NumBits1 > NumBits2;
19284 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19285 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19286 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19289 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19290 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19291 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19294 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19295 EVT VT1 = Val.getValueType();
19296 if (isZExtFree(VT1, VT2))
19299 if (Val.getOpcode() != ISD::LOAD)
19302 if (!VT1.isSimple() || !VT1.isInteger() ||
19303 !VT2.isSimple() || !VT2.isInteger())
19306 switch (VT1.getSimpleVT().SimpleTy) {
19311 // X86 has 8, 16, and 32-bit zero-extending loads.
19318 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19321 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19322 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19325 VT = VT.getScalarType();
19327 if (!VT.isSimple())
19330 switch (VT.getSimpleVT().SimpleTy) {
19341 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19342 // i16 instructions are longer (0x66 prefix) and potentially slower.
19343 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19346 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19347 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19348 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19349 /// are assumed to be legal.
19351 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19353 if (!VT.isSimple())
19356 // Not for i1 vectors
19357 if (VT.getScalarType() == MVT::i1)
19360 // Very little shuffling can be done for 64-bit vectors right now.
19361 if (VT.getSizeInBits() == 64)
19364 // We only care that the types being shuffled are legal. The lowering can
19365 // handle any possible shuffle mask that results.
19366 return isTypeLegal(VT.getSimpleVT());
19370 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19372 // Just delegate to the generic legality, clear masks aren't special.
19373 return isShuffleMaskLegal(Mask, VT);
19376 //===----------------------------------------------------------------------===//
19377 // X86 Scheduler Hooks
19378 //===----------------------------------------------------------------------===//
19380 /// Utility function to emit xbegin specifying the start of an RTM region.
19381 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19382 const TargetInstrInfo *TII) {
19383 DebugLoc DL = MI->getDebugLoc();
19385 const BasicBlock *BB = MBB->getBasicBlock();
19386 MachineFunction::iterator I = MBB;
19389 // For the v = xbegin(), we generate
19400 MachineBasicBlock *thisMBB = MBB;
19401 MachineFunction *MF = MBB->getParent();
19402 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19403 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19404 MF->insert(I, mainMBB);
19405 MF->insert(I, sinkMBB);
19407 // Transfer the remainder of BB and its successor edges to sinkMBB.
19408 sinkMBB->splice(sinkMBB->begin(), MBB,
19409 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19410 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19414 // # fallthrough to mainMBB
19415 // # abortion to sinkMBB
19416 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19417 thisMBB->addSuccessor(mainMBB);
19418 thisMBB->addSuccessor(sinkMBB);
19422 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19423 mainMBB->addSuccessor(sinkMBB);
19426 // EAX is live into the sinkMBB
19427 sinkMBB->addLiveIn(X86::EAX);
19428 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19429 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19432 MI->eraseFromParent();
19436 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19437 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19438 // in the .td file.
19439 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19440 const TargetInstrInfo *TII) {
19442 switch (MI->getOpcode()) {
19443 default: llvm_unreachable("illegal opcode!");
19444 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19445 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19446 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19447 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19448 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19449 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19450 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19451 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19454 DebugLoc dl = MI->getDebugLoc();
19455 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19457 unsigned NumArgs = MI->getNumOperands();
19458 for (unsigned i = 1; i < NumArgs; ++i) {
19459 MachineOperand &Op = MI->getOperand(i);
19460 if (!(Op.isReg() && Op.isImplicit()))
19461 MIB.addOperand(Op);
19463 if (MI->hasOneMemOperand())
19464 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19466 BuildMI(*BB, MI, dl,
19467 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19468 .addReg(X86::XMM0);
19470 MI->eraseFromParent();
19474 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19475 // defs in an instruction pattern
19476 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19477 const TargetInstrInfo *TII) {
19479 switch (MI->getOpcode()) {
19480 default: llvm_unreachable("illegal opcode!");
19481 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19482 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19483 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19484 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19485 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19486 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19487 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19488 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19491 DebugLoc dl = MI->getDebugLoc();
19492 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19494 unsigned NumArgs = MI->getNumOperands(); // remove the results
19495 for (unsigned i = 1; i < NumArgs; ++i) {
19496 MachineOperand &Op = MI->getOperand(i);
19497 if (!(Op.isReg() && Op.isImplicit()))
19498 MIB.addOperand(Op);
19500 if (MI->hasOneMemOperand())
19501 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19503 BuildMI(*BB, MI, dl,
19504 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19507 MI->eraseFromParent();
19511 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19512 const X86Subtarget *Subtarget) {
19513 DebugLoc dl = MI->getDebugLoc();
19514 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19515 // Address into RAX/EAX, other two args into ECX, EDX.
19516 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19517 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19518 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19519 for (int i = 0; i < X86::AddrNumOperands; ++i)
19520 MIB.addOperand(MI->getOperand(i));
19522 unsigned ValOps = X86::AddrNumOperands;
19523 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19524 .addReg(MI->getOperand(ValOps).getReg());
19525 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19526 .addReg(MI->getOperand(ValOps+1).getReg());
19528 // The instruction doesn't actually take any operands though.
19529 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19531 MI->eraseFromParent(); // The pseudo is gone now.
19535 MachineBasicBlock *
19536 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19537 MachineBasicBlock *MBB) const {
19538 // Emit va_arg instruction on X86-64.
19540 // Operands to this pseudo-instruction:
19541 // 0 ) Output : destination address (reg)
19542 // 1-5) Input : va_list address (addr, i64mem)
19543 // 6 ) ArgSize : Size (in bytes) of vararg type
19544 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19545 // 8 ) Align : Alignment of type
19546 // 9 ) EFLAGS (implicit-def)
19548 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19549 static_assert(X86::AddrNumOperands == 5,
19550 "VAARG_64 assumes 5 address operands");
19552 unsigned DestReg = MI->getOperand(0).getReg();
19553 MachineOperand &Base = MI->getOperand(1);
19554 MachineOperand &Scale = MI->getOperand(2);
19555 MachineOperand &Index = MI->getOperand(3);
19556 MachineOperand &Disp = MI->getOperand(4);
19557 MachineOperand &Segment = MI->getOperand(5);
19558 unsigned ArgSize = MI->getOperand(6).getImm();
19559 unsigned ArgMode = MI->getOperand(7).getImm();
19560 unsigned Align = MI->getOperand(8).getImm();
19562 // Memory Reference
19563 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19564 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19565 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19567 // Machine Information
19568 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19569 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19570 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19571 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19572 DebugLoc DL = MI->getDebugLoc();
19574 // struct va_list {
19577 // i64 overflow_area (address)
19578 // i64 reg_save_area (address)
19580 // sizeof(va_list) = 24
19581 // alignment(va_list) = 8
19583 unsigned TotalNumIntRegs = 6;
19584 unsigned TotalNumXMMRegs = 8;
19585 bool UseGPOffset = (ArgMode == 1);
19586 bool UseFPOffset = (ArgMode == 2);
19587 unsigned MaxOffset = TotalNumIntRegs * 8 +
19588 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19590 /* Align ArgSize to a multiple of 8 */
19591 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19592 bool NeedsAlign = (Align > 8);
19594 MachineBasicBlock *thisMBB = MBB;
19595 MachineBasicBlock *overflowMBB;
19596 MachineBasicBlock *offsetMBB;
19597 MachineBasicBlock *endMBB;
19599 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19600 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19601 unsigned OffsetReg = 0;
19603 if (!UseGPOffset && !UseFPOffset) {
19604 // If we only pull from the overflow region, we don't create a branch.
19605 // We don't need to alter control flow.
19606 OffsetDestReg = 0; // unused
19607 OverflowDestReg = DestReg;
19609 offsetMBB = nullptr;
19610 overflowMBB = thisMBB;
19613 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19614 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19615 // If not, pull from overflow_area. (branch to overflowMBB)
19620 // offsetMBB overflowMBB
19625 // Registers for the PHI in endMBB
19626 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19627 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19629 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19630 MachineFunction *MF = MBB->getParent();
19631 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19632 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19633 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19635 MachineFunction::iterator MBBIter = MBB;
19638 // Insert the new basic blocks
19639 MF->insert(MBBIter, offsetMBB);
19640 MF->insert(MBBIter, overflowMBB);
19641 MF->insert(MBBIter, endMBB);
19643 // Transfer the remainder of MBB and its successor edges to endMBB.
19644 endMBB->splice(endMBB->begin(), thisMBB,
19645 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19646 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19648 // Make offsetMBB and overflowMBB successors of thisMBB
19649 thisMBB->addSuccessor(offsetMBB);
19650 thisMBB->addSuccessor(overflowMBB);
19652 // endMBB is a successor of both offsetMBB and overflowMBB
19653 offsetMBB->addSuccessor(endMBB);
19654 overflowMBB->addSuccessor(endMBB);
19656 // Load the offset value into a register
19657 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19658 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19662 .addDisp(Disp, UseFPOffset ? 4 : 0)
19663 .addOperand(Segment)
19664 .setMemRefs(MMOBegin, MMOEnd);
19666 // Check if there is enough room left to pull this argument.
19667 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19669 .addImm(MaxOffset + 8 - ArgSizeA8);
19671 // Branch to "overflowMBB" if offset >= max
19672 // Fall through to "offsetMBB" otherwise
19673 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19674 .addMBB(overflowMBB);
19677 // In offsetMBB, emit code to use the reg_save_area.
19679 assert(OffsetReg != 0);
19681 // Read the reg_save_area address.
19682 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19683 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19688 .addOperand(Segment)
19689 .setMemRefs(MMOBegin, MMOEnd);
19691 // Zero-extend the offset
19692 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19693 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19696 .addImm(X86::sub_32bit);
19698 // Add the offset to the reg_save_area to get the final address.
19699 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19700 .addReg(OffsetReg64)
19701 .addReg(RegSaveReg);
19703 // Compute the offset for the next argument
19704 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19705 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19707 .addImm(UseFPOffset ? 16 : 8);
19709 // Store it back into the va_list.
19710 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19714 .addDisp(Disp, UseFPOffset ? 4 : 0)
19715 .addOperand(Segment)
19716 .addReg(NextOffsetReg)
19717 .setMemRefs(MMOBegin, MMOEnd);
19720 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19725 // Emit code to use overflow area
19728 // Load the overflow_area address into a register.
19729 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19730 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19735 .addOperand(Segment)
19736 .setMemRefs(MMOBegin, MMOEnd);
19738 // If we need to align it, do so. Otherwise, just copy the address
19739 // to OverflowDestReg.
19741 // Align the overflow address
19742 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19743 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19745 // aligned_addr = (addr + (align-1)) & ~(align-1)
19746 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19747 .addReg(OverflowAddrReg)
19750 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19752 .addImm(~(uint64_t)(Align-1));
19754 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19755 .addReg(OverflowAddrReg);
19758 // Compute the next overflow address after this argument.
19759 // (the overflow address should be kept 8-byte aligned)
19760 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19761 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19762 .addReg(OverflowDestReg)
19763 .addImm(ArgSizeA8);
19765 // Store the new overflow address.
19766 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19771 .addOperand(Segment)
19772 .addReg(NextAddrReg)
19773 .setMemRefs(MMOBegin, MMOEnd);
19775 // If we branched, emit the PHI to the front of endMBB.
19777 BuildMI(*endMBB, endMBB->begin(), DL,
19778 TII->get(X86::PHI), DestReg)
19779 .addReg(OffsetDestReg).addMBB(offsetMBB)
19780 .addReg(OverflowDestReg).addMBB(overflowMBB);
19783 // Erase the pseudo instruction
19784 MI->eraseFromParent();
19789 MachineBasicBlock *
19790 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19792 MachineBasicBlock *MBB) const {
19793 // Emit code to save XMM registers to the stack. The ABI says that the
19794 // number of registers to save is given in %al, so it's theoretically
19795 // possible to do an indirect jump trick to avoid saving all of them,
19796 // however this code takes a simpler approach and just executes all
19797 // of the stores if %al is non-zero. It's less code, and it's probably
19798 // easier on the hardware branch predictor, and stores aren't all that
19799 // expensive anyway.
19801 // Create the new basic blocks. One block contains all the XMM stores,
19802 // and one block is the final destination regardless of whether any
19803 // stores were performed.
19804 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19805 MachineFunction *F = MBB->getParent();
19806 MachineFunction::iterator MBBIter = MBB;
19808 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19809 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19810 F->insert(MBBIter, XMMSaveMBB);
19811 F->insert(MBBIter, EndMBB);
19813 // Transfer the remainder of MBB and its successor edges to EndMBB.
19814 EndMBB->splice(EndMBB->begin(), MBB,
19815 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19816 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19818 // The original block will now fall through to the XMM save block.
19819 MBB->addSuccessor(XMMSaveMBB);
19820 // The XMMSaveMBB will fall through to the end block.
19821 XMMSaveMBB->addSuccessor(EndMBB);
19823 // Now add the instructions.
19824 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19825 DebugLoc DL = MI->getDebugLoc();
19827 unsigned CountReg = MI->getOperand(0).getReg();
19828 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19829 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19831 if (!Subtarget->isTargetWin64()) {
19832 // If %al is 0, branch around the XMM save block.
19833 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19834 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19835 MBB->addSuccessor(EndMBB);
19838 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19839 // that was just emitted, but clearly shouldn't be "saved".
19840 assert((MI->getNumOperands() <= 3 ||
19841 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19842 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19843 && "Expected last argument to be EFLAGS");
19844 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19845 // In the XMM save block, save all the XMM argument registers.
19846 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19847 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19848 MachineMemOperand *MMO =
19849 F->getMachineMemOperand(
19850 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19851 MachineMemOperand::MOStore,
19852 /*Size=*/16, /*Align=*/16);
19853 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19854 .addFrameIndex(RegSaveFrameIndex)
19855 .addImm(/*Scale=*/1)
19856 .addReg(/*IndexReg=*/0)
19857 .addImm(/*Disp=*/Offset)
19858 .addReg(/*Segment=*/0)
19859 .addReg(MI->getOperand(i).getReg())
19860 .addMemOperand(MMO);
19863 MI->eraseFromParent(); // The pseudo instruction is gone now.
19868 // The EFLAGS operand of SelectItr might be missing a kill marker
19869 // because there were multiple uses of EFLAGS, and ISel didn't know
19870 // which to mark. Figure out whether SelectItr should have had a
19871 // kill marker, and set it if it should. Returns the correct kill
19873 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19874 MachineBasicBlock* BB,
19875 const TargetRegisterInfo* TRI) {
19876 // Scan forward through BB for a use/def of EFLAGS.
19877 MachineBasicBlock::iterator miI(std::next(SelectItr));
19878 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19879 const MachineInstr& mi = *miI;
19880 if (mi.readsRegister(X86::EFLAGS))
19882 if (mi.definesRegister(X86::EFLAGS))
19883 break; // Should have kill-flag - update below.
19886 // If we hit the end of the block, check whether EFLAGS is live into a
19888 if (miI == BB->end()) {
19889 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19890 sEnd = BB->succ_end();
19891 sItr != sEnd; ++sItr) {
19892 MachineBasicBlock* succ = *sItr;
19893 if (succ->isLiveIn(X86::EFLAGS))
19898 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19899 // out. SelectMI should have a kill flag on EFLAGS.
19900 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19904 MachineBasicBlock *
19905 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19906 MachineBasicBlock *BB) const {
19907 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19908 DebugLoc DL = MI->getDebugLoc();
19910 // To "insert" a SELECT_CC instruction, we actually have to insert the
19911 // diamond control-flow pattern. The incoming instruction knows the
19912 // destination vreg to set, the condition code register to branch on, the
19913 // true/false values to select between, and a branch opcode to use.
19914 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19915 MachineFunction::iterator It = BB;
19921 // cmpTY ccX, r1, r2
19923 // fallthrough --> copy0MBB
19924 MachineBasicBlock *thisMBB = BB;
19925 MachineFunction *F = BB->getParent();
19927 // We also lower double CMOVs:
19928 // (CMOV (CMOV F, T, cc1), T, cc2)
19929 // to two successives branches. For that, we look for another CMOV as the
19930 // following instruction.
19932 // Without this, we would add a PHI between the two jumps, which ends up
19933 // creating a few copies all around. For instance, for
19935 // (sitofp (zext (fcmp une)))
19937 // we would generate:
19939 // ucomiss %xmm1, %xmm0
19940 // movss <1.0f>, %xmm0
19941 // movaps %xmm0, %xmm1
19943 // xorps %xmm1, %xmm1
19946 // movaps %xmm1, %xmm0
19950 // because this custom-inserter would have generated:
19962 // A: X = ...; Y = ...
19964 // C: Z = PHI [X, A], [Y, B]
19966 // E: PHI [X, C], [Z, D]
19968 // If we lower both CMOVs in a single step, we can instead generate:
19980 // A: X = ...; Y = ...
19982 // E: PHI [X, A], [X, C], [Y, D]
19984 // Which, in our sitofp/fcmp example, gives us something like:
19986 // ucomiss %xmm1, %xmm0
19987 // movss <1.0f>, %xmm0
19990 // xorps %xmm0, %xmm0
19994 MachineInstr *NextCMOV = nullptr;
19995 MachineBasicBlock::iterator NextMIIt =
19996 std::next(MachineBasicBlock::iterator(MI));
19997 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19998 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19999 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
20000 NextCMOV = &*NextMIIt;
20002 MachineBasicBlock *jcc1MBB = nullptr;
20004 // If we have a double CMOV, we lower it to two successive branches to
20005 // the same block. EFLAGS is used by both, so mark it as live in the second.
20007 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20008 F->insert(It, jcc1MBB);
20009 jcc1MBB->addLiveIn(X86::EFLAGS);
20012 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20013 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20014 F->insert(It, copy0MBB);
20015 F->insert(It, sinkMBB);
20017 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20018 // live into the sink and copy blocks.
20019 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20021 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
20022 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20023 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20024 copy0MBB->addLiveIn(X86::EFLAGS);
20025 sinkMBB->addLiveIn(X86::EFLAGS);
20028 // Transfer the remainder of BB and its successor edges to sinkMBB.
20029 sinkMBB->splice(sinkMBB->begin(), BB,
20030 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20031 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20033 // Add the true and fallthrough blocks as its successors.
20035 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
20036 BB->addSuccessor(jcc1MBB);
20038 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20039 // jump to the sinkMBB.
20040 jcc1MBB->addSuccessor(copy0MBB);
20041 jcc1MBB->addSuccessor(sinkMBB);
20043 BB->addSuccessor(copy0MBB);
20046 // The true block target of the first (or only) branch is always sinkMBB.
20047 BB->addSuccessor(sinkMBB);
20049 // Create the conditional branch instruction.
20051 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20052 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20055 unsigned Opc2 = X86::GetCondBranchFromCond(
20056 (X86::CondCode)NextCMOV->getOperand(3).getImm());
20057 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20061 // %FalseValue = ...
20062 // # fallthrough to sinkMBB
20063 copy0MBB->addSuccessor(sinkMBB);
20066 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20068 MachineInstrBuilder MIB =
20069 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
20070 MI->getOperand(0).getReg())
20071 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20072 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20074 // If we have a double CMOV, the second Jcc provides the same incoming
20075 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20077 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20078 // Copy the PHI result to the register defined by the second CMOV.
20079 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20080 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20081 .addReg(MI->getOperand(0).getReg());
20082 NextCMOV->eraseFromParent();
20085 MI->eraseFromParent(); // The pseudo instruction is gone now.
20089 MachineBasicBlock *
20090 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20091 MachineBasicBlock *BB) const {
20092 MachineFunction *MF = BB->getParent();
20093 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20094 DebugLoc DL = MI->getDebugLoc();
20095 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20097 assert(MF->shouldSplitStack());
20099 const bool Is64Bit = Subtarget->is64Bit();
20100 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20102 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20103 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20106 // ... [Till the alloca]
20107 // If stacklet is not large enough, jump to mallocMBB
20110 // Allocate by subtracting from RSP
20111 // Jump to continueMBB
20114 // Allocate by call to runtime
20118 // [rest of original BB]
20121 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20122 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20123 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20125 MachineRegisterInfo &MRI = MF->getRegInfo();
20126 const TargetRegisterClass *AddrRegClass =
20127 getRegClassFor(getPointerTy(MF->getDataLayout()));
20129 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20130 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20131 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20132 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20133 sizeVReg = MI->getOperand(1).getReg(),
20134 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20136 MachineFunction::iterator MBBIter = BB;
20139 MF->insert(MBBIter, bumpMBB);
20140 MF->insert(MBBIter, mallocMBB);
20141 MF->insert(MBBIter, continueMBB);
20143 continueMBB->splice(continueMBB->begin(), BB,
20144 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20145 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20147 // Add code to the main basic block to check if the stack limit has been hit,
20148 // and if so, jump to mallocMBB otherwise to bumpMBB.
20149 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20150 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20151 .addReg(tmpSPVReg).addReg(sizeVReg);
20152 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20153 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20154 .addReg(SPLimitVReg);
20155 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20157 // bumpMBB simply decreases the stack pointer, since we know the current
20158 // stacklet has enough space.
20159 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20160 .addReg(SPLimitVReg);
20161 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20162 .addReg(SPLimitVReg);
20163 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20165 // Calls into a routine in libgcc to allocate more space from the heap.
20166 const uint32_t *RegMask =
20167 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20169 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20171 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20172 .addExternalSymbol("__morestack_allocate_stack_space")
20173 .addRegMask(RegMask)
20174 .addReg(X86::RDI, RegState::Implicit)
20175 .addReg(X86::RAX, RegState::ImplicitDefine);
20176 } else if (Is64Bit) {
20177 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20179 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20180 .addExternalSymbol("__morestack_allocate_stack_space")
20181 .addRegMask(RegMask)
20182 .addReg(X86::EDI, RegState::Implicit)
20183 .addReg(X86::EAX, RegState::ImplicitDefine);
20185 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20187 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20188 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20189 .addExternalSymbol("__morestack_allocate_stack_space")
20190 .addRegMask(RegMask)
20191 .addReg(X86::EAX, RegState::ImplicitDefine);
20195 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20198 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20199 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20200 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20202 // Set up the CFG correctly.
20203 BB->addSuccessor(bumpMBB);
20204 BB->addSuccessor(mallocMBB);
20205 mallocMBB->addSuccessor(continueMBB);
20206 bumpMBB->addSuccessor(continueMBB);
20208 // Take care of the PHI nodes.
20209 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20210 MI->getOperand(0).getReg())
20211 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20212 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20214 // Delete the original pseudo instruction.
20215 MI->eraseFromParent();
20218 return continueMBB;
20221 MachineBasicBlock *
20222 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20223 MachineBasicBlock *BB) const {
20224 DebugLoc DL = MI->getDebugLoc();
20226 assert(!Subtarget->isTargetMachO());
20228 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20231 MI->eraseFromParent(); // The pseudo instruction is gone now.
20235 MachineBasicBlock *
20236 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20237 MachineBasicBlock *BB) const {
20238 // This is pretty easy. We're taking the value that we received from
20239 // our load from the relocation, sticking it in either RDI (x86-64)
20240 // or EAX and doing an indirect call. The return value will then
20241 // be in the normal return register.
20242 MachineFunction *F = BB->getParent();
20243 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20244 DebugLoc DL = MI->getDebugLoc();
20246 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20247 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20249 // Get a register mask for the lowered call.
20250 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20251 // proper register mask.
20252 const uint32_t *RegMask =
20253 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20254 if (Subtarget->is64Bit()) {
20255 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20256 TII->get(X86::MOV64rm), X86::RDI)
20258 .addImm(0).addReg(0)
20259 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20260 MI->getOperand(3).getTargetFlags())
20262 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20263 addDirectMem(MIB, X86::RDI);
20264 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20265 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20266 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20267 TII->get(X86::MOV32rm), X86::EAX)
20269 .addImm(0).addReg(0)
20270 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20271 MI->getOperand(3).getTargetFlags())
20273 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20274 addDirectMem(MIB, X86::EAX);
20275 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20277 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20278 TII->get(X86::MOV32rm), X86::EAX)
20279 .addReg(TII->getGlobalBaseReg(F))
20280 .addImm(0).addReg(0)
20281 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20282 MI->getOperand(3).getTargetFlags())
20284 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20285 addDirectMem(MIB, X86::EAX);
20286 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20289 MI->eraseFromParent(); // The pseudo instruction is gone now.
20293 MachineBasicBlock *
20294 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20295 MachineBasicBlock *MBB) const {
20296 DebugLoc DL = MI->getDebugLoc();
20297 MachineFunction *MF = MBB->getParent();
20298 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20299 MachineRegisterInfo &MRI = MF->getRegInfo();
20301 const BasicBlock *BB = MBB->getBasicBlock();
20302 MachineFunction::iterator I = MBB;
20305 // Memory Reference
20306 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20307 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20310 unsigned MemOpndSlot = 0;
20312 unsigned CurOp = 0;
20314 DstReg = MI->getOperand(CurOp++).getReg();
20315 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20316 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20317 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20318 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20320 MemOpndSlot = CurOp;
20322 MVT PVT = getPointerTy(MF->getDataLayout());
20323 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20324 "Invalid Pointer Size!");
20326 // For v = setjmp(buf), we generate
20329 // buf[LabelOffset] = restoreMBB
20330 // SjLjSetup restoreMBB
20336 // v = phi(main, restore)
20339 // if base pointer being used, load it from frame
20342 MachineBasicBlock *thisMBB = MBB;
20343 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20344 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20345 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20346 MF->insert(I, mainMBB);
20347 MF->insert(I, sinkMBB);
20348 MF->push_back(restoreMBB);
20350 MachineInstrBuilder MIB;
20352 // Transfer the remainder of BB and its successor edges to sinkMBB.
20353 sinkMBB->splice(sinkMBB->begin(), MBB,
20354 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20355 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20358 unsigned PtrStoreOpc = 0;
20359 unsigned LabelReg = 0;
20360 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20361 Reloc::Model RM = MF->getTarget().getRelocationModel();
20362 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20363 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20365 // Prepare IP either in reg or imm.
20366 if (!UseImmLabel) {
20367 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20368 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20369 LabelReg = MRI.createVirtualRegister(PtrRC);
20370 if (Subtarget->is64Bit()) {
20371 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20375 .addMBB(restoreMBB)
20378 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20379 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20380 .addReg(XII->getGlobalBaseReg(MF))
20383 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20387 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20389 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20390 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20391 if (i == X86::AddrDisp)
20392 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20394 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20397 MIB.addReg(LabelReg);
20399 MIB.addMBB(restoreMBB);
20400 MIB.setMemRefs(MMOBegin, MMOEnd);
20402 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20403 .addMBB(restoreMBB);
20405 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20406 MIB.addRegMask(RegInfo->getNoPreservedMask());
20407 thisMBB->addSuccessor(mainMBB);
20408 thisMBB->addSuccessor(restoreMBB);
20412 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20413 mainMBB->addSuccessor(sinkMBB);
20416 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20417 TII->get(X86::PHI), DstReg)
20418 .addReg(mainDstReg).addMBB(mainMBB)
20419 .addReg(restoreDstReg).addMBB(restoreMBB);
20422 if (RegInfo->hasBasePointer(*MF)) {
20423 const bool Uses64BitFramePtr =
20424 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20425 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20426 X86FI->setRestoreBasePointer(MF);
20427 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20428 unsigned BasePtr = RegInfo->getBaseRegister();
20429 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20430 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20431 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20432 .setMIFlag(MachineInstr::FrameSetup);
20434 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20435 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20436 restoreMBB->addSuccessor(sinkMBB);
20438 MI->eraseFromParent();
20442 MachineBasicBlock *
20443 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20444 MachineBasicBlock *MBB) const {
20445 DebugLoc DL = MI->getDebugLoc();
20446 MachineFunction *MF = MBB->getParent();
20447 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20448 MachineRegisterInfo &MRI = MF->getRegInfo();
20450 // Memory Reference
20451 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20452 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20454 MVT PVT = getPointerTy(MF->getDataLayout());
20455 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20456 "Invalid Pointer Size!");
20458 const TargetRegisterClass *RC =
20459 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20460 unsigned Tmp = MRI.createVirtualRegister(RC);
20461 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20462 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20463 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20464 unsigned SP = RegInfo->getStackRegister();
20466 MachineInstrBuilder MIB;
20468 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20469 const int64_t SPOffset = 2 * PVT.getStoreSize();
20471 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20472 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20475 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20476 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20477 MIB.addOperand(MI->getOperand(i));
20478 MIB.setMemRefs(MMOBegin, MMOEnd);
20480 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20481 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20482 if (i == X86::AddrDisp)
20483 MIB.addDisp(MI->getOperand(i), LabelOffset);
20485 MIB.addOperand(MI->getOperand(i));
20487 MIB.setMemRefs(MMOBegin, MMOEnd);
20489 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20490 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20491 if (i == X86::AddrDisp)
20492 MIB.addDisp(MI->getOperand(i), SPOffset);
20494 MIB.addOperand(MI->getOperand(i));
20496 MIB.setMemRefs(MMOBegin, MMOEnd);
20498 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20500 MI->eraseFromParent();
20504 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20505 // accumulator loops. Writing back to the accumulator allows the coalescer
20506 // to remove extra copies in the loop.
20507 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20508 MachineBasicBlock *
20509 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20510 MachineBasicBlock *MBB) const {
20511 MachineOperand &AddendOp = MI->getOperand(3);
20513 // Bail out early if the addend isn't a register - we can't switch these.
20514 if (!AddendOp.isReg())
20517 MachineFunction &MF = *MBB->getParent();
20518 MachineRegisterInfo &MRI = MF.getRegInfo();
20520 // Check whether the addend is defined by a PHI:
20521 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20522 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20523 if (!AddendDef.isPHI())
20526 // Look for the following pattern:
20528 // %addend = phi [%entry, 0], [%loop, %result]
20530 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20534 // %addend = phi [%entry, 0], [%loop, %result]
20536 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20538 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20539 assert(AddendDef.getOperand(i).isReg());
20540 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20541 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20542 if (&PHISrcInst == MI) {
20543 // Found a matching instruction.
20544 unsigned NewFMAOpc = 0;
20545 switch (MI->getOpcode()) {
20546 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20547 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20548 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20549 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20550 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20551 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20552 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20553 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20554 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20555 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20556 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20557 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20558 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20559 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20560 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20561 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20562 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20563 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20564 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20565 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20567 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20568 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20569 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20570 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20571 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20572 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20573 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20574 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20575 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20576 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20577 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20578 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20579 default: llvm_unreachable("Unrecognized FMA variant.");
20582 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20583 MachineInstrBuilder MIB =
20584 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20585 .addOperand(MI->getOperand(0))
20586 .addOperand(MI->getOperand(3))
20587 .addOperand(MI->getOperand(2))
20588 .addOperand(MI->getOperand(1));
20589 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20590 MI->eraseFromParent();
20597 MachineBasicBlock *
20598 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20599 MachineBasicBlock *BB) const {
20600 switch (MI->getOpcode()) {
20601 default: llvm_unreachable("Unexpected instr type to insert");
20602 case X86::TAILJMPd64:
20603 case X86::TAILJMPr64:
20604 case X86::TAILJMPm64:
20605 case X86::TAILJMPd64_REX:
20606 case X86::TAILJMPr64_REX:
20607 case X86::TAILJMPm64_REX:
20608 llvm_unreachable("TAILJMP64 would not be touched here.");
20609 case X86::TCRETURNdi64:
20610 case X86::TCRETURNri64:
20611 case X86::TCRETURNmi64:
20613 case X86::WIN_ALLOCA:
20614 return EmitLoweredWinAlloca(MI, BB);
20615 case X86::SEG_ALLOCA_32:
20616 case X86::SEG_ALLOCA_64:
20617 return EmitLoweredSegAlloca(MI, BB);
20618 case X86::TLSCall_32:
20619 case X86::TLSCall_64:
20620 return EmitLoweredTLSCall(MI, BB);
20621 case X86::CMOV_GR8:
20622 case X86::CMOV_FR32:
20623 case X86::CMOV_FR64:
20624 case X86::CMOV_V4F32:
20625 case X86::CMOV_V2F64:
20626 case X86::CMOV_V2I64:
20627 case X86::CMOV_V8F32:
20628 case X86::CMOV_V4F64:
20629 case X86::CMOV_V4I64:
20630 case X86::CMOV_V16F32:
20631 case X86::CMOV_V8F64:
20632 case X86::CMOV_V8I64:
20633 case X86::CMOV_GR16:
20634 case X86::CMOV_GR32:
20635 case X86::CMOV_RFP32:
20636 case X86::CMOV_RFP64:
20637 case X86::CMOV_RFP80:
20638 case X86::CMOV_V8I1:
20639 case X86::CMOV_V16I1:
20640 case X86::CMOV_V32I1:
20641 case X86::CMOV_V64I1:
20642 return EmitLoweredSelect(MI, BB);
20644 case X86::FP32_TO_INT16_IN_MEM:
20645 case X86::FP32_TO_INT32_IN_MEM:
20646 case X86::FP32_TO_INT64_IN_MEM:
20647 case X86::FP64_TO_INT16_IN_MEM:
20648 case X86::FP64_TO_INT32_IN_MEM:
20649 case X86::FP64_TO_INT64_IN_MEM:
20650 case X86::FP80_TO_INT16_IN_MEM:
20651 case X86::FP80_TO_INT32_IN_MEM:
20652 case X86::FP80_TO_INT64_IN_MEM: {
20653 MachineFunction *F = BB->getParent();
20654 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20655 DebugLoc DL = MI->getDebugLoc();
20657 // Change the floating point control register to use "round towards zero"
20658 // mode when truncating to an integer value.
20659 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20660 addFrameReference(BuildMI(*BB, MI, DL,
20661 TII->get(X86::FNSTCW16m)), CWFrameIdx);
20663 // Load the old value of the high byte of the control word...
20665 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20666 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20669 // Set the high part to be round to zero...
20670 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20673 // Reload the modified control word now...
20674 addFrameReference(BuildMI(*BB, MI, DL,
20675 TII->get(X86::FLDCW16m)), CWFrameIdx);
20677 // Restore the memory image of control word to original value
20678 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20681 // Get the X86 opcode to use.
20683 switch (MI->getOpcode()) {
20684 default: llvm_unreachable("illegal opcode!");
20685 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20686 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20687 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20688 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20689 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20690 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20691 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20692 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20693 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20697 MachineOperand &Op = MI->getOperand(0);
20699 AM.BaseType = X86AddressMode::RegBase;
20700 AM.Base.Reg = Op.getReg();
20702 AM.BaseType = X86AddressMode::FrameIndexBase;
20703 AM.Base.FrameIndex = Op.getIndex();
20705 Op = MI->getOperand(1);
20707 AM.Scale = Op.getImm();
20708 Op = MI->getOperand(2);
20710 AM.IndexReg = Op.getImm();
20711 Op = MI->getOperand(3);
20712 if (Op.isGlobal()) {
20713 AM.GV = Op.getGlobal();
20715 AM.Disp = Op.getImm();
20717 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20718 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20720 // Reload the original control word now.
20721 addFrameReference(BuildMI(*BB, MI, DL,
20722 TII->get(X86::FLDCW16m)), CWFrameIdx);
20724 MI->eraseFromParent(); // The pseudo instruction is gone now.
20727 // String/text processing lowering.
20728 case X86::PCMPISTRM128REG:
20729 case X86::VPCMPISTRM128REG:
20730 case X86::PCMPISTRM128MEM:
20731 case X86::VPCMPISTRM128MEM:
20732 case X86::PCMPESTRM128REG:
20733 case X86::VPCMPESTRM128REG:
20734 case X86::PCMPESTRM128MEM:
20735 case X86::VPCMPESTRM128MEM:
20736 assert(Subtarget->hasSSE42() &&
20737 "Target must have SSE4.2 or AVX features enabled");
20738 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20740 // String/text processing lowering.
20741 case X86::PCMPISTRIREG:
20742 case X86::VPCMPISTRIREG:
20743 case X86::PCMPISTRIMEM:
20744 case X86::VPCMPISTRIMEM:
20745 case X86::PCMPESTRIREG:
20746 case X86::VPCMPESTRIREG:
20747 case X86::PCMPESTRIMEM:
20748 case X86::VPCMPESTRIMEM:
20749 assert(Subtarget->hasSSE42() &&
20750 "Target must have SSE4.2 or AVX features enabled");
20751 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20753 // Thread synchronization.
20755 return EmitMonitor(MI, BB, Subtarget);
20759 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20761 case X86::VASTART_SAVE_XMM_REGS:
20762 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20764 case X86::VAARG_64:
20765 return EmitVAARG64WithCustomInserter(MI, BB);
20767 case X86::EH_SjLj_SetJmp32:
20768 case X86::EH_SjLj_SetJmp64:
20769 return emitEHSjLjSetJmp(MI, BB);
20771 case X86::EH_SjLj_LongJmp32:
20772 case X86::EH_SjLj_LongJmp64:
20773 return emitEHSjLjLongJmp(MI, BB);
20775 case TargetOpcode::STATEPOINT:
20776 // As an implementation detail, STATEPOINT shares the STACKMAP format at
20777 // this point in the process. We diverge later.
20778 return emitPatchPoint(MI, BB);
20780 case TargetOpcode::STACKMAP:
20781 case TargetOpcode::PATCHPOINT:
20782 return emitPatchPoint(MI, BB);
20784 case X86::VFMADDPDr213r:
20785 case X86::VFMADDPSr213r:
20786 case X86::VFMADDSDr213r:
20787 case X86::VFMADDSSr213r:
20788 case X86::VFMSUBPDr213r:
20789 case X86::VFMSUBPSr213r:
20790 case X86::VFMSUBSDr213r:
20791 case X86::VFMSUBSSr213r:
20792 case X86::VFNMADDPDr213r:
20793 case X86::VFNMADDPSr213r:
20794 case X86::VFNMADDSDr213r:
20795 case X86::VFNMADDSSr213r:
20796 case X86::VFNMSUBPDr213r:
20797 case X86::VFNMSUBPSr213r:
20798 case X86::VFNMSUBSDr213r:
20799 case X86::VFNMSUBSSr213r:
20800 case X86::VFMADDSUBPDr213r:
20801 case X86::VFMADDSUBPSr213r:
20802 case X86::VFMSUBADDPDr213r:
20803 case X86::VFMSUBADDPSr213r:
20804 case X86::VFMADDPDr213rY:
20805 case X86::VFMADDPSr213rY:
20806 case X86::VFMSUBPDr213rY:
20807 case X86::VFMSUBPSr213rY:
20808 case X86::VFNMADDPDr213rY:
20809 case X86::VFNMADDPSr213rY:
20810 case X86::VFNMSUBPDr213rY:
20811 case X86::VFNMSUBPSr213rY:
20812 case X86::VFMADDSUBPDr213rY:
20813 case X86::VFMADDSUBPSr213rY:
20814 case X86::VFMSUBADDPDr213rY:
20815 case X86::VFMSUBADDPSr213rY:
20816 return emitFMA3Instr(MI, BB);
20820 //===----------------------------------------------------------------------===//
20821 // X86 Optimization Hooks
20822 //===----------------------------------------------------------------------===//
20824 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20827 const SelectionDAG &DAG,
20828 unsigned Depth) const {
20829 unsigned BitWidth = KnownZero.getBitWidth();
20830 unsigned Opc = Op.getOpcode();
20831 assert((Opc >= ISD::BUILTIN_OP_END ||
20832 Opc == ISD::INTRINSIC_WO_CHAIN ||
20833 Opc == ISD::INTRINSIC_W_CHAIN ||
20834 Opc == ISD::INTRINSIC_VOID) &&
20835 "Should use MaskedValueIsZero if you don't know whether Op"
20836 " is a target node!");
20838 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
20852 // These nodes' second result is a boolean.
20853 if (Op.getResNo() == 0)
20856 case X86ISD::SETCC:
20857 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20859 case ISD::INTRINSIC_WO_CHAIN: {
20860 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20861 unsigned NumLoBits = 0;
20864 case Intrinsic::x86_sse_movmsk_ps:
20865 case Intrinsic::x86_avx_movmsk_ps_256:
20866 case Intrinsic::x86_sse2_movmsk_pd:
20867 case Intrinsic::x86_avx_movmsk_pd_256:
20868 case Intrinsic::x86_mmx_pmovmskb:
20869 case Intrinsic::x86_sse2_pmovmskb_128:
20870 case Intrinsic::x86_avx2_pmovmskb: {
20871 // High bits of movmskp{s|d}, pmovmskb are known zero.
20873 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
20874 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
20875 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
20876 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
20877 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
20878 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
20879 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
20880 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
20882 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20891 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20893 const SelectionDAG &,
20894 unsigned Depth) const {
20895 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20896 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20897 return Op.getValueType().getScalarType().getSizeInBits();
20903 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20904 /// node is a GlobalAddress + offset.
20905 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20906 const GlobalValue* &GA,
20907 int64_t &Offset) const {
20908 if (N->getOpcode() == X86ISD::Wrapper) {
20909 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20910 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20911 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20915 return TargetLowering::isGAPlusOffset(N, GA, Offset);
20918 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20919 /// same as extracting the high 128-bit part of 256-bit vector and then
20920 /// inserting the result into the low part of a new 256-bit vector
20921 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20922 EVT VT = SVOp->getValueType(0);
20923 unsigned NumElems = VT.getVectorNumElements();
20925 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20926 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20927 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20928 SVOp->getMaskElt(j) >= 0)
20934 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20935 /// same as extracting the low 128-bit part of 256-bit vector and then
20936 /// inserting the result into the high part of a new 256-bit vector
20937 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20938 EVT VT = SVOp->getValueType(0);
20939 unsigned NumElems = VT.getVectorNumElements();
20941 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20942 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20943 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20944 SVOp->getMaskElt(j) >= 0)
20950 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20951 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20952 TargetLowering::DAGCombinerInfo &DCI,
20953 const X86Subtarget* Subtarget) {
20955 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20956 SDValue V1 = SVOp->getOperand(0);
20957 SDValue V2 = SVOp->getOperand(1);
20958 EVT VT = SVOp->getValueType(0);
20959 unsigned NumElems = VT.getVectorNumElements();
20961 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20962 V2.getOpcode() == ISD::CONCAT_VECTORS) {
20966 // V UNDEF BUILD_VECTOR UNDEF
20968 // CONCAT_VECTOR CONCAT_VECTOR
20971 // RESULT: V + zero extended
20973 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20974 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20975 V1.getOperand(1).getOpcode() != ISD::UNDEF)
20978 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20981 // To match the shuffle mask, the first half of the mask should
20982 // be exactly the first vector, and all the rest a splat with the
20983 // first element of the second one.
20984 for (unsigned i = 0; i != NumElems/2; ++i)
20985 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20986 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20989 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20990 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20991 if (Ld->hasNUsesOfValue(1, 0)) {
20992 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20993 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20995 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20997 Ld->getPointerInfo(),
20998 Ld->getAlignment(),
20999 false/*isVolatile*/, true/*ReadMem*/,
21000 false/*WriteMem*/);
21002 // Make sure the newly-created LOAD is in the same position as Ld in
21003 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21004 // and update uses of Ld's output chain to use the TokenFactor.
21005 if (Ld->hasAnyUseOfValue(1)) {
21006 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21007 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21008 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21009 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21010 SDValue(ResNode.getNode(), 1));
21013 return DAG.getBitcast(VT, ResNode);
21017 // Emit a zeroed vector and insert the desired subvector on its
21019 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21020 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21021 return DCI.CombineTo(N, InsV);
21024 //===--------------------------------------------------------------------===//
21025 // Combine some shuffles into subvector extracts and inserts:
21028 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21029 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21030 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21031 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21032 return DCI.CombineTo(N, InsV);
21035 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21036 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21037 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21038 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21039 return DCI.CombineTo(N, InsV);
21045 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21048 /// This is the leaf of the recursive combinine below. When we have found some
21049 /// chain of single-use x86 shuffle instructions and accumulated the combined
21050 /// shuffle mask represented by them, this will try to pattern match that mask
21051 /// into either a single instruction if there is a special purpose instruction
21052 /// for this operation, or into a PSHUFB instruction which is a fully general
21053 /// instruction but should only be used to replace chains over a certain depth.
21054 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21055 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21056 TargetLowering::DAGCombinerInfo &DCI,
21057 const X86Subtarget *Subtarget) {
21058 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21060 // Find the operand that enters the chain. Note that multiple uses are OK
21061 // here, we're not going to remove the operand we find.
21062 SDValue Input = Op.getOperand(0);
21063 while (Input.getOpcode() == ISD::BITCAST)
21064 Input = Input.getOperand(0);
21066 MVT VT = Input.getSimpleValueType();
21067 MVT RootVT = Root.getSimpleValueType();
21070 // Just remove no-op shuffle masks.
21071 if (Mask.size() == 1) {
21072 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21077 // Use the float domain if the operand type is a floating point type.
21078 bool FloatDomain = VT.isFloatingPoint();
21080 // For floating point shuffles, we don't have free copies in the shuffle
21081 // instructions or the ability to load as part of the instruction, so
21082 // canonicalize their shuffles to UNPCK or MOV variants.
21084 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21085 // vectors because it can have a load folded into it that UNPCK cannot. This
21086 // doesn't preclude something switching to the shorter encoding post-RA.
21088 // FIXME: Should teach these routines about AVX vector widths.
21089 if (FloatDomain && VT.getSizeInBits() == 128) {
21090 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21091 bool Lo = Mask.equals({0, 0});
21094 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21095 // is no slower than UNPCKLPD but has the option to fold the input operand
21096 // into even an unaligned memory load.
21097 if (Lo && Subtarget->hasSSE3()) {
21098 Shuffle = X86ISD::MOVDDUP;
21099 ShuffleVT = MVT::v2f64;
21101 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21102 // than the UNPCK variants.
21103 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21104 ShuffleVT = MVT::v4f32;
21106 if (Depth == 1 && Root->getOpcode() == Shuffle)
21107 return false; // Nothing to do!
21108 Op = DAG.getBitcast(ShuffleVT, Input);
21109 DCI.AddToWorklist(Op.getNode());
21110 if (Shuffle == X86ISD::MOVDDUP)
21111 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21113 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21114 DCI.AddToWorklist(Op.getNode());
21115 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21119 if (Subtarget->hasSSE3() &&
21120 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21121 bool Lo = Mask.equals({0, 0, 2, 2});
21122 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21123 MVT ShuffleVT = MVT::v4f32;
21124 if (Depth == 1 && Root->getOpcode() == Shuffle)
21125 return false; // Nothing to do!
21126 Op = DAG.getBitcast(ShuffleVT, Input);
21127 DCI.AddToWorklist(Op.getNode());
21128 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21129 DCI.AddToWorklist(Op.getNode());
21130 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21134 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21135 bool Lo = Mask.equals({0, 0, 1, 1});
21136 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21137 MVT ShuffleVT = MVT::v4f32;
21138 if (Depth == 1 && Root->getOpcode() == Shuffle)
21139 return false; // Nothing to do!
21140 Op = DAG.getBitcast(ShuffleVT, Input);
21141 DCI.AddToWorklist(Op.getNode());
21142 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21143 DCI.AddToWorklist(Op.getNode());
21144 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21150 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21151 // variants as none of these have single-instruction variants that are
21152 // superior to the UNPCK formulation.
21153 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21154 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21155 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21156 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21158 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21159 bool Lo = Mask[0] == 0;
21160 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21161 if (Depth == 1 && Root->getOpcode() == Shuffle)
21162 return false; // Nothing to do!
21164 switch (Mask.size()) {
21166 ShuffleVT = MVT::v8i16;
21169 ShuffleVT = MVT::v16i8;
21172 llvm_unreachable("Impossible mask size!");
21174 Op = DAG.getBitcast(ShuffleVT, Input);
21175 DCI.AddToWorklist(Op.getNode());
21176 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21177 DCI.AddToWorklist(Op.getNode());
21178 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21183 // Don't try to re-form single instruction chains under any circumstances now
21184 // that we've done encoding canonicalization for them.
21188 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21189 // can replace them with a single PSHUFB instruction profitably. Intel's
21190 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21191 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21192 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21193 SmallVector<SDValue, 16> PSHUFBMask;
21194 int NumBytes = VT.getSizeInBits() / 8;
21195 int Ratio = NumBytes / Mask.size();
21196 for (int i = 0; i < NumBytes; ++i) {
21197 if (Mask[i / Ratio] == SM_SentinelUndef) {
21198 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21201 int M = Mask[i / Ratio] != SM_SentinelZero
21202 ? Ratio * Mask[i / Ratio] + i % Ratio
21204 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21206 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21207 Op = DAG.getBitcast(ByteVT, Input);
21208 DCI.AddToWorklist(Op.getNode());
21209 SDValue PSHUFBMaskOp =
21210 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21211 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21212 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21213 DCI.AddToWorklist(Op.getNode());
21214 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21219 // Failed to find any combines.
21223 /// \brief Fully generic combining of x86 shuffle instructions.
21225 /// This should be the last combine run over the x86 shuffle instructions. Once
21226 /// they have been fully optimized, this will recursively consider all chains
21227 /// of single-use shuffle instructions, build a generic model of the cumulative
21228 /// shuffle operation, and check for simpler instructions which implement this
21229 /// operation. We use this primarily for two purposes:
21231 /// 1) Collapse generic shuffles to specialized single instructions when
21232 /// equivalent. In most cases, this is just an encoding size win, but
21233 /// sometimes we will collapse multiple generic shuffles into a single
21234 /// special-purpose shuffle.
21235 /// 2) Look for sequences of shuffle instructions with 3 or more total
21236 /// instructions, and replace them with the slightly more expensive SSSE3
21237 /// PSHUFB instruction if available. We do this as the last combining step
21238 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21239 /// a suitable short sequence of other instructions. The PHUFB will either
21240 /// use a register or have to read from memory and so is slightly (but only
21241 /// slightly) more expensive than the other shuffle instructions.
21243 /// Because this is inherently a quadratic operation (for each shuffle in
21244 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21245 /// This should never be an issue in practice as the shuffle lowering doesn't
21246 /// produce sequences of more than 8 instructions.
21248 /// FIXME: We will currently miss some cases where the redundant shuffling
21249 /// would simplify under the threshold for PSHUFB formation because of
21250 /// combine-ordering. To fix this, we should do the redundant instruction
21251 /// combining in this recursive walk.
21252 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21253 ArrayRef<int> RootMask,
21254 int Depth, bool HasPSHUFB,
21256 TargetLowering::DAGCombinerInfo &DCI,
21257 const X86Subtarget *Subtarget) {
21258 // Bound the depth of our recursive combine because this is ultimately
21259 // quadratic in nature.
21263 // Directly rip through bitcasts to find the underlying operand.
21264 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21265 Op = Op.getOperand(0);
21267 MVT VT = Op.getSimpleValueType();
21268 if (!VT.isVector())
21269 return false; // Bail if we hit a non-vector.
21271 assert(Root.getSimpleValueType().isVector() &&
21272 "Shuffles operate on vector types!");
21273 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21274 "Can only combine shuffles of the same vector register size.");
21276 if (!isTargetShuffle(Op.getOpcode()))
21278 SmallVector<int, 16> OpMask;
21280 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21281 // We only can combine unary shuffles which we can decode the mask for.
21282 if (!HaveMask || !IsUnary)
21285 assert(VT.getVectorNumElements() == OpMask.size() &&
21286 "Different mask size from vector size!");
21287 assert(((RootMask.size() > OpMask.size() &&
21288 RootMask.size() % OpMask.size() == 0) ||
21289 (OpMask.size() > RootMask.size() &&
21290 OpMask.size() % RootMask.size() == 0) ||
21291 OpMask.size() == RootMask.size()) &&
21292 "The smaller number of elements must divide the larger.");
21293 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21294 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21295 assert(((RootRatio == 1 && OpRatio == 1) ||
21296 (RootRatio == 1) != (OpRatio == 1)) &&
21297 "Must not have a ratio for both incoming and op masks!");
21299 SmallVector<int, 16> Mask;
21300 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21302 // Merge this shuffle operation's mask into our accumulated mask. Note that
21303 // this shuffle's mask will be the first applied to the input, followed by the
21304 // root mask to get us all the way to the root value arrangement. The reason
21305 // for this order is that we are recursing up the operation chain.
21306 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21307 int RootIdx = i / RootRatio;
21308 if (RootMask[RootIdx] < 0) {
21309 // This is a zero or undef lane, we're done.
21310 Mask.push_back(RootMask[RootIdx]);
21314 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21315 int OpIdx = RootMaskedIdx / OpRatio;
21316 if (OpMask[OpIdx] < 0) {
21317 // The incoming lanes are zero or undef, it doesn't matter which ones we
21319 Mask.push_back(OpMask[OpIdx]);
21323 // Ok, we have non-zero lanes, map them through.
21324 Mask.push_back(OpMask[OpIdx] * OpRatio +
21325 RootMaskedIdx % OpRatio);
21328 // See if we can recurse into the operand to combine more things.
21329 switch (Op.getOpcode()) {
21330 case X86ISD::PSHUFB:
21332 case X86ISD::PSHUFD:
21333 case X86ISD::PSHUFHW:
21334 case X86ISD::PSHUFLW:
21335 if (Op.getOperand(0).hasOneUse() &&
21336 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21337 HasPSHUFB, DAG, DCI, Subtarget))
21341 case X86ISD::UNPCKL:
21342 case X86ISD::UNPCKH:
21343 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21344 // We can't check for single use, we have to check that this shuffle is the only user.
21345 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21346 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21347 HasPSHUFB, DAG, DCI, Subtarget))
21352 // Minor canonicalization of the accumulated shuffle mask to make it easier
21353 // to match below. All this does is detect masks with squential pairs of
21354 // elements, and shrink them to the half-width mask. It does this in a loop
21355 // so it will reduce the size of the mask to the minimal width mask which
21356 // performs an equivalent shuffle.
21357 SmallVector<int, 16> WidenedMask;
21358 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21359 Mask = std::move(WidenedMask);
21360 WidenedMask.clear();
21363 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21367 /// \brief Get the PSHUF-style mask from PSHUF node.
21369 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21370 /// PSHUF-style masks that can be reused with such instructions.
21371 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21372 MVT VT = N.getSimpleValueType();
21373 SmallVector<int, 4> Mask;
21375 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21379 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21380 // matter. Check that the upper masks are repeats and remove them.
21381 if (VT.getSizeInBits() > 128) {
21382 int LaneElts = 128 / VT.getScalarSizeInBits();
21384 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21385 for (int j = 0; j < LaneElts; ++j)
21386 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21387 "Mask doesn't repeat in high 128-bit lanes!");
21389 Mask.resize(LaneElts);
21392 switch (N.getOpcode()) {
21393 case X86ISD::PSHUFD:
21395 case X86ISD::PSHUFLW:
21398 case X86ISD::PSHUFHW:
21399 Mask.erase(Mask.begin(), Mask.begin() + 4);
21400 for (int &M : Mask)
21404 llvm_unreachable("No valid shuffle instruction found!");
21408 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21410 /// We walk up the chain and look for a combinable shuffle, skipping over
21411 /// shuffles that we could hoist this shuffle's transformation past without
21412 /// altering anything.
21414 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21416 TargetLowering::DAGCombinerInfo &DCI) {
21417 assert(N.getOpcode() == X86ISD::PSHUFD &&
21418 "Called with something other than an x86 128-bit half shuffle!");
21421 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21422 // of the shuffles in the chain so that we can form a fresh chain to replace
21424 SmallVector<SDValue, 8> Chain;
21425 SDValue V = N.getOperand(0);
21426 for (; V.hasOneUse(); V = V.getOperand(0)) {
21427 switch (V.getOpcode()) {
21429 return SDValue(); // Nothing combined!
21432 // Skip bitcasts as we always know the type for the target specific
21436 case X86ISD::PSHUFD:
21437 // Found another dword shuffle.
21440 case X86ISD::PSHUFLW:
21441 // Check that the low words (being shuffled) are the identity in the
21442 // dword shuffle, and the high words are self-contained.
21443 if (Mask[0] != 0 || Mask[1] != 1 ||
21444 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21447 Chain.push_back(V);
21450 case X86ISD::PSHUFHW:
21451 // Check that the high words (being shuffled) are the identity in the
21452 // dword shuffle, and the low words are self-contained.
21453 if (Mask[2] != 2 || Mask[3] != 3 ||
21454 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21457 Chain.push_back(V);
21460 case X86ISD::UNPCKL:
21461 case X86ISD::UNPCKH:
21462 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21463 // shuffle into a preceding word shuffle.
21464 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21465 V.getSimpleValueType().getScalarType() != MVT::i16)
21468 // Search for a half-shuffle which we can combine with.
21469 unsigned CombineOp =
21470 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21471 if (V.getOperand(0) != V.getOperand(1) ||
21472 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21474 Chain.push_back(V);
21475 V = V.getOperand(0);
21477 switch (V.getOpcode()) {
21479 return SDValue(); // Nothing to combine.
21481 case X86ISD::PSHUFLW:
21482 case X86ISD::PSHUFHW:
21483 if (V.getOpcode() == CombineOp)
21486 Chain.push_back(V);
21490 V = V.getOperand(0);
21494 } while (V.hasOneUse());
21497 // Break out of the loop if we break out of the switch.
21501 if (!V.hasOneUse())
21502 // We fell out of the loop without finding a viable combining instruction.
21505 // Merge this node's mask and our incoming mask.
21506 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21507 for (int &M : Mask)
21509 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21510 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21512 // Rebuild the chain around this new shuffle.
21513 while (!Chain.empty()) {
21514 SDValue W = Chain.pop_back_val();
21516 if (V.getValueType() != W.getOperand(0).getValueType())
21517 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21519 switch (W.getOpcode()) {
21521 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21523 case X86ISD::UNPCKL:
21524 case X86ISD::UNPCKH:
21525 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21528 case X86ISD::PSHUFD:
21529 case X86ISD::PSHUFLW:
21530 case X86ISD::PSHUFHW:
21531 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21535 if (V.getValueType() != N.getValueType())
21536 V = DAG.getBitcast(N.getValueType(), V);
21538 // Return the new chain to replace N.
21542 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21544 /// We walk up the chain, skipping shuffles of the other half and looking
21545 /// through shuffles which switch halves trying to find a shuffle of the same
21546 /// pair of dwords.
21547 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21549 TargetLowering::DAGCombinerInfo &DCI) {
21551 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21552 "Called with something other than an x86 128-bit half shuffle!");
21554 unsigned CombineOpcode = N.getOpcode();
21556 // Walk up a single-use chain looking for a combinable shuffle.
21557 SDValue V = N.getOperand(0);
21558 for (; V.hasOneUse(); V = V.getOperand(0)) {
21559 switch (V.getOpcode()) {
21561 return false; // Nothing combined!
21564 // Skip bitcasts as we always know the type for the target specific
21568 case X86ISD::PSHUFLW:
21569 case X86ISD::PSHUFHW:
21570 if (V.getOpcode() == CombineOpcode)
21573 // Other-half shuffles are no-ops.
21576 // Break out of the loop if we break out of the switch.
21580 if (!V.hasOneUse())
21581 // We fell out of the loop without finding a viable combining instruction.
21584 // Combine away the bottom node as its shuffle will be accumulated into
21585 // a preceding shuffle.
21586 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21588 // Record the old value.
21591 // Merge this node's mask and our incoming mask (adjusted to account for all
21592 // the pshufd instructions encountered).
21593 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21594 for (int &M : Mask)
21596 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21597 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21599 // Check that the shuffles didn't cancel each other out. If not, we need to
21600 // combine to the new one.
21602 // Replace the combinable shuffle with the combined one, updating all users
21603 // so that we re-evaluate the chain here.
21604 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21609 /// \brief Try to combine x86 target specific shuffles.
21610 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21611 TargetLowering::DAGCombinerInfo &DCI,
21612 const X86Subtarget *Subtarget) {
21614 MVT VT = N.getSimpleValueType();
21615 SmallVector<int, 4> Mask;
21617 switch (N.getOpcode()) {
21618 case X86ISD::PSHUFD:
21619 case X86ISD::PSHUFLW:
21620 case X86ISD::PSHUFHW:
21621 Mask = getPSHUFShuffleMask(N);
21622 assert(Mask.size() == 4);
21628 // Nuke no-op shuffles that show up after combining.
21629 if (isNoopShuffleMask(Mask))
21630 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21632 // Look for simplifications involving one or two shuffle instructions.
21633 SDValue V = N.getOperand(0);
21634 switch (N.getOpcode()) {
21637 case X86ISD::PSHUFLW:
21638 case X86ISD::PSHUFHW:
21639 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21641 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21642 return SDValue(); // We combined away this shuffle, so we're done.
21644 // See if this reduces to a PSHUFD which is no more expensive and can
21645 // combine with more operations. Note that it has to at least flip the
21646 // dwords as otherwise it would have been removed as a no-op.
21647 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21648 int DMask[] = {0, 1, 2, 3};
21649 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21650 DMask[DOffset + 0] = DOffset + 1;
21651 DMask[DOffset + 1] = DOffset + 0;
21652 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21653 V = DAG.getBitcast(DVT, V);
21654 DCI.AddToWorklist(V.getNode());
21655 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21656 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21657 DCI.AddToWorklist(V.getNode());
21658 return DAG.getBitcast(VT, V);
21661 // Look for shuffle patterns which can be implemented as a single unpack.
21662 // FIXME: This doesn't handle the location of the PSHUFD generically, and
21663 // only works when we have a PSHUFD followed by two half-shuffles.
21664 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21665 (V.getOpcode() == X86ISD::PSHUFLW ||
21666 V.getOpcode() == X86ISD::PSHUFHW) &&
21667 V.getOpcode() != N.getOpcode() &&
21669 SDValue D = V.getOperand(0);
21670 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21671 D = D.getOperand(0);
21672 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21673 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21674 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21675 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21676 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21678 for (int i = 0; i < 4; ++i) {
21679 WordMask[i + NOffset] = Mask[i] + NOffset;
21680 WordMask[i + VOffset] = VMask[i] + VOffset;
21682 // Map the word mask through the DWord mask.
21684 for (int i = 0; i < 8; ++i)
21685 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21686 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21687 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21688 // We can replace all three shuffles with an unpack.
21689 V = DAG.getBitcast(VT, D.getOperand(0));
21690 DCI.AddToWorklist(V.getNode());
21691 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21700 case X86ISD::PSHUFD:
21701 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21710 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21712 /// We combine this directly on the abstract vector shuffle nodes so it is
21713 /// easier to generically match. We also insert dummy vector shuffle nodes for
21714 /// the operands which explicitly discard the lanes which are unused by this
21715 /// operation to try to flow through the rest of the combiner the fact that
21716 /// they're unused.
21717 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21719 EVT VT = N->getValueType(0);
21721 // We only handle target-independent shuffles.
21722 // FIXME: It would be easy and harmless to use the target shuffle mask
21723 // extraction tool to support more.
21724 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21727 auto *SVN = cast<ShuffleVectorSDNode>(N);
21728 ArrayRef<int> Mask = SVN->getMask();
21729 SDValue V1 = N->getOperand(0);
21730 SDValue V2 = N->getOperand(1);
21732 // We require the first shuffle operand to be the SUB node, and the second to
21733 // be the ADD node.
21734 // FIXME: We should support the commuted patterns.
21735 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21738 // If there are other uses of these operations we can't fold them.
21739 if (!V1->hasOneUse() || !V2->hasOneUse())
21742 // Ensure that both operations have the same operands. Note that we can
21743 // commute the FADD operands.
21744 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21745 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21746 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21749 // We're looking for blends between FADD and FSUB nodes. We insist on these
21750 // nodes being lined up in a specific expected pattern.
21751 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21752 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21753 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21756 // Only specific types are legal at this point, assert so we notice if and
21757 // when these change.
21758 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21759 VT == MVT::v4f64) &&
21760 "Unknown vector type encountered!");
21762 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21765 /// PerformShuffleCombine - Performs several different shuffle combines.
21766 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21767 TargetLowering::DAGCombinerInfo &DCI,
21768 const X86Subtarget *Subtarget) {
21770 SDValue N0 = N->getOperand(0);
21771 SDValue N1 = N->getOperand(1);
21772 EVT VT = N->getValueType(0);
21774 // Don't create instructions with illegal types after legalize types has run.
21775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21776 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21779 // If we have legalized the vector types, look for blends of FADD and FSUB
21780 // nodes that we can fuse into an ADDSUB node.
21781 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21782 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21785 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21786 if (Subtarget->hasFp256() && VT.is256BitVector() &&
21787 N->getOpcode() == ISD::VECTOR_SHUFFLE)
21788 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21790 // During Type Legalization, when promoting illegal vector types,
21791 // the backend might introduce new shuffle dag nodes and bitcasts.
21793 // This code performs the following transformation:
21794 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21795 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21797 // We do this only if both the bitcast and the BINOP dag nodes have
21798 // one use. Also, perform this transformation only if the new binary
21799 // operation is legal. This is to avoid introducing dag nodes that
21800 // potentially need to be further expanded (or custom lowered) into a
21801 // less optimal sequence of dag nodes.
21802 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21803 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21804 N0.getOpcode() == ISD::BITCAST) {
21805 SDValue BC0 = N0.getOperand(0);
21806 EVT SVT = BC0.getValueType();
21807 unsigned Opcode = BC0.getOpcode();
21808 unsigned NumElts = VT.getVectorNumElements();
21810 if (BC0.hasOneUse() && SVT.isVector() &&
21811 SVT.getVectorNumElements() * 2 == NumElts &&
21812 TLI.isOperationLegal(Opcode, VT)) {
21813 bool CanFold = false;
21825 unsigned SVTNumElts = SVT.getVectorNumElements();
21826 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21827 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21828 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21829 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21830 CanFold = SVOp->getMaskElt(i) < 0;
21833 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21834 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21835 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21836 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21841 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21842 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21843 // consecutive, non-overlapping, and in the right order.
21844 SmallVector<SDValue, 16> Elts;
21845 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21846 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21848 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21851 if (isTargetShuffle(N->getOpcode())) {
21853 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21854 if (Shuffle.getNode())
21857 // Try recursively combining arbitrary sequences of x86 shuffle
21858 // instructions into higher-order shuffles. We do this after combining
21859 // specific PSHUF instruction sequences into their minimal form so that we
21860 // can evaluate how many specialized shuffle instructions are involved in
21861 // a particular chain.
21862 SmallVector<int, 1> NonceMask; // Just a placeholder.
21863 NonceMask.push_back(0);
21864 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21865 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21867 return SDValue(); // This routine will use CombineTo to replace N.
21873 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21874 /// specific shuffle of a load can be folded into a single element load.
21875 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21876 /// shuffles have been custom lowered so we need to handle those here.
21877 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21878 TargetLowering::DAGCombinerInfo &DCI) {
21879 if (DCI.isBeforeLegalizeOps())
21882 SDValue InVec = N->getOperand(0);
21883 SDValue EltNo = N->getOperand(1);
21885 if (!isa<ConstantSDNode>(EltNo))
21888 EVT OriginalVT = InVec.getValueType();
21890 if (InVec.getOpcode() == ISD::BITCAST) {
21891 // Don't duplicate a load with other uses.
21892 if (!InVec.hasOneUse())
21894 EVT BCVT = InVec.getOperand(0).getValueType();
21895 if (!BCVT.isVector() ||
21896 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21898 InVec = InVec.getOperand(0);
21901 EVT CurrentVT = InVec.getValueType();
21903 if (!isTargetShuffle(InVec.getOpcode()))
21906 // Don't duplicate a load with other uses.
21907 if (!InVec.hasOneUse())
21910 SmallVector<int, 16> ShuffleMask;
21912 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21913 ShuffleMask, UnaryShuffle))
21916 // Select the input vector, guarding against out of range extract vector.
21917 unsigned NumElems = CurrentVT.getVectorNumElements();
21918 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21919 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21920 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21921 : InVec.getOperand(1);
21923 // If inputs to shuffle are the same for both ops, then allow 2 uses
21924 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21925 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21927 if (LdNode.getOpcode() == ISD::BITCAST) {
21928 // Don't duplicate a load with other uses.
21929 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21932 AllowedUses = 1; // only allow 1 load use if we have a bitcast
21933 LdNode = LdNode.getOperand(0);
21936 if (!ISD::isNormalLoad(LdNode.getNode()))
21939 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21941 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21944 EVT EltVT = N->getValueType(0);
21945 // If there's a bitcast before the shuffle, check if the load type and
21946 // alignment is valid.
21947 unsigned Align = LN0->getAlignment();
21948 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21949 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21950 EltVT.getTypeForEVT(*DAG.getContext()));
21952 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21955 // All checks match so transform back to vector_shuffle so that DAG combiner
21956 // can finish the job
21959 // Create shuffle node taking into account the case that its a unary shuffle
21960 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21961 : InVec.getOperand(1);
21962 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21963 InVec.getOperand(0), Shuffle,
21965 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21966 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21970 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21971 /// special and don't usually play with other vector types, it's better to
21972 /// handle them early to be sure we emit efficient code by avoiding
21973 /// store-load conversions.
21974 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21975 if (N->getValueType(0) != MVT::x86mmx ||
21976 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21977 N->getOperand(0)->getValueType(0) != MVT::v2i32)
21980 SDValue V = N->getOperand(0);
21981 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21982 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21983 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21984 N->getValueType(0), V.getOperand(0));
21989 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21990 /// generation and convert it from being a bunch of shuffles and extracts
21991 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21992 /// storing the value and loading scalars back, while for x64 we should
21993 /// use 64-bit extracts and shifts.
21994 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21995 TargetLowering::DAGCombinerInfo &DCI) {
21996 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21999 SDValue InputVector = N->getOperand(0);
22000 SDLoc dl(InputVector);
22001 // Detect mmx to i32 conversion through a v2i32 elt extract.
22002 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22003 N->getValueType(0) == MVT::i32 &&
22004 InputVector.getValueType() == MVT::v2i32) {
22006 // The bitcast source is a direct mmx result.
22007 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22008 if (MMXSrc.getValueType() == MVT::x86mmx)
22009 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22010 N->getValueType(0),
22011 InputVector.getNode()->getOperand(0));
22013 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22014 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22015 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22016 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22017 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22018 MMXSrcOp.getValueType() == MVT::v1i64 &&
22019 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22020 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22021 N->getValueType(0),
22022 MMXSrcOp.getOperand(0));
22025 EVT VT = N->getValueType(0);
22027 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22028 InputVector.getOpcode() == ISD::BITCAST &&
22029 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22030 uint64_t ExtractedElt =
22031 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22032 uint64_t InputValue =
22033 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22034 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22035 return DAG.getConstant(Res, dl, MVT::i1);
22037 // Only operate on vectors of 4 elements, where the alternative shuffling
22038 // gets to be more expensive.
22039 if (InputVector.getValueType() != MVT::v4i32)
22042 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22043 // single use which is a sign-extend or zero-extend, and all elements are
22045 SmallVector<SDNode *, 4> Uses;
22046 unsigned ExtractedElements = 0;
22047 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22048 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22049 if (UI.getUse().getResNo() != InputVector.getResNo())
22052 SDNode *Extract = *UI;
22053 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22056 if (Extract->getValueType(0) != MVT::i32)
22058 if (!Extract->hasOneUse())
22060 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22061 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22063 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22066 // Record which element was extracted.
22067 ExtractedElements |=
22068 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22070 Uses.push_back(Extract);
22073 // If not all the elements were used, this may not be worthwhile.
22074 if (ExtractedElements != 15)
22077 // Ok, we've now decided to do the transformation.
22078 // If 64-bit shifts are legal, use the extract-shift sequence,
22079 // otherwise bounce the vector off the cache.
22080 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22083 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22084 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22085 auto &DL = DAG.getDataLayout();
22086 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22087 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22088 DAG.getConstant(0, dl, VecIdxTy));
22089 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22090 DAG.getConstant(1, dl, VecIdxTy));
22092 SDValue ShAmt = DAG.getConstant(
22093 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22094 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22095 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22096 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22097 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22098 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22099 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22101 // Store the value to a temporary stack slot.
22102 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22103 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22104 MachinePointerInfo(), false, false, 0);
22106 EVT ElementType = InputVector.getValueType().getVectorElementType();
22107 unsigned EltSize = ElementType.getSizeInBits() / 8;
22109 // Replace each use (extract) with a load of the appropriate element.
22110 for (unsigned i = 0; i < 4; ++i) {
22111 uint64_t Offset = EltSize * i;
22112 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22113 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22115 SDValue ScalarAddr =
22116 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22118 // Load the scalar.
22119 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22120 ScalarAddr, MachinePointerInfo(),
22121 false, false, false, 0);
22126 // Replace the extracts
22127 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22128 UE = Uses.end(); UI != UE; ++UI) {
22129 SDNode *Extract = *UI;
22131 SDValue Idx = Extract->getOperand(1);
22132 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22133 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22136 // The replacement was made in place; don't return anything.
22140 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22141 static std::pair<unsigned, bool>
22142 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22143 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22144 if (!VT.isVector())
22145 return std::make_pair(0, false);
22147 bool NeedSplit = false;
22148 switch (VT.getSimpleVT().SimpleTy) {
22149 default: return std::make_pair(0, false);
22152 if (!Subtarget->hasVLX())
22153 return std::make_pair(0, false);
22157 if (!Subtarget->hasBWI())
22158 return std::make_pair(0, false);
22162 if (!Subtarget->hasAVX512())
22163 return std::make_pair(0, false);
22168 if (!Subtarget->hasAVX2())
22170 if (!Subtarget->hasAVX())
22171 return std::make_pair(0, false);
22176 if (!Subtarget->hasSSE2())
22177 return std::make_pair(0, false);
22180 // SSE2 has only a small subset of the operations.
22181 bool hasUnsigned = Subtarget->hasSSE41() ||
22182 (Subtarget->hasSSE2() && VT == MVT::v16i8);
22183 bool hasSigned = Subtarget->hasSSE41() ||
22184 (Subtarget->hasSSE2() && VT == MVT::v8i16);
22186 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22189 // Check for x CC y ? x : y.
22190 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22191 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22196 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22199 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22202 Opc = hasSigned ? ISD::SMIN : 0; break;
22205 Opc = hasSigned ? ISD::SMAX : 0; break;
22207 // Check for x CC y ? y : x -- a min/max with reversed arms.
22208 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22209 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22214 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22217 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22220 Opc = hasSigned ? ISD::SMAX : 0; break;
22223 Opc = hasSigned ? ISD::SMIN : 0; break;
22227 return std::make_pair(Opc, NeedSplit);
22231 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22232 const X86Subtarget *Subtarget) {
22234 SDValue Cond = N->getOperand(0);
22235 SDValue LHS = N->getOperand(1);
22236 SDValue RHS = N->getOperand(2);
22238 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22239 SDValue CondSrc = Cond->getOperand(0);
22240 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22241 Cond = CondSrc->getOperand(0);
22244 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22247 // A vselect where all conditions and data are constants can be optimized into
22248 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22249 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22250 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22253 unsigned MaskValue = 0;
22254 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22257 MVT VT = N->getSimpleValueType(0);
22258 unsigned NumElems = VT.getVectorNumElements();
22259 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22260 for (unsigned i = 0; i < NumElems; ++i) {
22261 // Be sure we emit undef where we can.
22262 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22263 ShuffleMask[i] = -1;
22265 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22268 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22269 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22271 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22274 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22276 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22277 TargetLowering::DAGCombinerInfo &DCI,
22278 const X86Subtarget *Subtarget) {
22280 SDValue Cond = N->getOperand(0);
22281 // Get the LHS/RHS of the select.
22282 SDValue LHS = N->getOperand(1);
22283 SDValue RHS = N->getOperand(2);
22284 EVT VT = LHS.getValueType();
22285 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22287 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22288 // instructions match the semantics of the common C idiom x<y?x:y but not
22289 // x<=y?x:y, because of how they handle negative zero (which can be
22290 // ignored in unsafe-math mode).
22291 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22292 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22293 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22294 (Subtarget->hasSSE2() ||
22295 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22296 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22298 unsigned Opcode = 0;
22299 // Check for x CC y ? x : y.
22300 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22301 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22305 // Converting this to a min would handle NaNs incorrectly, and swapping
22306 // the operands would cause it to handle comparisons between positive
22307 // and negative zero incorrectly.
22308 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22309 if (!DAG.getTarget().Options.UnsafeFPMath &&
22310 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22312 std::swap(LHS, RHS);
22314 Opcode = X86ISD::FMIN;
22317 // Converting this to a min would handle comparisons between positive
22318 // and negative zero incorrectly.
22319 if (!DAG.getTarget().Options.UnsafeFPMath &&
22320 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22322 Opcode = X86ISD::FMIN;
22325 // Converting this to a min would handle both negative zeros and NaNs
22326 // incorrectly, but we can swap the operands to fix both.
22327 std::swap(LHS, RHS);
22331 Opcode = X86ISD::FMIN;
22335 // Converting this to a max would handle comparisons between positive
22336 // and negative zero incorrectly.
22337 if (!DAG.getTarget().Options.UnsafeFPMath &&
22338 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22340 Opcode = X86ISD::FMAX;
22343 // Converting this to a max would handle NaNs incorrectly, and swapping
22344 // the operands would cause it to handle comparisons between positive
22345 // and negative zero incorrectly.
22346 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22347 if (!DAG.getTarget().Options.UnsafeFPMath &&
22348 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22350 std::swap(LHS, RHS);
22352 Opcode = X86ISD::FMAX;
22355 // Converting this to a max would handle both negative zeros and NaNs
22356 // incorrectly, but we can swap the operands to fix both.
22357 std::swap(LHS, RHS);
22361 Opcode = X86ISD::FMAX;
22364 // Check for x CC y ? y : x -- a min/max with reversed arms.
22365 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22366 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22370 // Converting this to a min would handle comparisons between positive
22371 // and negative zero incorrectly, and swapping the operands would
22372 // cause it to handle NaNs incorrectly.
22373 if (!DAG.getTarget().Options.UnsafeFPMath &&
22374 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22375 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22377 std::swap(LHS, RHS);
22379 Opcode = X86ISD::FMIN;
22382 // Converting this to a min would handle NaNs incorrectly.
22383 if (!DAG.getTarget().Options.UnsafeFPMath &&
22384 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22386 Opcode = X86ISD::FMIN;
22389 // Converting this to a min would handle both negative zeros and NaNs
22390 // incorrectly, but we can swap the operands to fix both.
22391 std::swap(LHS, RHS);
22395 Opcode = X86ISD::FMIN;
22399 // Converting this to a max would handle NaNs incorrectly.
22400 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22402 Opcode = X86ISD::FMAX;
22405 // Converting this to a max would handle comparisons between positive
22406 // and negative zero incorrectly, and swapping the operands would
22407 // cause it to handle NaNs incorrectly.
22408 if (!DAG.getTarget().Options.UnsafeFPMath &&
22409 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22410 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22412 std::swap(LHS, RHS);
22414 Opcode = X86ISD::FMAX;
22417 // Converting this to a max would handle both negative zeros and NaNs
22418 // incorrectly, but we can swap the operands to fix both.
22419 std::swap(LHS, RHS);
22423 Opcode = X86ISD::FMAX;
22429 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22432 EVT CondVT = Cond.getValueType();
22433 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22434 CondVT.getVectorElementType() == MVT::i1) {
22435 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22436 // lowering on KNL. In this case we convert it to
22437 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22438 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22439 // Since SKX these selects have a proper lowering.
22440 EVT OpVT = LHS.getValueType();
22441 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22442 (OpVT.getVectorElementType() == MVT::i8 ||
22443 OpVT.getVectorElementType() == MVT::i16) &&
22444 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22445 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22446 DCI.AddToWorklist(Cond.getNode());
22447 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22450 // If this is a select between two integer constants, try to do some
22452 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22453 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22454 // Don't do this for crazy integer types.
22455 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22456 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22457 // so that TrueC (the true value) is larger than FalseC.
22458 bool NeedsCondInvert = false;
22460 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22461 // Efficiently invertible.
22462 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22463 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22464 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22465 NeedsCondInvert = true;
22466 std::swap(TrueC, FalseC);
22469 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22470 if (FalseC->getAPIntValue() == 0 &&
22471 TrueC->getAPIntValue().isPowerOf2()) {
22472 if (NeedsCondInvert) // Invert the condition if needed.
22473 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22474 DAG.getConstant(1, DL, Cond.getValueType()));
22476 // Zero extend the condition if needed.
22477 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22479 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22480 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22481 DAG.getConstant(ShAmt, DL, MVT::i8));
22484 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22485 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22486 if (NeedsCondInvert) // Invert the condition if needed.
22487 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22488 DAG.getConstant(1, DL, Cond.getValueType()));
22490 // Zero extend the condition if needed.
22491 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22492 FalseC->getValueType(0), Cond);
22493 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22494 SDValue(FalseC, 0));
22497 // Optimize cases that will turn into an LEA instruction. This requires
22498 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22499 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22500 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22501 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22503 bool isFastMultiplier = false;
22505 switch ((unsigned char)Diff) {
22507 case 1: // result = add base, cond
22508 case 2: // result = lea base( , cond*2)
22509 case 3: // result = lea base(cond, cond*2)
22510 case 4: // result = lea base( , cond*4)
22511 case 5: // result = lea base(cond, cond*4)
22512 case 8: // result = lea base( , cond*8)
22513 case 9: // result = lea base(cond, cond*8)
22514 isFastMultiplier = true;
22519 if (isFastMultiplier) {
22520 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22521 if (NeedsCondInvert) // Invert the condition if needed.
22522 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22523 DAG.getConstant(1, DL, Cond.getValueType()));
22525 // Zero extend the condition if needed.
22526 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22528 // Scale the condition by the difference.
22530 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22531 DAG.getConstant(Diff, DL,
22532 Cond.getValueType()));
22534 // Add the base if non-zero.
22535 if (FalseC->getAPIntValue() != 0)
22536 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22537 SDValue(FalseC, 0));
22544 // Canonicalize max and min:
22545 // (x > y) ? x : y -> (x >= y) ? x : y
22546 // (x < y) ? x : y -> (x <= y) ? x : y
22547 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22548 // the need for an extra compare
22549 // against zero. e.g.
22550 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22552 // testl %edi, %edi
22554 // cmovgl %edi, %eax
22558 // cmovsl %eax, %edi
22559 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22560 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22561 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22562 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22567 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22568 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22569 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22570 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22575 // Early exit check
22576 if (!TLI.isTypeLegal(VT))
22579 // Match VSELECTs into subs with unsigned saturation.
22580 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22581 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22582 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22583 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22584 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22586 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22587 // left side invert the predicate to simplify logic below.
22589 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22591 CC = ISD::getSetCCInverse(CC, true);
22592 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22596 if (Other.getNode() && Other->getNumOperands() == 2 &&
22597 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22598 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22599 SDValue CondRHS = Cond->getOperand(1);
22601 // Look for a general sub with unsigned saturation first.
22602 // x >= y ? x-y : 0 --> subus x, y
22603 // x > y ? x-y : 0 --> subus x, y
22604 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22605 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22606 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22608 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22609 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22610 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22611 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22612 // If the RHS is a constant we have to reverse the const
22613 // canonicalization.
22614 // x > C-1 ? x+-C : 0 --> subus x, C
22615 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22616 CondRHSConst->getAPIntValue() ==
22617 (-OpRHSConst->getAPIntValue() - 1))
22618 return DAG.getNode(
22619 X86ISD::SUBUS, DL, VT, OpLHS,
22620 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22622 // Another special case: If C was a sign bit, the sub has been
22623 // canonicalized into a xor.
22624 // FIXME: Would it be better to use computeKnownBits to determine
22625 // whether it's safe to decanonicalize the xor?
22626 // x s< 0 ? x^C : 0 --> subus x, C
22627 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22628 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22629 OpRHSConst->getAPIntValue().isSignBit())
22630 // Note that we have to rebuild the RHS constant here to ensure we
22631 // don't rely on particular values of undef lanes.
22632 return DAG.getNode(
22633 X86ISD::SUBUS, DL, VT, OpLHS,
22634 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22639 // Try to match a min/max vector operation.
22640 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22641 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22642 unsigned Opc = ret.first;
22643 bool NeedSplit = ret.second;
22645 if (Opc && NeedSplit) {
22646 unsigned NumElems = VT.getVectorNumElements();
22647 // Extract the LHS vectors
22648 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22649 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22651 // Extract the RHS vectors
22652 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22653 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22655 // Create min/max for each subvector
22656 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22657 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22659 // Merge the result
22660 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22662 return DAG.getNode(Opc, DL, VT, LHS, RHS);
22665 // Simplify vector selection if condition value type matches vselect
22667 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22668 assert(Cond.getValueType().isVector() &&
22669 "vector select expects a vector selector!");
22671 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22672 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22674 // Try invert the condition if true value is not all 1s and false value
22676 if (!TValIsAllOnes && !FValIsAllZeros &&
22677 // Check if the selector will be produced by CMPP*/PCMP*
22678 Cond.getOpcode() == ISD::SETCC &&
22679 // Check if SETCC has already been promoted
22680 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22682 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22683 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22685 if (TValIsAllZeros || FValIsAllOnes) {
22686 SDValue CC = Cond.getOperand(2);
22687 ISD::CondCode NewCC =
22688 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22689 Cond.getOperand(0).getValueType().isInteger());
22690 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22691 std::swap(LHS, RHS);
22692 TValIsAllOnes = FValIsAllOnes;
22693 FValIsAllZeros = TValIsAllZeros;
22697 if (TValIsAllOnes || FValIsAllZeros) {
22700 if (TValIsAllOnes && FValIsAllZeros)
22702 else if (TValIsAllOnes)
22704 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22705 else if (FValIsAllZeros)
22706 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22707 DAG.getBitcast(CondVT, LHS));
22709 return DAG.getBitcast(VT, Ret);
22713 // We should generate an X86ISD::BLENDI from a vselect if its argument
22714 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22715 // constants. This specific pattern gets generated when we split a
22716 // selector for a 512 bit vector in a machine without AVX512 (but with
22717 // 256-bit vectors), during legalization:
22719 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22721 // Iff we find this pattern and the build_vectors are built from
22722 // constants, we translate the vselect into a shuffle_vector that we
22723 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22724 if ((N->getOpcode() == ISD::VSELECT ||
22725 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22726 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22727 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22728 if (Shuffle.getNode())
22732 // If this is a *dynamic* select (non-constant condition) and we can match
22733 // this node with one of the variable blend instructions, restructure the
22734 // condition so that the blends can use the high bit of each element and use
22735 // SimplifyDemandedBits to simplify the condition operand.
22736 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22737 !DCI.isBeforeLegalize() &&
22738 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22739 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22741 // Don't optimize vector selects that map to mask-registers.
22745 // We can only handle the cases where VSELECT is directly legal on the
22746 // subtarget. We custom lower VSELECT nodes with constant conditions and
22747 // this makes it hard to see whether a dynamic VSELECT will correctly
22748 // lower, so we both check the operation's status and explicitly handle the
22749 // cases where a *dynamic* blend will fail even though a constant-condition
22750 // blend could be custom lowered.
22751 // FIXME: We should find a better way to handle this class of problems.
22752 // Potentially, we should combine constant-condition vselect nodes
22753 // pre-legalization into shuffles and not mark as many types as custom
22755 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22757 // FIXME: We don't support i16-element blends currently. We could and
22758 // should support them by making *all* the bits in the condition be set
22759 // rather than just the high bit and using an i8-element blend.
22760 if (VT.getScalarType() == MVT::i16)
22762 // Dynamic blending was only available from SSE4.1 onward.
22763 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22765 // Byte blends are only available in AVX2
22766 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22767 !Subtarget->hasAVX2())
22770 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22771 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22773 APInt KnownZero, KnownOne;
22774 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22775 DCI.isBeforeLegalizeOps());
22776 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22777 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22779 // If we changed the computation somewhere in the DAG, this change
22780 // will affect all users of Cond.
22781 // Make sure it is fine and update all the nodes so that we do not
22782 // use the generic VSELECT anymore. Otherwise, we may perform
22783 // wrong optimizations as we messed up with the actual expectation
22784 // for the vector boolean values.
22785 if (Cond != TLO.Old) {
22786 // Check all uses of that condition operand to check whether it will be
22787 // consumed by non-BLEND instructions, which may depend on all bits are
22789 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22791 if (I->getOpcode() != ISD::VSELECT)
22792 // TODO: Add other opcodes eventually lowered into BLEND.
22795 // Update all the users of the condition, before committing the change,
22796 // so that the VSELECT optimizations that expect the correct vector
22797 // boolean value will not be triggered.
22798 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22800 DAG.ReplaceAllUsesOfValueWith(
22802 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22803 Cond, I->getOperand(1), I->getOperand(2)));
22804 DCI.CommitTargetLoweringOpt(TLO);
22807 // At this point, only Cond is changed. Change the condition
22808 // just for N to keep the opportunity to optimize all other
22809 // users their own way.
22810 DAG.ReplaceAllUsesOfValueWith(
22812 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22813 TLO.New, N->getOperand(1), N->getOperand(2)));
22821 // Check whether a boolean test is testing a boolean value generated by
22822 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22825 // Simplify the following patterns:
22826 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22827 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22828 // to (Op EFLAGS Cond)
22830 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22831 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22832 // to (Op EFLAGS !Cond)
22834 // where Op could be BRCOND or CMOV.
22836 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22837 // Quit if not CMP and SUB with its value result used.
22838 if (Cmp.getOpcode() != X86ISD::CMP &&
22839 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22842 // Quit if not used as a boolean value.
22843 if (CC != X86::COND_E && CC != X86::COND_NE)
22846 // Check CMP operands. One of them should be 0 or 1 and the other should be
22847 // an SetCC or extended from it.
22848 SDValue Op1 = Cmp.getOperand(0);
22849 SDValue Op2 = Cmp.getOperand(1);
22852 const ConstantSDNode* C = nullptr;
22853 bool needOppositeCond = (CC == X86::COND_E);
22854 bool checkAgainstTrue = false; // Is it a comparison against 1?
22856 if ((C = dyn_cast<ConstantSDNode>(Op1)))
22858 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22860 else // Quit if all operands are not constants.
22863 if (C->getZExtValue() == 1) {
22864 needOppositeCond = !needOppositeCond;
22865 checkAgainstTrue = true;
22866 } else if (C->getZExtValue() != 0)
22867 // Quit if the constant is neither 0 or 1.
22870 bool truncatedToBoolWithAnd = false;
22871 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22872 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22873 SetCC.getOpcode() == ISD::TRUNCATE ||
22874 SetCC.getOpcode() == ISD::AND) {
22875 if (SetCC.getOpcode() == ISD::AND) {
22877 ConstantSDNode *CS;
22878 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22879 CS->getZExtValue() == 1)
22881 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22882 CS->getZExtValue() == 1)
22886 SetCC = SetCC.getOperand(OpIdx);
22887 truncatedToBoolWithAnd = true;
22889 SetCC = SetCC.getOperand(0);
22892 switch (SetCC.getOpcode()) {
22893 case X86ISD::SETCC_CARRY:
22894 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22895 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22896 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22897 // truncated to i1 using 'and'.
22898 if (checkAgainstTrue && !truncatedToBoolWithAnd)
22900 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22901 "Invalid use of SETCC_CARRY!");
22903 case X86ISD::SETCC:
22904 // Set the condition code or opposite one if necessary.
22905 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22906 if (needOppositeCond)
22907 CC = X86::GetOppositeBranchCondition(CC);
22908 return SetCC.getOperand(1);
22909 case X86ISD::CMOV: {
22910 // Check whether false/true value has canonical one, i.e. 0 or 1.
22911 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22912 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22913 // Quit if true value is not a constant.
22916 // Quit if false value is not a constant.
22918 SDValue Op = SetCC.getOperand(0);
22919 // Skip 'zext' or 'trunc' node.
22920 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22921 Op.getOpcode() == ISD::TRUNCATE)
22922 Op = Op.getOperand(0);
22923 // A special case for rdrand/rdseed, where 0 is set if false cond is
22925 if ((Op.getOpcode() != X86ISD::RDRAND &&
22926 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22929 // Quit if false value is not the constant 0 or 1.
22930 bool FValIsFalse = true;
22931 if (FVal && FVal->getZExtValue() != 0) {
22932 if (FVal->getZExtValue() != 1)
22934 // If FVal is 1, opposite cond is needed.
22935 needOppositeCond = !needOppositeCond;
22936 FValIsFalse = false;
22938 // Quit if TVal is not the constant opposite of FVal.
22939 if (FValIsFalse && TVal->getZExtValue() != 1)
22941 if (!FValIsFalse && TVal->getZExtValue() != 0)
22943 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22944 if (needOppositeCond)
22945 CC = X86::GetOppositeBranchCondition(CC);
22946 return SetCC.getOperand(3);
22953 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22955 /// (X86or (X86setcc) (X86setcc))
22956 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
22957 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22958 X86::CondCode &CC1, SDValue &Flags,
22960 if (Cond->getOpcode() == X86ISD::CMP) {
22961 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22962 if (!CondOp1C || !CondOp1C->isNullValue())
22965 Cond = Cond->getOperand(0);
22970 SDValue SetCC0, SetCC1;
22971 switch (Cond->getOpcode()) {
22972 default: return false;
22979 SetCC0 = Cond->getOperand(0);
22980 SetCC1 = Cond->getOperand(1);
22984 // Make sure we have SETCC nodes, using the same flags value.
22985 if (SetCC0.getOpcode() != X86ISD::SETCC ||
22986 SetCC1.getOpcode() != X86ISD::SETCC ||
22987 SetCC0->getOperand(1) != SetCC1->getOperand(1))
22990 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22991 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22992 Flags = SetCC0->getOperand(1);
22996 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22997 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22998 TargetLowering::DAGCombinerInfo &DCI,
22999 const X86Subtarget *Subtarget) {
23002 // If the flag operand isn't dead, don't touch this CMOV.
23003 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23006 SDValue FalseOp = N->getOperand(0);
23007 SDValue TrueOp = N->getOperand(1);
23008 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23009 SDValue Cond = N->getOperand(3);
23011 if (CC == X86::COND_E || CC == X86::COND_NE) {
23012 switch (Cond.getOpcode()) {
23016 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23017 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23018 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23024 Flags = checkBoolTestSetCCCombine(Cond, CC);
23025 if (Flags.getNode() &&
23026 // Extra check as FCMOV only supports a subset of X86 cond.
23027 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23028 SDValue Ops[] = { FalseOp, TrueOp,
23029 DAG.getConstant(CC, DL, MVT::i8), Flags };
23030 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23033 // If this is a select between two integer constants, try to do some
23034 // optimizations. Note that the operands are ordered the opposite of SELECT
23036 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23037 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23038 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23039 // larger than FalseC (the false value).
23040 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23041 CC = X86::GetOppositeBranchCondition(CC);
23042 std::swap(TrueC, FalseC);
23043 std::swap(TrueOp, FalseOp);
23046 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23047 // This is efficient for any integer data type (including i8/i16) and
23049 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23050 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23051 DAG.getConstant(CC, DL, MVT::i8), Cond);
23053 // Zero extend the condition if needed.
23054 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23056 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23057 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23058 DAG.getConstant(ShAmt, DL, MVT::i8));
23059 if (N->getNumValues() == 2) // Dead flag value?
23060 return DCI.CombineTo(N, Cond, SDValue());
23064 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23065 // for any integer data type, including i8/i16.
23066 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23067 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23068 DAG.getConstant(CC, DL, MVT::i8), Cond);
23070 // Zero extend the condition if needed.
23071 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23072 FalseC->getValueType(0), Cond);
23073 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23074 SDValue(FalseC, 0));
23076 if (N->getNumValues() == 2) // Dead flag value?
23077 return DCI.CombineTo(N, Cond, SDValue());
23081 // Optimize cases that will turn into an LEA instruction. This requires
23082 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23083 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23084 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23085 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23087 bool isFastMultiplier = false;
23089 switch ((unsigned char)Diff) {
23091 case 1: // result = add base, cond
23092 case 2: // result = lea base( , cond*2)
23093 case 3: // result = lea base(cond, cond*2)
23094 case 4: // result = lea base( , cond*4)
23095 case 5: // result = lea base(cond, cond*4)
23096 case 8: // result = lea base( , cond*8)
23097 case 9: // result = lea base(cond, cond*8)
23098 isFastMultiplier = true;
23103 if (isFastMultiplier) {
23104 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23105 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23106 DAG.getConstant(CC, DL, MVT::i8), Cond);
23107 // Zero extend the condition if needed.
23108 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23110 // Scale the condition by the difference.
23112 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23113 DAG.getConstant(Diff, DL, Cond.getValueType()));
23115 // Add the base if non-zero.
23116 if (FalseC->getAPIntValue() != 0)
23117 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23118 SDValue(FalseC, 0));
23119 if (N->getNumValues() == 2) // Dead flag value?
23120 return DCI.CombineTo(N, Cond, SDValue());
23127 // Handle these cases:
23128 // (select (x != c), e, c) -> select (x != c), e, x),
23129 // (select (x == c), c, e) -> select (x == c), x, e)
23130 // where the c is an integer constant, and the "select" is the combination
23131 // of CMOV and CMP.
23133 // The rationale for this change is that the conditional-move from a constant
23134 // needs two instructions, however, conditional-move from a register needs
23135 // only one instruction.
23137 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23138 // some instruction-combining opportunities. This opt needs to be
23139 // postponed as late as possible.
23141 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23142 // the DCI.xxxx conditions are provided to postpone the optimization as
23143 // late as possible.
23145 ConstantSDNode *CmpAgainst = nullptr;
23146 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23147 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23148 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23150 if (CC == X86::COND_NE &&
23151 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23152 CC = X86::GetOppositeBranchCondition(CC);
23153 std::swap(TrueOp, FalseOp);
23156 if (CC == X86::COND_E &&
23157 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23158 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23159 DAG.getConstant(CC, DL, MVT::i8), Cond };
23160 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23165 // Fold and/or of setcc's to double CMOV:
23166 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23167 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23169 // This combine lets us generate:
23170 // cmovcc1 (jcc1 if we don't have CMOV)
23176 // cmovne (jne if we don't have CMOV)
23177 // When we can't use the CMOV instruction, it might increase branch
23179 // When we can use CMOV, or when there is no mispredict, this improves
23180 // throughput and reduces register pressure.
23182 if (CC == X86::COND_NE) {
23184 X86::CondCode CC0, CC1;
23186 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23188 std::swap(FalseOp, TrueOp);
23189 CC0 = X86::GetOppositeBranchCondition(CC0);
23190 CC1 = X86::GetOppositeBranchCondition(CC1);
23193 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23195 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23196 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23197 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23198 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23206 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23207 const X86Subtarget *Subtarget) {
23208 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23210 default: return SDValue();
23211 // SSE/AVX/AVX2 blend intrinsics.
23212 case Intrinsic::x86_avx2_pblendvb:
23213 // Don't try to simplify this intrinsic if we don't have AVX2.
23214 if (!Subtarget->hasAVX2())
23217 case Intrinsic::x86_avx_blendv_pd_256:
23218 case Intrinsic::x86_avx_blendv_ps_256:
23219 // Don't try to simplify this intrinsic if we don't have AVX.
23220 if (!Subtarget->hasAVX())
23223 case Intrinsic::x86_sse41_blendvps:
23224 case Intrinsic::x86_sse41_blendvpd:
23225 case Intrinsic::x86_sse41_pblendvb: {
23226 SDValue Op0 = N->getOperand(1);
23227 SDValue Op1 = N->getOperand(2);
23228 SDValue Mask = N->getOperand(3);
23230 // Don't try to simplify this intrinsic if we don't have SSE4.1.
23231 if (!Subtarget->hasSSE41())
23234 // fold (blend A, A, Mask) -> A
23237 // fold (blend A, B, allZeros) -> A
23238 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23240 // fold (blend A, B, allOnes) -> B
23241 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23244 // Simplify the case where the mask is a constant i32 value.
23245 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23246 if (C->isNullValue())
23248 if (C->isAllOnesValue())
23255 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23256 case Intrinsic::x86_sse2_psrai_w:
23257 case Intrinsic::x86_sse2_psrai_d:
23258 case Intrinsic::x86_avx2_psrai_w:
23259 case Intrinsic::x86_avx2_psrai_d:
23260 case Intrinsic::x86_sse2_psra_w:
23261 case Intrinsic::x86_sse2_psra_d:
23262 case Intrinsic::x86_avx2_psra_w:
23263 case Intrinsic::x86_avx2_psra_d: {
23264 SDValue Op0 = N->getOperand(1);
23265 SDValue Op1 = N->getOperand(2);
23266 EVT VT = Op0.getValueType();
23267 assert(VT.isVector() && "Expected a vector type!");
23269 if (isa<BuildVectorSDNode>(Op1))
23270 Op1 = Op1.getOperand(0);
23272 if (!isa<ConstantSDNode>(Op1))
23275 EVT SVT = VT.getVectorElementType();
23276 unsigned SVTBits = SVT.getSizeInBits();
23278 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23279 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23280 uint64_t ShAmt = C.getZExtValue();
23282 // Don't try to convert this shift into a ISD::SRA if the shift
23283 // count is bigger than or equal to the element size.
23284 if (ShAmt >= SVTBits)
23287 // Trivial case: if the shift count is zero, then fold this
23288 // into the first operand.
23292 // Replace this packed shift intrinsic with a target independent
23295 SDValue Splat = DAG.getConstant(C, DL, VT);
23296 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23301 /// PerformMulCombine - Optimize a single multiply with constant into two
23302 /// in order to implement it with two cheaper instructions, e.g.
23303 /// LEA + SHL, LEA + LEA.
23304 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23305 TargetLowering::DAGCombinerInfo &DCI) {
23306 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23309 EVT VT = N->getValueType(0);
23310 if (VT != MVT::i64 && VT != MVT::i32)
23313 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23316 uint64_t MulAmt = C->getZExtValue();
23317 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23320 uint64_t MulAmt1 = 0;
23321 uint64_t MulAmt2 = 0;
23322 if ((MulAmt % 9) == 0) {
23324 MulAmt2 = MulAmt / 9;
23325 } else if ((MulAmt % 5) == 0) {
23327 MulAmt2 = MulAmt / 5;
23328 } else if ((MulAmt % 3) == 0) {
23330 MulAmt2 = MulAmt / 3;
23333 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23336 if (isPowerOf2_64(MulAmt2) &&
23337 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23338 // If second multiplifer is pow2, issue it first. We want the multiply by
23339 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23341 std::swap(MulAmt1, MulAmt2);
23344 if (isPowerOf2_64(MulAmt1))
23345 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23346 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23348 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23349 DAG.getConstant(MulAmt1, DL, VT));
23351 if (isPowerOf2_64(MulAmt2))
23352 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23353 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23355 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23356 DAG.getConstant(MulAmt2, DL, VT));
23358 // Do not add new nodes to DAG combiner worklist.
23359 DCI.CombineTo(N, NewMul, false);
23364 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23365 SDValue N0 = N->getOperand(0);
23366 SDValue N1 = N->getOperand(1);
23367 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23368 EVT VT = N0.getValueType();
23370 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23371 // since the result of setcc_c is all zero's or all ones.
23372 if (VT.isInteger() && !VT.isVector() &&
23373 N1C && N0.getOpcode() == ISD::AND &&
23374 N0.getOperand(1).getOpcode() == ISD::Constant) {
23375 SDValue N00 = N0.getOperand(0);
23376 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23377 ((N00.getOpcode() == ISD::ANY_EXTEND ||
23378 N00.getOpcode() == ISD::ZERO_EXTEND) &&
23379 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23380 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23381 APInt ShAmt = N1C->getAPIntValue();
23382 Mask = Mask.shl(ShAmt);
23385 return DAG.getNode(ISD::AND, DL, VT,
23386 N00, DAG.getConstant(Mask, DL, VT));
23391 // Hardware support for vector shifts is sparse which makes us scalarize the
23392 // vector operations in many cases. Also, on sandybridge ADD is faster than
23394 // (shl V, 1) -> add V,V
23395 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23396 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23397 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23398 // We shift all of the values by one. In many cases we do not have
23399 // hardware support for this operation. This is better expressed as an ADD
23401 if (N1SplatC->getAPIntValue() == 1)
23402 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23408 /// \brief Returns a vector of 0s if the node in input is a vector logical
23409 /// shift by a constant amount which is known to be bigger than or equal
23410 /// to the vector element size in bits.
23411 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23412 const X86Subtarget *Subtarget) {
23413 EVT VT = N->getValueType(0);
23415 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23416 (!Subtarget->hasInt256() ||
23417 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23420 SDValue Amt = N->getOperand(1);
23422 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23423 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23424 APInt ShiftAmt = AmtSplat->getAPIntValue();
23425 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23427 // SSE2/AVX2 logical shifts always return a vector of 0s
23428 // if the shift amount is bigger than or equal to
23429 // the element size. The constant shift amount will be
23430 // encoded as a 8-bit immediate.
23431 if (ShiftAmt.trunc(8).uge(MaxAmount))
23432 return getZeroVector(VT, Subtarget, DAG, DL);
23438 /// PerformShiftCombine - Combine shifts.
23439 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23440 TargetLowering::DAGCombinerInfo &DCI,
23441 const X86Subtarget *Subtarget) {
23442 if (N->getOpcode() == ISD::SHL)
23443 if (SDValue V = PerformSHLCombine(N, DAG))
23446 // Try to fold this logical shift into a zero vector.
23447 if (N->getOpcode() != ISD::SRA)
23448 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23454 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23455 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23456 // and friends. Likewise for OR -> CMPNEQSS.
23457 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23458 TargetLowering::DAGCombinerInfo &DCI,
23459 const X86Subtarget *Subtarget) {
23462 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23463 // we're requiring SSE2 for both.
23464 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23465 SDValue N0 = N->getOperand(0);
23466 SDValue N1 = N->getOperand(1);
23467 SDValue CMP0 = N0->getOperand(1);
23468 SDValue CMP1 = N1->getOperand(1);
23471 // The SETCCs should both refer to the same CMP.
23472 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23475 SDValue CMP00 = CMP0->getOperand(0);
23476 SDValue CMP01 = CMP0->getOperand(1);
23477 EVT VT = CMP00.getValueType();
23479 if (VT == MVT::f32 || VT == MVT::f64) {
23480 bool ExpectingFlags = false;
23481 // Check for any users that want flags:
23482 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23483 !ExpectingFlags && UI != UE; ++UI)
23484 switch (UI->getOpcode()) {
23489 ExpectingFlags = true;
23491 case ISD::CopyToReg:
23492 case ISD::SIGN_EXTEND:
23493 case ISD::ZERO_EXTEND:
23494 case ISD::ANY_EXTEND:
23498 if (!ExpectingFlags) {
23499 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23500 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23502 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23503 X86::CondCode tmp = cc0;
23508 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23509 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23510 // FIXME: need symbolic constants for these magic numbers.
23511 // See X86ATTInstPrinter.cpp:printSSECC().
23512 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23513 if (Subtarget->hasAVX512()) {
23514 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23516 DAG.getConstant(x86cc, DL, MVT::i8));
23517 if (N->getValueType(0) != MVT::i1)
23518 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23522 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23523 CMP00.getValueType(), CMP00, CMP01,
23524 DAG.getConstant(x86cc, DL,
23527 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23528 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23530 if (is64BitFP && !Subtarget->is64Bit()) {
23531 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23532 // 64-bit integer, since that's not a legal type. Since
23533 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23534 // bits, but can do this little dance to extract the lowest 32 bits
23535 // and work with those going forward.
23536 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23538 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23539 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23540 Vector32, DAG.getIntPtrConstant(0, DL));
23544 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23545 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23546 DAG.getConstant(1, DL, IntVT));
23547 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23549 return OneBitOfTruth;
23557 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23558 /// so it can be folded inside ANDNP.
23559 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23560 EVT VT = N->getValueType(0);
23562 // Match direct AllOnes for 128 and 256-bit vectors
23563 if (ISD::isBuildVectorAllOnes(N))
23566 // Look through a bit convert.
23567 if (N->getOpcode() == ISD::BITCAST)
23568 N = N->getOperand(0).getNode();
23570 // Sometimes the operand may come from a insert_subvector building a 256-bit
23572 if (VT.is256BitVector() &&
23573 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23574 SDValue V1 = N->getOperand(0);
23575 SDValue V2 = N->getOperand(1);
23577 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23578 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23579 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23580 ISD::isBuildVectorAllOnes(V2.getNode()))
23587 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23588 // register. In most cases we actually compare or select YMM-sized registers
23589 // and mixing the two types creates horrible code. This method optimizes
23590 // some of the transition sequences.
23591 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23592 TargetLowering::DAGCombinerInfo &DCI,
23593 const X86Subtarget *Subtarget) {
23594 EVT VT = N->getValueType(0);
23595 if (!VT.is256BitVector())
23598 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23599 N->getOpcode() == ISD::ZERO_EXTEND ||
23600 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23602 SDValue Narrow = N->getOperand(0);
23603 EVT NarrowVT = Narrow->getValueType(0);
23604 if (!NarrowVT.is128BitVector())
23607 if (Narrow->getOpcode() != ISD::XOR &&
23608 Narrow->getOpcode() != ISD::AND &&
23609 Narrow->getOpcode() != ISD::OR)
23612 SDValue N0 = Narrow->getOperand(0);
23613 SDValue N1 = Narrow->getOperand(1);
23616 // The Left side has to be a trunc.
23617 if (N0.getOpcode() != ISD::TRUNCATE)
23620 // The type of the truncated inputs.
23621 EVT WideVT = N0->getOperand(0)->getValueType(0);
23625 // The right side has to be a 'trunc' or a constant vector.
23626 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23627 ConstantSDNode *RHSConstSplat = nullptr;
23628 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23629 RHSConstSplat = RHSBV->getConstantSplatNode();
23630 if (!RHSTrunc && !RHSConstSplat)
23633 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23635 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23638 // Set N0 and N1 to hold the inputs to the new wide operation.
23639 N0 = N0->getOperand(0);
23640 if (RHSConstSplat) {
23641 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23642 SDValue(RHSConstSplat, 0));
23643 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23644 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23645 } else if (RHSTrunc) {
23646 N1 = N1->getOperand(0);
23649 // Generate the wide operation.
23650 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23651 unsigned Opcode = N->getOpcode();
23653 case ISD::ANY_EXTEND:
23655 case ISD::ZERO_EXTEND: {
23656 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23657 APInt Mask = APInt::getAllOnesValue(InBits);
23658 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23659 return DAG.getNode(ISD::AND, DL, VT,
23660 Op, DAG.getConstant(Mask, DL, VT));
23662 case ISD::SIGN_EXTEND:
23663 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23664 Op, DAG.getValueType(NarrowVT));
23666 llvm_unreachable("Unexpected opcode");
23670 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23671 TargetLowering::DAGCombinerInfo &DCI,
23672 const X86Subtarget *Subtarget) {
23673 SDValue N0 = N->getOperand(0);
23674 SDValue N1 = N->getOperand(1);
23677 // A vector zext_in_reg may be represented as a shuffle,
23678 // feeding into a bitcast (this represents anyext) feeding into
23679 // an and with a mask.
23680 // We'd like to try to combine that into a shuffle with zero
23681 // plus a bitcast, removing the and.
23682 if (N0.getOpcode() != ISD::BITCAST ||
23683 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23686 // The other side of the AND should be a splat of 2^C, where C
23687 // is the number of bits in the source type.
23688 if (N1.getOpcode() == ISD::BITCAST)
23689 N1 = N1.getOperand(0);
23690 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23692 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23694 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23695 EVT SrcType = Shuffle->getValueType(0);
23697 // We expect a single-source shuffle
23698 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23701 unsigned SrcSize = SrcType.getScalarSizeInBits();
23703 APInt SplatValue, SplatUndef;
23704 unsigned SplatBitSize;
23706 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23707 SplatBitSize, HasAnyUndefs))
23710 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23711 // Make sure the splat matches the mask we expect
23712 if (SplatBitSize > ResSize ||
23713 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23716 // Make sure the input and output size make sense
23717 if (SrcSize >= ResSize || ResSize % SrcSize)
23720 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23721 // The number of u's between each two values depends on the ratio between
23722 // the source and dest type.
23723 unsigned ZextRatio = ResSize / SrcSize;
23724 bool IsZext = true;
23725 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23726 if (i % ZextRatio) {
23727 if (Shuffle->getMaskElt(i) > 0) {
23733 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23734 // Expected element number
23744 // Ok, perform the transformation - replace the shuffle with
23745 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23746 // (instead of undef) where the k elements come from the zero vector.
23747 SmallVector<int, 8> Mask;
23748 unsigned NumElems = SrcType.getVectorNumElements();
23749 for (unsigned i = 0; i < NumElems; ++i)
23751 Mask.push_back(NumElems);
23753 Mask.push_back(i / ZextRatio);
23755 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23756 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23757 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23760 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23761 TargetLowering::DAGCombinerInfo &DCI,
23762 const X86Subtarget *Subtarget) {
23763 if (DCI.isBeforeLegalizeOps())
23766 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23769 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23772 EVT VT = N->getValueType(0);
23773 SDValue N0 = N->getOperand(0);
23774 SDValue N1 = N->getOperand(1);
23777 // Create BEXTR instructions
23778 // BEXTR is ((X >> imm) & (2**size-1))
23779 if (VT == MVT::i32 || VT == MVT::i64) {
23780 // Check for BEXTR.
23781 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23782 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23783 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23784 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23785 if (MaskNode && ShiftNode) {
23786 uint64_t Mask = MaskNode->getZExtValue();
23787 uint64_t Shift = ShiftNode->getZExtValue();
23788 if (isMask_64(Mask)) {
23789 uint64_t MaskSize = countPopulation(Mask);
23790 if (Shift + MaskSize <= VT.getSizeInBits())
23791 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23792 DAG.getConstant(Shift | (MaskSize << 8), DL,
23801 // Want to form ANDNP nodes:
23802 // 1) In the hopes of then easily combining them with OR and AND nodes
23803 // to form PBLEND/PSIGN.
23804 // 2) To match ANDN packed intrinsics
23805 if (VT != MVT::v2i64 && VT != MVT::v4i64)
23808 // Check LHS for vnot
23809 if (N0.getOpcode() == ISD::XOR &&
23810 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23811 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23812 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23814 // Check RHS for vnot
23815 if (N1.getOpcode() == ISD::XOR &&
23816 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23817 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23818 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23823 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23824 TargetLowering::DAGCombinerInfo &DCI,
23825 const X86Subtarget *Subtarget) {
23826 if (DCI.isBeforeLegalizeOps())
23829 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23832 SDValue N0 = N->getOperand(0);
23833 SDValue N1 = N->getOperand(1);
23834 EVT VT = N->getValueType(0);
23836 // look for psign/blend
23837 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23838 if (!Subtarget->hasSSSE3() ||
23839 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23842 // Canonicalize pandn to RHS
23843 if (N0.getOpcode() == X86ISD::ANDNP)
23845 // or (and (m, y), (pandn m, x))
23846 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23847 SDValue Mask = N1.getOperand(0);
23848 SDValue X = N1.getOperand(1);
23850 if (N0.getOperand(0) == Mask)
23851 Y = N0.getOperand(1);
23852 if (N0.getOperand(1) == Mask)
23853 Y = N0.getOperand(0);
23855 // Check to see if the mask appeared in both the AND and ANDNP and
23859 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23860 // Look through mask bitcast.
23861 if (Mask.getOpcode() == ISD::BITCAST)
23862 Mask = Mask.getOperand(0);
23863 if (X.getOpcode() == ISD::BITCAST)
23864 X = X.getOperand(0);
23865 if (Y.getOpcode() == ISD::BITCAST)
23866 Y = Y.getOperand(0);
23868 EVT MaskVT = Mask.getValueType();
23870 // Validate that the Mask operand is a vector sra node.
23871 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23872 // there is no psrai.b
23873 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23874 unsigned SraAmt = ~0;
23875 if (Mask.getOpcode() == ISD::SRA) {
23876 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23877 if (auto *AmtConst = AmtBV->getConstantSplatNode())
23878 SraAmt = AmtConst->getZExtValue();
23879 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23880 SDValue SraC = Mask.getOperand(1);
23881 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
23883 if ((SraAmt + 1) != EltBits)
23888 // Now we know we at least have a plendvb with the mask val. See if
23889 // we can form a psignb/w/d.
23890 // psign = x.type == y.type == mask.type && y = sub(0, x);
23891 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23892 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23893 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23894 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23895 "Unsupported VT for PSIGN");
23896 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23897 return DAG.getBitcast(VT, Mask);
23899 // PBLENDVB only available on SSE 4.1
23900 if (!Subtarget->hasSSE41())
23903 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23905 X = DAG.getBitcast(BlendVT, X);
23906 Y = DAG.getBitcast(BlendVT, Y);
23907 Mask = DAG.getBitcast(BlendVT, Mask);
23908 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23909 return DAG.getBitcast(VT, Mask);
23913 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23916 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23917 MachineFunction &MF = DAG.getMachineFunction();
23919 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23921 // SHLD/SHRD instructions have lower register pressure, but on some
23922 // platforms they have higher latency than the equivalent
23923 // series of shifts/or that would otherwise be generated.
23924 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23925 // have higher latencies and we are not optimizing for size.
23926 if (!OptForSize && Subtarget->isSHLDSlow())
23929 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23931 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23933 if (!N0.hasOneUse() || !N1.hasOneUse())
23936 SDValue ShAmt0 = N0.getOperand(1);
23937 if (ShAmt0.getValueType() != MVT::i8)
23939 SDValue ShAmt1 = N1.getOperand(1);
23940 if (ShAmt1.getValueType() != MVT::i8)
23942 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23943 ShAmt0 = ShAmt0.getOperand(0);
23944 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23945 ShAmt1 = ShAmt1.getOperand(0);
23948 unsigned Opc = X86ISD::SHLD;
23949 SDValue Op0 = N0.getOperand(0);
23950 SDValue Op1 = N1.getOperand(0);
23951 if (ShAmt0.getOpcode() == ISD::SUB) {
23952 Opc = X86ISD::SHRD;
23953 std::swap(Op0, Op1);
23954 std::swap(ShAmt0, ShAmt1);
23957 unsigned Bits = VT.getSizeInBits();
23958 if (ShAmt1.getOpcode() == ISD::SUB) {
23959 SDValue Sum = ShAmt1.getOperand(0);
23960 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23961 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23962 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23963 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23964 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23965 return DAG.getNode(Opc, DL, VT,
23967 DAG.getNode(ISD::TRUNCATE, DL,
23970 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23971 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23973 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23974 return DAG.getNode(Opc, DL, VT,
23975 N0.getOperand(0), N1.getOperand(0),
23976 DAG.getNode(ISD::TRUNCATE, DL,
23983 // Generate NEG and CMOV for integer abs.
23984 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23985 EVT VT = N->getValueType(0);
23987 // Since X86 does not have CMOV for 8-bit integer, we don't convert
23988 // 8-bit integer abs to NEG and CMOV.
23989 if (VT.isInteger() && VT.getSizeInBits() == 8)
23992 SDValue N0 = N->getOperand(0);
23993 SDValue N1 = N->getOperand(1);
23996 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23997 // and change it to SUB and CMOV.
23998 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23999 N0.getOpcode() == ISD::ADD &&
24000 N0.getOperand(1) == N1 &&
24001 N1.getOpcode() == ISD::SRA &&
24002 N1.getOperand(0) == N0.getOperand(0))
24003 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24004 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24005 // Generate SUB & CMOV.
24006 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24007 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24009 SDValue Ops[] = { N0.getOperand(0), Neg,
24010 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24011 SDValue(Neg.getNode(), 1) };
24012 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24017 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24018 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24019 TargetLowering::DAGCombinerInfo &DCI,
24020 const X86Subtarget *Subtarget) {
24021 if (DCI.isBeforeLegalizeOps())
24024 if (Subtarget->hasCMov())
24025 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24031 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24032 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24033 TargetLowering::DAGCombinerInfo &DCI,
24034 const X86Subtarget *Subtarget) {
24035 LoadSDNode *Ld = cast<LoadSDNode>(N);
24036 EVT RegVT = Ld->getValueType(0);
24037 EVT MemVT = Ld->getMemoryVT();
24039 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24041 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24042 // into two 16-byte operations.
24043 ISD::LoadExtType Ext = Ld->getExtensionType();
24044 unsigned Alignment = Ld->getAlignment();
24045 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24046 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24047 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24048 unsigned NumElems = RegVT.getVectorNumElements();
24052 SDValue Ptr = Ld->getBasePtr();
24053 SDValue Increment =
24054 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24056 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24058 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24059 Ld->getPointerInfo(), Ld->isVolatile(),
24060 Ld->isNonTemporal(), Ld->isInvariant(),
24062 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24063 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24064 Ld->getPointerInfo(), Ld->isVolatile(),
24065 Ld->isNonTemporal(), Ld->isInvariant(),
24066 std::min(16U, Alignment));
24067 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24069 Load2.getValue(1));
24071 SDValue NewVec = DAG.getUNDEF(RegVT);
24072 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24073 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24074 return DCI.CombineTo(N, NewVec, TF, true);
24080 /// PerformMLOADCombine - Resolve extending loads
24081 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24082 TargetLowering::DAGCombinerInfo &DCI,
24083 const X86Subtarget *Subtarget) {
24084 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24085 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24088 EVT VT = Mld->getValueType(0);
24089 unsigned NumElems = VT.getVectorNumElements();
24090 EVT LdVT = Mld->getMemoryVT();
24093 assert(LdVT != VT && "Cannot extend to the same type");
24094 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24095 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24096 // From, To sizes and ElemCount must be pow of two
24097 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24098 "Unexpected size for extending masked load");
24100 unsigned SizeRatio = ToSz / FromSz;
24101 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24103 // Create a type on which we perform the shuffle
24104 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24105 LdVT.getScalarType(), NumElems*SizeRatio);
24106 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24108 // Convert Src0 value
24109 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24110 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24111 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24112 for (unsigned i = 0; i != NumElems; ++i)
24113 ShuffleVec[i] = i * SizeRatio;
24115 // Can't shuffle using an illegal type.
24116 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24117 && "WideVecVT should be legal");
24118 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24119 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24121 // Prepare the new mask
24123 SDValue Mask = Mld->getMask();
24124 if (Mask.getValueType() == VT) {
24125 // Mask and original value have the same type
24126 NewMask = DAG.getBitcast(WideVecVT, Mask);
24127 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24128 for (unsigned i = 0; i != NumElems; ++i)
24129 ShuffleVec[i] = i * SizeRatio;
24130 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24131 ShuffleVec[i] = NumElems*SizeRatio;
24132 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24133 DAG.getConstant(0, dl, WideVecVT),
24137 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24138 unsigned WidenNumElts = NumElems*SizeRatio;
24139 unsigned MaskNumElts = VT.getVectorNumElements();
24140 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24143 unsigned NumConcat = WidenNumElts / MaskNumElts;
24144 SmallVector<SDValue, 16> Ops(NumConcat);
24145 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24147 for (unsigned i = 1; i != NumConcat; ++i)
24150 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24153 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24154 Mld->getBasePtr(), NewMask, WideSrc0,
24155 Mld->getMemoryVT(), Mld->getMemOperand(),
24157 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24158 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24161 /// PerformMSTORECombine - Resolve truncating stores
24162 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24163 const X86Subtarget *Subtarget) {
24164 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24165 if (!Mst->isTruncatingStore())
24168 EVT VT = Mst->getValue().getValueType();
24169 unsigned NumElems = VT.getVectorNumElements();
24170 EVT StVT = Mst->getMemoryVT();
24173 assert(StVT != VT && "Cannot truncate to the same type");
24174 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24175 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24177 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24179 // The truncating store is legal in some cases. For example
24180 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24181 // are designated for truncate store.
24182 // In this case we don't need any further transformations.
24183 if (TLI.isTruncStoreLegal(VT, StVT))
24186 // From, To sizes and ElemCount must be pow of two
24187 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24188 "Unexpected size for truncating masked store");
24189 // We are going to use the original vector elt for storing.
24190 // Accumulated smaller vector elements must be a multiple of the store size.
24191 assert (((NumElems * FromSz) % ToSz) == 0 &&
24192 "Unexpected ratio for truncating masked store");
24194 unsigned SizeRatio = FromSz / ToSz;
24195 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24197 // Create a type on which we perform the shuffle
24198 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24199 StVT.getScalarType(), NumElems*SizeRatio);
24201 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24203 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24204 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24205 for (unsigned i = 0; i != NumElems; ++i)
24206 ShuffleVec[i] = i * SizeRatio;
24208 // Can't shuffle using an illegal type.
24209 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24210 && "WideVecVT should be legal");
24212 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24213 DAG.getUNDEF(WideVecVT),
24217 SDValue Mask = Mst->getMask();
24218 if (Mask.getValueType() == VT) {
24219 // Mask and original value have the same type
24220 NewMask = DAG.getBitcast(WideVecVT, Mask);
24221 for (unsigned i = 0; i != NumElems; ++i)
24222 ShuffleVec[i] = i * SizeRatio;
24223 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24224 ShuffleVec[i] = NumElems*SizeRatio;
24225 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24226 DAG.getConstant(0, dl, WideVecVT),
24230 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24231 unsigned WidenNumElts = NumElems*SizeRatio;
24232 unsigned MaskNumElts = VT.getVectorNumElements();
24233 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24236 unsigned NumConcat = WidenNumElts / MaskNumElts;
24237 SmallVector<SDValue, 16> Ops(NumConcat);
24238 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24240 for (unsigned i = 1; i != NumConcat; ++i)
24243 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24246 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24247 NewMask, StVT, Mst->getMemOperand(), false);
24249 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24250 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24251 const X86Subtarget *Subtarget) {
24252 StoreSDNode *St = cast<StoreSDNode>(N);
24253 EVT VT = St->getValue().getValueType();
24254 EVT StVT = St->getMemoryVT();
24256 SDValue StoredVal = St->getOperand(1);
24257 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24259 // If we are saving a concatenation of two XMM registers and 32-byte stores
24260 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24261 unsigned Alignment = St->getAlignment();
24262 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24263 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24264 StVT == VT && !IsAligned) {
24265 unsigned NumElems = VT.getVectorNumElements();
24269 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24270 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24273 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24274 SDValue Ptr0 = St->getBasePtr();
24275 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24277 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24278 St->getPointerInfo(), St->isVolatile(),
24279 St->isNonTemporal(), Alignment);
24280 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24281 St->getPointerInfo(), St->isVolatile(),
24282 St->isNonTemporal(),
24283 std::min(16U, Alignment));
24284 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24287 // Optimize trunc store (of multiple scalars) to shuffle and store.
24288 // First, pack all of the elements in one place. Next, store to memory
24289 // in fewer chunks.
24290 if (St->isTruncatingStore() && VT.isVector()) {
24291 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24292 unsigned NumElems = VT.getVectorNumElements();
24293 assert(StVT != VT && "Cannot truncate to the same type");
24294 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24295 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24297 // The truncating store is legal in some cases. For example
24298 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24299 // are designated for truncate store.
24300 // In this case we don't need any further transformations.
24301 if (TLI.isTruncStoreLegal(VT, StVT))
24304 // From, To sizes and ElemCount must be pow of two
24305 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24306 // We are going to use the original vector elt for storing.
24307 // Accumulated smaller vector elements must be a multiple of the store size.
24308 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24310 unsigned SizeRatio = FromSz / ToSz;
24312 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24314 // Create a type on which we perform the shuffle
24315 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24316 StVT.getScalarType(), NumElems*SizeRatio);
24318 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24320 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24321 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24322 for (unsigned i = 0; i != NumElems; ++i)
24323 ShuffleVec[i] = i * SizeRatio;
24325 // Can't shuffle using an illegal type.
24326 if (!TLI.isTypeLegal(WideVecVT))
24329 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24330 DAG.getUNDEF(WideVecVT),
24332 // At this point all of the data is stored at the bottom of the
24333 // register. We now need to save it to mem.
24335 // Find the largest store unit
24336 MVT StoreType = MVT::i8;
24337 for (MVT Tp : MVT::integer_valuetypes()) {
24338 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24342 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24343 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24344 (64 <= NumElems * ToSz))
24345 StoreType = MVT::f64;
24347 // Bitcast the original vector into a vector of store-size units
24348 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24349 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24350 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24351 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24352 SmallVector<SDValue, 8> Chains;
24353 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24354 TLI.getPointerTy(DAG.getDataLayout()));
24355 SDValue Ptr = St->getBasePtr();
24357 // Perform one or more big stores into memory.
24358 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24359 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24360 StoreType, ShuffWide,
24361 DAG.getIntPtrConstant(i, dl));
24362 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24363 St->getPointerInfo(), St->isVolatile(),
24364 St->isNonTemporal(), St->getAlignment());
24365 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24366 Chains.push_back(Ch);
24369 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24372 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24373 // the FP state in cases where an emms may be missing.
24374 // A preferable solution to the general problem is to figure out the right
24375 // places to insert EMMS. This qualifies as a quick hack.
24377 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24378 if (VT.getSizeInBits() != 64)
24381 const Function *F = DAG.getMachineFunction().getFunction();
24382 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24384 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24385 if ((VT.isVector() ||
24386 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24387 isa<LoadSDNode>(St->getValue()) &&
24388 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24389 St->getChain().hasOneUse() && !St->isVolatile()) {
24390 SDNode* LdVal = St->getValue().getNode();
24391 LoadSDNode *Ld = nullptr;
24392 int TokenFactorIndex = -1;
24393 SmallVector<SDValue, 8> Ops;
24394 SDNode* ChainVal = St->getChain().getNode();
24395 // Must be a store of a load. We currently handle two cases: the load
24396 // is a direct child, and it's under an intervening TokenFactor. It is
24397 // possible to dig deeper under nested TokenFactors.
24398 if (ChainVal == LdVal)
24399 Ld = cast<LoadSDNode>(St->getChain());
24400 else if (St->getValue().hasOneUse() &&
24401 ChainVal->getOpcode() == ISD::TokenFactor) {
24402 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24403 if (ChainVal->getOperand(i).getNode() == LdVal) {
24404 TokenFactorIndex = i;
24405 Ld = cast<LoadSDNode>(St->getValue());
24407 Ops.push_back(ChainVal->getOperand(i));
24411 if (!Ld || !ISD::isNormalLoad(Ld))
24414 // If this is not the MMX case, i.e. we are just turning i64 load/store
24415 // into f64 load/store, avoid the transformation if there are multiple
24416 // uses of the loaded value.
24417 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24422 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24423 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24425 if (Subtarget->is64Bit() || F64IsLegal) {
24426 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24427 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24428 Ld->getPointerInfo(), Ld->isVolatile(),
24429 Ld->isNonTemporal(), Ld->isInvariant(),
24430 Ld->getAlignment());
24431 SDValue NewChain = NewLd.getValue(1);
24432 if (TokenFactorIndex != -1) {
24433 Ops.push_back(NewChain);
24434 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24436 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24437 St->getPointerInfo(),
24438 St->isVolatile(), St->isNonTemporal(),
24439 St->getAlignment());
24442 // Otherwise, lower to two pairs of 32-bit loads / stores.
24443 SDValue LoAddr = Ld->getBasePtr();
24444 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24445 DAG.getConstant(4, LdDL, MVT::i32));
24447 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24448 Ld->getPointerInfo(),
24449 Ld->isVolatile(), Ld->isNonTemporal(),
24450 Ld->isInvariant(), Ld->getAlignment());
24451 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24452 Ld->getPointerInfo().getWithOffset(4),
24453 Ld->isVolatile(), Ld->isNonTemporal(),
24455 MinAlign(Ld->getAlignment(), 4));
24457 SDValue NewChain = LoLd.getValue(1);
24458 if (TokenFactorIndex != -1) {
24459 Ops.push_back(LoLd);
24460 Ops.push_back(HiLd);
24461 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24464 LoAddr = St->getBasePtr();
24465 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24466 DAG.getConstant(4, StDL, MVT::i32));
24468 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24469 St->getPointerInfo(),
24470 St->isVolatile(), St->isNonTemporal(),
24471 St->getAlignment());
24472 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24473 St->getPointerInfo().getWithOffset(4),
24475 St->isNonTemporal(),
24476 MinAlign(St->getAlignment(), 4));
24477 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24480 // This is similar to the above case, but here we handle a scalar 64-bit
24481 // integer store that is extracted from a vector on a 32-bit target.
24482 // If we have SSE2, then we can treat it like a floating-point double
24483 // to get past legalization. The execution dependencies fixup pass will
24484 // choose the optimal machine instruction for the store if this really is
24485 // an integer or v2f32 rather than an f64.
24486 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24487 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24488 SDValue OldExtract = St->getOperand(1);
24489 SDValue ExtOp0 = OldExtract.getOperand(0);
24490 unsigned VecSize = ExtOp0.getValueSizeInBits();
24491 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24492 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24493 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24494 BitCast, OldExtract.getOperand(1));
24495 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24496 St->getPointerInfo(), St->isVolatile(),
24497 St->isNonTemporal(), St->getAlignment());
24503 /// Return 'true' if this vector operation is "horizontal"
24504 /// and return the operands for the horizontal operation in LHS and RHS. A
24505 /// horizontal operation performs the binary operation on successive elements
24506 /// of its first operand, then on successive elements of its second operand,
24507 /// returning the resulting values in a vector. For example, if
24508 /// A = < float a0, float a1, float a2, float a3 >
24510 /// B = < float b0, float b1, float b2, float b3 >
24511 /// then the result of doing a horizontal operation on A and B is
24512 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24513 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24514 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24515 /// set to A, RHS to B, and the routine returns 'true'.
24516 /// Note that the binary operation should have the property that if one of the
24517 /// operands is UNDEF then the result is UNDEF.
24518 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24519 // Look for the following pattern: if
24520 // A = < float a0, float a1, float a2, float a3 >
24521 // B = < float b0, float b1, float b2, float b3 >
24523 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24524 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24525 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24526 // which is A horizontal-op B.
24528 // At least one of the operands should be a vector shuffle.
24529 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24530 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24533 MVT VT = LHS.getSimpleValueType();
24535 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24536 "Unsupported vector type for horizontal add/sub");
24538 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24539 // operate independently on 128-bit lanes.
24540 unsigned NumElts = VT.getVectorNumElements();
24541 unsigned NumLanes = VT.getSizeInBits()/128;
24542 unsigned NumLaneElts = NumElts / NumLanes;
24543 assert((NumLaneElts % 2 == 0) &&
24544 "Vector type should have an even number of elements in each lane");
24545 unsigned HalfLaneElts = NumLaneElts/2;
24547 // View LHS in the form
24548 // LHS = VECTOR_SHUFFLE A, B, LMask
24549 // If LHS is not a shuffle then pretend it is the shuffle
24550 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24551 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24554 SmallVector<int, 16> LMask(NumElts);
24555 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24556 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24557 A = LHS.getOperand(0);
24558 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24559 B = LHS.getOperand(1);
24560 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24561 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24563 if (LHS.getOpcode() != ISD::UNDEF)
24565 for (unsigned i = 0; i != NumElts; ++i)
24569 // Likewise, view RHS in the form
24570 // RHS = VECTOR_SHUFFLE C, D, RMask
24572 SmallVector<int, 16> RMask(NumElts);
24573 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24574 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24575 C = RHS.getOperand(0);
24576 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24577 D = RHS.getOperand(1);
24578 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24579 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24581 if (RHS.getOpcode() != ISD::UNDEF)
24583 for (unsigned i = 0; i != NumElts; ++i)
24587 // Check that the shuffles are both shuffling the same vectors.
24588 if (!(A == C && B == D) && !(A == D && B == C))
24591 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24592 if (!A.getNode() && !B.getNode())
24595 // If A and B occur in reverse order in RHS, then "swap" them (which means
24596 // rewriting the mask).
24598 ShuffleVectorSDNode::commuteMask(RMask);
24600 // At this point LHS and RHS are equivalent to
24601 // LHS = VECTOR_SHUFFLE A, B, LMask
24602 // RHS = VECTOR_SHUFFLE A, B, RMask
24603 // Check that the masks correspond to performing a horizontal operation.
24604 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24605 for (unsigned i = 0; i != NumLaneElts; ++i) {
24606 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24608 // Ignore any UNDEF components.
24609 if (LIdx < 0 || RIdx < 0 ||
24610 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24611 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24614 // Check that successive elements are being operated on. If not, this is
24615 // not a horizontal operation.
24616 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24617 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24618 if (!(LIdx == Index && RIdx == Index + 1) &&
24619 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24624 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24625 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24629 /// Do target-specific dag combines on floating point adds.
24630 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24631 const X86Subtarget *Subtarget) {
24632 EVT VT = N->getValueType(0);
24633 SDValue LHS = N->getOperand(0);
24634 SDValue RHS = N->getOperand(1);
24636 // Try to synthesize horizontal adds from adds of shuffles.
24637 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24638 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24639 isHorizontalBinOp(LHS, RHS, true))
24640 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24644 /// Do target-specific dag combines on floating point subs.
24645 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24646 const X86Subtarget *Subtarget) {
24647 EVT VT = N->getValueType(0);
24648 SDValue LHS = N->getOperand(0);
24649 SDValue RHS = N->getOperand(1);
24651 // Try to synthesize horizontal subs from subs of shuffles.
24652 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24653 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24654 isHorizontalBinOp(LHS, RHS, false))
24655 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24659 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24660 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24661 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24663 // F[X]OR(0.0, x) -> x
24664 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24665 if (C->getValueAPF().isPosZero())
24666 return N->getOperand(1);
24668 // F[X]OR(x, 0.0) -> x
24669 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24670 if (C->getValueAPF().isPosZero())
24671 return N->getOperand(0);
24675 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24676 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24677 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24679 // Only perform optimizations if UnsafeMath is used.
24680 if (!DAG.getTarget().Options.UnsafeFPMath)
24683 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24684 // into FMINC and FMAXC, which are Commutative operations.
24685 unsigned NewOp = 0;
24686 switch (N->getOpcode()) {
24687 default: llvm_unreachable("unknown opcode");
24688 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24689 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24692 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24693 N->getOperand(0), N->getOperand(1));
24696 /// Do target-specific dag combines on X86ISD::FAND nodes.
24697 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24698 // FAND(0.0, x) -> 0.0
24699 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24700 if (C->getValueAPF().isPosZero())
24701 return N->getOperand(0);
24703 // FAND(x, 0.0) -> 0.0
24704 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24705 if (C->getValueAPF().isPosZero())
24706 return N->getOperand(1);
24711 /// Do target-specific dag combines on X86ISD::FANDN nodes
24712 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24713 // FANDN(0.0, x) -> x
24714 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24715 if (C->getValueAPF().isPosZero())
24716 return N->getOperand(1);
24718 // FANDN(x, 0.0) -> 0.0
24719 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24720 if (C->getValueAPF().isPosZero())
24721 return N->getOperand(1);
24726 static SDValue PerformBTCombine(SDNode *N,
24728 TargetLowering::DAGCombinerInfo &DCI) {
24729 // BT ignores high bits in the bit index operand.
24730 SDValue Op1 = N->getOperand(1);
24731 if (Op1.hasOneUse()) {
24732 unsigned BitWidth = Op1.getValueSizeInBits();
24733 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24734 APInt KnownZero, KnownOne;
24735 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24736 !DCI.isBeforeLegalizeOps());
24737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24738 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24739 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24740 DCI.CommitTargetLoweringOpt(TLO);
24745 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24746 SDValue Op = N->getOperand(0);
24747 if (Op.getOpcode() == ISD::BITCAST)
24748 Op = Op.getOperand(0);
24749 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24750 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24751 VT.getVectorElementType().getSizeInBits() ==
24752 OpVT.getVectorElementType().getSizeInBits()) {
24753 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24758 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24759 const X86Subtarget *Subtarget) {
24760 EVT VT = N->getValueType(0);
24761 if (!VT.isVector())
24764 SDValue N0 = N->getOperand(0);
24765 SDValue N1 = N->getOperand(1);
24766 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24769 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24770 // both SSE and AVX2 since there is no sign-extended shift right
24771 // operation on a vector with 64-bit elements.
24772 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24773 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24774 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24775 N0.getOpcode() == ISD::SIGN_EXTEND)) {
24776 SDValue N00 = N0.getOperand(0);
24778 // EXTLOAD has a better solution on AVX2,
24779 // it may be replaced with X86ISD::VSEXT node.
24780 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24781 if (!ISD::isNormalLoad(N00.getNode()))
24784 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24785 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24787 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24793 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24794 TargetLowering::DAGCombinerInfo &DCI,
24795 const X86Subtarget *Subtarget) {
24796 SDValue N0 = N->getOperand(0);
24797 EVT VT = N->getValueType(0);
24798 EVT SVT = VT.getScalarType();
24799 EVT InVT = N0.getValueType();
24800 EVT InSVT = InVT.getScalarType();
24803 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24804 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24805 // This exposes the sext to the sdivrem lowering, so that it directly extends
24806 // from AH (which we otherwise need to do contortions to access).
24807 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24808 InVT == MVT::i8 && VT == MVT::i32) {
24809 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24810 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24811 N0.getOperand(0), N0.getOperand(1));
24812 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24813 return R.getValue(1);
24816 if (!DCI.isBeforeLegalizeOps()) {
24817 if (InVT == MVT::i1) {
24818 SDValue Zero = DAG.getConstant(0, DL, VT);
24820 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24821 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24826 if (VT.isVector() && Subtarget->hasSSE2()) {
24827 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24828 EVT InVT = N.getValueType();
24829 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24830 Size / InVT.getScalarSizeInBits());
24831 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24832 DAG.getUNDEF(InVT));
24834 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24837 // If target-size is less than 128-bits, extend to a type that would extend
24838 // to 128 bits, extend that and extract the original target vector.
24839 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24840 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24841 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24842 unsigned Scale = 128 / VT.getSizeInBits();
24844 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24845 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24846 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24847 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24848 DAG.getIntPtrConstant(0, DL));
24851 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24852 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24853 if (VT.getSizeInBits() == 128 &&
24854 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24855 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24856 SDValue ExOp = ExtendVecSize(DL, N0, 128);
24857 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24860 // On pre-AVX2 targets, split into 128-bit nodes of
24861 // ISD::SIGN_EXTEND_VECTOR_INREG.
24862 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24863 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24864 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24865 unsigned NumVecs = VT.getSizeInBits() / 128;
24866 unsigned NumSubElts = 128 / SVT.getSizeInBits();
24867 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24868 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24870 SmallVector<SDValue, 8> Opnds;
24871 for (unsigned i = 0, Offset = 0; i != NumVecs;
24872 ++i, Offset += NumSubElts) {
24873 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24874 DAG.getIntPtrConstant(Offset, DL));
24875 SrcVec = ExtendVecSize(DL, SrcVec, 128);
24876 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24877 Opnds.push_back(SrcVec);
24879 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24883 if (!Subtarget->hasFp256())
24886 if (VT.isVector() && VT.getSizeInBits() == 256)
24887 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24893 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24894 const X86Subtarget* Subtarget) {
24896 EVT VT = N->getValueType(0);
24898 // Let legalize expand this if it isn't a legal type yet.
24899 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24902 EVT ScalarVT = VT.getScalarType();
24903 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24904 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24905 !Subtarget->hasAVX512()))
24908 SDValue A = N->getOperand(0);
24909 SDValue B = N->getOperand(1);
24910 SDValue C = N->getOperand(2);
24912 bool NegA = (A.getOpcode() == ISD::FNEG);
24913 bool NegB = (B.getOpcode() == ISD::FNEG);
24914 bool NegC = (C.getOpcode() == ISD::FNEG);
24916 // Negative multiplication when NegA xor NegB
24917 bool NegMul = (NegA != NegB);
24919 A = A.getOperand(0);
24921 B = B.getOperand(0);
24923 C = C.getOperand(0);
24927 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24929 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24931 return DAG.getNode(Opcode, dl, VT, A, B, C);
24934 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24935 TargetLowering::DAGCombinerInfo &DCI,
24936 const X86Subtarget *Subtarget) {
24937 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
24938 // (and (i32 x86isd::setcc_carry), 1)
24939 // This eliminates the zext. This transformation is necessary because
24940 // ISD::SETCC is always legalized to i8.
24942 SDValue N0 = N->getOperand(0);
24943 EVT VT = N->getValueType(0);
24945 if (N0.getOpcode() == ISD::AND &&
24947 N0.getOperand(0).hasOneUse()) {
24948 SDValue N00 = N0.getOperand(0);
24949 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24950 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24951 if (!C || C->getZExtValue() != 1)
24953 return DAG.getNode(ISD::AND, dl, VT,
24954 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24955 N00.getOperand(0), N00.getOperand(1)),
24956 DAG.getConstant(1, dl, VT));
24960 if (N0.getOpcode() == ISD::TRUNCATE &&
24962 N0.getOperand(0).hasOneUse()) {
24963 SDValue N00 = N0.getOperand(0);
24964 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24965 return DAG.getNode(ISD::AND, dl, VT,
24966 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24967 N00.getOperand(0), N00.getOperand(1)),
24968 DAG.getConstant(1, dl, VT));
24972 if (VT.is256BitVector())
24973 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24976 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24977 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24978 // This exposes the zext to the udivrem lowering, so that it directly extends
24979 // from AH (which we otherwise need to do contortions to access).
24980 if (N0.getOpcode() == ISD::UDIVREM &&
24981 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24982 (VT == MVT::i32 || VT == MVT::i64)) {
24983 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24984 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24985 N0.getOperand(0), N0.getOperand(1));
24986 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24987 return R.getValue(1);
24993 // Optimize x == -y --> x+y == 0
24994 // x != -y --> x+y != 0
24995 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24996 const X86Subtarget* Subtarget) {
24997 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24998 SDValue LHS = N->getOperand(0);
24999 SDValue RHS = N->getOperand(1);
25000 EVT VT = N->getValueType(0);
25003 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25004 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25005 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25006 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25007 LHS.getOperand(1));
25008 return DAG.getSetCC(DL, N->getValueType(0), addV,
25009 DAG.getConstant(0, DL, addV.getValueType()), CC);
25011 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25012 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25013 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25014 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25015 RHS.getOperand(1));
25016 return DAG.getSetCC(DL, N->getValueType(0), addV,
25017 DAG.getConstant(0, DL, addV.getValueType()), CC);
25020 if (VT.getScalarType() == MVT::i1 &&
25021 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25023 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25024 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25025 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25027 if (!IsSEXT0 || !IsVZero1) {
25028 // Swap the operands and update the condition code.
25029 std::swap(LHS, RHS);
25030 CC = ISD::getSetCCSwappedOperands(CC);
25032 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25033 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25034 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25037 if (IsSEXT0 && IsVZero1) {
25038 assert(VT == LHS.getOperand(0).getValueType() &&
25039 "Uexpected operand type");
25040 if (CC == ISD::SETGT)
25041 return DAG.getConstant(0, DL, VT);
25042 if (CC == ISD::SETLE)
25043 return DAG.getConstant(1, DL, VT);
25044 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25045 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25047 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25048 "Unexpected condition code!");
25049 return LHS.getOperand(0);
25056 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25057 SelectionDAG &DAG) {
25059 MVT VT = Load->getSimpleValueType(0);
25060 MVT EVT = VT.getVectorElementType();
25061 SDValue Addr = Load->getOperand(1);
25062 SDValue NewAddr = DAG.getNode(
25063 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25064 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25065 Addr.getSimpleValueType()));
25068 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25069 DAG.getMachineFunction().getMachineMemOperand(
25070 Load->getMemOperand(), 0, EVT.getStoreSize()));
25074 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25075 const X86Subtarget *Subtarget) {
25077 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25078 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25079 "X86insertps is only defined for v4x32");
25081 SDValue Ld = N->getOperand(1);
25082 if (MayFoldLoad(Ld)) {
25083 // Extract the countS bits from the immediate so we can get the proper
25084 // address when narrowing the vector load to a specific element.
25085 // When the second source op is a memory address, insertps doesn't use
25086 // countS and just gets an f32 from that address.
25087 unsigned DestIndex =
25088 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25090 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25092 // Create this as a scalar to vector to match the instruction pattern.
25093 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25094 // countS bits are ignored when loading from memory on insertps, which
25095 // means we don't need to explicitly set them to 0.
25096 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25097 LoadScalarToVector, N->getOperand(2));
25102 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25103 SDValue V0 = N->getOperand(0);
25104 SDValue V1 = N->getOperand(1);
25106 EVT VT = N->getValueType(0);
25108 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25109 // operands and changing the mask to 1. This saves us a bunch of
25110 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25111 // x86InstrInfo knows how to commute this back after instruction selection
25112 // if it would help register allocation.
25114 // TODO: If optimizing for size or a processor that doesn't suffer from
25115 // partial register update stalls, this should be transformed into a MOVSD
25116 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25118 if (VT == MVT::v2f64)
25119 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25120 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25121 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25122 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25128 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25129 // as "sbb reg,reg", since it can be extended without zext and produces
25130 // an all-ones bit which is more useful than 0/1 in some cases.
25131 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25134 return DAG.getNode(ISD::AND, DL, VT,
25135 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25136 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25138 DAG.getConstant(1, DL, VT));
25139 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25140 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25141 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25142 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25146 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25147 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25148 TargetLowering::DAGCombinerInfo &DCI,
25149 const X86Subtarget *Subtarget) {
25151 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25152 SDValue EFLAGS = N->getOperand(1);
25154 if (CC == X86::COND_A) {
25155 // Try to convert COND_A into COND_B in an attempt to facilitate
25156 // materializing "setb reg".
25158 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25159 // cannot take an immediate as its first operand.
25161 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25162 EFLAGS.getValueType().isInteger() &&
25163 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25164 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25165 EFLAGS.getNode()->getVTList(),
25166 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25167 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25168 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25172 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25173 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25175 if (CC == X86::COND_B)
25176 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25178 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25179 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25180 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25186 // Optimize branch condition evaluation.
25188 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25189 TargetLowering::DAGCombinerInfo &DCI,
25190 const X86Subtarget *Subtarget) {
25192 SDValue Chain = N->getOperand(0);
25193 SDValue Dest = N->getOperand(1);
25194 SDValue EFLAGS = N->getOperand(3);
25195 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25197 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25198 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25199 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25206 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25207 SelectionDAG &DAG) {
25208 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25209 // optimize away operation when it's from a constant.
25211 // The general transformation is:
25212 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25213 // AND(VECTOR_CMP(x,y), constant2)
25214 // constant2 = UNARYOP(constant)
25216 // Early exit if this isn't a vector operation, the operand of the
25217 // unary operation isn't a bitwise AND, or if the sizes of the operations
25218 // aren't the same.
25219 EVT VT = N->getValueType(0);
25220 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25221 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25222 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25225 // Now check that the other operand of the AND is a constant. We could
25226 // make the transformation for non-constant splats as well, but it's unclear
25227 // that would be a benefit as it would not eliminate any operations, just
25228 // perform one more step in scalar code before moving to the vector unit.
25229 if (BuildVectorSDNode *BV =
25230 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25231 // Bail out if the vector isn't a constant.
25232 if (!BV->isConstant())
25235 // Everything checks out. Build up the new and improved node.
25237 EVT IntVT = BV->getValueType(0);
25238 // Create a new constant of the appropriate type for the transformed
25240 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25241 // The AND node needs bitcasts to/from an integer vector type around it.
25242 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25243 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25244 N->getOperand(0)->getOperand(0), MaskConst);
25245 SDValue Res = DAG.getBitcast(VT, NewAnd);
25252 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25253 const X86Subtarget *Subtarget) {
25254 SDValue Op0 = N->getOperand(0);
25255 EVT VT = N->getValueType(0);
25256 EVT InVT = Op0.getValueType();
25257 EVT InSVT = InVT.getScalarType();
25258 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25260 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25261 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25262 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25264 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25265 InVT.getVectorNumElements());
25266 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25268 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25269 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25271 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25277 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25278 const X86Subtarget *Subtarget) {
25279 // First try to optimize away the conversion entirely when it's
25280 // conditionally from a constant. Vectors only.
25281 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25284 // Now move on to more general possibilities.
25285 SDValue Op0 = N->getOperand(0);
25286 EVT VT = N->getValueType(0);
25287 EVT InVT = Op0.getValueType();
25288 EVT InSVT = InVT.getScalarType();
25290 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25291 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25292 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25294 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25295 InVT.getVectorNumElements());
25296 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25297 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25300 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25301 // a 32-bit target where SSE doesn't support i64->FP operations.
25302 if (Op0.getOpcode() == ISD::LOAD) {
25303 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25304 EVT LdVT = Ld->getValueType(0);
25306 // This transformation is not supported if the result type is f16
25307 if (VT == MVT::f16)
25310 if (!Ld->isVolatile() && !VT.isVector() &&
25311 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25312 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25313 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25314 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25315 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25322 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25323 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25324 X86TargetLowering::DAGCombinerInfo &DCI) {
25325 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25326 // the result is either zero or one (depending on the input carry bit).
25327 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25328 if (X86::isZeroNode(N->getOperand(0)) &&
25329 X86::isZeroNode(N->getOperand(1)) &&
25330 // We don't have a good way to replace an EFLAGS use, so only do this when
25332 SDValue(N, 1).use_empty()) {
25334 EVT VT = N->getValueType(0);
25335 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25336 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25337 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25338 DAG.getConstant(X86::COND_B, DL,
25341 DAG.getConstant(1, DL, VT));
25342 return DCI.CombineTo(N, Res1, CarryOut);
25348 // fold (add Y, (sete X, 0)) -> adc 0, Y
25349 // (add Y, (setne X, 0)) -> sbb -1, Y
25350 // (sub (sete X, 0), Y) -> sbb 0, Y
25351 // (sub (setne X, 0), Y) -> adc -1, Y
25352 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25355 // Look through ZExts.
25356 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25357 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25360 SDValue SetCC = Ext.getOperand(0);
25361 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25364 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25365 if (CC != X86::COND_E && CC != X86::COND_NE)
25368 SDValue Cmp = SetCC.getOperand(1);
25369 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25370 !X86::isZeroNode(Cmp.getOperand(1)) ||
25371 !Cmp.getOperand(0).getValueType().isInteger())
25374 SDValue CmpOp0 = Cmp.getOperand(0);
25375 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25376 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25378 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25379 if (CC == X86::COND_NE)
25380 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25381 DL, OtherVal.getValueType(), OtherVal,
25382 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25384 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25385 DL, OtherVal.getValueType(), OtherVal,
25386 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25389 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25390 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25391 const X86Subtarget *Subtarget) {
25392 EVT VT = N->getValueType(0);
25393 SDValue Op0 = N->getOperand(0);
25394 SDValue Op1 = N->getOperand(1);
25396 // Try to synthesize horizontal adds from adds of shuffles.
25397 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25398 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25399 isHorizontalBinOp(Op0, Op1, true))
25400 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25402 return OptimizeConditionalInDecrement(N, DAG);
25405 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25406 const X86Subtarget *Subtarget) {
25407 SDValue Op0 = N->getOperand(0);
25408 SDValue Op1 = N->getOperand(1);
25410 // X86 can't encode an immediate LHS of a sub. See if we can push the
25411 // negation into a preceding instruction.
25412 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25413 // If the RHS of the sub is a XOR with one use and a constant, invert the
25414 // immediate. Then add one to the LHS of the sub so we can turn
25415 // X-Y -> X+~Y+1, saving one register.
25416 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25417 isa<ConstantSDNode>(Op1.getOperand(1))) {
25418 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25419 EVT VT = Op0.getValueType();
25420 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25422 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25423 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25424 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25428 // Try to synthesize horizontal adds from adds of shuffles.
25429 EVT VT = N->getValueType(0);
25430 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25431 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25432 isHorizontalBinOp(Op0, Op1, true))
25433 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25435 return OptimizeConditionalInDecrement(N, DAG);
25438 /// performVZEXTCombine - Performs build vector combines
25439 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25440 TargetLowering::DAGCombinerInfo &DCI,
25441 const X86Subtarget *Subtarget) {
25443 MVT VT = N->getSimpleValueType(0);
25444 SDValue Op = N->getOperand(0);
25445 MVT OpVT = Op.getSimpleValueType();
25446 MVT OpEltVT = OpVT.getVectorElementType();
25447 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25449 // (vzext (bitcast (vzext (x)) -> (vzext x)
25451 while (V.getOpcode() == ISD::BITCAST)
25452 V = V.getOperand(0);
25454 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25455 MVT InnerVT = V.getSimpleValueType();
25456 MVT InnerEltVT = InnerVT.getVectorElementType();
25458 // If the element sizes match exactly, we can just do one larger vzext. This
25459 // is always an exact type match as vzext operates on integer types.
25460 if (OpEltVT == InnerEltVT) {
25461 assert(OpVT == InnerVT && "Types must match for vzext!");
25462 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25465 // The only other way we can combine them is if only a single element of the
25466 // inner vzext is used in the input to the outer vzext.
25467 if (InnerEltVT.getSizeInBits() < InputBits)
25470 // In this case, the inner vzext is completely dead because we're going to
25471 // only look at bits inside of the low element. Just do the outer vzext on
25472 // a bitcast of the input to the inner.
25473 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25476 // Check if we can bypass extracting and re-inserting an element of an input
25477 // vector. Essentialy:
25478 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25479 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25480 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25481 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25482 SDValue ExtractedV = V.getOperand(0);
25483 SDValue OrigV = ExtractedV.getOperand(0);
25484 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25485 if (ExtractIdx->getZExtValue() == 0) {
25486 MVT OrigVT = OrigV.getSimpleValueType();
25487 // Extract a subvector if necessary...
25488 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25489 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25490 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25491 OrigVT.getVectorNumElements() / Ratio);
25492 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25493 DAG.getIntPtrConstant(0, DL));
25495 Op = DAG.getBitcast(OpVT, OrigV);
25496 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25503 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25504 DAGCombinerInfo &DCI) const {
25505 SelectionDAG &DAG = DCI.DAG;
25506 switch (N->getOpcode()) {
25508 case ISD::EXTRACT_VECTOR_ELT:
25509 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25512 case X86ISD::SHRUNKBLEND:
25513 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25514 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25515 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25516 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25517 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25518 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25519 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25522 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25523 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25524 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25525 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25526 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25527 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25528 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25529 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25530 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25531 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25532 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25533 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25535 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25537 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25538 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25539 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25540 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25541 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25542 case ISD::ANY_EXTEND:
25543 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25544 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25545 case ISD::SIGN_EXTEND_INREG:
25546 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25547 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25548 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25549 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25550 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25551 case X86ISD::SHUFP: // Handle all target specific shuffles
25552 case X86ISD::PALIGNR:
25553 case X86ISD::UNPCKH:
25554 case X86ISD::UNPCKL:
25555 case X86ISD::MOVHLPS:
25556 case X86ISD::MOVLHPS:
25557 case X86ISD::PSHUFB:
25558 case X86ISD::PSHUFD:
25559 case X86ISD::PSHUFHW:
25560 case X86ISD::PSHUFLW:
25561 case X86ISD::MOVSS:
25562 case X86ISD::MOVSD:
25563 case X86ISD::VPERMILPI:
25564 case X86ISD::VPERM2X128:
25565 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25566 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25567 case ISD::INTRINSIC_WO_CHAIN:
25568 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25569 case X86ISD::INSERTPS: {
25570 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25571 return PerformINSERTPSCombine(N, DAG, Subtarget);
25574 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25580 /// isTypeDesirableForOp - Return true if the target has native support for
25581 /// the specified value type and it is 'desirable' to use the type for the
25582 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25583 /// instruction encodings are longer and some i16 instructions are slow.
25584 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25585 if (!isTypeLegal(VT))
25587 if (VT != MVT::i16)
25594 case ISD::SIGN_EXTEND:
25595 case ISD::ZERO_EXTEND:
25596 case ISD::ANY_EXTEND:
25609 /// IsDesirableToPromoteOp - This method query the target whether it is
25610 /// beneficial for dag combiner to promote the specified node. If true, it
25611 /// should return the desired promotion type by reference.
25612 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25613 EVT VT = Op.getValueType();
25614 if (VT != MVT::i16)
25617 bool Promote = false;
25618 bool Commute = false;
25619 switch (Op.getOpcode()) {
25622 LoadSDNode *LD = cast<LoadSDNode>(Op);
25623 // If the non-extending load has a single use and it's not live out, then it
25624 // might be folded.
25625 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25626 Op.hasOneUse()*/) {
25627 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25628 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25629 // The only case where we'd want to promote LOAD (rather then it being
25630 // promoted as an operand is when it's only use is liveout.
25631 if (UI->getOpcode() != ISD::CopyToReg)
25638 case ISD::SIGN_EXTEND:
25639 case ISD::ZERO_EXTEND:
25640 case ISD::ANY_EXTEND:
25645 SDValue N0 = Op.getOperand(0);
25646 // Look out for (store (shl (load), x)).
25647 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25660 SDValue N0 = Op.getOperand(0);
25661 SDValue N1 = Op.getOperand(1);
25662 if (!Commute && MayFoldLoad(N1))
25664 // Avoid disabling potential load folding opportunities.
25665 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25667 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25677 //===----------------------------------------------------------------------===//
25678 // X86 Inline Assembly Support
25679 //===----------------------------------------------------------------------===//
25681 // Helper to match a string separated by whitespace.
25682 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25683 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25685 for (StringRef Piece : Pieces) {
25686 if (!S.startswith(Piece)) // Check if the piece matches.
25689 S = S.substr(Piece.size());
25690 StringRef::size_type Pos = S.find_first_not_of(" \t");
25691 if (Pos == 0) // We matched a prefix.
25700 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25702 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25703 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25704 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25705 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25707 if (AsmPieces.size() == 3)
25709 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25716 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25717 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25719 std::string AsmStr = IA->getAsmString();
25721 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25722 if (!Ty || Ty->getBitWidth() % 16 != 0)
25725 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25726 SmallVector<StringRef, 4> AsmPieces;
25727 SplitString(AsmStr, AsmPieces, ";\n");
25729 switch (AsmPieces.size()) {
25730 default: return false;
25732 // FIXME: this should verify that we are targeting a 486 or better. If not,
25733 // we will turn this bswap into something that will be lowered to logical
25734 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25735 // lower so don't worry about this.
25737 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25738 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25739 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25740 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25741 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25742 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25743 // No need to check constraints, nothing other than the equivalent of
25744 // "=r,0" would be valid here.
25745 return IntrinsicLowering::LowerToByteSwap(CI);
25748 // rorw $$8, ${0:w} --> llvm.bswap.i16
25749 if (CI->getType()->isIntegerTy(16) &&
25750 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25751 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25752 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25754 StringRef ConstraintsStr = IA->getConstraintString();
25755 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25756 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25757 if (clobbersFlagRegisters(AsmPieces))
25758 return IntrinsicLowering::LowerToByteSwap(CI);
25762 if (CI->getType()->isIntegerTy(32) &&
25763 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25764 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25765 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25766 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25768 StringRef ConstraintsStr = IA->getConstraintString();
25769 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25770 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25771 if (clobbersFlagRegisters(AsmPieces))
25772 return IntrinsicLowering::LowerToByteSwap(CI);
25775 if (CI->getType()->isIntegerTy(64)) {
25776 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25777 if (Constraints.size() >= 2 &&
25778 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25779 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25780 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
25781 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25782 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25783 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25784 return IntrinsicLowering::LowerToByteSwap(CI);
25792 /// getConstraintType - Given a constraint letter, return the type of
25793 /// constraint it is for this target.
25794 X86TargetLowering::ConstraintType
25795 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25796 if (Constraint.size() == 1) {
25797 switch (Constraint[0]) {
25808 return C_RegisterClass;
25832 return TargetLowering::getConstraintType(Constraint);
25835 /// Examine constraint type and operand type and determine a weight value.
25836 /// This object must already have been set up with the operand type
25837 /// and the current alternative constraint selected.
25838 TargetLowering::ConstraintWeight
25839 X86TargetLowering::getSingleConstraintMatchWeight(
25840 AsmOperandInfo &info, const char *constraint) const {
25841 ConstraintWeight weight = CW_Invalid;
25842 Value *CallOperandVal = info.CallOperandVal;
25843 // If we don't have a value, we can't do a match,
25844 // but allow it at the lowest weight.
25845 if (!CallOperandVal)
25847 Type *type = CallOperandVal->getType();
25848 // Look at the constraint type.
25849 switch (*constraint) {
25851 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25862 if (CallOperandVal->getType()->isIntegerTy())
25863 weight = CW_SpecificReg;
25868 if (type->isFloatingPointTy())
25869 weight = CW_SpecificReg;
25872 if (type->isX86_MMXTy() && Subtarget->hasMMX())
25873 weight = CW_SpecificReg;
25877 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25878 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25879 weight = CW_Register;
25882 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25883 if (C->getZExtValue() <= 31)
25884 weight = CW_Constant;
25888 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25889 if (C->getZExtValue() <= 63)
25890 weight = CW_Constant;
25894 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25895 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25896 weight = CW_Constant;
25900 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25901 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25902 weight = CW_Constant;
25906 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25907 if (C->getZExtValue() <= 3)
25908 weight = CW_Constant;
25912 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25913 if (C->getZExtValue() <= 0xff)
25914 weight = CW_Constant;
25919 if (isa<ConstantFP>(CallOperandVal)) {
25920 weight = CW_Constant;
25924 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25925 if ((C->getSExtValue() >= -0x80000000LL) &&
25926 (C->getSExtValue() <= 0x7fffffffLL))
25927 weight = CW_Constant;
25931 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25932 if (C->getZExtValue() <= 0xffffffff)
25933 weight = CW_Constant;
25940 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25941 /// with another that has more specific requirements based on the type of the
25942 /// corresponding operand.
25943 const char *X86TargetLowering::
25944 LowerXConstraint(EVT ConstraintVT) const {
25945 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25946 // 'f' like normal targets.
25947 if (ConstraintVT.isFloatingPoint()) {
25948 if (Subtarget->hasSSE2())
25950 if (Subtarget->hasSSE1())
25954 return TargetLowering::LowerXConstraint(ConstraintVT);
25957 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25958 /// vector. If it is invalid, don't add anything to Ops.
25959 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25960 std::string &Constraint,
25961 std::vector<SDValue>&Ops,
25962 SelectionDAG &DAG) const {
25965 // Only support length 1 constraints for now.
25966 if (Constraint.length() > 1) return;
25968 char ConstraintLetter = Constraint[0];
25969 switch (ConstraintLetter) {
25972 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25973 if (C->getZExtValue() <= 31) {
25974 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25975 Op.getValueType());
25981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25982 if (C->getZExtValue() <= 63) {
25983 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25984 Op.getValueType());
25990 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25991 if (isInt<8>(C->getSExtValue())) {
25992 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25993 Op.getValueType());
25999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26000 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26001 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26002 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26003 Op.getValueType());
26009 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26010 if (C->getZExtValue() <= 3) {
26011 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26012 Op.getValueType());
26018 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26019 if (C->getZExtValue() <= 255) {
26020 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26021 Op.getValueType());
26027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26028 if (C->getZExtValue() <= 127) {
26029 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26030 Op.getValueType());
26036 // 32-bit signed value
26037 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26038 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26039 C->getSExtValue())) {
26040 // Widen to 64 bits here to get it sign extended.
26041 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26044 // FIXME gcc accepts some relocatable values here too, but only in certain
26045 // memory models; it's complicated.
26050 // 32-bit unsigned value
26051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26052 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26053 C->getZExtValue())) {
26054 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26055 Op.getValueType());
26059 // FIXME gcc accepts some relocatable values here too, but only in certain
26060 // memory models; it's complicated.
26064 // Literal immediates are always ok.
26065 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26066 // Widen to 64 bits here to get it sign extended.
26067 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26071 // In any sort of PIC mode addresses need to be computed at runtime by
26072 // adding in a register or some sort of table lookup. These can't
26073 // be used as immediates.
26074 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26077 // If we are in non-pic codegen mode, we allow the address of a global (with
26078 // an optional displacement) to be used with 'i'.
26079 GlobalAddressSDNode *GA = nullptr;
26080 int64_t Offset = 0;
26082 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26084 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26085 Offset += GA->getOffset();
26087 } else if (Op.getOpcode() == ISD::ADD) {
26088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26089 Offset += C->getZExtValue();
26090 Op = Op.getOperand(0);
26093 } else if (Op.getOpcode() == ISD::SUB) {
26094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26095 Offset += -C->getZExtValue();
26096 Op = Op.getOperand(0);
26101 // Otherwise, this isn't something we can handle, reject it.
26105 const GlobalValue *GV = GA->getGlobal();
26106 // If we require an extra load to get this address, as in PIC mode, we
26107 // can't accept it.
26108 if (isGlobalStubReference(
26109 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26112 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26113 GA->getValueType(0), Offset);
26118 if (Result.getNode()) {
26119 Ops.push_back(Result);
26122 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26125 std::pair<unsigned, const TargetRegisterClass *>
26126 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26127 StringRef Constraint,
26129 // First, see if this is a constraint that directly corresponds to an LLVM
26131 if (Constraint.size() == 1) {
26132 // GCC Constraint Letters
26133 switch (Constraint[0]) {
26135 // TODO: Slight differences here in allocation order and leaving
26136 // RIP in the class. Do they matter any more here than they do
26137 // in the normal allocation?
26138 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26139 if (Subtarget->is64Bit()) {
26140 if (VT == MVT::i32 || VT == MVT::f32)
26141 return std::make_pair(0U, &X86::GR32RegClass);
26142 if (VT == MVT::i16)
26143 return std::make_pair(0U, &X86::GR16RegClass);
26144 if (VT == MVT::i8 || VT == MVT::i1)
26145 return std::make_pair(0U, &X86::GR8RegClass);
26146 if (VT == MVT::i64 || VT == MVT::f64)
26147 return std::make_pair(0U, &X86::GR64RegClass);
26150 // 32-bit fallthrough
26151 case 'Q': // Q_REGS
26152 if (VT == MVT::i32 || VT == MVT::f32)
26153 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26154 if (VT == MVT::i16)
26155 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26156 if (VT == MVT::i8 || VT == MVT::i1)
26157 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26158 if (VT == MVT::i64)
26159 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26161 case 'r': // GENERAL_REGS
26162 case 'l': // INDEX_REGS
26163 if (VT == MVT::i8 || VT == MVT::i1)
26164 return std::make_pair(0U, &X86::GR8RegClass);
26165 if (VT == MVT::i16)
26166 return std::make_pair(0U, &X86::GR16RegClass);
26167 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26168 return std::make_pair(0U, &X86::GR32RegClass);
26169 return std::make_pair(0U, &X86::GR64RegClass);
26170 case 'R': // LEGACY_REGS
26171 if (VT == MVT::i8 || VT == MVT::i1)
26172 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26173 if (VT == MVT::i16)
26174 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26175 if (VT == MVT::i32 || !Subtarget->is64Bit())
26176 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26177 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26178 case 'f': // FP Stack registers.
26179 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26180 // value to the correct fpstack register class.
26181 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26182 return std::make_pair(0U, &X86::RFP32RegClass);
26183 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26184 return std::make_pair(0U, &X86::RFP64RegClass);
26185 return std::make_pair(0U, &X86::RFP80RegClass);
26186 case 'y': // MMX_REGS if MMX allowed.
26187 if (!Subtarget->hasMMX()) break;
26188 return std::make_pair(0U, &X86::VR64RegClass);
26189 case 'Y': // SSE_REGS if SSE2 allowed
26190 if (!Subtarget->hasSSE2()) break;
26192 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26193 if (!Subtarget->hasSSE1()) break;
26195 switch (VT.SimpleTy) {
26197 // Scalar SSE types.
26200 return std::make_pair(0U, &X86::FR32RegClass);
26203 return std::make_pair(0U, &X86::FR64RegClass);
26211 return std::make_pair(0U, &X86::VR128RegClass);
26219 return std::make_pair(0U, &X86::VR256RegClass);
26224 return std::make_pair(0U, &X86::VR512RegClass);
26230 // Use the default implementation in TargetLowering to convert the register
26231 // constraint into a member of a register class.
26232 std::pair<unsigned, const TargetRegisterClass*> Res;
26233 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26235 // Not found as a standard register?
26237 // Map st(0) -> st(7) -> ST0
26238 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26239 tolower(Constraint[1]) == 's' &&
26240 tolower(Constraint[2]) == 't' &&
26241 Constraint[3] == '(' &&
26242 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26243 Constraint[5] == ')' &&
26244 Constraint[6] == '}') {
26246 Res.first = X86::FP0+Constraint[4]-'0';
26247 Res.second = &X86::RFP80RegClass;
26251 // GCC allows "st(0)" to be called just plain "st".
26252 if (StringRef("{st}").equals_lower(Constraint)) {
26253 Res.first = X86::FP0;
26254 Res.second = &X86::RFP80RegClass;
26259 if (StringRef("{flags}").equals_lower(Constraint)) {
26260 Res.first = X86::EFLAGS;
26261 Res.second = &X86::CCRRegClass;
26265 // 'A' means EAX + EDX.
26266 if (Constraint == "A") {
26267 Res.first = X86::EAX;
26268 Res.second = &X86::GR32_ADRegClass;
26274 // Otherwise, check to see if this is a register class of the wrong value
26275 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26276 // turn into {ax},{dx}.
26277 // MVT::Other is used to specify clobber names.
26278 if (Res.second->hasType(VT) || VT == MVT::Other)
26279 return Res; // Correct type already, nothing to do.
26281 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26282 // return "eax". This should even work for things like getting 64bit integer
26283 // registers when given an f64 type.
26284 const TargetRegisterClass *Class = Res.second;
26285 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26286 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26287 unsigned Size = VT.getSizeInBits();
26288 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26289 : Size == 16 ? MVT::i16
26290 : Size == 32 ? MVT::i32
26291 : Size == 64 ? MVT::i64
26293 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26295 Res.first = DestReg;
26296 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26297 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26298 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26299 : &X86::GR64RegClass;
26300 assert(Res.second->contains(Res.first) && "Register in register class");
26302 // No register found/type mismatch.
26304 Res.second = nullptr;
26306 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26307 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26308 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26309 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26310 Class == &X86::VR512RegClass) {
26311 // Handle references to XMM physical registers that got mapped into the
26312 // wrong class. This can happen with constraints like {xmm0} where the
26313 // target independent register mapper will just pick the first match it can
26314 // find, ignoring the required type.
26316 if (VT == MVT::f32 || VT == MVT::i32)
26317 Res.second = &X86::FR32RegClass;
26318 else if (VT == MVT::f64 || VT == MVT::i64)
26319 Res.second = &X86::FR64RegClass;
26320 else if (X86::VR128RegClass.hasType(VT))
26321 Res.second = &X86::VR128RegClass;
26322 else if (X86::VR256RegClass.hasType(VT))
26323 Res.second = &X86::VR256RegClass;
26324 else if (X86::VR512RegClass.hasType(VT))
26325 Res.second = &X86::VR512RegClass;
26327 // Type mismatch and not a clobber: Return an error;
26329 Res.second = nullptr;
26336 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26337 const AddrMode &AM, Type *Ty,
26338 unsigned AS) const {
26339 // Scaling factors are not free at all.
26340 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26341 // will take 2 allocations in the out of order engine instead of 1
26342 // for plain addressing mode, i.e. inst (reg1).
26344 // vaddps (%rsi,%drx), %ymm0, %ymm1
26345 // Requires two allocations (one for the load, one for the computation)
26347 // vaddps (%rsi), %ymm0, %ymm1
26348 // Requires just 1 allocation, i.e., freeing allocations for other operations
26349 // and having less micro operations to execute.
26351 // For some X86 architectures, this is even worse because for instance for
26352 // stores, the complex addressing mode forces the instruction to use the
26353 // "load" ports instead of the dedicated "store" port.
26354 // E.g., on Haswell:
26355 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26356 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26357 if (isLegalAddressingMode(DL, AM, Ty, AS))
26358 // Scale represents reg2 * scale, thus account for 1
26359 // as soon as we use a second register.
26360 return AM.Scale != 0;
26364 bool X86TargetLowering::isTargetFTOL() const {
26365 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();