1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71 const X86Subtarget &STI)
72 : TargetLowering(TM), Subtarget(&STI) {
73 X86ScalarSSEf64 = Subtarget->hasSSE2();
74 X86ScalarSSEf32 = Subtarget->hasSSE1();
75 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77 // Set up the TargetLowering object.
78 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
80 // X86 is weird. It always uses i8 for shift amounts and setcc results.
81 setBooleanContents(ZeroOrOneBooleanContent);
82 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85 // For 64-bit, since we have so many registers, use the ILP scheduler.
86 // For 32-bit, use the register pressure specific scheduling.
87 // For Atom, always use ILP scheduling.
88 if (Subtarget->isAtom())
89 setSchedulingPreference(Sched::ILP);
90 else if (Subtarget->is64Bit())
91 setSchedulingPreference(Sched::ILP);
93 setSchedulingPreference(Sched::RegPressure);
94 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97 // Bypass expensive divides on Atom when compiling with O2.
98 if (TM.getOptLevel() >= CodeGenOpt::Default) {
99 if (Subtarget->hasSlowDivide32())
100 addBypassSlowDiv(32, 8);
101 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102 addBypassSlowDiv(64, 16);
105 if (Subtarget->isTargetKnownWindowsMSVC()) {
106 // Setup Windows compiler runtime calls.
107 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109 setLibcallName(RTLIB::SREM_I64, "_allrem");
110 setLibcallName(RTLIB::UREM_I64, "_aullrem");
111 setLibcallName(RTLIB::MUL_I64, "_allmul");
112 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
119 if (Subtarget->isTargetDarwin()) {
120 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121 setUseUnderscoreSetJmp(false);
122 setUseUnderscoreLongJmp(false);
123 } else if (Subtarget->isTargetWindowsGNU()) {
124 // MS runtime is weird: it exports _setjmp, but longjmp!
125 setUseUnderscoreSetJmp(true);
126 setUseUnderscoreLongJmp(false);
128 setUseUnderscoreSetJmp(true);
129 setUseUnderscoreLongJmp(true);
132 // Set up the register classes.
133 addRegisterClass(MVT::i8, &X86::GR8RegClass);
134 addRegisterClass(MVT::i16, &X86::GR16RegClass);
135 addRegisterClass(MVT::i32, &X86::GR32RegClass);
136 if (Subtarget->is64Bit())
137 addRegisterClass(MVT::i64, &X86::GR64RegClass);
139 for (MVT VT : MVT::integer_valuetypes())
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 // We don't accept any truncstore of integer registers.
143 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
150 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 // SETOEQ and SETUNE require checking two conditions.
153 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
163 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
166 if (Subtarget->is64Bit()) {
167 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
168 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
169 } else if (!Subtarget->useSoftFloat()) {
170 // We have an algorithm for SSE2->double, and we turn this into a
171 // 64-bit FILD followed by conditional FADD for other targets.
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 // We have an algorithm for SSE2, and we turn this into a 64-bit
174 // FILD for other targets.
175 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
178 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
180 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
183 if (!Subtarget->useSoftFloat()) {
184 // SSE has no i16 to fp conversion, only i32
185 if (X86ScalarSSEf32) {
186 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
187 // f32 and f64 cases are Legal, f80 case is not
188 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
191 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
198 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
199 // are Legal, f80 is custom lowered.
200 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
203 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
205 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
206 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
208 if (X86ScalarSSEf32) {
209 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
210 // f32 and f64 cases are Legal, f80 case is not
211 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
213 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
214 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
217 // Handle FP_TO_UINT by promoting the destination to a larger signed
219 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
220 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
221 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
223 if (Subtarget->is64Bit()) {
224 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
227 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
229 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
230 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
232 } else if (!Subtarget->useSoftFloat()) {
233 // Since AVX is a superset of SSE3, only check for SSE here.
234 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235 // Expand FP_TO_UINT into a select.
236 // FIXME: We would like to use a Custom expander here eventually to do
237 // the optimal thing for SSE vs. the default expansion in the legalizer.
238 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
240 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
241 // With SSE3 we can use fisttpll to convert to a signed i64; without
242 // SSE, we're stuck with a fistpll.
243 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
245 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
248 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249 if (!X86ScalarSSEf64) {
250 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
251 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
252 if (Subtarget->is64Bit()) {
253 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
254 // Without SSE, i64->f64 goes through memory.
255 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
259 // Scalar integer divide and remainder are lowered to use operations that
260 // produce two results, to match the available instructions. This exposes
261 // the two-result form to trivial CSE, which is able to combine x/y and x%y
262 // into a single instruction.
264 // Scalar integer multiply-high is also lowered to use two-result
265 // operations, to match the available instructions. However, plain multiply
266 // (low) operations are left as Legal, as there are single-result
267 // instructions for this in x86. Using the two-result multiply instructions
268 // when both high and low results are needed must be arranged by dagcombine.
269 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
271 setOperationAction(ISD::MULHS, VT, Expand);
272 setOperationAction(ISD::MULHU, VT, Expand);
273 setOperationAction(ISD::SDIV, VT, Expand);
274 setOperationAction(ISD::UDIV, VT, Expand);
275 setOperationAction(ISD::SREM, VT, Expand);
276 setOperationAction(ISD::UREM, VT, Expand);
278 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279 setOperationAction(ISD::ADDC, VT, Custom);
280 setOperationAction(ISD::ADDE, VT, Custom);
281 setOperationAction(ISD::SUBC, VT, Custom);
282 setOperationAction(ISD::SUBE, VT, Custom);
285 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
286 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
287 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
288 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
289 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
290 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
291 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
292 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
293 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
294 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
295 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
296 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
297 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
301 if (Subtarget->is64Bit())
302 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
304 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
305 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
306 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
308 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
309 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
310 // is. We should promote the value to 64-bits to solve this.
311 // This is what the CRT headers do - `fmodf` is an inline header
312 // function casting to f64 and calling `fmod`.
313 setOperationAction(ISD::FREM , MVT::f32 , Promote);
315 setOperationAction(ISD::FREM , MVT::f32 , Expand);
318 setOperationAction(ISD::FREM , MVT::f64 , Expand);
319 setOperationAction(ISD::FREM , MVT::f80 , Expand);
320 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
322 // Promote the i8 variants and force them on up to i32 which has a shorter
324 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
325 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
326 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
327 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
328 if (Subtarget->hasBMI()) {
329 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
331 if (Subtarget->is64Bit())
332 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
334 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
335 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
336 if (Subtarget->is64Bit())
337 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
340 if (Subtarget->hasLZCNT()) {
341 // When promoting the i8 variants, force them to i32 for a shorter
343 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
344 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
346 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
347 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
348 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
349 if (Subtarget->is64Bit())
350 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
352 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
353 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
354 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
355 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
356 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
357 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
358 if (Subtarget->is64Bit()) {
359 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
364 // Special handling for half-precision floating point conversions.
365 // If we don't have F16C support, then lower half float conversions
366 // into library calls.
367 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
368 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
369 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
372 // There's never any support for operations beyond MVT::f32.
373 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
374 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
375 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
376 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
378 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
379 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
381 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
382 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
383 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
385 if (Subtarget->hasPOPCNT()) {
386 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
388 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
389 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
390 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
391 if (Subtarget->is64Bit())
392 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
395 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
397 if (!Subtarget->hasMOVBE())
398 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
400 // These should be promoted to a larger select which is supported.
401 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
402 // X86 wants to expand cmov itself.
403 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
404 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
405 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
406 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
407 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
408 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
409 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
410 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
411 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
412 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
413 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
414 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
415 if (Subtarget->is64Bit()) {
416 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
417 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
419 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
420 setOperationAction(ISD::CATCHRET , MVT::Other, Custom);
421 setOperationAction(ISD::CLEANUPRET , MVT::Other, Custom);
422 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
423 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
424 // support continuation, user-level threading, and etc.. As a result, no
425 // other SjLj exception interfaces are implemented and please don't build
426 // your own exception handling based on them.
427 // LLVM/Clang supports zero-cost DWARF exception handling.
428 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
429 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
433 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
434 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
435 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
436 if (Subtarget->is64Bit())
437 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
438 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
439 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
440 if (Subtarget->is64Bit()) {
441 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
442 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
443 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
444 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
445 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
447 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
448 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
449 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
450 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
451 if (Subtarget->is64Bit()) {
452 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
453 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
454 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
457 if (Subtarget->hasSSE1())
458 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
460 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
462 // Expand certain atomics
463 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
465 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
466 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
467 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470 if (Subtarget->hasCmpxchg16b()) {
471 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474 // FIXME - use subtarget debug flags
475 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
476 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
477 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480 if (Subtarget->isTarget64BitLP64()) {
481 setExceptionPointerRegister(X86::RAX);
482 setExceptionSelectorRegister(X86::RDX);
484 setExceptionPointerRegister(X86::EAX);
485 setExceptionSelectorRegister(X86::EDX);
487 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
488 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
490 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
491 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
493 setOperationAction(ISD::TRAP, MVT::Other, Legal);
494 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
496 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
497 setOperationAction(ISD::VASTART , MVT::Other, Custom);
498 setOperationAction(ISD::VAEND , MVT::Other, Expand);
499 if (Subtarget->is64Bit()) {
500 setOperationAction(ISD::VAARG , MVT::Other, Custom);
501 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
503 // TargetInfo::CharPtrBuiltinVaList
504 setOperationAction(ISD::VAARG , MVT::Other, Expand);
505 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
508 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
509 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
511 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
513 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
514 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
515 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
517 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
518 // f32 and f64 use SSE.
519 // Set up the FP register classes.
520 addRegisterClass(MVT::f32, &X86::FR32RegClass);
521 addRegisterClass(MVT::f64, &X86::FR64RegClass);
523 // Use ANDPD to simulate FABS.
524 setOperationAction(ISD::FABS , MVT::f64, Custom);
525 setOperationAction(ISD::FABS , MVT::f32, Custom);
527 // Use XORP to simulate FNEG.
528 setOperationAction(ISD::FNEG , MVT::f64, Custom);
529 setOperationAction(ISD::FNEG , MVT::f32, Custom);
531 // Use ANDPD and ORPD to simulate FCOPYSIGN.
532 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
533 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
535 // Lower this to FGETSIGNx86 plus an AND.
536 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
537 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
539 // We don't support sin/cos/fmod
540 setOperationAction(ISD::FSIN , MVT::f64, Expand);
541 setOperationAction(ISD::FCOS , MVT::f64, Expand);
542 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
543 setOperationAction(ISD::FSIN , MVT::f32, Expand);
544 setOperationAction(ISD::FCOS , MVT::f32, Expand);
545 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
547 // Expand FP immediates into loads from the stack, except for the special
549 addLegalFPImmediate(APFloat(+0.0)); // xorpd
550 addLegalFPImmediate(APFloat(+0.0f)); // xorps
551 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
552 // Use SSE for f32, x87 for f64.
553 // Set up the FP register classes.
554 addRegisterClass(MVT::f32, &X86::FR32RegClass);
555 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
557 // Use ANDPS to simulate FABS.
558 setOperationAction(ISD::FABS , MVT::f32, Custom);
560 // Use XORP to simulate FNEG.
561 setOperationAction(ISD::FNEG , MVT::f32, Custom);
563 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
565 // Use ANDPS and ORPS to simulate FCOPYSIGN.
566 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
567 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
569 // We don't support sin/cos/fmod
570 setOperationAction(ISD::FSIN , MVT::f32, Expand);
571 setOperationAction(ISD::FCOS , MVT::f32, Expand);
572 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
574 // Special cases we handle for FP constants.
575 addLegalFPImmediate(APFloat(+0.0f)); // xorps
576 addLegalFPImmediate(APFloat(+0.0)); // FLD0
577 addLegalFPImmediate(APFloat(+1.0)); // FLD1
578 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
579 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
581 if (!TM.Options.UnsafeFPMath) {
582 setOperationAction(ISD::FSIN , MVT::f64, Expand);
583 setOperationAction(ISD::FCOS , MVT::f64, Expand);
584 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
586 } else if (!Subtarget->useSoftFloat()) {
587 // f32 and f64 in x87.
588 // Set up the FP register classes.
589 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
590 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
592 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
593 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
594 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
597 if (!TM.Options.UnsafeFPMath) {
598 setOperationAction(ISD::FSIN , MVT::f64, Expand);
599 setOperationAction(ISD::FSIN , MVT::f32, Expand);
600 setOperationAction(ISD::FCOS , MVT::f64, Expand);
601 setOperationAction(ISD::FCOS , MVT::f32, Expand);
602 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
603 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
605 addLegalFPImmediate(APFloat(+0.0)); // FLD0
606 addLegalFPImmediate(APFloat(+1.0)); // FLD1
607 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
608 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
609 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
610 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
611 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
612 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
615 // We don't support FMA.
616 setOperationAction(ISD::FMA, MVT::f64, Expand);
617 setOperationAction(ISD::FMA, MVT::f32, Expand);
619 // Long double always uses X87.
620 if (!Subtarget->useSoftFloat()) {
621 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
622 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
623 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
625 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
626 addLegalFPImmediate(TmpFlt); // FLD0
628 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
631 APFloat TmpFlt2(+1.0);
632 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
634 addLegalFPImmediate(TmpFlt2); // FLD1
635 TmpFlt2.changeSign();
636 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
639 if (!TM.Options.UnsafeFPMath) {
640 setOperationAction(ISD::FSIN , MVT::f80, Expand);
641 setOperationAction(ISD::FCOS , MVT::f80, Expand);
642 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
645 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
646 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
647 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
648 setOperationAction(ISD::FRINT, MVT::f80, Expand);
649 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
650 setOperationAction(ISD::FMA, MVT::f80, Expand);
653 // Always use a library call for pow.
654 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
655 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
656 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
658 setOperationAction(ISD::FLOG, MVT::f80, Expand);
659 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
660 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
661 setOperationAction(ISD::FEXP, MVT::f80, Expand);
662 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
663 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
664 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
666 // First set operation action for all vector types to either promote
667 // (for widening) or expand (for scalarization). Then we will selectively
668 // turn on ones that can be effectively codegen'd.
669 for (MVT VT : MVT::vector_valuetypes()) {
670 setOperationAction(ISD::ADD , VT, Expand);
671 setOperationAction(ISD::SUB , VT, Expand);
672 setOperationAction(ISD::FADD, VT, Expand);
673 setOperationAction(ISD::FNEG, VT, Expand);
674 setOperationAction(ISD::FSUB, VT, Expand);
675 setOperationAction(ISD::MUL , VT, Expand);
676 setOperationAction(ISD::FMUL, VT, Expand);
677 setOperationAction(ISD::SDIV, VT, Expand);
678 setOperationAction(ISD::UDIV, VT, Expand);
679 setOperationAction(ISD::FDIV, VT, Expand);
680 setOperationAction(ISD::SREM, VT, Expand);
681 setOperationAction(ISD::UREM, VT, Expand);
682 setOperationAction(ISD::LOAD, VT, Expand);
683 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
684 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
685 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
686 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
687 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
688 setOperationAction(ISD::FABS, VT, Expand);
689 setOperationAction(ISD::FSIN, VT, Expand);
690 setOperationAction(ISD::FSINCOS, VT, Expand);
691 setOperationAction(ISD::FCOS, VT, Expand);
692 setOperationAction(ISD::FSINCOS, VT, Expand);
693 setOperationAction(ISD::FREM, VT, Expand);
694 setOperationAction(ISD::FMA, VT, Expand);
695 setOperationAction(ISD::FPOWI, VT, Expand);
696 setOperationAction(ISD::FSQRT, VT, Expand);
697 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
698 setOperationAction(ISD::FFLOOR, VT, Expand);
699 setOperationAction(ISD::FCEIL, VT, Expand);
700 setOperationAction(ISD::FTRUNC, VT, Expand);
701 setOperationAction(ISD::FRINT, VT, Expand);
702 setOperationAction(ISD::FNEARBYINT, VT, Expand);
703 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
704 setOperationAction(ISD::MULHS, VT, Expand);
705 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
706 setOperationAction(ISD::MULHU, VT, Expand);
707 setOperationAction(ISD::SDIVREM, VT, Expand);
708 setOperationAction(ISD::UDIVREM, VT, Expand);
709 setOperationAction(ISD::FPOW, VT, Expand);
710 setOperationAction(ISD::CTPOP, VT, Expand);
711 setOperationAction(ISD::CTTZ, VT, Expand);
712 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
713 setOperationAction(ISD::CTLZ, VT, Expand);
714 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
715 setOperationAction(ISD::SHL, VT, Expand);
716 setOperationAction(ISD::SRA, VT, Expand);
717 setOperationAction(ISD::SRL, VT, Expand);
718 setOperationAction(ISD::ROTL, VT, Expand);
719 setOperationAction(ISD::ROTR, VT, Expand);
720 setOperationAction(ISD::BSWAP, VT, Expand);
721 setOperationAction(ISD::SETCC, VT, Expand);
722 setOperationAction(ISD::FLOG, VT, Expand);
723 setOperationAction(ISD::FLOG2, VT, Expand);
724 setOperationAction(ISD::FLOG10, VT, Expand);
725 setOperationAction(ISD::FEXP, VT, Expand);
726 setOperationAction(ISD::FEXP2, VT, Expand);
727 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
728 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
729 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
730 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
731 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
732 setOperationAction(ISD::TRUNCATE, VT, Expand);
733 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
734 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
735 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
736 setOperationAction(ISD::VSELECT, VT, Expand);
737 setOperationAction(ISD::SELECT_CC, VT, Expand);
738 for (MVT InnerVT : MVT::vector_valuetypes()) {
739 setTruncStoreAction(InnerVT, VT, Expand);
741 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
742 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
744 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
745 // types, we have to deal with them whether we ask for Expansion or not.
746 // Setting Expand causes its own optimisation problems though, so leave
748 if (VT.getVectorElementType() == MVT::i1)
749 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
751 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
752 // split/scalarized right now.
753 if (VT.getVectorElementType() == MVT::f16)
754 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
759 // with -msoft-float, disable use of MMX as well.
760 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
761 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
762 // No operations on x86mmx supported, everything uses intrinsics.
765 // MMX-sized vectors (other than x86mmx) are expected to be expanded
766 // into smaller operations.
767 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
768 setOperationAction(ISD::MULHS, MMXTy, Expand);
769 setOperationAction(ISD::AND, MMXTy, Expand);
770 setOperationAction(ISD::OR, MMXTy, Expand);
771 setOperationAction(ISD::XOR, MMXTy, Expand);
772 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
773 setOperationAction(ISD::SELECT, MMXTy, Expand);
774 setOperationAction(ISD::BITCAST, MMXTy, Expand);
776 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
778 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
779 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
781 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
782 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
783 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
784 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
785 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
786 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
787 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
788 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
789 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
790 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
791 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
792 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
793 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
794 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
797 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
798 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
800 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
801 // registers cannot be used even for integer operations.
802 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
803 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
804 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
805 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
807 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
808 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
809 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
810 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
811 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
812 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
813 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
814 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
815 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
816 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
817 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
818 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
819 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
820 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
821 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
822 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
823 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
824 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
825 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
826 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
827 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
828 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
829 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
831 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
832 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
833 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
834 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
836 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
837 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
838 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
839 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
841 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
842 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
843 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
844 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
848 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
850 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
852 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
853 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
854 MVT VT = (MVT::SimpleValueType)i;
855 // Do not attempt to custom lower non-power-of-2 vectors
856 if (!isPowerOf2_32(VT.getVectorNumElements()))
858 // Do not attempt to custom lower non-128-bit vectors
859 if (!VT.is128BitVector())
861 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
862 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
863 setOperationAction(ISD::VSELECT, VT, Custom);
864 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
867 // We support custom legalizing of sext and anyext loads for specific
868 // memory vector types which we can load as a scalar (or sequence of
869 // scalars) and extend in-register to a legal 128-bit vector type. For sext
870 // loads these must work with a single scalar load.
871 for (MVT VT : MVT::integer_vector_valuetypes()) {
872 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
873 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
874 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
875 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
877 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
878 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
879 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
880 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
883 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
884 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
885 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
887 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
888 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
889 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
890 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892 if (Subtarget->is64Bit()) {
893 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
894 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
897 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
898 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
899 MVT VT = (MVT::SimpleValueType)i;
901 // Do not attempt to promote non-128-bit vectors
902 if (!VT.is128BitVector())
905 setOperationAction(ISD::AND, VT, Promote);
906 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
907 setOperationAction(ISD::OR, VT, Promote);
908 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
909 setOperationAction(ISD::XOR, VT, Promote);
910 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
911 setOperationAction(ISD::LOAD, VT, Promote);
912 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
913 setOperationAction(ISD::SELECT, VT, Promote);
914 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
917 // Custom lower v2i64 and v2f64 selects.
918 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
919 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
920 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
921 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
923 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
924 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
926 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
928 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
929 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
930 // As there is no 64-bit GPR available, we need build a special custom
931 // sequence to convert from v2i32 to v2f32.
932 if (!Subtarget->is64Bit())
933 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
935 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
936 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
938 for (MVT VT : MVT::fp_vector_valuetypes())
939 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
941 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
942 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
943 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
946 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
947 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
948 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
949 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
950 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
951 setOperationAction(ISD::FRINT, RoundedTy, Legal);
952 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
955 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
956 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
957 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
958 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
959 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
960 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
961 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
962 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
964 // FIXME: Do we need to handle scalar-to-vector here?
965 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
967 // We directly match byte blends in the backend as they match the VSELECT
969 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
971 // SSE41 brings specific instructions for doing vector sign extend even in
972 // cases where we don't have SRA.
973 for (MVT VT : MVT::integer_vector_valuetypes()) {
974 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
975 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
976 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
979 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
980 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
981 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
982 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
983 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
987 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
988 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
989 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
990 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
991 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
992 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
994 // i8 and i16 vectors are custom because the source register and source
995 // source memory operand types are not the same width. f32 vectors are
996 // custom since the immediate controlling the insert encodes additional
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
999 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1000 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1001 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1003 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1004 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1005 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1006 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1008 // FIXME: these should be Legal, but that's only for the case where
1009 // the index is constant. For now custom expand to deal with that.
1010 if (Subtarget->is64Bit()) {
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1016 if (Subtarget->hasSSE2()) {
1017 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1018 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1019 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1021 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1022 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1024 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1027 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1028 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1030 // In the customized shift lowering, the legal cases in AVX2 will be
1032 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1033 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1035 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1036 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1038 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1039 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1042 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1043 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1044 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1045 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1046 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1047 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1048 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1050 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1051 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1052 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1054 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1058 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1059 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1060 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1061 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1062 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1063 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1064 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1065 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1067 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1068 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1069 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1070 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1071 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1072 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1073 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1074 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1075 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1076 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1077 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1078 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1080 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1081 // even though v8i16 is a legal type.
1082 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1083 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1084 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1086 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1087 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1088 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1090 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1091 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1093 for (MVT VT : MVT::fp_vector_valuetypes())
1094 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1096 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1097 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1099 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1100 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1102 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1103 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1105 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1106 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1107 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1108 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1110 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1111 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1112 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1114 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1115 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1116 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1117 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1118 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1119 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1120 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1121 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1122 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1123 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1124 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1125 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1127 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1128 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1129 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1130 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1132 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1133 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1135 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1136 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1137 setOperationAction(ISD::FMA, MVT::f32, Legal);
1138 setOperationAction(ISD::FMA, MVT::f64, Legal);
1141 if (Subtarget->hasInt256()) {
1142 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1143 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1144 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1145 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1147 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1148 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1149 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1150 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1152 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1153 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1154 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1155 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1157 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1158 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1159 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1160 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1162 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1163 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1164 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1165 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1166 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1167 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1168 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1169 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1170 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1171 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1172 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1173 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1175 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1176 // when we have a 256bit-wide blend with immediate.
1177 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1179 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1180 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1182 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1183 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1184 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1185 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1187 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1188 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1189 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1190 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1191 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1192 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1194 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1195 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1199 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1200 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1201 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1202 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1204 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1205 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1206 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1207 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1209 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1210 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1211 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1212 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1213 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1214 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1215 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1216 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1217 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1218 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1219 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1220 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1223 // In the customized shift lowering, the legal cases in AVX2 will be
1225 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1226 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1228 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1229 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1231 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1232 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1234 // Custom lower several nodes for 256-bit types.
1235 for (MVT VT : MVT::vector_valuetypes()) {
1236 if (VT.getScalarSizeInBits() >= 32) {
1237 setOperationAction(ISD::MLOAD, VT, Legal);
1238 setOperationAction(ISD::MSTORE, VT, Legal);
1240 // Extract subvector is special because the value type
1241 // (result) is 128-bit but the source is 256-bit wide.
1242 if (VT.is128BitVector()) {
1243 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1245 // Do not attempt to custom lower other non-256-bit vectors
1246 if (!VT.is256BitVector())
1249 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1250 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1251 setOperationAction(ISD::VSELECT, VT, Custom);
1252 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1253 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1254 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1255 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1256 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1259 if (Subtarget->hasInt256())
1260 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1263 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1264 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1265 MVT VT = (MVT::SimpleValueType)i;
1267 // Do not attempt to promote non-256-bit vectors
1268 if (!VT.is256BitVector())
1271 setOperationAction(ISD::AND, VT, Promote);
1272 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1273 setOperationAction(ISD::OR, VT, Promote);
1274 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1275 setOperationAction(ISD::XOR, VT, Promote);
1276 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1277 setOperationAction(ISD::LOAD, VT, Promote);
1278 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1279 setOperationAction(ISD::SELECT, VT, Promote);
1280 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1284 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1285 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1286 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1287 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1288 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1290 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1291 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1292 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1294 for (MVT VT : MVT::fp_vector_valuetypes())
1295 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1297 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1298 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1299 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1300 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1301 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1302 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1303 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1304 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1305 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1306 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1307 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1308 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1310 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1311 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1312 setOperationAction(ISD::XOR, MVT::i1, Legal);
1313 setOperationAction(ISD::OR, MVT::i1, Legal);
1314 setOperationAction(ISD::AND, MVT::i1, Legal);
1315 setOperationAction(ISD::SUB, MVT::i1, Custom);
1316 setOperationAction(ISD::ADD, MVT::i1, Custom);
1317 setOperationAction(ISD::MUL, MVT::i1, Custom);
1318 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1319 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1320 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1321 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1322 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1324 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1325 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1326 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1327 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1328 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1329 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1331 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1332 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1333 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1335 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1337 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1340 // FIXME: [US]INT_TO_FP are not legal for f80.
1341 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1342 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1343 if (Subtarget->is64Bit()) {
1344 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1347 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1348 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1349 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1350 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1351 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1352 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1353 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1354 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1355 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1356 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1357 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1358 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1359 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1360 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1361 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1362 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1364 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1365 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1366 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1367 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1368 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1369 if (Subtarget->hasVLX()){
1370 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1371 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1372 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1373 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1374 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1376 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1377 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1378 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1379 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1380 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1382 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1384 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1385 if (Subtarget->hasDQI()) {
1386 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1387 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1389 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1390 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1391 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1392 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1393 if (Subtarget->hasVLX()) {
1394 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1395 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1396 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1397 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1398 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1399 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1400 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1401 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1404 if (Subtarget->hasVLX()) {
1405 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1406 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1407 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1408 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1409 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1410 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1411 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1412 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1414 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1415 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1416 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1417 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1418 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1419 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1420 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1421 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1422 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1423 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1424 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1425 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1426 if (Subtarget->hasDQI()) {
1427 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1428 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1430 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1431 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1432 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1433 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1434 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1435 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1436 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1437 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1438 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1439 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1444 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1445 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1447 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1448 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1450 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1452 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1454 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1455 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1456 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1457 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1459 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1460 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1461 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1462 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1464 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1465 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1466 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1467 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1468 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1469 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1470 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1471 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1473 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1474 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1476 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1477 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1479 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1481 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1482 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1484 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1485 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1487 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1488 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1490 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1491 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1492 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1493 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1494 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1495 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1497 if (Subtarget->hasCDI()) {
1498 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1499 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1500 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Legal);
1501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Legal);
1503 if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1504 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1505 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1506 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1507 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1508 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Legal);
1509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Legal);
1510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Legal);
1511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Legal);
1513 if (Subtarget->hasDQI()) {
1514 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1515 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1516 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1518 // Custom lower several nodes.
1519 for (MVT VT : MVT::vector_valuetypes()) {
1520 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1522 setOperationAction(ISD::AND, VT, Legal);
1523 setOperationAction(ISD::OR, VT, Legal);
1524 setOperationAction(ISD::XOR, VT, Legal);
1526 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1527 setOperationAction(ISD::MGATHER, VT, Custom);
1528 setOperationAction(ISD::MSCATTER, VT, Custom);
1530 // Extract subvector is special because the value type
1531 // (result) is 256/128-bit but the source is 512-bit wide.
1532 if (VT.is128BitVector() || VT.is256BitVector()) {
1533 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1535 if (VT.getVectorElementType() == MVT::i1)
1536 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1538 // Do not attempt to custom lower other non-512-bit vectors
1539 if (!VT.is512BitVector())
1542 if (EltSize >= 32) {
1543 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1544 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1545 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1546 setOperationAction(ISD::VSELECT, VT, Legal);
1547 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1548 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1549 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1550 setOperationAction(ISD::MLOAD, VT, Legal);
1551 setOperationAction(ISD::MSTORE, VT, Legal);
1554 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1555 MVT VT = (MVT::SimpleValueType)i;
1557 // Do not attempt to promote non-512-bit vectors.
1558 if (!VT.is512BitVector())
1561 setOperationAction(ISD::SELECT, VT, Promote);
1562 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1566 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1567 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1568 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1570 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1571 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1573 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1574 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1575 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1576 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1577 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1578 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1579 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1580 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1581 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1582 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1583 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1584 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Legal);
1585 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Legal);
1586 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1587 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1588 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1589 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1590 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1591 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1592 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1593 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1594 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1595 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1596 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1597 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1598 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1599 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1600 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1601 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1602 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1603 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1605 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1606 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1607 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1608 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1609 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1610 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1611 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1612 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1614 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1615 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1616 if (Subtarget->hasVLX())
1617 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1619 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1620 const MVT VT = (MVT::SimpleValueType)i;
1622 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1624 // Do not attempt to promote non-512-bit vectors.
1625 if (!VT.is512BitVector())
1629 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1630 setOperationAction(ISD::VSELECT, VT, Legal);
1635 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1636 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1637 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1639 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1640 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1641 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1642 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1643 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1644 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1645 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1646 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1647 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1648 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1650 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1651 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1652 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1653 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1654 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1655 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1656 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1657 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1659 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1660 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1661 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1662 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1663 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1664 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1665 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1666 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1669 // We want to custom lower some of our intrinsics.
1670 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1671 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1672 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1673 if (!Subtarget->is64Bit())
1674 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1676 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1677 // handle type legalization for these operations here.
1679 // FIXME: We really should do custom legalization for addition and
1680 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1681 // than generic legalization for 64-bit multiplication-with-overflow, though.
1682 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1683 // Add/Sub/Mul with overflow operations are custom lowered.
1685 setOperationAction(ISD::SADDO, VT, Custom);
1686 setOperationAction(ISD::UADDO, VT, Custom);
1687 setOperationAction(ISD::SSUBO, VT, Custom);
1688 setOperationAction(ISD::USUBO, VT, Custom);
1689 setOperationAction(ISD::SMULO, VT, Custom);
1690 setOperationAction(ISD::UMULO, VT, Custom);
1694 if (!Subtarget->is64Bit()) {
1695 // These libcalls are not available in 32-bit.
1696 setLibcallName(RTLIB::SHL_I128, nullptr);
1697 setLibcallName(RTLIB::SRL_I128, nullptr);
1698 setLibcallName(RTLIB::SRA_I128, nullptr);
1701 // Combine sin / cos into one node or libcall if possible.
1702 if (Subtarget->hasSinCos()) {
1703 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1704 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1705 if (Subtarget->isTargetDarwin()) {
1706 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1707 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1708 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1709 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1713 if (Subtarget->isTargetWin64()) {
1714 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1715 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1716 setOperationAction(ISD::SREM, MVT::i128, Custom);
1717 setOperationAction(ISD::UREM, MVT::i128, Custom);
1718 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1719 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1722 // We have target-specific dag combine patterns for the following nodes:
1723 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1724 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1725 setTargetDAGCombine(ISD::BITCAST);
1726 setTargetDAGCombine(ISD::VSELECT);
1727 setTargetDAGCombine(ISD::SELECT);
1728 setTargetDAGCombine(ISD::SHL);
1729 setTargetDAGCombine(ISD::SRA);
1730 setTargetDAGCombine(ISD::SRL);
1731 setTargetDAGCombine(ISD::OR);
1732 setTargetDAGCombine(ISD::AND);
1733 setTargetDAGCombine(ISD::ADD);
1734 setTargetDAGCombine(ISD::FADD);
1735 setTargetDAGCombine(ISD::FSUB);
1736 setTargetDAGCombine(ISD::FMA);
1737 setTargetDAGCombine(ISD::SUB);
1738 setTargetDAGCombine(ISD::LOAD);
1739 setTargetDAGCombine(ISD::MLOAD);
1740 setTargetDAGCombine(ISD::STORE);
1741 setTargetDAGCombine(ISD::MSTORE);
1742 setTargetDAGCombine(ISD::ZERO_EXTEND);
1743 setTargetDAGCombine(ISD::ANY_EXTEND);
1744 setTargetDAGCombine(ISD::SIGN_EXTEND);
1745 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1746 setTargetDAGCombine(ISD::SINT_TO_FP);
1747 setTargetDAGCombine(ISD::UINT_TO_FP);
1748 setTargetDAGCombine(ISD::SETCC);
1749 setTargetDAGCombine(ISD::BUILD_VECTOR);
1750 setTargetDAGCombine(ISD::MUL);
1751 setTargetDAGCombine(ISD::XOR);
1753 computeRegisterProperties(Subtarget->getRegisterInfo());
1755 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1756 MaxStoresPerMemsetOptSize = 8;
1757 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1758 MaxStoresPerMemcpyOptSize = 4;
1759 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1760 MaxStoresPerMemmoveOptSize = 4;
1761 setPrefLoopAlignment(4); // 2^4 bytes.
1763 // Predictable cmov don't hurt on atom because it's in-order.
1764 PredictableSelectIsExpensive = !Subtarget->isAtom();
1765 EnableExtLdPromotion = true;
1766 setPrefFunctionAlignment(4); // 2^4 bytes.
1768 verifyIntrinsicTables();
1771 // This has so far only been implemented for 64-bit MachO.
1772 bool X86TargetLowering::useLoadStackGuardNode() const {
1773 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1776 TargetLoweringBase::LegalizeTypeAction
1777 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1778 if (ExperimentalVectorWideningLegalization &&
1779 VT.getVectorNumElements() != 1 &&
1780 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1781 return TypeWidenVector;
1783 return TargetLoweringBase::getPreferredVectorAction(VT);
1786 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1789 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1791 const unsigned NumElts = VT.getVectorNumElements();
1792 const EVT EltVT = VT.getVectorElementType();
1793 if (VT.is512BitVector()) {
1794 if (Subtarget->hasAVX512())
1795 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1796 EltVT == MVT::f32 || EltVT == MVT::f64)
1798 case 8: return MVT::v8i1;
1799 case 16: return MVT::v16i1;
1801 if (Subtarget->hasBWI())
1802 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1804 case 32: return MVT::v32i1;
1805 case 64: return MVT::v64i1;
1809 if (VT.is256BitVector() || VT.is128BitVector()) {
1810 if (Subtarget->hasVLX())
1811 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1812 EltVT == MVT::f32 || EltVT == MVT::f64)
1814 case 2: return MVT::v2i1;
1815 case 4: return MVT::v4i1;
1816 case 8: return MVT::v8i1;
1818 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1819 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1821 case 8: return MVT::v8i1;
1822 case 16: return MVT::v16i1;
1823 case 32: return MVT::v32i1;
1827 return VT.changeVectorElementTypeToInteger();
1830 /// Helper for getByValTypeAlignment to determine
1831 /// the desired ByVal argument alignment.
1832 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1835 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1836 if (VTy->getBitWidth() == 128)
1838 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1839 unsigned EltAlign = 0;
1840 getMaxByValAlign(ATy->getElementType(), EltAlign);
1841 if (EltAlign > MaxAlign)
1842 MaxAlign = EltAlign;
1843 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1844 for (auto *EltTy : STy->elements()) {
1845 unsigned EltAlign = 0;
1846 getMaxByValAlign(EltTy, EltAlign);
1847 if (EltAlign > MaxAlign)
1848 MaxAlign = EltAlign;
1855 /// Return the desired alignment for ByVal aggregate
1856 /// function arguments in the caller parameter area. For X86, aggregates
1857 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1858 /// are at 4-byte boundaries.
1859 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1860 const DataLayout &DL) const {
1861 if (Subtarget->is64Bit()) {
1862 // Max of 8 and alignment of type.
1863 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1870 if (Subtarget->hasSSE1())
1871 getMaxByValAlign(Ty, Align);
1875 /// Returns the target specific optimal type for load
1876 /// and store operations as a result of memset, memcpy, and memmove
1877 /// lowering. If DstAlign is zero that means it's safe to destination
1878 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1879 /// means there isn't a need to check it against alignment requirement,
1880 /// probably because the source does not need to be loaded. If 'IsMemset' is
1881 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1882 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1883 /// source is constant so it does not need to be loaded.
1884 /// It returns EVT::Other if the type should be determined using generic
1885 /// target-independent logic.
1887 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1888 unsigned DstAlign, unsigned SrcAlign,
1889 bool IsMemset, bool ZeroMemset,
1891 MachineFunction &MF) const {
1892 const Function *F = MF.getFunction();
1893 if ((!IsMemset || ZeroMemset) &&
1894 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1896 (!Subtarget->isUnalignedMem16Slow() ||
1897 ((DstAlign == 0 || DstAlign >= 16) &&
1898 (SrcAlign == 0 || SrcAlign >= 16)))) {
1900 // FIXME: Check if unaligned 32-byte accesses are slow.
1901 if (Subtarget->hasInt256())
1903 if (Subtarget->hasFp256())
1906 if (Subtarget->hasSSE2())
1908 if (Subtarget->hasSSE1())
1910 } else if (!MemcpyStrSrc && Size >= 8 &&
1911 !Subtarget->is64Bit() &&
1912 Subtarget->hasSSE2()) {
1913 // Do not use f64 to lower memcpy if source is string constant. It's
1914 // better to use i32 to avoid the loads.
1918 // This is a compromise. If we reach here, unaligned accesses may be slow on
1919 // this target. However, creating smaller, aligned accesses could be even
1920 // slower and would certainly be a lot more code.
1921 if (Subtarget->is64Bit() && Size >= 8)
1926 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1928 return X86ScalarSSEf32;
1929 else if (VT == MVT::f64)
1930 return X86ScalarSSEf64;
1935 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1940 switch (VT.getSizeInBits()) {
1942 // 8-byte and under are always assumed to be fast.
1946 *Fast = !Subtarget->isUnalignedMem16Slow();
1949 *Fast = !Subtarget->isUnalignedMem32Slow();
1951 // TODO: What about AVX-512 (512-bit) accesses?
1954 // Misaligned accesses of any size are always allowed.
1958 /// Return the entry encoding for a jump table in the
1959 /// current function. The returned value is a member of the
1960 /// MachineJumpTableInfo::JTEntryKind enum.
1961 unsigned X86TargetLowering::getJumpTableEncoding() const {
1962 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1964 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1965 Subtarget->isPICStyleGOT())
1966 return MachineJumpTableInfo::EK_Custom32;
1968 // Otherwise, use the normal jump table encoding heuristics.
1969 return TargetLowering::getJumpTableEncoding();
1972 bool X86TargetLowering::useSoftFloat() const {
1973 return Subtarget->useSoftFloat();
1977 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1978 const MachineBasicBlock *MBB,
1979 unsigned uid,MCContext &Ctx) const{
1980 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1981 Subtarget->isPICStyleGOT());
1982 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1984 return MCSymbolRefExpr::create(MBB->getSymbol(),
1985 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1988 /// Returns relocation base for the given PIC jumptable.
1989 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1990 SelectionDAG &DAG) const {
1991 if (!Subtarget->is64Bit())
1992 // This doesn't have SDLoc associated with it, but is not really the
1993 // same as a Register.
1994 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1995 getPointerTy(DAG.getDataLayout()));
1999 /// This returns the relocation base for the given PIC jumptable,
2000 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2001 const MCExpr *X86TargetLowering::
2002 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2003 MCContext &Ctx) const {
2004 // X86-64 uses RIP relative addressing based on the jump table label.
2005 if (Subtarget->isPICStyleRIPRel())
2006 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2008 // Otherwise, the reference is relative to the PIC base.
2009 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2012 std::pair<const TargetRegisterClass *, uint8_t>
2013 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2015 const TargetRegisterClass *RRC = nullptr;
2017 switch (VT.SimpleTy) {
2019 return TargetLowering::findRepresentativeClass(TRI, VT);
2020 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2021 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2024 RRC = &X86::VR64RegClass;
2026 case MVT::f32: case MVT::f64:
2027 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2028 case MVT::v4f32: case MVT::v2f64:
2029 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2031 RRC = &X86::VR128RegClass;
2034 return std::make_pair(RRC, Cost);
2037 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2038 unsigned &Offset) const {
2039 if (!Subtarget->isTargetLinux())
2042 if (Subtarget->is64Bit()) {
2043 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2045 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2057 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2058 unsigned DestAS) const {
2059 assert(SrcAS != DestAS && "Expected different address spaces!");
2061 return SrcAS < 256 && DestAS < 256;
2064 //===----------------------------------------------------------------------===//
2065 // Return Value Calling Convention Implementation
2066 //===----------------------------------------------------------------------===//
2068 #include "X86GenCallingConv.inc"
2071 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2072 MachineFunction &MF, bool isVarArg,
2073 const SmallVectorImpl<ISD::OutputArg> &Outs,
2074 LLVMContext &Context) const {
2075 SmallVector<CCValAssign, 16> RVLocs;
2076 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2077 return CCInfo.CheckReturn(Outs, RetCC_X86);
2080 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2081 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2086 X86TargetLowering::LowerReturn(SDValue Chain,
2087 CallingConv::ID CallConv, bool isVarArg,
2088 const SmallVectorImpl<ISD::OutputArg> &Outs,
2089 const SmallVectorImpl<SDValue> &OutVals,
2090 SDLoc dl, SelectionDAG &DAG) const {
2091 MachineFunction &MF = DAG.getMachineFunction();
2092 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2094 SmallVector<CCValAssign, 16> RVLocs;
2095 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2096 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2099 SmallVector<SDValue, 6> RetOps;
2100 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2101 // Operand #1 = Bytes To Pop
2102 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2105 // Copy the result values into the output registers.
2106 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2107 CCValAssign &VA = RVLocs[i];
2108 assert(VA.isRegLoc() && "Can only return in registers!");
2109 SDValue ValToCopy = OutVals[i];
2110 EVT ValVT = ValToCopy.getValueType();
2112 // Promote values to the appropriate types.
2113 if (VA.getLocInfo() == CCValAssign::SExt)
2114 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2115 else if (VA.getLocInfo() == CCValAssign::ZExt)
2116 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2117 else if (VA.getLocInfo() == CCValAssign::AExt) {
2118 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2119 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2121 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2123 else if (VA.getLocInfo() == CCValAssign::BCvt)
2124 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2126 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2127 "Unexpected FP-extend for return value.");
2129 // If this is x86-64, and we disabled SSE, we can't return FP values,
2130 // or SSE or MMX vectors.
2131 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2132 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2133 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2134 report_fatal_error("SSE register return with SSE disabled");
2136 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2137 // llvm-gcc has never done it right and no one has noticed, so this
2138 // should be OK for now.
2139 if (ValVT == MVT::f64 &&
2140 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2141 report_fatal_error("SSE2 register return with SSE2 disabled");
2143 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2144 // the RET instruction and handled by the FP Stackifier.
2145 if (VA.getLocReg() == X86::FP0 ||
2146 VA.getLocReg() == X86::FP1) {
2147 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2148 // change the value to the FP stack register class.
2149 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2150 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2151 RetOps.push_back(ValToCopy);
2152 // Don't emit a copytoreg.
2156 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2157 // which is returned in RAX / RDX.
2158 if (Subtarget->is64Bit()) {
2159 if (ValVT == MVT::x86mmx) {
2160 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2161 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2162 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2164 // If we don't have SSE2 available, convert to v4f32 so the generated
2165 // register is legal.
2166 if (!Subtarget->hasSSE2())
2167 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2172 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2173 Flag = Chain.getValue(1);
2174 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2177 // All x86 ABIs require that for returning structs by value we copy
2178 // the sret argument into %rax/%eax (depending on ABI) for the return.
2179 // We saved the argument into a virtual register in the entry block,
2180 // so now we copy the value out and into %rax/%eax.
2182 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2183 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2184 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2185 // either case FuncInfo->setSRetReturnReg() will have been called.
2186 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2187 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2188 getPointerTy(MF.getDataLayout()));
2191 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2192 X86::RAX : X86::EAX;
2193 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2194 Flag = Chain.getValue(1);
2196 // RAX/EAX now acts like a return value.
2198 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2201 RetOps[0] = Chain; // Update chain.
2203 // Add the flag if we have it.
2205 RetOps.push_back(Flag);
2207 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2210 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2211 if (N->getNumValues() != 1)
2213 if (!N->hasNUsesOfValue(1, 0))
2216 SDValue TCChain = Chain;
2217 SDNode *Copy = *N->use_begin();
2218 if (Copy->getOpcode() == ISD::CopyToReg) {
2219 // If the copy has a glue operand, we conservatively assume it isn't safe to
2220 // perform a tail call.
2221 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2223 TCChain = Copy->getOperand(0);
2224 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2227 bool HasRet = false;
2228 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2230 if (UI->getOpcode() != X86ISD::RET_FLAG)
2232 // If we are returning more than one value, we can definitely
2233 // not make a tail call see PR19530
2234 if (UI->getNumOperands() > 4)
2236 if (UI->getNumOperands() == 4 &&
2237 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2250 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2251 ISD::NodeType ExtendKind) const {
2253 // TODO: Is this also valid on 32-bit?
2254 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2255 ReturnMVT = MVT::i8;
2257 ReturnMVT = MVT::i32;
2259 EVT MinVT = getRegisterType(Context, ReturnMVT);
2260 return VT.bitsLT(MinVT) ? MinVT : VT;
2263 /// Lower the result values of a call into the
2264 /// appropriate copies out of appropriate physical registers.
2267 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2268 CallingConv::ID CallConv, bool isVarArg,
2269 const SmallVectorImpl<ISD::InputArg> &Ins,
2270 SDLoc dl, SelectionDAG &DAG,
2271 SmallVectorImpl<SDValue> &InVals) const {
2273 // Assign locations to each value returned by this call.
2274 SmallVector<CCValAssign, 16> RVLocs;
2275 bool Is64Bit = Subtarget->is64Bit();
2276 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2278 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2280 // Copy all of the result registers out of their specified physreg.
2281 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2282 CCValAssign &VA = RVLocs[i];
2283 EVT CopyVT = VA.getLocVT();
2285 // If this is x86-64, and we disabled SSE, we can't return FP values
2286 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2287 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2288 report_fatal_error("SSE register return with SSE disabled");
2291 // If we prefer to use the value in xmm registers, copy it out as f80 and
2292 // use a truncate to move it from fp stack reg to xmm reg.
2293 bool RoundAfterCopy = false;
2294 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2295 isScalarFPTypeInSSEReg(VA.getValVT())) {
2297 RoundAfterCopy = (CopyVT != VA.getLocVT());
2300 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2301 CopyVT, InFlag).getValue(1);
2302 SDValue Val = Chain.getValue(0);
2305 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2306 // This truncation won't change the value.
2307 DAG.getIntPtrConstant(1, dl));
2309 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2310 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2312 InFlag = Chain.getValue(2);
2313 InVals.push_back(Val);
2319 //===----------------------------------------------------------------------===//
2320 // C & StdCall & Fast Calling Convention implementation
2321 //===----------------------------------------------------------------------===//
2322 // StdCall calling convention seems to be standard for many Windows' API
2323 // routines and around. It differs from C calling convention just a little:
2324 // callee should clean up the stack, not caller. Symbols should be also
2325 // decorated in some fancy way :) It doesn't support any vector arguments.
2326 // For info on fast calling convention see Fast Calling Convention (tail call)
2327 // implementation LowerX86_32FastCCCallTo.
2329 /// CallIsStructReturn - Determines whether a call uses struct return
2331 enum StructReturnType {
2336 static StructReturnType
2337 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2339 return NotStructReturn;
2341 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2342 if (!Flags.isSRet())
2343 return NotStructReturn;
2344 if (Flags.isInReg())
2345 return RegStructReturn;
2346 return StackStructReturn;
2349 /// Determines whether a function uses struct return semantics.
2350 static StructReturnType
2351 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2353 return NotStructReturn;
2355 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2356 if (!Flags.isSRet())
2357 return NotStructReturn;
2358 if (Flags.isInReg())
2359 return RegStructReturn;
2360 return StackStructReturn;
2363 /// Make a copy of an aggregate at address specified by "Src" to address
2364 /// "Dst" with size and alignment information specified by the specific
2365 /// parameter attribute. The copy will be passed as a byval function parameter.
2367 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2368 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2370 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2372 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2373 /*isVolatile*/false, /*AlwaysInline=*/true,
2374 /*isTailCall*/false,
2375 MachinePointerInfo(), MachinePointerInfo());
2378 /// Return true if the calling convention is one that
2379 /// supports tail call optimization.
2380 static bool IsTailCallConvention(CallingConv::ID CC) {
2381 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2382 CC == CallingConv::HiPE);
2385 /// \brief Return true if the calling convention is a C calling convention.
2386 static bool IsCCallConvention(CallingConv::ID CC) {
2387 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2388 CC == CallingConv::X86_64_SysV);
2391 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2393 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2394 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2398 CallingConv::ID CalleeCC = CS.getCallingConv();
2399 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2405 /// Return true if the function is being made into
2406 /// a tailcall target by changing its ABI.
2407 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2408 bool GuaranteedTailCallOpt) {
2409 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2413 X86TargetLowering::LowerMemArgument(SDValue Chain,
2414 CallingConv::ID CallConv,
2415 const SmallVectorImpl<ISD::InputArg> &Ins,
2416 SDLoc dl, SelectionDAG &DAG,
2417 const CCValAssign &VA,
2418 MachineFrameInfo *MFI,
2420 // Create the nodes corresponding to a load from this parameter slot.
2421 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2422 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2423 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2424 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2427 // If value is passed by pointer we have address passed instead of the value
2429 bool ExtendedInMem = VA.isExtInLoc() &&
2430 VA.getValVT().getScalarType() == MVT::i1;
2432 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2433 ValVT = VA.getLocVT();
2435 ValVT = VA.getValVT();
2437 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2438 // changed with more analysis.
2439 // In case of tail call optimization mark all arguments mutable. Since they
2440 // could be overwritten by lowering of arguments in case of a tail call.
2441 if (Flags.isByVal()) {
2442 unsigned Bytes = Flags.getByValSize();
2443 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2444 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2445 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2447 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2448 VA.getLocMemOffset(), isImmutable);
2449 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2450 SDValue Val = DAG.getLoad(
2451 ValVT, dl, Chain, FIN,
2452 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2454 return ExtendedInMem ?
2455 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2459 // FIXME: Get this from tablegen.
2460 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2461 const X86Subtarget *Subtarget) {
2462 assert(Subtarget->is64Bit());
2464 if (Subtarget->isCallingConvWin64(CallConv)) {
2465 static const MCPhysReg GPR64ArgRegsWin64[] = {
2466 X86::RCX, X86::RDX, X86::R8, X86::R9
2468 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2471 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2472 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2474 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2477 // FIXME: Get this from tablegen.
2478 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2479 CallingConv::ID CallConv,
2480 const X86Subtarget *Subtarget) {
2481 assert(Subtarget->is64Bit());
2482 if (Subtarget->isCallingConvWin64(CallConv)) {
2483 // The XMM registers which might contain var arg parameters are shadowed
2484 // in their paired GPR. So we only need to save the GPR to their home
2486 // TODO: __vectorcall will change this.
2490 const Function *Fn = MF.getFunction();
2491 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2492 bool isSoftFloat = Subtarget->useSoftFloat();
2493 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2494 "SSE register cannot be used when SSE is disabled!");
2495 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2496 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2500 static const MCPhysReg XMMArgRegs64Bit[] = {
2501 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2502 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2504 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2508 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2509 CallingConv::ID CallConv,
2511 const SmallVectorImpl<ISD::InputArg> &Ins,
2514 SmallVectorImpl<SDValue> &InVals)
2516 MachineFunction &MF = DAG.getMachineFunction();
2517 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2518 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2520 const Function* Fn = MF.getFunction();
2521 if (Fn->hasExternalLinkage() &&
2522 Subtarget->isTargetCygMing() &&
2523 Fn->getName() == "main")
2524 FuncInfo->setForceFramePointer(true);
2526 MachineFrameInfo *MFI = MF.getFrameInfo();
2527 bool Is64Bit = Subtarget->is64Bit();
2528 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2530 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2531 "Var args not supported with calling convention fastcc, ghc or hipe");
2533 // Assign locations to all of the incoming arguments.
2534 SmallVector<CCValAssign, 16> ArgLocs;
2535 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2537 // Allocate shadow area for Win64
2539 CCInfo.AllocateStack(32, 8);
2541 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2543 unsigned LastVal = ~0U;
2545 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2546 CCValAssign &VA = ArgLocs[i];
2547 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2549 assert(VA.getValNo() != LastVal &&
2550 "Don't support value assigned to multiple locs yet");
2552 LastVal = VA.getValNo();
2554 if (VA.isRegLoc()) {
2555 EVT RegVT = VA.getLocVT();
2556 const TargetRegisterClass *RC;
2557 if (RegVT == MVT::i32)
2558 RC = &X86::GR32RegClass;
2559 else if (Is64Bit && RegVT == MVT::i64)
2560 RC = &X86::GR64RegClass;
2561 else if (RegVT == MVT::f32)
2562 RC = &X86::FR32RegClass;
2563 else if (RegVT == MVT::f64)
2564 RC = &X86::FR64RegClass;
2565 else if (RegVT.is512BitVector())
2566 RC = &X86::VR512RegClass;
2567 else if (RegVT.is256BitVector())
2568 RC = &X86::VR256RegClass;
2569 else if (RegVT.is128BitVector())
2570 RC = &X86::VR128RegClass;
2571 else if (RegVT == MVT::x86mmx)
2572 RC = &X86::VR64RegClass;
2573 else if (RegVT == MVT::i1)
2574 RC = &X86::VK1RegClass;
2575 else if (RegVT == MVT::v8i1)
2576 RC = &X86::VK8RegClass;
2577 else if (RegVT == MVT::v16i1)
2578 RC = &X86::VK16RegClass;
2579 else if (RegVT == MVT::v32i1)
2580 RC = &X86::VK32RegClass;
2581 else if (RegVT == MVT::v64i1)
2582 RC = &X86::VK64RegClass;
2584 llvm_unreachable("Unknown argument type!");
2586 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2587 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2589 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2590 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2592 if (VA.getLocInfo() == CCValAssign::SExt)
2593 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2594 DAG.getValueType(VA.getValVT()));
2595 else if (VA.getLocInfo() == CCValAssign::ZExt)
2596 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2597 DAG.getValueType(VA.getValVT()));
2598 else if (VA.getLocInfo() == CCValAssign::BCvt)
2599 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2601 if (VA.isExtInLoc()) {
2602 // Handle MMX values passed in XMM regs.
2603 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2604 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2606 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2609 assert(VA.isMemLoc());
2610 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2613 // If value is passed via pointer - do a load.
2614 if (VA.getLocInfo() == CCValAssign::Indirect)
2615 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2616 MachinePointerInfo(), false, false, false, 0);
2618 InVals.push_back(ArgValue);
2621 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2622 // All x86 ABIs require that for returning structs by value we copy the
2623 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2624 // the argument into a virtual register so that we can access it from the
2626 if (Ins[i].Flags.isSRet()) {
2627 unsigned Reg = FuncInfo->getSRetReturnReg();
2629 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2630 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2631 FuncInfo->setSRetReturnReg(Reg);
2633 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2634 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2639 unsigned StackSize = CCInfo.getNextStackOffset();
2640 // Align stack specially for tail calls.
2641 if (FuncIsMadeTailCallSafe(CallConv,
2642 MF.getTarget().Options.GuaranteedTailCallOpt))
2643 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2645 // If the function takes variable number of arguments, make a frame index for
2646 // the start of the first vararg value... for expansion of llvm.va_start. We
2647 // can skip this if there are no va_start calls.
2648 if (MFI->hasVAStart() &&
2649 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2650 CallConv != CallingConv::X86_ThisCall))) {
2651 FuncInfo->setVarArgsFrameIndex(
2652 MFI->CreateFixedObject(1, StackSize, true));
2655 MachineModuleInfo &MMI = MF.getMMI();
2656 const Function *WinEHParent = nullptr;
2657 if (MMI.hasWinEHFuncInfo(Fn))
2658 WinEHParent = MMI.getWinEHParent(Fn);
2659 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2660 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2662 // Figure out if XMM registers are in use.
2663 assert(!(Subtarget->useSoftFloat() &&
2664 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2665 "SSE register cannot be used when SSE is disabled!");
2667 // 64-bit calling conventions support varargs and register parameters, so we
2668 // have to do extra work to spill them in the prologue.
2669 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2670 // Find the first unallocated argument registers.
2671 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2672 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2673 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2674 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2675 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2676 "SSE register cannot be used when SSE is disabled!");
2678 // Gather all the live in physical registers.
2679 SmallVector<SDValue, 6> LiveGPRs;
2680 SmallVector<SDValue, 8> LiveXMMRegs;
2682 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2683 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2685 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2687 if (!ArgXMMs.empty()) {
2688 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2689 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2690 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2691 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2692 LiveXMMRegs.push_back(
2693 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2698 // Get to the caller-allocated home save location. Add 8 to account
2699 // for the return address.
2700 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2701 FuncInfo->setRegSaveFrameIndex(
2702 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2703 // Fixup to set vararg frame on shadow area (4 x i64).
2705 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2707 // For X86-64, if there are vararg parameters that are passed via
2708 // registers, then we must store them to their spots on the stack so
2709 // they may be loaded by deferencing the result of va_next.
2710 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2711 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2712 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2713 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2716 // Store the integer parameter registers.
2717 SmallVector<SDValue, 8> MemOps;
2718 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2719 getPointerTy(DAG.getDataLayout()));
2720 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2721 for (SDValue Val : LiveGPRs) {
2722 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2723 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2725 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2726 MachinePointerInfo::getFixedStack(
2727 DAG.getMachineFunction(),
2728 FuncInfo->getRegSaveFrameIndex(), Offset),
2730 MemOps.push_back(Store);
2734 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2735 // Now store the XMM (fp + vector) parameter registers.
2736 SmallVector<SDValue, 12> SaveXMMOps;
2737 SaveXMMOps.push_back(Chain);
2738 SaveXMMOps.push_back(ALVal);
2739 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2740 FuncInfo->getRegSaveFrameIndex(), dl));
2741 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2742 FuncInfo->getVarArgsFPOffset(), dl));
2743 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2745 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2746 MVT::Other, SaveXMMOps));
2749 if (!MemOps.empty())
2750 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2751 } else if (IsWin64 && IsWinEHOutlined) {
2752 // Get to the caller-allocated home save location. Add 8 to account
2753 // for the return address.
2754 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2755 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2756 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2758 MMI.getWinEHFuncInfo(Fn)
2759 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2760 FuncInfo->getRegSaveFrameIndex();
2762 // Store the second integer parameter (rdx) into rsp+16 relative to the
2763 // stack pointer at the entry of the function.
2764 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2765 getPointerTy(DAG.getDataLayout()));
2766 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2767 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2768 Chain = DAG.getStore(
2769 Val.getValue(1), dl, Val, RSFIN,
2770 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2771 FuncInfo->getRegSaveFrameIndex()),
2772 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2775 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2776 // Find the largest legal vector type.
2777 MVT VecVT = MVT::Other;
2778 // FIXME: Only some x86_32 calling conventions support AVX512.
2779 if (Subtarget->hasAVX512() &&
2780 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2781 CallConv == CallingConv::Intel_OCL_BI)))
2782 VecVT = MVT::v16f32;
2783 else if (Subtarget->hasAVX())
2785 else if (Subtarget->hasSSE2())
2788 // We forward some GPRs and some vector types.
2789 SmallVector<MVT, 2> RegParmTypes;
2790 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2791 RegParmTypes.push_back(IntVT);
2792 if (VecVT != MVT::Other)
2793 RegParmTypes.push_back(VecVT);
2795 // Compute the set of forwarded registers. The rest are scratch.
2796 SmallVectorImpl<ForwardedRegister> &Forwards =
2797 FuncInfo->getForwardedMustTailRegParms();
2798 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2800 // Conservatively forward AL on x86_64, since it might be used for varargs.
2801 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2802 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2803 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2806 // Copy all forwards from physical to virtual registers.
2807 for (ForwardedRegister &F : Forwards) {
2808 // FIXME: Can we use a less constrained schedule?
2809 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2810 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2811 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2815 // Some CCs need callee pop.
2816 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2817 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2818 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2820 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2821 // If this is an sret function, the return should pop the hidden pointer.
2822 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2823 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2824 argsAreStructReturn(Ins) == StackStructReturn)
2825 FuncInfo->setBytesToPopOnReturn(4);
2829 // RegSaveFrameIndex is X86-64 only.
2830 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2831 if (CallConv == CallingConv::X86_FastCall ||
2832 CallConv == CallingConv::X86_ThisCall)
2833 // fastcc functions can't have varargs.
2834 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2837 FuncInfo->setArgumentStackSize(StackSize);
2839 if (IsWinEHParent) {
2841 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2842 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2843 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2844 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2845 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2846 MachinePointerInfo::getFixedStack(
2847 DAG.getMachineFunction(), UnwindHelpFI),
2848 /*isVolatile=*/true,
2849 /*isNonTemporal=*/false, /*Alignment=*/0);
2851 // Functions using Win32 EH are considered to have opaque SP adjustments
2852 // to force local variables to be addressed from the frame or base
2854 MFI->setHasOpaqueSPAdjustment(true);
2862 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2863 SDValue StackPtr, SDValue Arg,
2864 SDLoc dl, SelectionDAG &DAG,
2865 const CCValAssign &VA,
2866 ISD::ArgFlagsTy Flags) const {
2867 unsigned LocMemOffset = VA.getLocMemOffset();
2868 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2869 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2871 if (Flags.isByVal())
2872 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2874 return DAG.getStore(
2875 Chain, dl, Arg, PtrOff,
2876 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2880 /// Emit a load of return address if tail call
2881 /// optimization is performed and it is required.
2883 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2884 SDValue &OutRetAddr, SDValue Chain,
2885 bool IsTailCall, bool Is64Bit,
2886 int FPDiff, SDLoc dl) const {
2887 // Adjust the Return address stack slot.
2888 EVT VT = getPointerTy(DAG.getDataLayout());
2889 OutRetAddr = getReturnAddressFrameIndex(DAG);
2891 // Load the "old" Return address.
2892 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2893 false, false, false, 0);
2894 return SDValue(OutRetAddr.getNode(), 1);
2897 /// Emit a store of the return address if tail call
2898 /// optimization is performed and it is required (FPDiff!=0).
2899 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2900 SDValue Chain, SDValue RetAddrFrIdx,
2901 EVT PtrVT, unsigned SlotSize,
2902 int FPDiff, SDLoc dl) {
2903 // Store the return address to the appropriate stack slot.
2904 if (!FPDiff) return Chain;
2905 // Calculate the new stack slot for the return address.
2906 int NewReturnAddrFI =
2907 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2909 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2910 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2911 MachinePointerInfo::getFixedStack(
2912 DAG.getMachineFunction(), NewReturnAddrFI),
2917 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2918 /// operation of specified width.
2919 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2921 unsigned NumElems = VT.getVectorNumElements();
2922 SmallVector<int, 8> Mask;
2923 Mask.push_back(NumElems);
2924 for (unsigned i = 1; i != NumElems; ++i)
2926 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2930 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2931 SmallVectorImpl<SDValue> &InVals) const {
2932 SelectionDAG &DAG = CLI.DAG;
2934 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2935 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2936 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2937 SDValue Chain = CLI.Chain;
2938 SDValue Callee = CLI.Callee;
2939 CallingConv::ID CallConv = CLI.CallConv;
2940 bool &isTailCall = CLI.IsTailCall;
2941 bool isVarArg = CLI.IsVarArg;
2943 MachineFunction &MF = DAG.getMachineFunction();
2944 bool Is64Bit = Subtarget->is64Bit();
2945 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2946 StructReturnType SR = callIsStructReturn(Outs);
2947 bool IsSibcall = false;
2948 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2949 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2951 if (Attr.getValueAsString() == "true")
2954 if (Subtarget->isPICStyleGOT() &&
2955 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2956 // If we are using a GOT, disable tail calls to external symbols with
2957 // default visibility. Tail calling such a symbol requires using a GOT
2958 // relocation, which forces early binding of the symbol. This breaks code
2959 // that require lazy function symbol resolution. Using musttail or
2960 // GuaranteedTailCallOpt will override this.
2961 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2962 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2963 G->getGlobal()->hasDefaultVisibility()))
2967 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2969 // Force this to be a tail call. The verifier rules are enough to ensure
2970 // that we can lower this successfully without moving the return address
2973 } else if (isTailCall) {
2974 // Check if it's really possible to do a tail call.
2975 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2976 isVarArg, SR != NotStructReturn,
2977 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2978 Outs, OutVals, Ins, DAG);
2980 // Sibcalls are automatically detected tailcalls which do not require
2982 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2989 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2990 "Var args not supported with calling convention fastcc, ghc or hipe");
2992 // Analyze operands of the call, assigning locations to each operand.
2993 SmallVector<CCValAssign, 16> ArgLocs;
2994 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2996 // Allocate shadow area for Win64
2998 CCInfo.AllocateStack(32, 8);
3000 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3002 // Get a count of how many bytes are to be pushed on the stack.
3003 unsigned NumBytes = CCInfo.getNextStackOffset();
3005 // This is a sibcall. The memory operands are available in caller's
3006 // own caller's stack.
3008 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3009 IsTailCallConvention(CallConv))
3010 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3013 if (isTailCall && !IsSibcall && !IsMustTail) {
3014 // Lower arguments at fp - stackoffset + fpdiff.
3015 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3017 FPDiff = NumBytesCallerPushed - NumBytes;
3019 // Set the delta of movement of the returnaddr stackslot.
3020 // But only set if delta is greater than previous delta.
3021 if (FPDiff < X86Info->getTCReturnAddrDelta())
3022 X86Info->setTCReturnAddrDelta(FPDiff);
3025 unsigned NumBytesToPush = NumBytes;
3026 unsigned NumBytesToPop = NumBytes;
3028 // If we have an inalloca argument, all stack space has already been allocated
3029 // for us and be right at the top of the stack. We don't support multiple
3030 // arguments passed in memory when using inalloca.
3031 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3033 if (!ArgLocs.back().isMemLoc())
3034 report_fatal_error("cannot use inalloca attribute on a register "
3036 if (ArgLocs.back().getLocMemOffset() != 0)
3037 report_fatal_error("any parameter with the inalloca attribute must be "
3038 "the only memory argument");
3042 Chain = DAG.getCALLSEQ_START(
3043 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3045 SDValue RetAddrFrIdx;
3046 // Load return address for tail calls.
3047 if (isTailCall && FPDiff)
3048 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3049 Is64Bit, FPDiff, dl);
3051 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3052 SmallVector<SDValue, 8> MemOpChains;
3055 // Walk the register/memloc assignments, inserting copies/loads. In the case
3056 // of tail call optimization arguments are handle later.
3057 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3058 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3059 // Skip inalloca arguments, they have already been written.
3060 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3061 if (Flags.isInAlloca())
3064 CCValAssign &VA = ArgLocs[i];
3065 EVT RegVT = VA.getLocVT();
3066 SDValue Arg = OutVals[i];
3067 bool isByVal = Flags.isByVal();
3069 // Promote the value if needed.
3070 switch (VA.getLocInfo()) {
3071 default: llvm_unreachable("Unknown loc info!");
3072 case CCValAssign::Full: break;
3073 case CCValAssign::SExt:
3074 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3076 case CCValAssign::ZExt:
3077 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3079 case CCValAssign::AExt:
3080 if (Arg.getValueType().isVector() &&
3081 Arg.getValueType().getScalarType() == MVT::i1)
3082 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3083 else if (RegVT.is128BitVector()) {
3084 // Special case: passing MMX values in XMM registers.
3085 Arg = DAG.getBitcast(MVT::i64, Arg);
3086 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3087 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3089 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3091 case CCValAssign::BCvt:
3092 Arg = DAG.getBitcast(RegVT, Arg);
3094 case CCValAssign::Indirect: {
3095 // Store the argument.
3096 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3097 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3098 Chain = DAG.getStore(
3099 Chain, dl, Arg, SpillSlot,
3100 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3107 if (VA.isRegLoc()) {
3108 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3109 if (isVarArg && IsWin64) {
3110 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3111 // shadow reg if callee is a varargs function.
3112 unsigned ShadowReg = 0;
3113 switch (VA.getLocReg()) {
3114 case X86::XMM0: ShadowReg = X86::RCX; break;
3115 case X86::XMM1: ShadowReg = X86::RDX; break;
3116 case X86::XMM2: ShadowReg = X86::R8; break;
3117 case X86::XMM3: ShadowReg = X86::R9; break;
3120 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3122 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3123 assert(VA.isMemLoc());
3124 if (!StackPtr.getNode())
3125 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3126 getPointerTy(DAG.getDataLayout()));
3127 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3128 dl, DAG, VA, Flags));
3132 if (!MemOpChains.empty())
3133 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3135 if (Subtarget->isPICStyleGOT()) {
3136 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3139 RegsToPass.push_back(std::make_pair(
3140 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3141 getPointerTy(DAG.getDataLayout()))));
3143 // If we are tail calling and generating PIC/GOT style code load the
3144 // address of the callee into ECX. The value in ecx is used as target of
3145 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3146 // for tail calls on PIC/GOT architectures. Normally we would just put the
3147 // address of GOT into ebx and then call target@PLT. But for tail calls
3148 // ebx would be restored (since ebx is callee saved) before jumping to the
3151 // Note: The actual moving to ECX is done further down.
3152 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3153 if (G && !G->getGlobal()->hasLocalLinkage() &&
3154 G->getGlobal()->hasDefaultVisibility())
3155 Callee = LowerGlobalAddress(Callee, DAG);
3156 else if (isa<ExternalSymbolSDNode>(Callee))
3157 Callee = LowerExternalSymbol(Callee, DAG);
3161 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3162 // From AMD64 ABI document:
3163 // For calls that may call functions that use varargs or stdargs
3164 // (prototype-less calls or calls to functions containing ellipsis (...) in
3165 // the declaration) %al is used as hidden argument to specify the number
3166 // of SSE registers used. The contents of %al do not need to match exactly
3167 // the number of registers, but must be an ubound on the number of SSE
3168 // registers used and is in the range 0 - 8 inclusive.
3170 // Count the number of XMM registers allocated.
3171 static const MCPhysReg XMMArgRegs[] = {
3172 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3173 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3175 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3176 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3177 && "SSE registers cannot be used when SSE is disabled");
3179 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3180 DAG.getConstant(NumXMMRegs, dl,
3184 if (isVarArg && IsMustTail) {
3185 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3186 for (const auto &F : Forwards) {
3187 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3188 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3192 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3193 // don't need this because the eligibility check rejects calls that require
3194 // shuffling arguments passed in memory.
3195 if (!IsSibcall && isTailCall) {
3196 // Force all the incoming stack arguments to be loaded from the stack
3197 // before any new outgoing arguments are stored to the stack, because the
3198 // outgoing stack slots may alias the incoming argument stack slots, and
3199 // the alias isn't otherwise explicit. This is slightly more conservative
3200 // than necessary, because it means that each store effectively depends
3201 // on every argument instead of just those arguments it would clobber.
3202 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3204 SmallVector<SDValue, 8> MemOpChains2;
3207 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3208 CCValAssign &VA = ArgLocs[i];
3211 assert(VA.isMemLoc());
3212 SDValue Arg = OutVals[i];
3213 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3214 // Skip inalloca arguments. They don't require any work.
3215 if (Flags.isInAlloca())
3217 // Create frame index.
3218 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3219 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3220 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3221 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3223 if (Flags.isByVal()) {
3224 // Copy relative to framepointer.
3225 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3226 if (!StackPtr.getNode())
3227 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3228 getPointerTy(DAG.getDataLayout()));
3229 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3232 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3236 // Store relative to framepointer.
3237 MemOpChains2.push_back(DAG.getStore(
3238 ArgChain, dl, Arg, FIN,
3239 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3244 if (!MemOpChains2.empty())
3245 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3247 // Store the return address to the appropriate stack slot.
3248 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3249 getPointerTy(DAG.getDataLayout()),
3250 RegInfo->getSlotSize(), FPDiff, dl);
3253 // Build a sequence of copy-to-reg nodes chained together with token chain
3254 // and flag operands which copy the outgoing args into registers.
3256 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3257 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3258 RegsToPass[i].second, InFlag);
3259 InFlag = Chain.getValue(1);
3262 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3263 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3264 // In the 64-bit large code model, we have to make all calls
3265 // through a register, since the call instruction's 32-bit
3266 // pc-relative offset may not be large enough to hold the whole
3268 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3269 // If the callee is a GlobalAddress node (quite common, every direct call
3270 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3272 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3274 // We should use extra load for direct calls to dllimported functions in
3276 const GlobalValue *GV = G->getGlobal();
3277 if (!GV->hasDLLImportStorageClass()) {
3278 unsigned char OpFlags = 0;
3279 bool ExtraLoad = false;
3280 unsigned WrapperKind = ISD::DELETED_NODE;
3282 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3283 // external symbols most go through the PLT in PIC mode. If the symbol
3284 // has hidden or protected visibility, or if it is static or local, then
3285 // we don't need to use the PLT - we can directly call it.
3286 if (Subtarget->isTargetELF() &&
3287 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3288 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3289 OpFlags = X86II::MO_PLT;
3290 } else if (Subtarget->isPICStyleStubAny() &&
3291 !GV->isStrongDefinitionForLinker() &&
3292 (!Subtarget->getTargetTriple().isMacOSX() ||
3293 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3294 // PC-relative references to external symbols should go through $stub,
3295 // unless we're building with the leopard linker or later, which
3296 // automatically synthesizes these stubs.
3297 OpFlags = X86II::MO_DARWIN_STUB;
3298 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3299 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3300 // If the function is marked as non-lazy, generate an indirect call
3301 // which loads from the GOT directly. This avoids runtime overhead
3302 // at the cost of eager binding (and one extra byte of encoding).
3303 OpFlags = X86II::MO_GOTPCREL;
3304 WrapperKind = X86ISD::WrapperRIP;
3308 Callee = DAG.getTargetGlobalAddress(
3309 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3311 // Add a wrapper if needed.
3312 if (WrapperKind != ISD::DELETED_NODE)
3313 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3314 getPointerTy(DAG.getDataLayout()), Callee);
3315 // Add extra indirection if needed.
3317 Callee = DAG.getLoad(
3318 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3319 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3322 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3323 unsigned char OpFlags = 0;
3325 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3326 // external symbols should go through the PLT.
3327 if (Subtarget->isTargetELF() &&
3328 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3329 OpFlags = X86II::MO_PLT;
3330 } else if (Subtarget->isPICStyleStubAny() &&
3331 (!Subtarget->getTargetTriple().isMacOSX() ||
3332 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3333 // PC-relative references to external symbols should go through $stub,
3334 // unless we're building with the leopard linker or later, which
3335 // automatically synthesizes these stubs.
3336 OpFlags = X86II::MO_DARWIN_STUB;
3339 Callee = DAG.getTargetExternalSymbol(
3340 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3341 } else if (Subtarget->isTarget64BitILP32() &&
3342 Callee->getValueType(0) == MVT::i32) {
3343 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3344 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3347 // Returns a chain & a flag for retval copy to use.
3348 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3349 SmallVector<SDValue, 8> Ops;
3351 if (!IsSibcall && isTailCall) {
3352 Chain = DAG.getCALLSEQ_END(Chain,
3353 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3354 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3355 InFlag = Chain.getValue(1);
3358 Ops.push_back(Chain);
3359 Ops.push_back(Callee);
3362 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3364 // Add argument registers to the end of the list so that they are known live
3366 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3367 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3368 RegsToPass[i].second.getValueType()));
3370 // Add a register mask operand representing the call-preserved registers.
3371 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3372 assert(Mask && "Missing call preserved mask for calling convention");
3374 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3375 // the function clobbers all registers. If an exception is thrown, the runtime
3376 // will not restore CSRs.
3377 // FIXME: Model this more precisely so that we can register allocate across
3378 // the normal edge and spill and fill across the exceptional edge.
3379 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3380 const Function *CallerFn = MF.getFunction();
3381 EHPersonality Pers =
3382 CallerFn->hasPersonalityFn()
3383 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3384 : EHPersonality::Unknown;
3385 if (isMSVCEHPersonality(Pers))
3386 Mask = RegInfo->getNoPreservedMask();
3389 Ops.push_back(DAG.getRegisterMask(Mask));
3391 if (InFlag.getNode())
3392 Ops.push_back(InFlag);
3396 //// If this is the first return lowered for this function, add the regs
3397 //// to the liveout set for the function.
3398 // This isn't right, although it's probably harmless on x86; liveouts
3399 // should be computed from returns not tail calls. Consider a void
3400 // function making a tail call to a function returning int.
3401 MF.getFrameInfo()->setHasTailCall();
3402 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3405 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3406 InFlag = Chain.getValue(1);
3408 // Create the CALLSEQ_END node.
3409 unsigned NumBytesForCalleeToPop;
3410 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3411 DAG.getTarget().Options.GuaranteedTailCallOpt))
3412 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3413 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3414 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3415 SR == StackStructReturn)
3416 // If this is a call to a struct-return function, the callee
3417 // pops the hidden struct pointer, so we have to push it back.
3418 // This is common for Darwin/X86, Linux & Mingw32 targets.
3419 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3420 NumBytesForCalleeToPop = 4;
3422 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3424 // Returns a flag for retval copy to use.
3426 Chain = DAG.getCALLSEQ_END(Chain,
3427 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3428 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3431 InFlag = Chain.getValue(1);
3434 // Handle result values, copying them out of physregs into vregs that we
3436 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3437 Ins, dl, DAG, InVals);
3440 //===----------------------------------------------------------------------===//
3441 // Fast Calling Convention (tail call) implementation
3442 //===----------------------------------------------------------------------===//
3444 // Like std call, callee cleans arguments, convention except that ECX is
3445 // reserved for storing the tail called function address. Only 2 registers are
3446 // free for argument passing (inreg). Tail call optimization is performed
3448 // * tailcallopt is enabled
3449 // * caller/callee are fastcc
3450 // On X86_64 architecture with GOT-style position independent code only local
3451 // (within module) calls are supported at the moment.
3452 // To keep the stack aligned according to platform abi the function
3453 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3454 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3455 // If a tail called function callee has more arguments than the caller the
3456 // caller needs to make sure that there is room to move the RETADDR to. This is
3457 // achieved by reserving an area the size of the argument delta right after the
3458 // original RETADDR, but before the saved framepointer or the spilled registers
3459 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3471 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3474 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3475 SelectionDAG& DAG) const {
3476 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3477 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3478 unsigned StackAlignment = TFI.getStackAlignment();
3479 uint64_t AlignMask = StackAlignment - 1;
3480 int64_t Offset = StackSize;
3481 unsigned SlotSize = RegInfo->getSlotSize();
3482 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3483 // Number smaller than 12 so just add the difference.
3484 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3486 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3487 Offset = ((~AlignMask) & Offset) + StackAlignment +
3488 (StackAlignment-SlotSize);
3493 /// Return true if the given stack call argument is already available in the
3494 /// same position (relatively) of the caller's incoming argument stack.
3496 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3497 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3498 const X86InstrInfo *TII) {
3499 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3501 if (Arg.getOpcode() == ISD::CopyFromReg) {
3502 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3503 if (!TargetRegisterInfo::isVirtualRegister(VR))
3505 MachineInstr *Def = MRI->getVRegDef(VR);
3508 if (!Flags.isByVal()) {
3509 if (!TII->isLoadFromStackSlot(Def, FI))
3512 unsigned Opcode = Def->getOpcode();
3513 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3514 Opcode == X86::LEA64_32r) &&
3515 Def->getOperand(1).isFI()) {
3516 FI = Def->getOperand(1).getIndex();
3517 Bytes = Flags.getByValSize();
3521 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3522 if (Flags.isByVal())
3523 // ByVal argument is passed in as a pointer but it's now being
3524 // dereferenced. e.g.
3525 // define @foo(%struct.X* %A) {
3526 // tail call @bar(%struct.X* byval %A)
3529 SDValue Ptr = Ld->getBasePtr();
3530 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3533 FI = FINode->getIndex();
3534 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3535 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3536 FI = FINode->getIndex();
3537 Bytes = Flags.getByValSize();
3541 assert(FI != INT_MAX);
3542 if (!MFI->isFixedObjectIndex(FI))
3544 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3547 /// Check whether the call is eligible for tail call optimization. Targets
3548 /// that want to do tail call optimization should implement this function.
3550 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3551 CallingConv::ID CalleeCC,
3553 bool isCalleeStructRet,
3554 bool isCallerStructRet,
3556 const SmallVectorImpl<ISD::OutputArg> &Outs,
3557 const SmallVectorImpl<SDValue> &OutVals,
3558 const SmallVectorImpl<ISD::InputArg> &Ins,
3559 SelectionDAG &DAG) const {
3560 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3563 // If -tailcallopt is specified, make fastcc functions tail-callable.
3564 const MachineFunction &MF = DAG.getMachineFunction();
3565 const Function *CallerF = MF.getFunction();
3567 // If the function return type is x86_fp80 and the callee return type is not,
3568 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3569 // perform a tailcall optimization here.
3570 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3573 CallingConv::ID CallerCC = CallerF->getCallingConv();
3574 bool CCMatch = CallerCC == CalleeCC;
3575 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3576 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3578 // Win64 functions have extra shadow space for argument homing. Don't do the
3579 // sibcall if the caller and callee have mismatched expectations for this
3581 if (IsCalleeWin64 != IsCallerWin64)
3584 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3585 if (IsTailCallConvention(CalleeCC) && CCMatch)
3590 // Look for obvious safe cases to perform tail call optimization that do not
3591 // require ABI changes. This is what gcc calls sibcall.
3593 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3594 // emit a special epilogue.
3595 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3596 if (RegInfo->needsStackRealignment(MF))
3599 // Also avoid sibcall optimization if either caller or callee uses struct
3600 // return semantics.
3601 if (isCalleeStructRet || isCallerStructRet)
3604 // An stdcall/thiscall caller is expected to clean up its arguments; the
3605 // callee isn't going to do that.
3606 // FIXME: this is more restrictive than needed. We could produce a tailcall
3607 // when the stack adjustment matches. For example, with a thiscall that takes
3608 // only one argument.
3609 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3610 CallerCC == CallingConv::X86_ThisCall))
3613 // Do not sibcall optimize vararg calls unless all arguments are passed via
3615 if (isVarArg && !Outs.empty()) {
3617 // Optimizing for varargs on Win64 is unlikely to be safe without
3618 // additional testing.
3619 if (IsCalleeWin64 || IsCallerWin64)
3622 SmallVector<CCValAssign, 16> ArgLocs;
3623 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3626 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3627 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3628 if (!ArgLocs[i].isRegLoc())
3632 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3633 // stack. Therefore, if it's not used by the call it is not safe to optimize
3634 // this into a sibcall.
3635 bool Unused = false;
3636 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3643 SmallVector<CCValAssign, 16> RVLocs;
3644 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3646 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3647 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3648 CCValAssign &VA = RVLocs[i];
3649 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3654 // If the calling conventions do not match, then we'd better make sure the
3655 // results are returned in the same way as what the caller expects.
3657 SmallVector<CCValAssign, 16> RVLocs1;
3658 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3660 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3662 SmallVector<CCValAssign, 16> RVLocs2;
3663 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3665 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3667 if (RVLocs1.size() != RVLocs2.size())
3669 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3670 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3672 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3674 if (RVLocs1[i].isRegLoc()) {
3675 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3678 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3684 // If the callee takes no arguments then go on to check the results of the
3686 if (!Outs.empty()) {
3687 // Check if stack adjustment is needed. For now, do not do this if any
3688 // argument is passed on the stack.
3689 SmallVector<CCValAssign, 16> ArgLocs;
3690 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3693 // Allocate shadow area for Win64
3695 CCInfo.AllocateStack(32, 8);
3697 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3698 if (CCInfo.getNextStackOffset()) {
3699 MachineFunction &MF = DAG.getMachineFunction();
3700 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3703 // Check if the arguments are already laid out in the right way as
3704 // the caller's fixed stack objects.
3705 MachineFrameInfo *MFI = MF.getFrameInfo();
3706 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3707 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3708 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3709 CCValAssign &VA = ArgLocs[i];
3710 SDValue Arg = OutVals[i];
3711 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3712 if (VA.getLocInfo() == CCValAssign::Indirect)
3714 if (!VA.isRegLoc()) {
3715 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3722 // If the tailcall address may be in a register, then make sure it's
3723 // possible to register allocate for it. In 32-bit, the call address can
3724 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3725 // callee-saved registers are restored. These happen to be the same
3726 // registers used to pass 'inreg' arguments so watch out for those.
3727 if (!Subtarget->is64Bit() &&
3728 ((!isa<GlobalAddressSDNode>(Callee) &&
3729 !isa<ExternalSymbolSDNode>(Callee)) ||
3730 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3731 unsigned NumInRegs = 0;
3732 // In PIC we need an extra register to formulate the address computation
3734 unsigned MaxInRegs =
3735 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3737 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3738 CCValAssign &VA = ArgLocs[i];
3741 unsigned Reg = VA.getLocReg();
3744 case X86::EAX: case X86::EDX: case X86::ECX:
3745 if (++NumInRegs == MaxInRegs)
3757 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3758 const TargetLibraryInfo *libInfo) const {
3759 return X86::createFastISel(funcInfo, libInfo);
3762 //===----------------------------------------------------------------------===//
3763 // Other Lowering Hooks
3764 //===----------------------------------------------------------------------===//
3766 static bool MayFoldLoad(SDValue Op) {
3767 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3770 static bool MayFoldIntoStore(SDValue Op) {
3771 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3774 static bool isTargetShuffle(unsigned Opcode) {
3776 default: return false;
3777 case X86ISD::BLENDI:
3778 case X86ISD::PSHUFB:
3779 case X86ISD::PSHUFD:
3780 case X86ISD::PSHUFHW:
3781 case X86ISD::PSHUFLW:
3783 case X86ISD::PALIGNR:
3784 case X86ISD::MOVLHPS:
3785 case X86ISD::MOVLHPD:
3786 case X86ISD::MOVHLPS:
3787 case X86ISD::MOVLPS:
3788 case X86ISD::MOVLPD:
3789 case X86ISD::MOVSHDUP:
3790 case X86ISD::MOVSLDUP:
3791 case X86ISD::MOVDDUP:
3794 case X86ISD::UNPCKL:
3795 case X86ISD::UNPCKH:
3796 case X86ISD::VPERMILPI:
3797 case X86ISD::VPERM2X128:
3798 case X86ISD::VPERMI:
3799 case X86ISD::VPERMV:
3800 case X86ISD::VPERMV3:
3805 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3806 SDValue V1, unsigned TargetMask,
3807 SelectionDAG &DAG) {
3809 default: llvm_unreachable("Unknown x86 shuffle node");
3810 case X86ISD::PSHUFD:
3811 case X86ISD::PSHUFHW:
3812 case X86ISD::PSHUFLW:
3813 case X86ISD::VPERMILPI:
3814 case X86ISD::VPERMI:
3815 return DAG.getNode(Opc, dl, VT, V1,
3816 DAG.getConstant(TargetMask, dl, MVT::i8));
3820 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3821 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3823 default: llvm_unreachable("Unknown x86 shuffle node");
3824 case X86ISD::MOVLHPS:
3825 case X86ISD::MOVLHPD:
3826 case X86ISD::MOVHLPS:
3827 case X86ISD::MOVLPS:
3828 case X86ISD::MOVLPD:
3831 case X86ISD::UNPCKL:
3832 case X86ISD::UNPCKH:
3833 return DAG.getNode(Opc, dl, VT, V1, V2);
3837 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3838 MachineFunction &MF = DAG.getMachineFunction();
3839 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3840 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3841 int ReturnAddrIndex = FuncInfo->getRAIndex();
3843 if (ReturnAddrIndex == 0) {
3844 // Set up a frame object for the return address.
3845 unsigned SlotSize = RegInfo->getSlotSize();
3846 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3849 FuncInfo->setRAIndex(ReturnAddrIndex);
3852 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3855 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3856 bool hasSymbolicDisplacement) {
3857 // Offset should fit into 32 bit immediate field.
3858 if (!isInt<32>(Offset))
3861 // If we don't have a symbolic displacement - we don't have any extra
3863 if (!hasSymbolicDisplacement)
3866 // FIXME: Some tweaks might be needed for medium code model.
3867 if (M != CodeModel::Small && M != CodeModel::Kernel)
3870 // For small code model we assume that latest object is 16MB before end of 31
3871 // bits boundary. We may also accept pretty large negative constants knowing
3872 // that all objects are in the positive half of address space.
3873 if (M == CodeModel::Small && Offset < 16*1024*1024)
3876 // For kernel code model we know that all object resist in the negative half
3877 // of 32bits address space. We may not accept negative offsets, since they may
3878 // be just off and we may accept pretty large positive ones.
3879 if (M == CodeModel::Kernel && Offset >= 0)
3885 /// Determines whether the callee is required to pop its own arguments.
3886 /// Callee pop is necessary to support tail calls.
3887 bool X86::isCalleePop(CallingConv::ID CallingConv,
3888 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3889 switch (CallingConv) {
3892 case CallingConv::X86_StdCall:
3893 case CallingConv::X86_FastCall:
3894 case CallingConv::X86_ThisCall:
3896 case CallingConv::Fast:
3897 case CallingConv::GHC:
3898 case CallingConv::HiPE:
3905 /// \brief Return true if the condition is an unsigned comparison operation.
3906 static bool isX86CCUnsigned(unsigned X86CC) {
3908 default: llvm_unreachable("Invalid integer condition!");
3909 case X86::COND_E: return true;
3910 case X86::COND_G: return false;
3911 case X86::COND_GE: return false;
3912 case X86::COND_L: return false;
3913 case X86::COND_LE: return false;
3914 case X86::COND_NE: return true;
3915 case X86::COND_B: return true;
3916 case X86::COND_A: return true;
3917 case X86::COND_BE: return true;
3918 case X86::COND_AE: return true;
3920 llvm_unreachable("covered switch fell through?!");
3923 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3924 /// condition code, returning the condition code and the LHS/RHS of the
3925 /// comparison to make.
3926 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3927 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3929 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3930 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3931 // X > -1 -> X == 0, jump !sign.
3932 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3933 return X86::COND_NS;
3935 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3936 // X < 0 -> X == 0, jump on sign.
3939 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3941 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3942 return X86::COND_LE;
3946 switch (SetCCOpcode) {
3947 default: llvm_unreachable("Invalid integer condition!");
3948 case ISD::SETEQ: return X86::COND_E;
3949 case ISD::SETGT: return X86::COND_G;
3950 case ISD::SETGE: return X86::COND_GE;
3951 case ISD::SETLT: return X86::COND_L;
3952 case ISD::SETLE: return X86::COND_LE;
3953 case ISD::SETNE: return X86::COND_NE;
3954 case ISD::SETULT: return X86::COND_B;
3955 case ISD::SETUGT: return X86::COND_A;
3956 case ISD::SETULE: return X86::COND_BE;
3957 case ISD::SETUGE: return X86::COND_AE;
3961 // First determine if it is required or is profitable to flip the operands.
3963 // If LHS is a foldable load, but RHS is not, flip the condition.
3964 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3965 !ISD::isNON_EXTLoad(RHS.getNode())) {
3966 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3967 std::swap(LHS, RHS);
3970 switch (SetCCOpcode) {
3976 std::swap(LHS, RHS);
3980 // On a floating point condition, the flags are set as follows:
3982 // 0 | 0 | 0 | X > Y
3983 // 0 | 0 | 1 | X < Y
3984 // 1 | 0 | 0 | X == Y
3985 // 1 | 1 | 1 | unordered
3986 switch (SetCCOpcode) {
3987 default: llvm_unreachable("Condcode should be pre-legalized away");
3989 case ISD::SETEQ: return X86::COND_E;
3990 case ISD::SETOLT: // flipped
3992 case ISD::SETGT: return X86::COND_A;
3993 case ISD::SETOLE: // flipped
3995 case ISD::SETGE: return X86::COND_AE;
3996 case ISD::SETUGT: // flipped
3998 case ISD::SETLT: return X86::COND_B;
3999 case ISD::SETUGE: // flipped
4001 case ISD::SETLE: return X86::COND_BE;
4003 case ISD::SETNE: return X86::COND_NE;
4004 case ISD::SETUO: return X86::COND_P;
4005 case ISD::SETO: return X86::COND_NP;
4007 case ISD::SETUNE: return X86::COND_INVALID;
4011 /// Is there a floating point cmov for the specific X86 condition code?
4012 /// Current x86 isa includes the following FP cmov instructions:
4013 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4014 static bool hasFPCMov(unsigned X86CC) {
4030 /// Returns true if the target can instruction select the
4031 /// specified FP immediate natively. If false, the legalizer will
4032 /// materialize the FP immediate as a load from a constant pool.
4033 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4034 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4035 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4041 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4042 ISD::LoadExtType ExtTy,
4044 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4045 // relocation target a movq or addq instruction: don't let the load shrink.
4046 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4047 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4048 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4049 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4053 /// \brief Returns true if it is beneficial to convert a load of a constant
4054 /// to just the constant itself.
4055 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4057 assert(Ty->isIntegerTy());
4059 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4060 if (BitSize == 0 || BitSize > 64)
4065 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4066 unsigned Index) const {
4067 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4070 return (Index == 0 || Index == ResVT.getVectorNumElements());
4073 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4074 // Speculate cttz only if we can directly use TZCNT.
4075 return Subtarget->hasBMI();
4078 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4079 // Speculate ctlz only if we can directly use LZCNT.
4080 return Subtarget->hasLZCNT();
4083 /// Return true if every element in Mask, beginning
4084 /// from position Pos and ending in Pos+Size is undef.
4085 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4086 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4092 /// Return true if Val is undef or if its value falls within the
4093 /// specified range (L, H].
4094 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4095 return (Val < 0) || (Val >= Low && Val < Hi);
4098 /// Val is either less than zero (undef) or equal to the specified value.
4099 static bool isUndefOrEqual(int Val, int CmpVal) {
4100 return (Val < 0 || Val == CmpVal);
4103 /// Return true if every element in Mask, beginning
4104 /// from position Pos and ending in Pos+Size, falls within the specified
4105 /// sequential range (Low, Low+Size]. or is undef.
4106 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4107 unsigned Pos, unsigned Size, int Low) {
4108 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4109 if (!isUndefOrEqual(Mask[i], Low))
4114 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4115 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4116 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4117 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4118 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4121 // The index should be aligned on a vecWidth-bit boundary.
4123 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4125 MVT VT = N->getSimpleValueType(0);
4126 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4127 bool Result = (Index * ElSize) % vecWidth == 0;
4132 /// Return true if the specified INSERT_SUBVECTOR
4133 /// operand specifies a subvector insert that is suitable for input to
4134 /// insertion of 128 or 256-bit subvectors
4135 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4136 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4137 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4139 // The index should be aligned on a vecWidth-bit boundary.
4141 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4143 MVT VT = N->getSimpleValueType(0);
4144 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4145 bool Result = (Index * ElSize) % vecWidth == 0;
4150 bool X86::isVINSERT128Index(SDNode *N) {
4151 return isVINSERTIndex(N, 128);
4154 bool X86::isVINSERT256Index(SDNode *N) {
4155 return isVINSERTIndex(N, 256);
4158 bool X86::isVEXTRACT128Index(SDNode *N) {
4159 return isVEXTRACTIndex(N, 128);
4162 bool X86::isVEXTRACT256Index(SDNode *N) {
4163 return isVEXTRACTIndex(N, 256);
4166 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4167 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4168 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4169 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4172 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4174 MVT VecVT = N->getOperand(0).getSimpleValueType();
4175 MVT ElVT = VecVT.getVectorElementType();
4177 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4178 return Index / NumElemsPerChunk;
4181 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4182 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4183 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4184 llvm_unreachable("Illegal insert subvector for VINSERT");
4187 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4189 MVT VecVT = N->getSimpleValueType(0);
4190 MVT ElVT = VecVT.getVectorElementType();
4192 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4193 return Index / NumElemsPerChunk;
4196 /// Return the appropriate immediate to extract the specified
4197 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4198 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4199 return getExtractVEXTRACTImmediate(N, 128);
4202 /// Return the appropriate immediate to extract the specified
4203 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4204 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4205 return getExtractVEXTRACTImmediate(N, 256);
4208 /// Return the appropriate immediate to insert at the specified
4209 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4210 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4211 return getInsertVINSERTImmediate(N, 128);
4214 /// Return the appropriate immediate to insert at the specified
4215 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4216 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4217 return getInsertVINSERTImmediate(N, 256);
4220 /// Returns true if Elt is a constant integer zero
4221 static bool isZero(SDValue V) {
4222 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4223 return C && C->isNullValue();
4226 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4227 bool X86::isZeroNode(SDValue Elt) {
4230 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4231 return CFP->getValueAPF().isPosZero();
4235 /// Returns a vector of specified type with all zero elements.
4236 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4237 SelectionDAG &DAG, SDLoc dl) {
4238 assert(VT.isVector() && "Expected a vector type");
4240 // Always build SSE zero vectors as <4 x i32> bitcasted
4241 // to their dest type. This ensures they get CSE'd.
4243 if (VT.is128BitVector()) { // SSE
4244 if (Subtarget->hasSSE2()) { // SSE2
4245 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4246 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4248 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4249 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4251 } else if (VT.is256BitVector()) { // AVX
4252 if (Subtarget->hasInt256()) { // AVX2
4253 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4254 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4255 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4257 // 256-bit logic and arithmetic instructions in AVX are all
4258 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4259 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4260 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4261 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4263 } else if (VT.is512BitVector()) { // AVX-512
4264 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4265 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4266 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4267 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4268 } else if (VT.getScalarType() == MVT::i1) {
4270 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4271 && "Unexpected vector type");
4272 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4273 && "Unexpected vector type");
4274 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4275 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4276 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4278 llvm_unreachable("Unexpected vector type");
4280 return DAG.getBitcast(VT, Vec);
4283 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4284 SelectionDAG &DAG, SDLoc dl,
4285 unsigned vectorWidth) {
4286 assert((vectorWidth == 128 || vectorWidth == 256) &&
4287 "Unsupported vector width");
4288 EVT VT = Vec.getValueType();
4289 EVT ElVT = VT.getVectorElementType();
4290 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4291 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4292 VT.getVectorNumElements()/Factor);
4294 // Extract from UNDEF is UNDEF.
4295 if (Vec.getOpcode() == ISD::UNDEF)
4296 return DAG.getUNDEF(ResultVT);
4298 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4299 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4301 // This is the index of the first element of the vectorWidth-bit chunk
4303 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4306 // If the input is a buildvector just emit a smaller one.
4307 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4308 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4309 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4312 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4313 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4316 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4317 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4318 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4319 /// instructions or a simple subregister reference. Idx is an index in the
4320 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4321 /// lowering EXTRACT_VECTOR_ELT operations easier.
4322 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4323 SelectionDAG &DAG, SDLoc dl) {
4324 assert((Vec.getValueType().is256BitVector() ||
4325 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4326 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4329 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4330 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4331 SelectionDAG &DAG, SDLoc dl) {
4332 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4333 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4336 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4337 unsigned IdxVal, SelectionDAG &DAG,
4338 SDLoc dl, unsigned vectorWidth) {
4339 assert((vectorWidth == 128 || vectorWidth == 256) &&
4340 "Unsupported vector width");
4341 // Inserting UNDEF is Result
4342 if (Vec.getOpcode() == ISD::UNDEF)
4344 EVT VT = Vec.getValueType();
4345 EVT ElVT = VT.getVectorElementType();
4346 EVT ResultVT = Result.getValueType();
4348 // Insert the relevant vectorWidth bits.
4349 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4351 // This is the index of the first element of the vectorWidth-bit chunk
4353 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4356 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4357 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4360 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4361 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4362 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4363 /// simple superregister reference. Idx is an index in the 128 bits
4364 /// we want. It need not be aligned to a 128-bit boundary. That makes
4365 /// lowering INSERT_VECTOR_ELT operations easier.
4366 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4367 SelectionDAG &DAG, SDLoc dl) {
4368 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4370 // For insertion into the zero index (low half) of a 256-bit vector, it is
4371 // more efficient to generate a blend with immediate instead of an insert*128.
4372 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4373 // extend the subvector to the size of the result vector. Make sure that
4374 // we are not recursing on that node by checking for undef here.
4375 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4376 Result.getOpcode() != ISD::UNDEF) {
4377 EVT ResultVT = Result.getValueType();
4378 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4379 SDValue Undef = DAG.getUNDEF(ResultVT);
4380 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4383 // The blend instruction, and therefore its mask, depend on the data type.
4384 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4385 if (ScalarType.isFloatingPoint()) {
4386 // Choose either vblendps (float) or vblendpd (double).
4387 unsigned ScalarSize = ScalarType.getSizeInBits();
4388 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4389 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4390 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4391 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4394 const X86Subtarget &Subtarget =
4395 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4397 // AVX2 is needed for 256-bit integer blend support.
4398 // Integers must be cast to 32-bit because there is only vpblendd;
4399 // vpblendw can't be used for this because it has a handicapped mask.
4401 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4402 // is still more efficient than using the wrong domain vinsertf128 that
4403 // will be created by InsertSubVector().
4404 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4406 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4407 Vec256 = DAG.getBitcast(CastVT, Vec256);
4408 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4409 return DAG.getBitcast(ResultVT, Vec256);
4412 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4415 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4416 SelectionDAG &DAG, SDLoc dl) {
4417 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4418 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4421 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4422 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4423 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4424 /// large BUILD_VECTORS.
4425 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4426 unsigned NumElems, SelectionDAG &DAG,
4428 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4429 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4432 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4433 unsigned NumElems, SelectionDAG &DAG,
4435 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4436 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4439 /// Returns a vector of specified type with all bits set.
4440 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4441 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4442 /// Then bitcast to their original type, ensuring they get CSE'd.
4443 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4445 assert(VT.isVector() && "Expected a vector type");
4447 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4449 if (VT.is256BitVector()) {
4450 if (HasInt256) { // AVX2
4451 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4452 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4454 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4455 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4457 } else if (VT.is128BitVector()) {
4458 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4460 llvm_unreachable("Unexpected vector type");
4462 return DAG.getBitcast(VT, Vec);
4465 /// Returns a vector_shuffle node for an unpackl operation.
4466 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4468 unsigned NumElems = VT.getVectorNumElements();
4469 SmallVector<int, 8> Mask;
4470 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4472 Mask.push_back(i + NumElems);
4474 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4477 /// Returns a vector_shuffle node for an unpackh operation.
4478 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4480 unsigned NumElems = VT.getVectorNumElements();
4481 SmallVector<int, 8> Mask;
4482 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4483 Mask.push_back(i + Half);
4484 Mask.push_back(i + NumElems + Half);
4486 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4489 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4490 /// This produces a shuffle where the low element of V2 is swizzled into the
4491 /// zero/undef vector, landing at element Idx.
4492 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4493 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4495 const X86Subtarget *Subtarget,
4496 SelectionDAG &DAG) {
4497 MVT VT = V2.getSimpleValueType();
4499 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4500 unsigned NumElems = VT.getVectorNumElements();
4501 SmallVector<int, 16> MaskVec;
4502 for (unsigned i = 0; i != NumElems; ++i)
4503 // If this is the insertion idx, put the low elt of V2 here.
4504 MaskVec.push_back(i == Idx ? NumElems : i);
4505 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4508 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4509 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4510 /// uses one source. Note that this will set IsUnary for shuffles which use a
4511 /// single input multiple times, and in those cases it will
4512 /// adjust the mask to only have indices within that single input.
4513 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4514 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4515 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4516 unsigned NumElems = VT.getVectorNumElements();
4520 bool IsFakeUnary = false;
4521 switch(N->getOpcode()) {
4522 case X86ISD::BLENDI:
4523 ImmN = N->getOperand(N->getNumOperands()-1);
4524 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4527 ImmN = N->getOperand(N->getNumOperands()-1);
4528 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4531 case X86ISD::UNPCKH:
4532 DecodeUNPCKHMask(VT, Mask);
4533 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4535 case X86ISD::UNPCKL:
4536 DecodeUNPCKLMask(VT, Mask);
4537 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4539 case X86ISD::MOVHLPS:
4540 DecodeMOVHLPSMask(NumElems, Mask);
4541 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4543 case X86ISD::MOVLHPS:
4544 DecodeMOVLHPSMask(NumElems, Mask);
4545 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4547 case X86ISD::PALIGNR:
4548 ImmN = N->getOperand(N->getNumOperands()-1);
4549 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4551 case X86ISD::PSHUFD:
4552 case X86ISD::VPERMILPI:
4553 ImmN = N->getOperand(N->getNumOperands()-1);
4554 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4557 case X86ISD::PSHUFHW:
4558 ImmN = N->getOperand(N->getNumOperands()-1);
4559 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4562 case X86ISD::PSHUFLW:
4563 ImmN = N->getOperand(N->getNumOperands()-1);
4564 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4567 case X86ISD::PSHUFB: {
4569 SDValue MaskNode = N->getOperand(1);
4570 while (MaskNode->getOpcode() == ISD::BITCAST)
4571 MaskNode = MaskNode->getOperand(0);
4573 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4574 // If we have a build-vector, then things are easy.
4575 EVT VT = MaskNode.getValueType();
4576 assert(VT.isVector() &&
4577 "Can't produce a non-vector with a build_vector!");
4578 if (!VT.isInteger())
4581 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4583 SmallVector<uint64_t, 32> RawMask;
4584 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4585 SDValue Op = MaskNode->getOperand(i);
4586 if (Op->getOpcode() == ISD::UNDEF) {
4587 RawMask.push_back((uint64_t)SM_SentinelUndef);
4590 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4593 APInt MaskElement = CN->getAPIntValue();
4595 // We now have to decode the element which could be any integer size and
4596 // extract each byte of it.
4597 for (int j = 0; j < NumBytesPerElement; ++j) {
4598 // Note that this is x86 and so always little endian: the low byte is
4599 // the first byte of the mask.
4600 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4601 MaskElement = MaskElement.lshr(8);
4604 DecodePSHUFBMask(RawMask, Mask);
4608 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4612 SDValue Ptr = MaskLoad->getBasePtr();
4613 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4614 Ptr->getOpcode() == X86ISD::WrapperRIP)
4615 Ptr = Ptr->getOperand(0);
4617 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4618 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4621 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4622 DecodePSHUFBMask(C, Mask);
4630 case X86ISD::VPERMI:
4631 ImmN = N->getOperand(N->getNumOperands()-1);
4632 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4637 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4639 case X86ISD::VPERM2X128:
4640 ImmN = N->getOperand(N->getNumOperands()-1);
4641 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4642 if (Mask.empty()) return false;
4643 // Mask only contains negative index if an element is zero.
4644 if (std::any_of(Mask.begin(), Mask.end(),
4645 [](int M){ return M == SM_SentinelZero; }))
4648 case X86ISD::MOVSLDUP:
4649 DecodeMOVSLDUPMask(VT, Mask);
4652 case X86ISD::MOVSHDUP:
4653 DecodeMOVSHDUPMask(VT, Mask);
4656 case X86ISD::MOVDDUP:
4657 DecodeMOVDDUPMask(VT, Mask);
4660 case X86ISD::MOVLHPD:
4661 case X86ISD::MOVLPD:
4662 case X86ISD::MOVLPS:
4663 // Not yet implemented
4665 case X86ISD::VPERMV: {
4667 SDValue MaskNode = N->getOperand(0);
4668 while (MaskNode->getOpcode() == ISD::BITCAST)
4669 MaskNode = MaskNode->getOperand(0);
4671 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4672 SmallVector<uint64_t, 32> RawMask;
4673 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4674 // If we have a build-vector, then things are easy.
4675 assert(MaskNode.getValueType().isInteger() &&
4676 MaskNode.getValueType().getVectorNumElements() ==
4677 VT.getVectorNumElements());
4679 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4680 SDValue Op = MaskNode->getOperand(i);
4681 if (Op->getOpcode() == ISD::UNDEF)
4682 RawMask.push_back((uint64_t)SM_SentinelUndef);
4683 else if (isa<ConstantSDNode>(Op)) {
4684 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4685 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4689 DecodeVPERMVMask(RawMask, Mask);
4692 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4693 unsigned NumEltsInMask = MaskNode->getNumOperands();
4694 MaskNode = MaskNode->getOperand(0);
4695 auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4697 APInt MaskEltValue = CN->getAPIntValue();
4698 for (unsigned i = 0; i < NumEltsInMask; ++i)
4699 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4700 DecodeVPERMVMask(RawMask, Mask);
4703 // It may be a scalar load
4706 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4710 SDValue Ptr = MaskLoad->getBasePtr();
4711 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4712 Ptr->getOpcode() == X86ISD::WrapperRIP)
4713 Ptr = Ptr->getOperand(0);
4715 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4716 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4719 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4721 DecodeVPERMVMask(C, VT, Mask);
4728 case X86ISD::VPERMV3: {
4730 SDValue MaskNode = N->getOperand(1);
4731 while (MaskNode->getOpcode() == ISD::BITCAST)
4732 MaskNode = MaskNode->getOperand(1);
4734 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4735 // If we have a build-vector, then things are easy.
4736 assert(MaskNode.getValueType().isInteger() &&
4737 MaskNode.getValueType().getVectorNumElements() ==
4738 VT.getVectorNumElements());
4740 SmallVector<uint64_t, 32> RawMask;
4741 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4743 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4744 SDValue Op = MaskNode->getOperand(i);
4745 if (Op->getOpcode() == ISD::UNDEF)
4746 RawMask.push_back((uint64_t)SM_SentinelUndef);
4748 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4751 APInt MaskElement = CN->getAPIntValue();
4752 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4755 DecodeVPERMV3Mask(RawMask, Mask);
4759 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4763 SDValue Ptr = MaskLoad->getBasePtr();
4764 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4765 Ptr->getOpcode() == X86ISD::WrapperRIP)
4766 Ptr = Ptr->getOperand(0);
4768 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4769 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4772 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4774 DecodeVPERMV3Mask(C, VT, Mask);
4781 default: llvm_unreachable("unknown target shuffle node");
4784 // If we have a fake unary shuffle, the shuffle mask is spread across two
4785 // inputs that are actually the same node. Re-map the mask to always point
4786 // into the first input.
4789 if (M >= (int)Mask.size())
4795 /// Returns the scalar element that will make up the ith
4796 /// element of the result of the vector shuffle.
4797 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4800 return SDValue(); // Limit search depth.
4802 SDValue V = SDValue(N, 0);
4803 EVT VT = V.getValueType();
4804 unsigned Opcode = V.getOpcode();
4806 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4807 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4808 int Elt = SV->getMaskElt(Index);
4811 return DAG.getUNDEF(VT.getVectorElementType());
4813 unsigned NumElems = VT.getVectorNumElements();
4814 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4815 : SV->getOperand(1);
4816 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4819 // Recurse into target specific vector shuffles to find scalars.
4820 if (isTargetShuffle(Opcode)) {
4821 MVT ShufVT = V.getSimpleValueType();
4822 unsigned NumElems = ShufVT.getVectorNumElements();
4823 SmallVector<int, 16> ShuffleMask;
4826 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4829 int Elt = ShuffleMask[Index];
4831 return DAG.getUNDEF(ShufVT.getVectorElementType());
4833 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4835 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4839 // Actual nodes that may contain scalar elements
4840 if (Opcode == ISD::BITCAST) {
4841 V = V.getOperand(0);
4842 EVT SrcVT = V.getValueType();
4843 unsigned NumElems = VT.getVectorNumElements();
4845 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4849 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4850 return (Index == 0) ? V.getOperand(0)
4851 : DAG.getUNDEF(VT.getVectorElementType());
4853 if (V.getOpcode() == ISD::BUILD_VECTOR)
4854 return V.getOperand(Index);
4859 /// Custom lower build_vector of v16i8.
4860 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4861 unsigned NumNonZero, unsigned NumZero,
4863 const X86Subtarget* Subtarget,
4864 const TargetLowering &TLI) {
4872 // SSE4.1 - use PINSRB to insert each byte directly.
4873 if (Subtarget->hasSSE41()) {
4874 for (unsigned i = 0; i < 16; ++i) {
4875 bool isNonZero = (NonZeros & (1 << i)) != 0;
4879 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4881 V = DAG.getUNDEF(MVT::v16i8);
4884 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4885 MVT::v16i8, V, Op.getOperand(i),
4886 DAG.getIntPtrConstant(i, dl));
4893 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4894 for (unsigned i = 0; i < 16; ++i) {
4895 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4896 if (ThisIsNonZero && First) {
4898 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4900 V = DAG.getUNDEF(MVT::v8i16);
4905 SDValue ThisElt, LastElt;
4906 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4907 if (LastIsNonZero) {
4908 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4909 MVT::i16, Op.getOperand(i-1));
4911 if (ThisIsNonZero) {
4912 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4913 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4914 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4916 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4920 if (ThisElt.getNode())
4921 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4922 DAG.getIntPtrConstant(i/2, dl));
4926 return DAG.getBitcast(MVT::v16i8, V);
4929 /// Custom lower build_vector of v8i16.
4930 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4931 unsigned NumNonZero, unsigned NumZero,
4933 const X86Subtarget* Subtarget,
4934 const TargetLowering &TLI) {
4941 for (unsigned i = 0; i < 8; ++i) {
4942 bool isNonZero = (NonZeros & (1 << i)) != 0;
4946 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4948 V = DAG.getUNDEF(MVT::v8i16);
4951 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4952 MVT::v8i16, V, Op.getOperand(i),
4953 DAG.getIntPtrConstant(i, dl));
4960 /// Custom lower build_vector of v4i32 or v4f32.
4961 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4962 const X86Subtarget *Subtarget,
4963 const TargetLowering &TLI) {
4964 // Find all zeroable elements.
4965 std::bitset<4> Zeroable;
4966 for (int i=0; i < 4; ++i) {
4967 SDValue Elt = Op->getOperand(i);
4968 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4970 assert(Zeroable.size() - Zeroable.count() > 1 &&
4971 "We expect at least two non-zero elements!");
4973 // We only know how to deal with build_vector nodes where elements are either
4974 // zeroable or extract_vector_elt with constant index.
4975 SDValue FirstNonZero;
4976 unsigned FirstNonZeroIdx;
4977 for (unsigned i=0; i < 4; ++i) {
4980 SDValue Elt = Op->getOperand(i);
4981 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4982 !isa<ConstantSDNode>(Elt.getOperand(1)))
4984 // Make sure that this node is extracting from a 128-bit vector.
4985 MVT VT = Elt.getOperand(0).getSimpleValueType();
4986 if (!VT.is128BitVector())
4988 if (!FirstNonZero.getNode()) {
4990 FirstNonZeroIdx = i;
4994 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4995 SDValue V1 = FirstNonZero.getOperand(0);
4996 MVT VT = V1.getSimpleValueType();
4998 // See if this build_vector can be lowered as a blend with zero.
5000 unsigned EltMaskIdx, EltIdx;
5002 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5003 if (Zeroable[EltIdx]) {
5004 // The zero vector will be on the right hand side.
5005 Mask[EltIdx] = EltIdx+4;
5009 Elt = Op->getOperand(EltIdx);
5010 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5011 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5012 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5014 Mask[EltIdx] = EltIdx;
5018 // Let the shuffle legalizer deal with blend operations.
5019 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5020 if (V1.getSimpleValueType() != VT)
5021 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5022 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5025 // See if we can lower this build_vector to a INSERTPS.
5026 if (!Subtarget->hasSSE41())
5029 SDValue V2 = Elt.getOperand(0);
5030 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5033 bool CanFold = true;
5034 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5038 SDValue Current = Op->getOperand(i);
5039 SDValue SrcVector = Current->getOperand(0);
5042 CanFold = SrcVector == V1 &&
5043 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5049 assert(V1.getNode() && "Expected at least two non-zero elements!");
5050 if (V1.getSimpleValueType() != MVT::v4f32)
5051 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5052 if (V2.getSimpleValueType() != MVT::v4f32)
5053 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5055 // Ok, we can emit an INSERTPS instruction.
5056 unsigned ZMask = Zeroable.to_ulong();
5058 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5059 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5061 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5062 DAG.getIntPtrConstant(InsertPSMask, DL));
5063 return DAG.getBitcast(VT, Result);
5066 /// Return a vector logical shift node.
5067 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5068 unsigned NumBits, SelectionDAG &DAG,
5069 const TargetLowering &TLI, SDLoc dl) {
5070 assert(VT.is128BitVector() && "Unknown type for VShift");
5071 MVT ShVT = MVT::v2i64;
5072 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5073 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5074 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5075 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5076 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5077 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5081 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5083 // Check if the scalar load can be widened into a vector load. And if
5084 // the address is "base + cst" see if the cst can be "absorbed" into
5085 // the shuffle mask.
5086 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5087 SDValue Ptr = LD->getBasePtr();
5088 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5090 EVT PVT = LD->getValueType(0);
5091 if (PVT != MVT::i32 && PVT != MVT::f32)
5096 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5097 FI = FINode->getIndex();
5099 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5100 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5101 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5102 Offset = Ptr.getConstantOperandVal(1);
5103 Ptr = Ptr.getOperand(0);
5108 // FIXME: 256-bit vector instructions don't require a strict alignment,
5109 // improve this code to support it better.
5110 unsigned RequiredAlign = VT.getSizeInBits()/8;
5111 SDValue Chain = LD->getChain();
5112 // Make sure the stack object alignment is at least 16 or 32.
5113 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5114 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5115 if (MFI->isFixedObjectIndex(FI)) {
5116 // Can't change the alignment. FIXME: It's possible to compute
5117 // the exact stack offset and reference FI + adjust offset instead.
5118 // If someone *really* cares about this. That's the way to implement it.
5121 MFI->setObjectAlignment(FI, RequiredAlign);
5125 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5126 // Ptr + (Offset & ~15).
5129 if ((Offset % RequiredAlign) & 3)
5131 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5134 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5135 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5138 int EltNo = (Offset - StartOffset) >> 2;
5139 unsigned NumElems = VT.getVectorNumElements();
5141 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5142 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5143 LD->getPointerInfo().getWithOffset(StartOffset),
5144 false, false, false, 0);
5146 SmallVector<int, 8> Mask(NumElems, EltNo);
5148 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5154 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5155 /// elements can be replaced by a single large load which has the same value as
5156 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5158 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5160 /// FIXME: we'd also like to handle the case where the last elements are zero
5161 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5162 /// There's even a handy isZeroNode for that purpose.
5163 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5164 SDLoc &DL, SelectionDAG &DAG,
5165 bool isAfterLegalize) {
5166 unsigned NumElems = Elts.size();
5168 LoadSDNode *LDBase = nullptr;
5169 unsigned LastLoadedElt = -1U;
5171 // For each element in the initializer, see if we've found a load or an undef.
5172 // If we don't find an initial load element, or later load elements are
5173 // non-consecutive, bail out.
5174 for (unsigned i = 0; i < NumElems; ++i) {
5175 SDValue Elt = Elts[i];
5176 // Look through a bitcast.
5177 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5178 Elt = Elt.getOperand(0);
5179 if (!Elt.getNode() ||
5180 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5183 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5185 LDBase = cast<LoadSDNode>(Elt.getNode());
5189 if (Elt.getOpcode() == ISD::UNDEF)
5192 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5193 EVT LdVT = Elt.getValueType();
5194 // Each loaded element must be the correct fractional portion of the
5195 // requested vector load.
5196 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5198 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5203 // If we have found an entire vector of loads and undefs, then return a large
5204 // load of the entire vector width starting at the base pointer. If we found
5205 // consecutive loads for the low half, generate a vzext_load node.
5206 if (LastLoadedElt == NumElems - 1) {
5207 assert(LDBase && "Did not find base load for merging consecutive loads");
5208 EVT EltVT = LDBase->getValueType(0);
5209 // Ensure that the input vector size for the merged loads matches the
5210 // cumulative size of the input elements.
5211 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5214 if (isAfterLegalize &&
5215 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5218 SDValue NewLd = SDValue();
5220 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5221 LDBase->getPointerInfo(), LDBase->isVolatile(),
5222 LDBase->isNonTemporal(), LDBase->isInvariant(),
5223 LDBase->getAlignment());
5225 if (LDBase->hasAnyUseOfValue(1)) {
5226 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5228 SDValue(NewLd.getNode(), 1));
5229 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5230 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5231 SDValue(NewLd.getNode(), 1));
5237 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5238 //of a v4i32 / v4f32. It's probably worth generalizing.
5239 EVT EltVT = VT.getVectorElementType();
5240 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5241 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5242 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5243 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5245 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5246 LDBase->getPointerInfo(),
5247 LDBase->getAlignment(),
5248 false/*isVolatile*/, true/*ReadMem*/,
5251 // Make sure the newly-created LOAD is in the same position as LDBase in
5252 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5253 // update uses of LDBase's output chain to use the TokenFactor.
5254 if (LDBase->hasAnyUseOfValue(1)) {
5255 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5256 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5257 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5258 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5259 SDValue(ResNode.getNode(), 1));
5262 return DAG.getBitcast(VT, ResNode);
5267 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5268 /// to generate a splat value for the following cases:
5269 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5270 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5271 /// a scalar load, or a constant.
5272 /// The VBROADCAST node is returned when a pattern is found,
5273 /// or SDValue() otherwise.
5274 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5275 SelectionDAG &DAG) {
5276 // VBROADCAST requires AVX.
5277 // TODO: Splats could be generated for non-AVX CPUs using SSE
5278 // instructions, but there's less potential gain for only 128-bit vectors.
5279 if (!Subtarget->hasAVX())
5282 MVT VT = Op.getSimpleValueType();
5285 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5286 "Unsupported vector type for broadcast.");
5291 switch (Op.getOpcode()) {
5293 // Unknown pattern found.
5296 case ISD::BUILD_VECTOR: {
5297 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5298 BitVector UndefElements;
5299 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5301 // We need a splat of a single value to use broadcast, and it doesn't
5302 // make any sense if the value is only in one element of the vector.
5303 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5307 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5308 Ld.getOpcode() == ISD::ConstantFP);
5310 // Make sure that all of the users of a non-constant load are from the
5311 // BUILD_VECTOR node.
5312 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5317 case ISD::VECTOR_SHUFFLE: {
5318 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5320 // Shuffles must have a splat mask where the first element is
5322 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5325 SDValue Sc = Op.getOperand(0);
5326 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5327 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5329 if (!Subtarget->hasInt256())
5332 // Use the register form of the broadcast instruction available on AVX2.
5333 if (VT.getSizeInBits() >= 256)
5334 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5335 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5338 Ld = Sc.getOperand(0);
5339 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5340 Ld.getOpcode() == ISD::ConstantFP);
5342 // The scalar_to_vector node and the suspected
5343 // load node must have exactly one user.
5344 // Constants may have multiple users.
5346 // AVX-512 has register version of the broadcast
5347 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5348 Ld.getValueType().getSizeInBits() >= 32;
5349 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5356 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5357 bool IsGE256 = (VT.getSizeInBits() >= 256);
5359 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5360 // instruction to save 8 or more bytes of constant pool data.
5361 // TODO: If multiple splats are generated to load the same constant,
5362 // it may be detrimental to overall size. There needs to be a way to detect
5363 // that condition to know if this is truly a size win.
5364 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5366 // Handle broadcasting a single constant scalar from the constant pool
5368 // On Sandybridge (no AVX2), it is still better to load a constant vector
5369 // from the constant pool and not to broadcast it from a scalar.
5370 // But override that restriction when optimizing for size.
5371 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5372 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5373 EVT CVT = Ld.getValueType();
5374 assert(!CVT.isVector() && "Must not broadcast a vector type");
5376 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5377 // For size optimization, also splat v2f64 and v2i64, and for size opt
5378 // with AVX2, also splat i8 and i16.
5379 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5380 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5381 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5382 const Constant *C = nullptr;
5383 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5384 C = CI->getConstantIntValue();
5385 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5386 C = CF->getConstantFPValue();
5388 assert(C && "Invalid constant type");
5390 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5392 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5393 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5395 CVT, dl, DAG.getEntryNode(), CP,
5396 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5397 false, false, Alignment);
5399 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5403 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5405 // Handle AVX2 in-register broadcasts.
5406 if (!IsLoad && Subtarget->hasInt256() &&
5407 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5408 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5410 // The scalar source must be a normal load.
5414 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5415 (Subtarget->hasVLX() && ScalarSize == 64))
5416 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5418 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5419 // double since there is no vbroadcastsd xmm
5420 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5421 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5422 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5425 // Unsupported broadcast.
5429 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5430 /// underlying vector and index.
5432 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5434 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5436 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5437 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5440 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5442 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5444 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5445 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5448 // In this case the vector is the extract_subvector expression and the index
5449 // is 2, as specified by the shuffle.
5450 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5451 SDValue ShuffleVec = SVOp->getOperand(0);
5452 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5453 assert(ShuffleVecVT.getVectorElementType() ==
5454 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5456 int ShuffleIdx = SVOp->getMaskElt(Idx);
5457 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5458 ExtractedFromVec = ShuffleVec;
5464 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5465 MVT VT = Op.getSimpleValueType();
5467 // Skip if insert_vec_elt is not supported.
5468 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5469 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5473 unsigned NumElems = Op.getNumOperands();
5477 SmallVector<unsigned, 4> InsertIndices;
5478 SmallVector<int, 8> Mask(NumElems, -1);
5480 for (unsigned i = 0; i != NumElems; ++i) {
5481 unsigned Opc = Op.getOperand(i).getOpcode();
5483 if (Opc == ISD::UNDEF)
5486 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5487 // Quit if more than 1 elements need inserting.
5488 if (InsertIndices.size() > 1)
5491 InsertIndices.push_back(i);
5495 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5496 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5497 // Quit if non-constant index.
5498 if (!isa<ConstantSDNode>(ExtIdx))
5500 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5502 // Quit if extracted from vector of different type.
5503 if (ExtractedFromVec.getValueType() != VT)
5506 if (!VecIn1.getNode())
5507 VecIn1 = ExtractedFromVec;
5508 else if (VecIn1 != ExtractedFromVec) {
5509 if (!VecIn2.getNode())
5510 VecIn2 = ExtractedFromVec;
5511 else if (VecIn2 != ExtractedFromVec)
5512 // Quit if more than 2 vectors to shuffle
5516 if (ExtractedFromVec == VecIn1)
5518 else if (ExtractedFromVec == VecIn2)
5519 Mask[i] = Idx + NumElems;
5522 if (!VecIn1.getNode())
5525 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5526 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5527 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5528 unsigned Idx = InsertIndices[i];
5529 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5530 DAG.getIntPtrConstant(Idx, DL));
5536 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5537 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5538 Op.getScalarValueSizeInBits() == 1 &&
5539 "Can not convert non-constant vector");
5540 uint64_t Immediate = 0;
5541 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5542 SDValue In = Op.getOperand(idx);
5543 if (In.getOpcode() != ISD::UNDEF)
5544 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5548 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5549 return DAG.getConstant(Immediate, dl, VT);
5551 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5553 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5555 MVT VT = Op.getSimpleValueType();
5556 assert((VT.getVectorElementType() == MVT::i1) &&
5557 "Unexpected type in LowerBUILD_VECTORvXi1!");
5560 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5561 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5562 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5563 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5566 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5567 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5568 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5569 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5572 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5573 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5574 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5575 return DAG.getBitcast(VT, Imm);
5576 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5577 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5578 DAG.getIntPtrConstant(0, dl));
5581 // Vector has one or more non-const elements
5582 uint64_t Immediate = 0;
5583 SmallVector<unsigned, 16> NonConstIdx;
5584 bool IsSplat = true;
5585 bool HasConstElts = false;
5587 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5588 SDValue In = Op.getOperand(idx);
5589 if (In.getOpcode() == ISD::UNDEF)
5591 if (!isa<ConstantSDNode>(In))
5592 NonConstIdx.push_back(idx);
5594 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5595 HasConstElts = true;
5599 else if (In != Op.getOperand(SplatIdx))
5603 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5605 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5606 DAG.getConstant(1, dl, VT),
5607 DAG.getConstant(0, dl, VT));
5609 // insert elements one by one
5613 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5614 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5616 else if (HasConstElts)
5617 Imm = DAG.getConstant(0, dl, VT);
5619 Imm = DAG.getUNDEF(VT);
5620 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5621 DstVec = DAG.getBitcast(VT, Imm);
5623 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5624 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5625 DAG.getIntPtrConstant(0, dl));
5628 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5629 unsigned InsertIdx = NonConstIdx[i];
5630 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5631 Op.getOperand(InsertIdx),
5632 DAG.getIntPtrConstant(InsertIdx, dl));
5637 /// \brief Return true if \p N implements a horizontal binop and return the
5638 /// operands for the horizontal binop into V0 and V1.
5640 /// This is a helper function of LowerToHorizontalOp().
5641 /// This function checks that the build_vector \p N in input implements a
5642 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5643 /// operation to match.
5644 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5645 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5646 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5649 /// This function only analyzes elements of \p N whose indices are
5650 /// in range [BaseIdx, LastIdx).
5651 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5653 unsigned BaseIdx, unsigned LastIdx,
5654 SDValue &V0, SDValue &V1) {
5655 EVT VT = N->getValueType(0);
5657 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5658 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5659 "Invalid Vector in input!");
5661 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5662 bool CanFold = true;
5663 unsigned ExpectedVExtractIdx = BaseIdx;
5664 unsigned NumElts = LastIdx - BaseIdx;
5665 V0 = DAG.getUNDEF(VT);
5666 V1 = DAG.getUNDEF(VT);
5668 // Check if N implements a horizontal binop.
5669 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5670 SDValue Op = N->getOperand(i + BaseIdx);
5673 if (Op->getOpcode() == ISD::UNDEF) {
5674 // Update the expected vector extract index.
5675 if (i * 2 == NumElts)
5676 ExpectedVExtractIdx = BaseIdx;
5677 ExpectedVExtractIdx += 2;
5681 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5686 SDValue Op0 = Op.getOperand(0);
5687 SDValue Op1 = Op.getOperand(1);
5689 // Try to match the following pattern:
5690 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5691 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5692 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5693 Op0.getOperand(0) == Op1.getOperand(0) &&
5694 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5695 isa<ConstantSDNode>(Op1.getOperand(1)));
5699 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5700 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5702 if (i * 2 < NumElts) {
5703 if (V0.getOpcode() == ISD::UNDEF) {
5704 V0 = Op0.getOperand(0);
5705 if (V0.getValueType() != VT)
5709 if (V1.getOpcode() == ISD::UNDEF) {
5710 V1 = Op0.getOperand(0);
5711 if (V1.getValueType() != VT)
5714 if (i * 2 == NumElts)
5715 ExpectedVExtractIdx = BaseIdx;
5718 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5719 if (I0 == ExpectedVExtractIdx)
5720 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5721 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5722 // Try to match the following dag sequence:
5723 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5724 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5728 ExpectedVExtractIdx += 2;
5734 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5735 /// a concat_vector.
5737 /// This is a helper function of LowerToHorizontalOp().
5738 /// This function expects two 256-bit vectors called V0 and V1.
5739 /// At first, each vector is split into two separate 128-bit vectors.
5740 /// Then, the resulting 128-bit vectors are used to implement two
5741 /// horizontal binary operations.
5743 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5745 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5746 /// the two new horizontal binop.
5747 /// When Mode is set, the first horizontal binop dag node would take as input
5748 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5749 /// horizontal binop dag node would take as input the lower 128-bit of V1
5750 /// and the upper 128-bit of V1.
5752 /// HADD V0_LO, V0_HI
5753 /// HADD V1_LO, V1_HI
5755 /// Otherwise, the first horizontal binop dag node takes as input the lower
5756 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5757 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5759 /// HADD V0_LO, V1_LO
5760 /// HADD V0_HI, V1_HI
5762 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5763 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5764 /// the upper 128-bits of the result.
5765 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5766 SDLoc DL, SelectionDAG &DAG,
5767 unsigned X86Opcode, bool Mode,
5768 bool isUndefLO, bool isUndefHI) {
5769 EVT VT = V0.getValueType();
5770 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5771 "Invalid nodes in input!");
5773 unsigned NumElts = VT.getVectorNumElements();
5774 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5775 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5776 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5777 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5778 EVT NewVT = V0_LO.getValueType();
5780 SDValue LO = DAG.getUNDEF(NewVT);
5781 SDValue HI = DAG.getUNDEF(NewVT);
5784 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5785 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5786 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5787 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5788 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5790 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5791 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5792 V1_LO->getOpcode() != ISD::UNDEF))
5793 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5795 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5796 V1_HI->getOpcode() != ISD::UNDEF))
5797 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5800 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5803 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5805 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5806 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5807 EVT VT = BV->getValueType(0);
5808 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5809 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5813 unsigned NumElts = VT.getVectorNumElements();
5814 SDValue InVec0 = DAG.getUNDEF(VT);
5815 SDValue InVec1 = DAG.getUNDEF(VT);
5817 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5818 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5820 // Odd-numbered elements in the input build vector are obtained from
5821 // adding two integer/float elements.
5822 // Even-numbered elements in the input build vector are obtained from
5823 // subtracting two integer/float elements.
5824 unsigned ExpectedOpcode = ISD::FSUB;
5825 unsigned NextExpectedOpcode = ISD::FADD;
5826 bool AddFound = false;
5827 bool SubFound = false;
5829 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5830 SDValue Op = BV->getOperand(i);
5832 // Skip 'undef' values.
5833 unsigned Opcode = Op.getOpcode();
5834 if (Opcode == ISD::UNDEF) {
5835 std::swap(ExpectedOpcode, NextExpectedOpcode);
5839 // Early exit if we found an unexpected opcode.
5840 if (Opcode != ExpectedOpcode)
5843 SDValue Op0 = Op.getOperand(0);
5844 SDValue Op1 = Op.getOperand(1);
5846 // Try to match the following pattern:
5847 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5848 // Early exit if we cannot match that sequence.
5849 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5850 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5851 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5852 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5853 Op0.getOperand(1) != Op1.getOperand(1))
5856 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5860 // We found a valid add/sub node. Update the information accordingly.
5866 // Update InVec0 and InVec1.
5867 if (InVec0.getOpcode() == ISD::UNDEF) {
5868 InVec0 = Op0.getOperand(0);
5869 if (InVec0.getValueType() != VT)
5872 if (InVec1.getOpcode() == ISD::UNDEF) {
5873 InVec1 = Op1.getOperand(0);
5874 if (InVec1.getValueType() != VT)
5878 // Make sure that operands in input to each add/sub node always
5879 // come from a same pair of vectors.
5880 if (InVec0 != Op0.getOperand(0)) {
5881 if (ExpectedOpcode == ISD::FSUB)
5884 // FADD is commutable. Try to commute the operands
5885 // and then test again.
5886 std::swap(Op0, Op1);
5887 if (InVec0 != Op0.getOperand(0))
5891 if (InVec1 != Op1.getOperand(0))
5894 // Update the pair of expected opcodes.
5895 std::swap(ExpectedOpcode, NextExpectedOpcode);
5898 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5899 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5900 InVec1.getOpcode() != ISD::UNDEF)
5901 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5906 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5907 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5908 const X86Subtarget *Subtarget,
5909 SelectionDAG &DAG) {
5910 EVT VT = BV->getValueType(0);
5911 unsigned NumElts = VT.getVectorNumElements();
5912 unsigned NumUndefsLO = 0;
5913 unsigned NumUndefsHI = 0;
5914 unsigned Half = NumElts/2;
5916 // Count the number of UNDEF operands in the build_vector in input.
5917 for (unsigned i = 0, e = Half; i != e; ++i)
5918 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5921 for (unsigned i = Half, e = NumElts; i != e; ++i)
5922 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5925 // Early exit if this is either a build_vector of all UNDEFs or all the
5926 // operands but one are UNDEF.
5927 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5931 SDValue InVec0, InVec1;
5932 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5933 // Try to match an SSE3 float HADD/HSUB.
5934 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5935 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5937 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5938 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5939 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5940 // Try to match an SSSE3 integer HADD/HSUB.
5941 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5942 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5944 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5945 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5948 if (!Subtarget->hasAVX())
5951 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5952 // Try to match an AVX horizontal add/sub of packed single/double
5953 // precision floating point values from 256-bit vectors.
5954 SDValue InVec2, InVec3;
5955 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5956 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5957 ((InVec0.getOpcode() == ISD::UNDEF ||
5958 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5959 ((InVec1.getOpcode() == ISD::UNDEF ||
5960 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5961 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5963 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5964 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5965 ((InVec0.getOpcode() == ISD::UNDEF ||
5966 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5967 ((InVec1.getOpcode() == ISD::UNDEF ||
5968 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5969 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5970 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5971 // Try to match an AVX2 horizontal add/sub of signed integers.
5972 SDValue InVec2, InVec3;
5974 bool CanFold = true;
5976 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5977 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5978 ((InVec0.getOpcode() == ISD::UNDEF ||
5979 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5980 ((InVec1.getOpcode() == ISD::UNDEF ||
5981 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5982 X86Opcode = X86ISD::HADD;
5983 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5984 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5985 ((InVec0.getOpcode() == ISD::UNDEF ||
5986 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5987 ((InVec1.getOpcode() == ISD::UNDEF ||
5988 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5989 X86Opcode = X86ISD::HSUB;
5994 // Fold this build_vector into a single horizontal add/sub.
5995 // Do this only if the target has AVX2.
5996 if (Subtarget->hasAVX2())
5997 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5999 // Do not try to expand this build_vector into a pair of horizontal
6000 // add/sub if we can emit a pair of scalar add/sub.
6001 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6004 // Convert this build_vector into a pair of horizontal binop followed by
6006 bool isUndefLO = NumUndefsLO == Half;
6007 bool isUndefHI = NumUndefsHI == Half;
6008 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6009 isUndefLO, isUndefHI);
6013 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6014 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6016 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6017 X86Opcode = X86ISD::HADD;
6018 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6019 X86Opcode = X86ISD::HSUB;
6020 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6021 X86Opcode = X86ISD::FHADD;
6022 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6023 X86Opcode = X86ISD::FHSUB;
6027 // Don't try to expand this build_vector into a pair of horizontal add/sub
6028 // if we can simply emit a pair of scalar add/sub.
6029 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6032 // Convert this build_vector into two horizontal add/sub followed by
6034 bool isUndefLO = NumUndefsLO == Half;
6035 bool isUndefHI = NumUndefsHI == Half;
6036 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6037 isUndefLO, isUndefHI);
6044 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6047 MVT VT = Op.getSimpleValueType();
6048 MVT ExtVT = VT.getVectorElementType();
6049 unsigned NumElems = Op.getNumOperands();
6051 // Generate vectors for predicate vectors.
6052 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6053 return LowerBUILD_VECTORvXi1(Op, DAG);
6055 // Vectors containing all zeros can be matched by pxor and xorps later
6056 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6057 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6058 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6059 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6062 return getZeroVector(VT, Subtarget, DAG, dl);
6065 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6066 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6067 // vpcmpeqd on 256-bit vectors.
6068 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6069 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6072 if (!VT.is512BitVector())
6073 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6076 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6077 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6079 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6080 return HorizontalOp;
6081 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6084 unsigned EVTBits = ExtVT.getSizeInBits();
6086 unsigned NumZero = 0;
6087 unsigned NumNonZero = 0;
6088 unsigned NonZeros = 0;
6089 bool IsAllConstants = true;
6090 SmallSet<SDValue, 8> Values;
6091 for (unsigned i = 0; i < NumElems; ++i) {
6092 SDValue Elt = Op.getOperand(i);
6093 if (Elt.getOpcode() == ISD::UNDEF)
6096 if (Elt.getOpcode() != ISD::Constant &&
6097 Elt.getOpcode() != ISD::ConstantFP)
6098 IsAllConstants = false;
6099 if (X86::isZeroNode(Elt))
6102 NonZeros |= (1 << i);
6107 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6108 if (NumNonZero == 0)
6109 return DAG.getUNDEF(VT);
6111 // Special case for single non-zero, non-undef, element.
6112 if (NumNonZero == 1) {
6113 unsigned Idx = countTrailingZeros(NonZeros);
6114 SDValue Item = Op.getOperand(Idx);
6116 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6117 // the value are obviously zero, truncate the value to i32 and do the
6118 // insertion that way. Only do this if the value is non-constant or if the
6119 // value is a constant being inserted into element 0. It is cheaper to do
6120 // a constant pool load than it is to do a movd + shuffle.
6121 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6122 (!IsAllConstants || Idx == 0)) {
6123 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6125 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6126 EVT VecVT = MVT::v4i32;
6128 // Truncate the value (which may itself be a constant) to i32, and
6129 // convert it to a vector with movd (S2V+shuffle to zero extend).
6130 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6131 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6132 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6133 Item, Idx * 2, true, Subtarget, DAG));
6137 // If we have a constant or non-constant insertion into the low element of
6138 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6139 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6140 // depending on what the source datatype is.
6143 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6145 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6146 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6147 if (VT.is512BitVector()) {
6148 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6149 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6150 Item, DAG.getIntPtrConstant(0, dl));
6152 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6153 "Expected an SSE value type!");
6154 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6155 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6156 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6159 // We can't directly insert an i8 or i16 into a vector, so zero extend
6161 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6162 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6163 if (VT.is256BitVector()) {
6164 if (Subtarget->hasAVX()) {
6165 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6166 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6168 // Without AVX, we need to extend to a 128-bit vector and then
6169 // insert into the 256-bit vector.
6170 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6171 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6172 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6175 assert(VT.is128BitVector() && "Expected an SSE value type!");
6176 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6177 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6179 return DAG.getBitcast(VT, Item);
6183 // Is it a vector logical left shift?
6184 if (NumElems == 2 && Idx == 1 &&
6185 X86::isZeroNode(Op.getOperand(0)) &&
6186 !X86::isZeroNode(Op.getOperand(1))) {
6187 unsigned NumBits = VT.getSizeInBits();
6188 return getVShift(true, VT,
6189 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6190 VT, Op.getOperand(1)),
6191 NumBits/2, DAG, *this, dl);
6194 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6197 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6198 // is a non-constant being inserted into an element other than the low one,
6199 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6200 // movd/movss) to move this into the low element, then shuffle it into
6202 if (EVTBits == 32) {
6203 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6204 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6208 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6209 if (Values.size() == 1) {
6210 if (EVTBits == 32) {
6211 // Instead of a shuffle like this:
6212 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6213 // Check if it's possible to issue this instead.
6214 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6215 unsigned Idx = countTrailingZeros(NonZeros);
6216 SDValue Item = Op.getOperand(Idx);
6217 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6218 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6223 // A vector full of immediates; various special cases are already
6224 // handled, so this is best done with a single constant-pool load.
6228 // For AVX-length vectors, see if we can use a vector load to get all of the
6229 // elements, otherwise build the individual 128-bit pieces and use
6230 // shuffles to put them in place.
6231 if (VT.is256BitVector() || VT.is512BitVector()) {
6232 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6234 // Check for a build vector of consecutive loads.
6235 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6238 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6240 // Build both the lower and upper subvector.
6241 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6242 makeArrayRef(&V[0], NumElems/2));
6243 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6244 makeArrayRef(&V[NumElems / 2], NumElems/2));
6246 // Recreate the wider vector with the lower and upper part.
6247 if (VT.is256BitVector())
6248 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6249 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6252 // Let legalizer expand 2-wide build_vectors.
6253 if (EVTBits == 64) {
6254 if (NumNonZero == 1) {
6255 // One half is zero or undef.
6256 unsigned Idx = countTrailingZeros(NonZeros);
6257 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6258 Op.getOperand(Idx));
6259 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6264 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6265 if (EVTBits == 8 && NumElems == 16)
6266 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6270 if (EVTBits == 16 && NumElems == 8)
6271 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6275 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6276 if (EVTBits == 32 && NumElems == 4)
6277 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6280 // If element VT is == 32 bits, turn it into a number of shuffles.
6281 SmallVector<SDValue, 8> V(NumElems);
6282 if (NumElems == 4 && NumZero > 0) {
6283 for (unsigned i = 0; i < 4; ++i) {
6284 bool isZero = !(NonZeros & (1 << i));
6286 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6288 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6291 for (unsigned i = 0; i < 2; ++i) {
6292 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6295 V[i] = V[i*2]; // Must be a zero vector.
6298 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6301 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6304 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6309 bool Reverse1 = (NonZeros & 0x3) == 2;
6310 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6314 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6315 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6317 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6320 if (Values.size() > 1 && VT.is128BitVector()) {
6321 // Check for a build vector of consecutive loads.
6322 for (unsigned i = 0; i < NumElems; ++i)
6323 V[i] = Op.getOperand(i);
6325 // Check for elements which are consecutive loads.
6326 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6329 // Check for a build vector from mostly shuffle plus few inserting.
6330 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6333 // For SSE 4.1, use insertps to put the high elements into the low element.
6334 if (Subtarget->hasSSE41()) {
6336 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6337 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6339 Result = DAG.getUNDEF(VT);
6341 for (unsigned i = 1; i < NumElems; ++i) {
6342 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6343 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6344 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6349 // Otherwise, expand into a number of unpckl*, start by extending each of
6350 // our (non-undef) elements to the full vector width with the element in the
6351 // bottom slot of the vector (which generates no code for SSE).
6352 for (unsigned i = 0; i < NumElems; ++i) {
6353 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6354 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6356 V[i] = DAG.getUNDEF(VT);
6359 // Next, we iteratively mix elements, e.g. for v4f32:
6360 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6361 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6362 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6363 unsigned EltStride = NumElems >> 1;
6364 while (EltStride != 0) {
6365 for (unsigned i = 0; i < EltStride; ++i) {
6366 // If V[i+EltStride] is undef and this is the first round of mixing,
6367 // then it is safe to just drop this shuffle: V[i] is already in the
6368 // right place, the one element (since it's the first round) being
6369 // inserted as undef can be dropped. This isn't safe for successive
6370 // rounds because they will permute elements within both vectors.
6371 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6372 EltStride == NumElems/2)
6375 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6384 // 256-bit AVX can use the vinsertf128 instruction
6385 // to create 256-bit vectors from two other 128-bit ones.
6386 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6388 MVT ResVT = Op.getSimpleValueType();
6390 assert((ResVT.is256BitVector() ||
6391 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6393 SDValue V1 = Op.getOperand(0);
6394 SDValue V2 = Op.getOperand(1);
6395 unsigned NumElems = ResVT.getVectorNumElements();
6396 if (ResVT.is256BitVector())
6397 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6399 if (Op.getNumOperands() == 4) {
6400 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6401 ResVT.getVectorNumElements()/2);
6402 SDValue V3 = Op.getOperand(2);
6403 SDValue V4 = Op.getOperand(3);
6404 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6405 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6407 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6410 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6411 const X86Subtarget *Subtarget,
6412 SelectionDAG & DAG) {
6414 MVT ResVT = Op.getSimpleValueType();
6415 unsigned NumOfOperands = Op.getNumOperands();
6417 assert(isPowerOf2_32(NumOfOperands) &&
6418 "Unexpected number of operands in CONCAT_VECTORS");
6420 if (NumOfOperands > 2) {
6421 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6422 ResVT.getVectorNumElements()/2);
6423 SmallVector<SDValue, 2> Ops;
6424 for (unsigned i = 0; i < NumOfOperands/2; i++)
6425 Ops.push_back(Op.getOperand(i));
6426 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6428 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6429 Ops.push_back(Op.getOperand(i));
6430 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6431 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6434 SDValue V1 = Op.getOperand(0);
6435 SDValue V2 = Op.getOperand(1);
6436 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6437 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6439 if (IsZeroV1 && IsZeroV2)
6440 return getZeroVector(ResVT, Subtarget, DAG, dl);
6442 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6443 SDValue Undef = DAG.getUNDEF(ResVT);
6444 unsigned NumElems = ResVT.getVectorNumElements();
6445 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6447 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6448 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6452 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6453 // Zero the upper bits of V1
6454 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6455 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6458 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6461 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6462 const X86Subtarget *Subtarget,
6463 SelectionDAG &DAG) {
6464 MVT VT = Op.getSimpleValueType();
6465 if (VT.getVectorElementType() == MVT::i1)
6466 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6468 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6469 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6470 Op.getNumOperands() == 4)));
6472 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6473 // from two other 128-bit ones.
6475 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6476 return LowerAVXCONCAT_VECTORS(Op, DAG);
6480 //===----------------------------------------------------------------------===//
6481 // Vector shuffle lowering
6483 // This is an experimental code path for lowering vector shuffles on x86. It is
6484 // designed to handle arbitrary vector shuffles and blends, gracefully
6485 // degrading performance as necessary. It works hard to recognize idiomatic
6486 // shuffles and lower them to optimal instruction patterns without leaving
6487 // a framework that allows reasonably efficient handling of all vector shuffle
6489 //===----------------------------------------------------------------------===//
6491 /// \brief Tiny helper function to identify a no-op mask.
6493 /// This is a somewhat boring predicate function. It checks whether the mask
6494 /// array input, which is assumed to be a single-input shuffle mask of the kind
6495 /// used by the X86 shuffle instructions (not a fully general
6496 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6497 /// in-place shuffle are 'no-op's.
6498 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6499 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6500 if (Mask[i] != -1 && Mask[i] != i)
6505 /// \brief Helper function to classify a mask as a single-input mask.
6507 /// This isn't a generic single-input test because in the vector shuffle
6508 /// lowering we canonicalize single inputs to be the first input operand. This
6509 /// means we can more quickly test for a single input by only checking whether
6510 /// an input from the second operand exists. We also assume that the size of
6511 /// mask corresponds to the size of the input vectors which isn't true in the
6512 /// fully general case.
6513 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6515 if (M >= (int)Mask.size())
6520 /// \brief Test whether there are elements crossing 128-bit lanes in this
6523 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6524 /// and we routinely test for these.
6525 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6526 int LaneSize = 128 / VT.getScalarSizeInBits();
6527 int Size = Mask.size();
6528 for (int i = 0; i < Size; ++i)
6529 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6534 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6536 /// This checks a shuffle mask to see if it is performing the same
6537 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6538 /// that it is also not lane-crossing. It may however involve a blend from the
6539 /// same lane of a second vector.
6541 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6542 /// non-trivial to compute in the face of undef lanes. The representation is
6543 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6544 /// entries from both V1 and V2 inputs to the wider mask.
6546 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6547 SmallVectorImpl<int> &RepeatedMask) {
6548 int LaneSize = 128 / VT.getScalarSizeInBits();
6549 RepeatedMask.resize(LaneSize, -1);
6550 int Size = Mask.size();
6551 for (int i = 0; i < Size; ++i) {
6554 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6555 // This entry crosses lanes, so there is no way to model this shuffle.
6558 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6559 if (RepeatedMask[i % LaneSize] == -1)
6560 // This is the first non-undef entry in this slot of a 128-bit lane.
6561 RepeatedMask[i % LaneSize] =
6562 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6563 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6564 // Found a mismatch with the repeated mask.
6570 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6573 /// This is a fast way to test a shuffle mask against a fixed pattern:
6575 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6577 /// It returns true if the mask is exactly as wide as the argument list, and
6578 /// each element of the mask is either -1 (signifying undef) or the value given
6579 /// in the argument.
6580 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6581 ArrayRef<int> ExpectedMask) {
6582 if (Mask.size() != ExpectedMask.size())
6585 int Size = Mask.size();
6587 // If the values are build vectors, we can look through them to find
6588 // equivalent inputs that make the shuffles equivalent.
6589 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6590 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6592 for (int i = 0; i < Size; ++i)
6593 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6594 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6595 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6596 if (!MaskBV || !ExpectedBV ||
6597 MaskBV->getOperand(Mask[i] % Size) !=
6598 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6605 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6607 /// This helper function produces an 8-bit shuffle immediate corresponding to
6608 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6609 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6612 /// NB: We rely heavily on "undef" masks preserving the input lane.
6613 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6614 SelectionDAG &DAG) {
6615 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6616 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6617 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6618 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6619 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6622 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6623 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6624 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6625 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6626 return DAG.getConstant(Imm, DL, MVT::i8);
6629 /// \brief Compute whether each element of a shuffle is zeroable.
6631 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6632 /// Either it is an undef element in the shuffle mask, the element of the input
6633 /// referenced is undef, or the element of the input referenced is known to be
6634 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6635 /// as many lanes with this technique as possible to simplify the remaining
6637 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6638 SDValue V1, SDValue V2) {
6639 SmallBitVector Zeroable(Mask.size(), false);
6641 while (V1.getOpcode() == ISD::BITCAST)
6642 V1 = V1->getOperand(0);
6643 while (V2.getOpcode() == ISD::BITCAST)
6644 V2 = V2->getOperand(0);
6646 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6647 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6649 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6651 // Handle the easy cases.
6652 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6657 // If this is an index into a build_vector node (which has the same number
6658 // of elements), dig out the input value and use it.
6659 SDValue V = M < Size ? V1 : V2;
6660 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6663 SDValue Input = V.getOperand(M % Size);
6664 // The UNDEF opcode check really should be dead code here, but not quite
6665 // worth asserting on (it isn't invalid, just unexpected).
6666 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6673 /// \brief Try to emit a bitmask instruction for a shuffle.
6675 /// This handles cases where we can model a blend exactly as a bitmask due to
6676 /// one of the inputs being zeroable.
6677 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6678 SDValue V2, ArrayRef<int> Mask,
6679 SelectionDAG &DAG) {
6680 MVT EltVT = VT.getScalarType();
6681 int NumEltBits = EltVT.getSizeInBits();
6682 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6683 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6684 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6686 if (EltVT.isFloatingPoint()) {
6687 Zero = DAG.getBitcast(EltVT, Zero);
6688 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6690 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6691 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6693 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6696 if (Mask[i] % Size != i)
6697 return SDValue(); // Not a blend.
6699 V = Mask[i] < Size ? V1 : V2;
6700 else if (V != (Mask[i] < Size ? V1 : V2))
6701 return SDValue(); // Can only let one input through the mask.
6703 VMaskOps[i] = AllOnes;
6706 return SDValue(); // No non-zeroable elements!
6708 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6709 V = DAG.getNode(VT.isFloatingPoint()
6710 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6715 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6717 /// This is used as a fallback approach when first class blend instructions are
6718 /// unavailable. Currently it is only suitable for integer vectors, but could
6719 /// be generalized for floating point vectors if desirable.
6720 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6721 SDValue V2, ArrayRef<int> Mask,
6722 SelectionDAG &DAG) {
6723 assert(VT.isInteger() && "Only supports integer vector types!");
6724 MVT EltVT = VT.getScalarType();
6725 int NumEltBits = EltVT.getSizeInBits();
6726 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6727 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6729 SmallVector<SDValue, 16> MaskOps;
6730 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6731 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6732 return SDValue(); // Shuffled input!
6733 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6736 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6737 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6738 // We have to cast V2 around.
6739 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6740 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6741 DAG.getBitcast(MaskVT, V1Mask),
6742 DAG.getBitcast(MaskVT, V2)));
6743 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6746 /// \brief Try to emit a blend instruction for a shuffle.
6748 /// This doesn't do any checks for the availability of instructions for blending
6749 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6750 /// be matched in the backend with the type given. What it does check for is
6751 /// that the shuffle mask is in fact a blend.
6752 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6753 SDValue V2, ArrayRef<int> Mask,
6754 const X86Subtarget *Subtarget,
6755 SelectionDAG &DAG) {
6756 unsigned BlendMask = 0;
6757 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6758 if (Mask[i] >= Size) {
6759 if (Mask[i] != i + Size)
6760 return SDValue(); // Shuffled V2 input!
6761 BlendMask |= 1u << i;
6764 if (Mask[i] >= 0 && Mask[i] != i)
6765 return SDValue(); // Shuffled V1 input!
6767 switch (VT.SimpleTy) {
6772 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6773 DAG.getConstant(BlendMask, DL, MVT::i8));
6777 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6781 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6782 // that instruction.
6783 if (Subtarget->hasAVX2()) {
6784 // Scale the blend by the number of 32-bit dwords per element.
6785 int Scale = VT.getScalarSizeInBits() / 32;
6787 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6788 if (Mask[i] >= Size)
6789 for (int j = 0; j < Scale; ++j)
6790 BlendMask |= 1u << (i * Scale + j);
6792 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6793 V1 = DAG.getBitcast(BlendVT, V1);
6794 V2 = DAG.getBitcast(BlendVT, V2);
6795 return DAG.getBitcast(
6796 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6797 DAG.getConstant(BlendMask, DL, MVT::i8)));
6801 // For integer shuffles we need to expand the mask and cast the inputs to
6802 // v8i16s prior to blending.
6803 int Scale = 8 / VT.getVectorNumElements();
6805 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6806 if (Mask[i] >= Size)
6807 for (int j = 0; j < Scale; ++j)
6808 BlendMask |= 1u << (i * Scale + j);
6810 V1 = DAG.getBitcast(MVT::v8i16, V1);
6811 V2 = DAG.getBitcast(MVT::v8i16, V2);
6812 return DAG.getBitcast(VT,
6813 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6814 DAG.getConstant(BlendMask, DL, MVT::i8)));
6818 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6819 SmallVector<int, 8> RepeatedMask;
6820 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6821 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6822 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6824 for (int i = 0; i < 8; ++i)
6825 if (RepeatedMask[i] >= 16)
6826 BlendMask |= 1u << i;
6827 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6828 DAG.getConstant(BlendMask, DL, MVT::i8));
6834 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6835 "256-bit byte-blends require AVX2 support!");
6837 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6838 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6841 // Scale the blend by the number of bytes per element.
6842 int Scale = VT.getScalarSizeInBits() / 8;
6844 // This form of blend is always done on bytes. Compute the byte vector
6846 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6848 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6849 // mix of LLVM's code generator and the x86 backend. We tell the code
6850 // generator that boolean values in the elements of an x86 vector register
6851 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6852 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6853 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6854 // of the element (the remaining are ignored) and 0 in that high bit would
6855 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6856 // the LLVM model for boolean values in vector elements gets the relevant
6857 // bit set, it is set backwards and over constrained relative to x86's
6859 SmallVector<SDValue, 32> VSELECTMask;
6860 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6861 for (int j = 0; j < Scale; ++j)
6862 VSELECTMask.push_back(
6863 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6864 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6867 V1 = DAG.getBitcast(BlendVT, V1);
6868 V2 = DAG.getBitcast(BlendVT, V2);
6869 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6870 DAG.getNode(ISD::BUILD_VECTOR, DL,
6871 BlendVT, VSELECTMask),
6876 llvm_unreachable("Not a supported integer vector type!");
6880 /// \brief Try to lower as a blend of elements from two inputs followed by
6881 /// a single-input permutation.
6883 /// This matches the pattern where we can blend elements from two inputs and
6884 /// then reduce the shuffle to a single-input permutation.
6885 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6888 SelectionDAG &DAG) {
6889 // We build up the blend mask while checking whether a blend is a viable way
6890 // to reduce the shuffle.
6891 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6892 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6894 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6898 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6900 if (BlendMask[Mask[i] % Size] == -1)
6901 BlendMask[Mask[i] % Size] = Mask[i];
6902 else if (BlendMask[Mask[i] % Size] != Mask[i])
6903 return SDValue(); // Can't blend in the needed input!
6905 PermuteMask[i] = Mask[i] % Size;
6908 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6909 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6912 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6913 /// blends and permutes.
6915 /// This matches the extremely common pattern for handling combined
6916 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6917 /// operations. It will try to pick the best arrangement of shuffles and
6919 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6923 SelectionDAG &DAG) {
6924 // Shuffle the input elements into the desired positions in V1 and V2 and
6925 // blend them together.
6926 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6927 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6928 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6929 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6930 if (Mask[i] >= 0 && Mask[i] < Size) {
6931 V1Mask[i] = Mask[i];
6933 } else if (Mask[i] >= Size) {
6934 V2Mask[i] = Mask[i] - Size;
6935 BlendMask[i] = i + Size;
6938 // Try to lower with the simpler initial blend strategy unless one of the
6939 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6940 // shuffle may be able to fold with a load or other benefit. However, when
6941 // we'll have to do 2x as many shuffles in order to achieve this, blending
6942 // first is a better strategy.
6943 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6944 if (SDValue BlendPerm =
6945 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6948 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6949 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6950 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6953 /// \brief Try to lower a vector shuffle as a byte rotation.
6955 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6956 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6957 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6958 /// try to generically lower a vector shuffle through such an pattern. It
6959 /// does not check for the profitability of lowering either as PALIGNR or
6960 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6961 /// This matches shuffle vectors that look like:
6963 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6965 /// Essentially it concatenates V1 and V2, shifts right by some number of
6966 /// elements, and takes the low elements as the result. Note that while this is
6967 /// specified as a *right shift* because x86 is little-endian, it is a *left
6968 /// rotate* of the vector lanes.
6969 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6972 const X86Subtarget *Subtarget,
6973 SelectionDAG &DAG) {
6974 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6976 int NumElts = Mask.size();
6977 int NumLanes = VT.getSizeInBits() / 128;
6978 int NumLaneElts = NumElts / NumLanes;
6980 // We need to detect various ways of spelling a rotation:
6981 // [11, 12, 13, 14, 15, 0, 1, 2]
6982 // [-1, 12, 13, 14, -1, -1, 1, -1]
6983 // [-1, -1, -1, -1, -1, -1, 1, 2]
6984 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6985 // [-1, 4, 5, 6, -1, -1, 9, -1]
6986 // [-1, 4, 5, 6, -1, -1, -1, -1]
6989 for (int l = 0; l < NumElts; l += NumLaneElts) {
6990 for (int i = 0; i < NumLaneElts; ++i) {
6991 if (Mask[l + i] == -1)
6993 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6995 // Get the mod-Size index and lane correct it.
6996 int LaneIdx = (Mask[l + i] % NumElts) - l;
6997 // Make sure it was in this lane.
6998 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7001 // Determine where a rotated vector would have started.
7002 int StartIdx = i - LaneIdx;
7004 // The identity rotation isn't interesting, stop.
7007 // If we found the tail of a vector the rotation must be the missing
7008 // front. If we found the head of a vector, it must be how much of the
7010 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7013 Rotation = CandidateRotation;
7014 else if (Rotation != CandidateRotation)
7015 // The rotations don't match, so we can't match this mask.
7018 // Compute which value this mask is pointing at.
7019 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7021 // Compute which of the two target values this index should be assigned
7022 // to. This reflects whether the high elements are remaining or the low
7023 // elements are remaining.
7024 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7026 // Either set up this value if we've not encountered it before, or check
7027 // that it remains consistent.
7030 else if (TargetV != MaskV)
7031 // This may be a rotation, but it pulls from the inputs in some
7032 // unsupported interleaving.
7037 // Check that we successfully analyzed the mask, and normalize the results.
7038 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7039 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7045 // The actual rotate instruction rotates bytes, so we need to scale the
7046 // rotation based on how many bytes are in the vector lane.
7047 int Scale = 16 / NumLaneElts;
7049 // SSSE3 targets can use the palignr instruction.
7050 if (Subtarget->hasSSSE3()) {
7051 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7052 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7053 Lo = DAG.getBitcast(AlignVT, Lo);
7054 Hi = DAG.getBitcast(AlignVT, Hi);
7056 return DAG.getBitcast(
7057 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7058 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7061 assert(VT.getSizeInBits() == 128 &&
7062 "Rotate-based lowering only supports 128-bit lowering!");
7063 assert(Mask.size() <= 16 &&
7064 "Can shuffle at most 16 bytes in a 128-bit vector!");
7066 // Default SSE2 implementation
7067 int LoByteShift = 16 - Rotation * Scale;
7068 int HiByteShift = Rotation * Scale;
7070 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7071 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7072 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7074 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7075 DAG.getConstant(LoByteShift, DL, MVT::i8));
7076 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7077 DAG.getConstant(HiByteShift, DL, MVT::i8));
7078 return DAG.getBitcast(VT,
7079 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7082 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7084 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7085 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7086 /// matches elements from one of the input vectors shuffled to the left or
7087 /// right with zeroable elements 'shifted in'. It handles both the strictly
7088 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7091 /// PSHL : (little-endian) left bit shift.
7092 /// [ zz, 0, zz, 2 ]
7093 /// [ -1, 4, zz, -1 ]
7094 /// PSRL : (little-endian) right bit shift.
7096 /// [ -1, -1, 7, zz]
7097 /// PSLLDQ : (little-endian) left byte shift
7098 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7099 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7100 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7101 /// PSRLDQ : (little-endian) right byte shift
7102 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7103 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7104 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7105 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7106 SDValue V2, ArrayRef<int> Mask,
7107 SelectionDAG &DAG) {
7108 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7110 int Size = Mask.size();
7111 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7113 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7114 for (int i = 0; i < Size; i += Scale)
7115 for (int j = 0; j < Shift; ++j)
7116 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7122 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7123 for (int i = 0; i != Size; i += Scale) {
7124 unsigned Pos = Left ? i + Shift : i;
7125 unsigned Low = Left ? i : i + Shift;
7126 unsigned Len = Scale - Shift;
7127 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7128 Low + (V == V1 ? 0 : Size)))
7132 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7133 bool ByteShift = ShiftEltBits > 64;
7134 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7135 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7136 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7138 // Normalize the scale for byte shifts to still produce an i64 element
7140 Scale = ByteShift ? Scale / 2 : Scale;
7142 // We need to round trip through the appropriate type for the shift.
7143 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7144 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7145 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7146 "Illegal integer vector type");
7147 V = DAG.getBitcast(ShiftVT, V);
7149 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7150 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7151 return DAG.getBitcast(VT, V);
7154 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7155 // keep doubling the size of the integer elements up to that. We can
7156 // then shift the elements of the integer vector by whole multiples of
7157 // their width within the elements of the larger integer vector. Test each
7158 // multiple to see if we can find a match with the moved element indices
7159 // and that the shifted in elements are all zeroable.
7160 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7161 for (int Shift = 1; Shift != Scale; ++Shift)
7162 for (bool Left : {true, false})
7163 if (CheckZeros(Shift, Scale, Left))
7164 for (SDValue V : {V1, V2})
7165 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7172 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7173 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7174 SDValue V2, ArrayRef<int> Mask,
7175 SelectionDAG &DAG) {
7176 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7177 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7179 int Size = Mask.size();
7180 int HalfSize = Size / 2;
7181 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7183 // Upper half must be undefined.
7184 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7187 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7188 // Remainder of lower half result is zero and upper half is all undef.
7189 auto LowerAsEXTRQ = [&]() {
7190 // Determine the extraction length from the part of the
7191 // lower half that isn't zeroable.
7193 for (; Len >= 0; --Len)
7194 if (!Zeroable[Len - 1])
7196 assert(Len > 0 && "Zeroable shuffle mask");
7198 // Attempt to match first Len sequential elements from the lower half.
7201 for (int i = 0; i != Len; ++i) {
7205 SDValue &V = (M < Size ? V1 : V2);
7208 // All mask elements must be in the lower half.
7212 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7223 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7224 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7225 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7226 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7227 DAG.getConstant(BitLen, DL, MVT::i8),
7228 DAG.getConstant(BitIdx, DL, MVT::i8));
7231 if (SDValue ExtrQ = LowerAsEXTRQ())
7234 // INSERTQ: Extract lowest Len elements from lower half of second source and
7235 // insert over first source, starting at Idx.
7236 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7237 auto LowerAsInsertQ = [&]() {
7238 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7241 // Attempt to match first source from mask before insertion point.
7242 if (isUndefInRange(Mask, 0, Idx)) {
7244 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7246 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7252 // Extend the extraction length looking to match both the insertion of
7253 // the second source and the remaining elements of the first.
7254 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7259 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7261 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7267 // Match the remaining elements of the lower half.
7268 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7270 } else if ((!Base || (Base == V1)) &&
7271 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7273 } else if ((!Base || (Base == V2)) &&
7274 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7281 // We may not have a base (first source) - this can safely be undefined.
7283 Base = DAG.getUNDEF(VT);
7285 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7286 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7287 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7288 DAG.getConstant(BitLen, DL, MVT::i8),
7289 DAG.getConstant(BitIdx, DL, MVT::i8));
7296 if (SDValue InsertQ = LowerAsInsertQ())
7302 /// \brief Lower a vector shuffle as a zero or any extension.
7304 /// Given a specific number of elements, element bit width, and extension
7305 /// stride, produce either a zero or any extension based on the available
7306 /// features of the subtarget.
7307 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7308 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7309 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7310 assert(Scale > 1 && "Need a scale to extend.");
7311 int NumElements = VT.getVectorNumElements();
7312 int EltBits = VT.getScalarSizeInBits();
7313 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7314 "Only 8, 16, and 32 bit elements can be extended.");
7315 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7317 // Found a valid zext mask! Try various lowering strategies based on the
7318 // input type and available ISA extensions.
7319 if (Subtarget->hasSSE41()) {
7320 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7321 NumElements / Scale);
7322 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7325 // For any extends we can cheat for larger element sizes and use shuffle
7326 // instructions that can fold with a load and/or copy.
7327 if (AnyExt && EltBits == 32) {
7328 int PSHUFDMask[4] = {0, -1, 1, -1};
7329 return DAG.getBitcast(
7330 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7331 DAG.getBitcast(MVT::v4i32, InputV),
7332 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7334 if (AnyExt && EltBits == 16 && Scale > 2) {
7335 int PSHUFDMask[4] = {0, -1, 0, -1};
7336 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7337 DAG.getBitcast(MVT::v4i32, InputV),
7338 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7339 int PSHUFHWMask[4] = {1, -1, -1, -1};
7340 return DAG.getBitcast(
7341 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7342 DAG.getBitcast(MVT::v8i16, InputV),
7343 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7346 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7348 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7349 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7350 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7352 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7353 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7354 DAG.getConstant(EltBits, DL, MVT::i8),
7355 DAG.getConstant(0, DL, MVT::i8)));
7356 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7357 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7360 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7361 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7362 DAG.getConstant(EltBits, DL, MVT::i8),
7363 DAG.getConstant(EltBits, DL, MVT::i8)));
7364 return DAG.getNode(ISD::BITCAST, DL, VT,
7365 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7368 // If this would require more than 2 unpack instructions to expand, use
7369 // pshufb when available. We can only use more than 2 unpack instructions
7370 // when zero extending i8 elements which also makes it easier to use pshufb.
7371 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7372 assert(NumElements == 16 && "Unexpected byte vector width!");
7373 SDValue PSHUFBMask[16];
7374 for (int i = 0; i < 16; ++i)
7376 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7377 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7378 return DAG.getBitcast(VT,
7379 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7380 DAG.getNode(ISD::BUILD_VECTOR, DL,
7381 MVT::v16i8, PSHUFBMask)));
7384 // Otherwise emit a sequence of unpacks.
7386 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7387 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7388 : getZeroVector(InputVT, Subtarget, DAG, DL);
7389 InputV = DAG.getBitcast(InputVT, InputV);
7390 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7394 } while (Scale > 1);
7395 return DAG.getBitcast(VT, InputV);
7398 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7400 /// This routine will try to do everything in its power to cleverly lower
7401 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7402 /// check for the profitability of this lowering, it tries to aggressively
7403 /// match this pattern. It will use all of the micro-architectural details it
7404 /// can to emit an efficient lowering. It handles both blends with all-zero
7405 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7406 /// masking out later).
7408 /// The reason we have dedicated lowering for zext-style shuffles is that they
7409 /// are both incredibly common and often quite performance sensitive.
7410 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7411 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7412 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7413 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7415 int Bits = VT.getSizeInBits();
7416 int NumElements = VT.getVectorNumElements();
7417 assert(VT.getScalarSizeInBits() <= 32 &&
7418 "Exceeds 32-bit integer zero extension limit");
7419 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7421 // Define a helper function to check a particular ext-scale and lower to it if
7423 auto Lower = [&](int Scale) -> SDValue {
7426 for (int i = 0; i < NumElements; ++i) {
7428 continue; // Valid anywhere but doesn't tell us anything.
7429 if (i % Scale != 0) {
7430 // Each of the extended elements need to be zeroable.
7434 // We no longer are in the anyext case.
7439 // Each of the base elements needs to be consecutive indices into the
7440 // same input vector.
7441 SDValue V = Mask[i] < NumElements ? V1 : V2;
7444 else if (InputV != V)
7445 return SDValue(); // Flip-flopping inputs.
7447 if (Mask[i] % NumElements != i / Scale)
7448 return SDValue(); // Non-consecutive strided elements.
7451 // If we fail to find an input, we have a zero-shuffle which should always
7452 // have already been handled.
7453 // FIXME: Maybe handle this here in case during blending we end up with one?
7457 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7458 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7461 // The widest scale possible for extending is to a 64-bit integer.
7462 assert(Bits % 64 == 0 &&
7463 "The number of bits in a vector must be divisible by 64 on x86!");
7464 int NumExtElements = Bits / 64;
7466 // Each iteration, try extending the elements half as much, but into twice as
7468 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7469 assert(NumElements % NumExtElements == 0 &&
7470 "The input vector size must be divisible by the extended size.");
7471 if (SDValue V = Lower(NumElements / NumExtElements))
7475 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7479 // Returns one of the source operands if the shuffle can be reduced to a
7480 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7481 auto CanZExtLowHalf = [&]() {
7482 for (int i = NumElements / 2; i != NumElements; ++i)
7485 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7487 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7492 if (SDValue V = CanZExtLowHalf()) {
7493 V = DAG.getBitcast(MVT::v2i64, V);
7494 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7495 return DAG.getBitcast(VT, V);
7498 // No viable ext lowering found.
7502 /// \brief Try to get a scalar value for a specific element of a vector.
7504 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7505 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7506 SelectionDAG &DAG) {
7507 MVT VT = V.getSimpleValueType();
7508 MVT EltVT = VT.getVectorElementType();
7509 while (V.getOpcode() == ISD::BITCAST)
7510 V = V.getOperand(0);
7511 // If the bitcasts shift the element size, we can't extract an equivalent
7513 MVT NewVT = V.getSimpleValueType();
7514 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7517 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7518 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7519 // Ensure the scalar operand is the same size as the destination.
7520 // FIXME: Add support for scalar truncation where possible.
7521 SDValue S = V.getOperand(Idx);
7522 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7523 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7529 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7531 /// This is particularly important because the set of instructions varies
7532 /// significantly based on whether the operand is a load or not.
7533 static bool isShuffleFoldableLoad(SDValue V) {
7534 while (V.getOpcode() == ISD::BITCAST)
7535 V = V.getOperand(0);
7537 return ISD::isNON_EXTLoad(V.getNode());
7540 /// \brief Try to lower insertion of a single element into a zero vector.
7542 /// This is a common pattern that we have especially efficient patterns to lower
7543 /// across all subtarget feature sets.
7544 static SDValue lowerVectorShuffleAsElementInsertion(
7545 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7546 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7547 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7549 MVT EltVT = VT.getVectorElementType();
7551 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7552 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7554 bool IsV1Zeroable = true;
7555 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7556 if (i != V2Index && !Zeroable[i]) {
7557 IsV1Zeroable = false;
7561 // Check for a single input from a SCALAR_TO_VECTOR node.
7562 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7563 // all the smarts here sunk into that routine. However, the current
7564 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7565 // vector shuffle lowering is dead.
7566 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7568 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7569 // We need to zext the scalar if it is smaller than an i32.
7570 V2S = DAG.getBitcast(EltVT, V2S);
7571 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7572 // Using zext to expand a narrow element won't work for non-zero
7577 // Zero-extend directly to i32.
7579 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7581 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7582 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7583 EltVT == MVT::i16) {
7584 // Either not inserting from the low element of the input or the input
7585 // element size is too small to use VZEXT_MOVL to clear the high bits.
7589 if (!IsV1Zeroable) {
7590 // If V1 can't be treated as a zero vector we have fewer options to lower
7591 // this. We can't support integer vectors or non-zero targets cheaply, and
7592 // the V1 elements can't be permuted in any way.
7593 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7594 if (!VT.isFloatingPoint() || V2Index != 0)
7596 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7597 V1Mask[V2Index] = -1;
7598 if (!isNoopShuffleMask(V1Mask))
7600 // This is essentially a special case blend operation, but if we have
7601 // general purpose blend operations, they are always faster. Bail and let
7602 // the rest of the lowering handle these as blends.
7603 if (Subtarget->hasSSE41())
7606 // Otherwise, use MOVSD or MOVSS.
7607 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7608 "Only two types of floating point element types to handle!");
7609 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7613 // This lowering only works for the low element with floating point vectors.
7614 if (VT.isFloatingPoint() && V2Index != 0)
7617 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7619 V2 = DAG.getBitcast(VT, V2);
7622 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7623 // the desired position. Otherwise it is more efficient to do a vector
7624 // shift left. We know that we can do a vector shift left because all
7625 // the inputs are zero.
7626 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7627 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7628 V2Shuffle[V2Index] = 0;
7629 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7631 V2 = DAG.getBitcast(MVT::v2i64, V2);
7633 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7634 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7635 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7636 DAG.getDataLayout(), VT)));
7637 V2 = DAG.getBitcast(VT, V2);
7643 /// \brief Try to lower broadcast of a single element.
7645 /// For convenience, this code also bundles all of the subtarget feature set
7646 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7647 /// a convenient way to factor it out.
7648 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7650 const X86Subtarget *Subtarget,
7651 SelectionDAG &DAG) {
7652 if (!Subtarget->hasAVX())
7654 if (VT.isInteger() && !Subtarget->hasAVX2())
7657 // Check that the mask is a broadcast.
7658 int BroadcastIdx = -1;
7660 if (M >= 0 && BroadcastIdx == -1)
7662 else if (M >= 0 && M != BroadcastIdx)
7665 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7666 "a sorted mask where the broadcast "
7669 // Go up the chain of (vector) values to find a scalar load that we can
7670 // combine with the broadcast.
7672 switch (V.getOpcode()) {
7673 case ISD::CONCAT_VECTORS: {
7674 int OperandSize = Mask.size() / V.getNumOperands();
7675 V = V.getOperand(BroadcastIdx / OperandSize);
7676 BroadcastIdx %= OperandSize;
7680 case ISD::INSERT_SUBVECTOR: {
7681 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7682 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7686 int BeginIdx = (int)ConstantIdx->getZExtValue();
7688 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7689 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7690 BroadcastIdx -= BeginIdx;
7701 // Check if this is a broadcast of a scalar. We special case lowering
7702 // for scalars so that we can more effectively fold with loads.
7703 // First, look through bitcast: if the original value has a larger element
7704 // type than the shuffle, the broadcast element is in essence truncated.
7705 // Make that explicit to ease folding.
7706 if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7707 EVT EltVT = VT.getVectorElementType();
7708 SDValue V0 = V.getOperand(0);
7709 EVT V0VT = V0.getValueType();
7711 if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7712 ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7713 (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7714 V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7719 // Also check the simpler case, where we can directly reuse the scalar.
7720 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7721 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7722 V = V.getOperand(BroadcastIdx);
7724 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7725 // Only AVX2 has register broadcasts.
7726 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7728 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7729 // We can't broadcast from a vector register without AVX2, and we can only
7730 // broadcast from the zero-element of a vector register.
7734 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7737 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7738 // INSERTPS when the V1 elements are already in the correct locations
7739 // because otherwise we can just always use two SHUFPS instructions which
7740 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7741 // perform INSERTPS if a single V1 element is out of place and all V2
7742 // elements are zeroable.
7743 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7745 SelectionDAG &DAG) {
7746 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7747 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7748 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7749 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7751 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7754 int V1DstIndex = -1;
7755 int V2DstIndex = -1;
7756 bool V1UsedInPlace = false;
7758 for (int i = 0; i < 4; ++i) {
7759 // Synthesize a zero mask from the zeroable elements (includes undefs).
7765 // Flag if we use any V1 inputs in place.
7767 V1UsedInPlace = true;
7771 // We can only insert a single non-zeroable element.
7772 if (V1DstIndex != -1 || V2DstIndex != -1)
7776 // V1 input out of place for insertion.
7779 // V2 input for insertion.
7784 // Don't bother if we have no (non-zeroable) element for insertion.
7785 if (V1DstIndex == -1 && V2DstIndex == -1)
7788 // Determine element insertion src/dst indices. The src index is from the
7789 // start of the inserted vector, not the start of the concatenated vector.
7790 unsigned V2SrcIndex = 0;
7791 if (V1DstIndex != -1) {
7792 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7793 // and don't use the original V2 at all.
7794 V2SrcIndex = Mask[V1DstIndex];
7795 V2DstIndex = V1DstIndex;
7798 V2SrcIndex = Mask[V2DstIndex] - 4;
7801 // If no V1 inputs are used in place, then the result is created only from
7802 // the zero mask and the V2 insertion - so remove V1 dependency.
7804 V1 = DAG.getUNDEF(MVT::v4f32);
7806 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7807 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7809 // Insert the V2 element into the desired position.
7811 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7812 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7815 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7816 /// UNPCK instruction.
7818 /// This specifically targets cases where we end up with alternating between
7819 /// the two inputs, and so can permute them into something that feeds a single
7820 /// UNPCK instruction. Note that this routine only targets integer vectors
7821 /// because for floating point vectors we have a generalized SHUFPS lowering
7822 /// strategy that handles everything that doesn't *exactly* match an unpack,
7823 /// making this clever lowering unnecessary.
7824 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7825 SDValue V2, ArrayRef<int> Mask,
7826 SelectionDAG &DAG) {
7827 assert(!VT.isFloatingPoint() &&
7828 "This routine only supports integer vectors.");
7829 assert(!isSingleInputShuffleMask(Mask) &&
7830 "This routine should only be used when blending two inputs.");
7831 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7833 int Size = Mask.size();
7835 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7836 return M >= 0 && M % Size < Size / 2;
7838 int NumHiInputs = std::count_if(
7839 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7841 bool UnpackLo = NumLoInputs >= NumHiInputs;
7843 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7844 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7845 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7847 for (int i = 0; i < Size; ++i) {
7851 // Each element of the unpack contains Scale elements from this mask.
7852 int UnpackIdx = i / Scale;
7854 // We only handle the case where V1 feeds the first slots of the unpack.
7855 // We rely on canonicalization to ensure this is the case.
7856 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7859 // Setup the mask for this input. The indexing is tricky as we have to
7860 // handle the unpack stride.
7861 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7862 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7866 // If we will have to shuffle both inputs to use the unpack, check whether
7867 // we can just unpack first and shuffle the result. If so, skip this unpack.
7868 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7869 !isNoopShuffleMask(V2Mask))
7872 // Shuffle the inputs into place.
7873 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7874 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7876 // Cast the inputs to the type we will use to unpack them.
7877 V1 = DAG.getBitcast(UnpackVT, V1);
7878 V2 = DAG.getBitcast(UnpackVT, V2);
7880 // Unpack the inputs and cast the result back to the desired type.
7881 return DAG.getBitcast(
7882 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7886 // We try each unpack from the largest to the smallest to try and find one
7887 // that fits this mask.
7888 int OrigNumElements = VT.getVectorNumElements();
7889 int OrigScalarSize = VT.getScalarSizeInBits();
7890 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7891 int Scale = ScalarSize / OrigScalarSize;
7892 int NumElements = OrigNumElements / Scale;
7893 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7894 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7898 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7900 if (NumLoInputs == 0 || NumHiInputs == 0) {
7901 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7902 "We have to have *some* inputs!");
7903 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7905 // FIXME: We could consider the total complexity of the permute of each
7906 // possible unpacking. Or at the least we should consider how many
7907 // half-crossings are created.
7908 // FIXME: We could consider commuting the unpacks.
7910 SmallVector<int, 32> PermMask;
7911 PermMask.assign(Size, -1);
7912 for (int i = 0; i < Size; ++i) {
7916 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7919 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7921 return DAG.getVectorShuffle(
7922 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7924 DAG.getUNDEF(VT), PermMask);
7930 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7932 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7933 /// support for floating point shuffles but not integer shuffles. These
7934 /// instructions will incur a domain crossing penalty on some chips though so
7935 /// it is better to avoid lowering through this for integer vectors where
7937 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7938 const X86Subtarget *Subtarget,
7939 SelectionDAG &DAG) {
7941 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7942 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7943 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7944 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7945 ArrayRef<int> Mask = SVOp->getMask();
7946 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7948 if (isSingleInputShuffleMask(Mask)) {
7949 // Use low duplicate instructions for masks that match their pattern.
7950 if (Subtarget->hasSSE3())
7951 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7952 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7954 // Straight shuffle of a single input vector. Simulate this by using the
7955 // single input as both of the "inputs" to this instruction..
7956 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7958 if (Subtarget->hasAVX()) {
7959 // If we have AVX, we can use VPERMILPS which will allow folding a load
7960 // into the shuffle.
7961 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7962 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7965 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7966 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7968 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7969 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7971 // If we have a single input, insert that into V1 if we can do so cheaply.
7972 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7973 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7974 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7976 // Try inverting the insertion since for v2 masks it is easy to do and we
7977 // can't reliably sort the mask one way or the other.
7978 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7979 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7980 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7981 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7985 // Try to use one of the special instruction patterns to handle two common
7986 // blend patterns if a zero-blend above didn't work.
7987 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7988 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7989 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7990 // We can either use a special instruction to load over the low double or
7991 // to move just the low double.
7993 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7995 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7997 if (Subtarget->hasSSE41())
7998 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8002 // Use dedicated unpack instructions for masks that match their pattern.
8003 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8004 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8005 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8006 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8008 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8009 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8010 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8013 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8015 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8016 /// the integer unit to minimize domain crossing penalties. However, for blends
8017 /// it falls back to the floating point shuffle operation with appropriate bit
8019 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8020 const X86Subtarget *Subtarget,
8021 SelectionDAG &DAG) {
8023 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8024 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8025 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8026 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8027 ArrayRef<int> Mask = SVOp->getMask();
8028 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8030 if (isSingleInputShuffleMask(Mask)) {
8031 // Check for being able to broadcast a single element.
8032 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8033 Mask, Subtarget, DAG))
8036 // Straight shuffle of a single input vector. For everything from SSE2
8037 // onward this has a single fast instruction with no scary immediates.
8038 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8039 V1 = DAG.getBitcast(MVT::v4i32, V1);
8040 int WidenedMask[4] = {
8041 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8042 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8043 return DAG.getBitcast(
8045 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8046 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8048 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8049 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8050 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8051 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8053 // If we have a blend of two PACKUS operations an the blend aligns with the
8054 // low and half halves, we can just merge the PACKUS operations. This is
8055 // particularly important as it lets us merge shuffles that this routine itself
8057 auto GetPackNode = [](SDValue V) {
8058 while (V.getOpcode() == ISD::BITCAST)
8059 V = V.getOperand(0);
8061 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8063 if (SDValue V1Pack = GetPackNode(V1))
8064 if (SDValue V2Pack = GetPackNode(V2))
8065 return DAG.getBitcast(MVT::v2i64,
8066 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8067 Mask[0] == 0 ? V1Pack.getOperand(0)
8068 : V1Pack.getOperand(1),
8069 Mask[1] == 2 ? V2Pack.getOperand(0)
8070 : V2Pack.getOperand(1)));
8072 // Try to use shift instructions.
8074 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8077 // When loading a scalar and then shuffling it into a vector we can often do
8078 // the insertion cheaply.
8079 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8080 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8082 // Try inverting the insertion since for v2 masks it is easy to do and we
8083 // can't reliably sort the mask one way or the other.
8084 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8085 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8086 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8089 // We have different paths for blend lowering, but they all must use the
8090 // *exact* same predicate.
8091 bool IsBlendSupported = Subtarget->hasSSE41();
8092 if (IsBlendSupported)
8093 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8097 // Use dedicated unpack instructions for masks that match their pattern.
8098 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8099 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8100 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8101 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8103 // Try to use byte rotation instructions.
8104 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8105 if (Subtarget->hasSSSE3())
8106 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8107 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8110 // If we have direct support for blends, we should lower by decomposing into
8111 // a permute. That will be faster than the domain cross.
8112 if (IsBlendSupported)
8113 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8116 // We implement this with SHUFPD which is pretty lame because it will likely
8117 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8118 // However, all the alternatives are still more cycles and newer chips don't
8119 // have this problem. It would be really nice if x86 had better shuffles here.
8120 V1 = DAG.getBitcast(MVT::v2f64, V1);
8121 V2 = DAG.getBitcast(MVT::v2f64, V2);
8122 return DAG.getBitcast(MVT::v2i64,
8123 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8126 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8128 /// This is used to disable more specialized lowerings when the shufps lowering
8129 /// will happen to be efficient.
8130 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8131 // This routine only handles 128-bit shufps.
8132 assert(Mask.size() == 4 && "Unsupported mask size!");
8134 // To lower with a single SHUFPS we need to have the low half and high half
8135 // each requiring a single input.
8136 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8138 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8144 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8146 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8147 /// It makes no assumptions about whether this is the *best* lowering, it simply
8149 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8150 ArrayRef<int> Mask, SDValue V1,
8151 SDValue V2, SelectionDAG &DAG) {
8152 SDValue LowV = V1, HighV = V2;
8153 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8156 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8158 if (NumV2Elements == 1) {
8160 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8163 // Compute the index adjacent to V2Index and in the same half by toggling
8165 int V2AdjIndex = V2Index ^ 1;
8167 if (Mask[V2AdjIndex] == -1) {
8168 // Handles all the cases where we have a single V2 element and an undef.
8169 // This will only ever happen in the high lanes because we commute the
8170 // vector otherwise.
8172 std::swap(LowV, HighV);
8173 NewMask[V2Index] -= 4;
8175 // Handle the case where the V2 element ends up adjacent to a V1 element.
8176 // To make this work, blend them together as the first step.
8177 int V1Index = V2AdjIndex;
8178 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8179 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8180 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8182 // Now proceed to reconstruct the final blend as we have the necessary
8183 // high or low half formed.
8190 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8191 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8193 } else if (NumV2Elements == 2) {
8194 if (Mask[0] < 4 && Mask[1] < 4) {
8195 // Handle the easy case where we have V1 in the low lanes and V2 in the
8199 } else if (Mask[2] < 4 && Mask[3] < 4) {
8200 // We also handle the reversed case because this utility may get called
8201 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8202 // arrange things in the right direction.
8208 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8209 // trying to place elements directly, just blend them and set up the final
8210 // shuffle to place them.
8212 // The first two blend mask elements are for V1, the second two are for
8214 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8215 Mask[2] < 4 ? Mask[2] : Mask[3],
8216 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8217 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8218 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8219 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8221 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8224 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8225 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8226 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8227 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8230 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8231 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8234 /// \brief Lower 4-lane 32-bit floating point shuffles.
8236 /// Uses instructions exclusively from the floating point unit to minimize
8237 /// domain crossing penalties, as these are sufficient to implement all v4f32
8239 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8240 const X86Subtarget *Subtarget,
8241 SelectionDAG &DAG) {
8243 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8244 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8245 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8246 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8247 ArrayRef<int> Mask = SVOp->getMask();
8248 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8251 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8253 if (NumV2Elements == 0) {
8254 // Check for being able to broadcast a single element.
8255 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8256 Mask, Subtarget, DAG))
8259 // Use even/odd duplicate instructions for masks that match their pattern.
8260 if (Subtarget->hasSSE3()) {
8261 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8262 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8263 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8264 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8267 if (Subtarget->hasAVX()) {
8268 // If we have AVX, we can use VPERMILPS which will allow folding a load
8269 // into the shuffle.
8270 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8271 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8274 // Otherwise, use a straight shuffle of a single input vector. We pass the
8275 // input vector to both operands to simulate this with a SHUFPS.
8276 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8277 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8280 // There are special ways we can lower some single-element blends. However, we
8281 // have custom ways we can lower more complex single-element blends below that
8282 // we defer to if both this and BLENDPS fail to match, so restrict this to
8283 // when the V2 input is targeting element 0 of the mask -- that is the fast
8285 if (NumV2Elements == 1 && Mask[0] >= 4)
8286 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8287 Mask, Subtarget, DAG))
8290 if (Subtarget->hasSSE41()) {
8291 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8295 // Use INSERTPS if we can complete the shuffle efficiently.
8296 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8299 if (!isSingleSHUFPSMask(Mask))
8300 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8301 DL, MVT::v4f32, V1, V2, Mask, DAG))
8305 // Use dedicated unpack instructions for masks that match their pattern.
8306 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8307 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8308 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8309 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8310 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8311 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8312 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8313 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8315 // Otherwise fall back to a SHUFPS lowering strategy.
8316 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8319 /// \brief Lower 4-lane i32 vector shuffles.
8321 /// We try to handle these with integer-domain shuffles where we can, but for
8322 /// blends we use the floating point domain blend instructions.
8323 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8324 const X86Subtarget *Subtarget,
8325 SelectionDAG &DAG) {
8327 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8328 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8329 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8330 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8331 ArrayRef<int> Mask = SVOp->getMask();
8332 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8334 // Whenever we can lower this as a zext, that instruction is strictly faster
8335 // than any alternative. It also allows us to fold memory operands into the
8336 // shuffle in many cases.
8337 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8338 Mask, Subtarget, DAG))
8342 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8344 if (NumV2Elements == 0) {
8345 // Check for being able to broadcast a single element.
8346 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8347 Mask, Subtarget, DAG))
8350 // Straight shuffle of a single input vector. For everything from SSE2
8351 // onward this has a single fast instruction with no scary immediates.
8352 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8353 // but we aren't actually going to use the UNPCK instruction because doing
8354 // so prevents folding a load into this instruction or making a copy.
8355 const int UnpackLoMask[] = {0, 0, 1, 1};
8356 const int UnpackHiMask[] = {2, 2, 3, 3};
8357 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8358 Mask = UnpackLoMask;
8359 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8360 Mask = UnpackHiMask;
8362 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8363 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8366 // Try to use shift instructions.
8368 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8371 // There are special ways we can lower some single-element blends.
8372 if (NumV2Elements == 1)
8373 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8374 Mask, Subtarget, DAG))
8377 // We have different paths for blend lowering, but they all must use the
8378 // *exact* same predicate.
8379 bool IsBlendSupported = Subtarget->hasSSE41();
8380 if (IsBlendSupported)
8381 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8385 if (SDValue Masked =
8386 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8389 // Use dedicated unpack instructions for masks that match their pattern.
8390 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8391 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8392 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8393 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8394 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8395 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8396 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8397 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8399 // Try to use byte rotation instructions.
8400 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8401 if (Subtarget->hasSSSE3())
8402 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8403 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8406 // If we have direct support for blends, we should lower by decomposing into
8407 // a permute. That will be faster than the domain cross.
8408 if (IsBlendSupported)
8409 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8412 // Try to lower by permuting the inputs into an unpack instruction.
8413 if (SDValue Unpack =
8414 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8417 // We implement this with SHUFPS because it can blend from two vectors.
8418 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8419 // up the inputs, bypassing domain shift penalties that we would encur if we
8420 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8422 return DAG.getBitcast(
8424 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8425 DAG.getBitcast(MVT::v4f32, V2), Mask));
8428 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8429 /// shuffle lowering, and the most complex part.
8431 /// The lowering strategy is to try to form pairs of input lanes which are
8432 /// targeted at the same half of the final vector, and then use a dword shuffle
8433 /// to place them onto the right half, and finally unpack the paired lanes into
8434 /// their final position.
8436 /// The exact breakdown of how to form these dword pairs and align them on the
8437 /// correct sides is really tricky. See the comments within the function for
8438 /// more of the details.
8440 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8441 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8442 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8443 /// vector, form the analogous 128-bit 8-element Mask.
8444 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8445 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8446 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8447 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8448 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8450 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8451 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8452 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8454 SmallVector<int, 4> LoInputs;
8455 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8456 [](int M) { return M >= 0; });
8457 std::sort(LoInputs.begin(), LoInputs.end());
8458 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8459 SmallVector<int, 4> HiInputs;
8460 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8461 [](int M) { return M >= 0; });
8462 std::sort(HiInputs.begin(), HiInputs.end());
8463 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8465 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8466 int NumHToL = LoInputs.size() - NumLToL;
8468 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8469 int NumHToH = HiInputs.size() - NumLToH;
8470 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8471 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8472 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8473 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8475 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8476 // such inputs we can swap two of the dwords across the half mark and end up
8477 // with <=2 inputs to each half in each half. Once there, we can fall through
8478 // to the generic code below. For example:
8480 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8481 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8483 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8484 // and an existing 2-into-2 on the other half. In this case we may have to
8485 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8486 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8487 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8488 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8489 // half than the one we target for fixing) will be fixed when we re-enter this
8490 // path. We will also combine away any sequence of PSHUFD instructions that
8491 // result into a single instruction. Here is an example of the tricky case:
8493 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8494 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8496 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8498 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8499 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8501 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8502 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8504 // The result is fine to be handled by the generic logic.
8505 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8506 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8507 int AOffset, int BOffset) {
8508 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8509 "Must call this with A having 3 or 1 inputs from the A half.");
8510 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8511 "Must call this with B having 1 or 3 inputs from the B half.");
8512 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8513 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8515 bool ThreeAInputs = AToAInputs.size() == 3;
8517 // Compute the index of dword with only one word among the three inputs in
8518 // a half by taking the sum of the half with three inputs and subtracting
8519 // the sum of the actual three inputs. The difference is the remaining
8522 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8523 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8524 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8525 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8526 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8527 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8528 int TripleNonInputIdx =
8529 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8530 TripleDWord = TripleNonInputIdx / 2;
8532 // We use xor with one to compute the adjacent DWord to whichever one the
8534 OneInputDWord = (OneInput / 2) ^ 1;
8536 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8537 // and BToA inputs. If there is also such a problem with the BToB and AToB
8538 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8539 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8540 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8541 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8542 // Compute how many inputs will be flipped by swapping these DWords. We
8544 // to balance this to ensure we don't form a 3-1 shuffle in the other
8546 int NumFlippedAToBInputs =
8547 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8548 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8549 int NumFlippedBToBInputs =
8550 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8551 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8552 if ((NumFlippedAToBInputs == 1 &&
8553 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8554 (NumFlippedBToBInputs == 1 &&
8555 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8556 // We choose whether to fix the A half or B half based on whether that
8557 // half has zero flipped inputs. At zero, we may not be able to fix it
8558 // with that half. We also bias towards fixing the B half because that
8559 // will more commonly be the high half, and we have to bias one way.
8560 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8561 ArrayRef<int> Inputs) {
8562 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8563 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8564 PinnedIdx ^ 1) != Inputs.end();
8565 // Determine whether the free index is in the flipped dword or the
8566 // unflipped dword based on where the pinned index is. We use this bit
8567 // in an xor to conditionally select the adjacent dword.
8568 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8569 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8570 FixFreeIdx) != Inputs.end();
8571 if (IsFixIdxInput == IsFixFreeIdxInput)
8573 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8574 FixFreeIdx) != Inputs.end();
8575 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8576 "We need to be changing the number of flipped inputs!");
8577 int PSHUFHalfMask[] = {0, 1, 2, 3};
8578 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8579 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8581 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8584 if (M != -1 && M == FixIdx)
8586 else if (M != -1 && M == FixFreeIdx)
8589 if (NumFlippedBToBInputs != 0) {
8591 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8592 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8594 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8595 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8596 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8601 int PSHUFDMask[] = {0, 1, 2, 3};
8602 PSHUFDMask[ADWord] = BDWord;
8603 PSHUFDMask[BDWord] = ADWord;
8606 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8607 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8609 // Adjust the mask to match the new locations of A and B.
8611 if (M != -1 && M/2 == ADWord)
8612 M = 2 * BDWord + M % 2;
8613 else if (M != -1 && M/2 == BDWord)
8614 M = 2 * ADWord + M % 2;
8616 // Recurse back into this routine to re-compute state now that this isn't
8617 // a 3 and 1 problem.
8618 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8621 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8622 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8623 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8624 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8626 // At this point there are at most two inputs to the low and high halves from
8627 // each half. That means the inputs can always be grouped into dwords and
8628 // those dwords can then be moved to the correct half with a dword shuffle.
8629 // We use at most one low and one high word shuffle to collect these paired
8630 // inputs into dwords, and finally a dword shuffle to place them.
8631 int PSHUFLMask[4] = {-1, -1, -1, -1};
8632 int PSHUFHMask[4] = {-1, -1, -1, -1};
8633 int PSHUFDMask[4] = {-1, -1, -1, -1};
8635 // First fix the masks for all the inputs that are staying in their
8636 // original halves. This will then dictate the targets of the cross-half
8638 auto fixInPlaceInputs =
8639 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8640 MutableArrayRef<int> SourceHalfMask,
8641 MutableArrayRef<int> HalfMask, int HalfOffset) {
8642 if (InPlaceInputs.empty())
8644 if (InPlaceInputs.size() == 1) {
8645 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8646 InPlaceInputs[0] - HalfOffset;
8647 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8650 if (IncomingInputs.empty()) {
8651 // Just fix all of the in place inputs.
8652 for (int Input : InPlaceInputs) {
8653 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8654 PSHUFDMask[Input / 2] = Input / 2;
8659 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8660 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8661 InPlaceInputs[0] - HalfOffset;
8662 // Put the second input next to the first so that they are packed into
8663 // a dword. We find the adjacent index by toggling the low bit.
8664 int AdjIndex = InPlaceInputs[0] ^ 1;
8665 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8666 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8667 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8669 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8670 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8672 // Now gather the cross-half inputs and place them into a free dword of
8673 // their target half.
8674 // FIXME: This operation could almost certainly be simplified dramatically to
8675 // look more like the 3-1 fixing operation.
8676 auto moveInputsToRightHalf = [&PSHUFDMask](
8677 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8678 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8679 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8681 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8682 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8684 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8686 int LowWord = Word & ~1;
8687 int HighWord = Word | 1;
8688 return isWordClobbered(SourceHalfMask, LowWord) ||
8689 isWordClobbered(SourceHalfMask, HighWord);
8692 if (IncomingInputs.empty())
8695 if (ExistingInputs.empty()) {
8696 // Map any dwords with inputs from them into the right half.
8697 for (int Input : IncomingInputs) {
8698 // If the source half mask maps over the inputs, turn those into
8699 // swaps and use the swapped lane.
8700 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8701 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8702 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8703 Input - SourceOffset;
8704 // We have to swap the uses in our half mask in one sweep.
8705 for (int &M : HalfMask)
8706 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8708 else if (M == Input)
8709 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8711 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8712 Input - SourceOffset &&
8713 "Previous placement doesn't match!");
8715 // Note that this correctly re-maps both when we do a swap and when
8716 // we observe the other side of the swap above. We rely on that to
8717 // avoid swapping the members of the input list directly.
8718 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8721 // Map the input's dword into the correct half.
8722 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8723 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8725 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8727 "Previous placement doesn't match!");
8730 // And just directly shift any other-half mask elements to be same-half
8731 // as we will have mirrored the dword containing the element into the
8732 // same position within that half.
8733 for (int &M : HalfMask)
8734 if (M >= SourceOffset && M < SourceOffset + 4) {
8735 M = M - SourceOffset + DestOffset;
8736 assert(M >= 0 && "This should never wrap below zero!");
8741 // Ensure we have the input in a viable dword of its current half. This
8742 // is particularly tricky because the original position may be clobbered
8743 // by inputs being moved and *staying* in that half.
8744 if (IncomingInputs.size() == 1) {
8745 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8746 int InputFixed = std::find(std::begin(SourceHalfMask),
8747 std::end(SourceHalfMask), -1) -
8748 std::begin(SourceHalfMask) + SourceOffset;
8749 SourceHalfMask[InputFixed - SourceOffset] =
8750 IncomingInputs[0] - SourceOffset;
8751 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8753 IncomingInputs[0] = InputFixed;
8755 } else if (IncomingInputs.size() == 2) {
8756 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8757 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8758 // We have two non-adjacent or clobbered inputs we need to extract from
8759 // the source half. To do this, we need to map them into some adjacent
8760 // dword slot in the source mask.
8761 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8762 IncomingInputs[1] - SourceOffset};
8764 // If there is a free slot in the source half mask adjacent to one of
8765 // the inputs, place the other input in it. We use (Index XOR 1) to
8766 // compute an adjacent index.
8767 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8768 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8769 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8770 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8771 InputsFixed[1] = InputsFixed[0] ^ 1;
8772 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8773 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8774 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8775 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8776 InputsFixed[0] = InputsFixed[1] ^ 1;
8777 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8778 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8779 // The two inputs are in the same DWord but it is clobbered and the
8780 // adjacent DWord isn't used at all. Move both inputs to the free
8782 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8783 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8784 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8785 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8787 // The only way we hit this point is if there is no clobbering
8788 // (because there are no off-half inputs to this half) and there is no
8789 // free slot adjacent to one of the inputs. In this case, we have to
8790 // swap an input with a non-input.
8791 for (int i = 0; i < 4; ++i)
8792 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8793 "We can't handle any clobbers here!");
8794 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8795 "Cannot have adjacent inputs here!");
8797 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8798 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8800 // We also have to update the final source mask in this case because
8801 // it may need to undo the above swap.
8802 for (int &M : FinalSourceHalfMask)
8803 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8804 M = InputsFixed[1] + SourceOffset;
8805 else if (M == InputsFixed[1] + SourceOffset)
8806 M = (InputsFixed[0] ^ 1) + SourceOffset;
8808 InputsFixed[1] = InputsFixed[0] ^ 1;
8811 // Point everything at the fixed inputs.
8812 for (int &M : HalfMask)
8813 if (M == IncomingInputs[0])
8814 M = InputsFixed[0] + SourceOffset;
8815 else if (M == IncomingInputs[1])
8816 M = InputsFixed[1] + SourceOffset;
8818 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8819 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8822 llvm_unreachable("Unhandled input size!");
8825 // Now hoist the DWord down to the right half.
8826 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8827 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8828 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8829 for (int &M : HalfMask)
8830 for (int Input : IncomingInputs)
8832 M = FreeDWord * 2 + Input % 2;
8834 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8835 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8836 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8837 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8839 // Now enact all the shuffles we've computed to move the inputs into their
8841 if (!isNoopShuffleMask(PSHUFLMask))
8842 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8843 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8844 if (!isNoopShuffleMask(PSHUFHMask))
8845 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8846 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8847 if (!isNoopShuffleMask(PSHUFDMask))
8850 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8851 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8853 // At this point, each half should contain all its inputs, and we can then
8854 // just shuffle them into their final position.
8855 assert(std::count_if(LoMask.begin(), LoMask.end(),
8856 [](int M) { return M >= 4; }) == 0 &&
8857 "Failed to lift all the high half inputs to the low mask!");
8858 assert(std::count_if(HiMask.begin(), HiMask.end(),
8859 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8860 "Failed to lift all the low half inputs to the high mask!");
8862 // Do a half shuffle for the low mask.
8863 if (!isNoopShuffleMask(LoMask))
8864 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8865 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8867 // Do a half shuffle with the high mask after shifting its values down.
8868 for (int &M : HiMask)
8871 if (!isNoopShuffleMask(HiMask))
8872 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8873 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8878 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8879 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8880 SDValue V2, ArrayRef<int> Mask,
8881 SelectionDAG &DAG, bool &V1InUse,
8883 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8889 int Size = Mask.size();
8890 int Scale = 16 / Size;
8891 for (int i = 0; i < 16; ++i) {
8892 if (Mask[i / Scale] == -1) {
8893 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8895 const int ZeroMask = 0x80;
8896 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8898 int V2Idx = Mask[i / Scale] < Size
8900 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8901 if (Zeroable[i / Scale])
8902 V1Idx = V2Idx = ZeroMask;
8903 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8904 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8905 V1InUse |= (ZeroMask != V1Idx);
8906 V2InUse |= (ZeroMask != V2Idx);
8911 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8912 DAG.getBitcast(MVT::v16i8, V1),
8913 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8915 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8916 DAG.getBitcast(MVT::v16i8, V2),
8917 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8919 // If we need shuffled inputs from both, blend the two.
8921 if (V1InUse && V2InUse)
8922 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8924 V = V1InUse ? V1 : V2;
8926 // Cast the result back to the correct type.
8927 return DAG.getBitcast(VT, V);
8930 /// \brief Generic lowering of 8-lane i16 shuffles.
8932 /// This handles both single-input shuffles and combined shuffle/blends with
8933 /// two inputs. The single input shuffles are immediately delegated to
8934 /// a dedicated lowering routine.
8936 /// The blends are lowered in one of three fundamental ways. If there are few
8937 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8938 /// of the input is significantly cheaper when lowered as an interleaving of
8939 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8940 /// halves of the inputs separately (making them have relatively few inputs)
8941 /// and then concatenate them.
8942 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8943 const X86Subtarget *Subtarget,
8944 SelectionDAG &DAG) {
8946 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8947 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8948 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8949 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8950 ArrayRef<int> OrigMask = SVOp->getMask();
8951 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8952 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8953 MutableArrayRef<int> Mask(MaskStorage);
8955 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8957 // Whenever we can lower this as a zext, that instruction is strictly faster
8958 // than any alternative.
8959 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8960 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8963 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8965 auto isV2 = [](int M) { return M >= 8; };
8967 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8969 if (NumV2Inputs == 0) {
8970 // Check for being able to broadcast a single element.
8971 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8972 Mask, Subtarget, DAG))
8975 // Try to use shift instructions.
8977 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8980 // Use dedicated unpack instructions for masks that match their pattern.
8981 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8982 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8983 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8984 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8986 // Try to use byte rotation instructions.
8987 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8988 Mask, Subtarget, DAG))
8991 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8995 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8996 "All single-input shuffles should be canonicalized to be V1-input "
8999 // Try to use shift instructions.
9001 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9004 // See if we can use SSE4A Extraction / Insertion.
9005 if (Subtarget->hasSSE4A())
9006 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9009 // There are special ways we can lower some single-element blends.
9010 if (NumV2Inputs == 1)
9011 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9012 Mask, Subtarget, DAG))
9015 // We have different paths for blend lowering, but they all must use the
9016 // *exact* same predicate.
9017 bool IsBlendSupported = Subtarget->hasSSE41();
9018 if (IsBlendSupported)
9019 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9023 if (SDValue Masked =
9024 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9027 // Use dedicated unpack instructions for masks that match their pattern.
9028 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9029 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9030 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9031 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9033 // Try to use byte rotation instructions.
9034 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9035 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9038 if (SDValue BitBlend =
9039 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9042 if (SDValue Unpack =
9043 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
9046 // If we can't directly blend but can use PSHUFB, that will be better as it
9047 // can both shuffle and set up the inefficient blend.
9048 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9049 bool V1InUse, V2InUse;
9050 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9054 // We can always bit-blend if we have to so the fallback strategy is to
9055 // decompose into single-input permutes and blends.
9056 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9060 /// \brief Check whether a compaction lowering can be done by dropping even
9061 /// elements and compute how many times even elements must be dropped.
9063 /// This handles shuffles which take every Nth element where N is a power of
9064 /// two. Example shuffle masks:
9066 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9067 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9068 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9069 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9070 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9071 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9073 /// Any of these lanes can of course be undef.
9075 /// This routine only supports N <= 3.
9076 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9079 /// \returns N above, or the number of times even elements must be dropped if
9080 /// there is such a number. Otherwise returns zero.
9081 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9082 // Figure out whether we're looping over two inputs or just one.
9083 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9085 // The modulus for the shuffle vector entries is based on whether this is
9086 // a single input or not.
9087 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9088 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9089 "We should only be called with masks with a power-of-2 size!");
9091 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9093 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9094 // and 2^3 simultaneously. This is because we may have ambiguity with
9095 // partially undef inputs.
9096 bool ViableForN[3] = {true, true, true};
9098 for (int i = 0, e = Mask.size(); i < e; ++i) {
9099 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9104 bool IsAnyViable = false;
9105 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9106 if (ViableForN[j]) {
9109 // The shuffle mask must be equal to (i * 2^N) % M.
9110 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9113 ViableForN[j] = false;
9115 // Early exit if we exhaust the possible powers of two.
9120 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9124 // Return 0 as there is no viable power of two.
9128 /// \brief Generic lowering of v16i8 shuffles.
9130 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9131 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9132 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9133 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9135 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9136 const X86Subtarget *Subtarget,
9137 SelectionDAG &DAG) {
9139 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9140 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9141 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9142 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9143 ArrayRef<int> Mask = SVOp->getMask();
9144 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9146 // Try to use shift instructions.
9148 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9151 // Try to use byte rotation instructions.
9152 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9153 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9156 // Try to use a zext lowering.
9157 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9158 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9161 // See if we can use SSE4A Extraction / Insertion.
9162 if (Subtarget->hasSSE4A())
9163 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9167 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9169 // For single-input shuffles, there are some nicer lowering tricks we can use.
9170 if (NumV2Elements == 0) {
9171 // Check for being able to broadcast a single element.
9172 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9173 Mask, Subtarget, DAG))
9176 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9177 // Notably, this handles splat and partial-splat shuffles more efficiently.
9178 // However, it only makes sense if the pre-duplication shuffle simplifies
9179 // things significantly. Currently, this means we need to be able to
9180 // express the pre-duplication shuffle as an i16 shuffle.
9182 // FIXME: We should check for other patterns which can be widened into an
9183 // i16 shuffle as well.
9184 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9185 for (int i = 0; i < 16; i += 2)
9186 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9191 auto tryToWidenViaDuplication = [&]() -> SDValue {
9192 if (!canWidenViaDuplication(Mask))
9194 SmallVector<int, 4> LoInputs;
9195 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9196 [](int M) { return M >= 0 && M < 8; });
9197 std::sort(LoInputs.begin(), LoInputs.end());
9198 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9200 SmallVector<int, 4> HiInputs;
9201 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9202 [](int M) { return M >= 8; });
9203 std::sort(HiInputs.begin(), HiInputs.end());
9204 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9207 bool TargetLo = LoInputs.size() >= HiInputs.size();
9208 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9209 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9211 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9212 SmallDenseMap<int, int, 8> LaneMap;
9213 for (int I : InPlaceInputs) {
9214 PreDupI16Shuffle[I/2] = I/2;
9217 int j = TargetLo ? 0 : 4, je = j + 4;
9218 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9219 // Check if j is already a shuffle of this input. This happens when
9220 // there are two adjacent bytes after we move the low one.
9221 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9222 // If we haven't yet mapped the input, search for a slot into which
9224 while (j < je && PreDupI16Shuffle[j] != -1)
9228 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9231 // Map this input with the i16 shuffle.
9232 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9235 // Update the lane map based on the mapping we ended up with.
9236 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9238 V1 = DAG.getBitcast(
9240 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9241 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9243 // Unpack the bytes to form the i16s that will be shuffled into place.
9244 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9245 MVT::v16i8, V1, V1);
9247 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9248 for (int i = 0; i < 16; ++i)
9249 if (Mask[i] != -1) {
9250 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9251 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9252 if (PostDupI16Shuffle[i / 2] == -1)
9253 PostDupI16Shuffle[i / 2] = MappedMask;
9255 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9256 "Conflicting entrties in the original shuffle!");
9258 return DAG.getBitcast(
9260 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9261 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9263 if (SDValue V = tryToWidenViaDuplication())
9267 if (SDValue Masked =
9268 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9271 // Use dedicated unpack instructions for masks that match their pattern.
9272 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9273 0, 16, 1, 17, 2, 18, 3, 19,
9275 4, 20, 5, 21, 6, 22, 7, 23}))
9276 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9277 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9278 8, 24, 9, 25, 10, 26, 11, 27,
9280 12, 28, 13, 29, 14, 30, 15, 31}))
9281 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9283 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9284 // with PSHUFB. It is important to do this before we attempt to generate any
9285 // blends but after all of the single-input lowerings. If the single input
9286 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9287 // want to preserve that and we can DAG combine any longer sequences into
9288 // a PSHUFB in the end. But once we start blending from multiple inputs,
9289 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9290 // and there are *very* few patterns that would actually be faster than the
9291 // PSHUFB approach because of its ability to zero lanes.
9293 // FIXME: The only exceptions to the above are blends which are exact
9294 // interleavings with direct instructions supporting them. We currently don't
9295 // handle those well here.
9296 if (Subtarget->hasSSSE3()) {
9297 bool V1InUse = false;
9298 bool V2InUse = false;
9300 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9301 DAG, V1InUse, V2InUse);
9303 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9304 // do so. This avoids using them to handle blends-with-zero which is
9305 // important as a single pshufb is significantly faster for that.
9306 if (V1InUse && V2InUse) {
9307 if (Subtarget->hasSSE41())
9308 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9309 Mask, Subtarget, DAG))
9312 // We can use an unpack to do the blending rather than an or in some
9313 // cases. Even though the or may be (very minorly) more efficient, we
9314 // preference this lowering because there are common cases where part of
9315 // the complexity of the shuffles goes away when we do the final blend as
9317 // FIXME: It might be worth trying to detect if the unpack-feeding
9318 // shuffles will both be pshufb, in which case we shouldn't bother with
9320 if (SDValue Unpack =
9321 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9328 // There are special ways we can lower some single-element blends.
9329 if (NumV2Elements == 1)
9330 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9331 Mask, Subtarget, DAG))
9334 if (SDValue BitBlend =
9335 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9338 // Check whether a compaction lowering can be done. This handles shuffles
9339 // which take every Nth element for some even N. See the helper function for
9342 // We special case these as they can be particularly efficiently handled with
9343 // the PACKUSB instruction on x86 and they show up in common patterns of
9344 // rearranging bytes to truncate wide elements.
9345 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9346 // NumEvenDrops is the power of two stride of the elements. Another way of
9347 // thinking about it is that we need to drop the even elements this many
9348 // times to get the original input.
9349 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9351 // First we need to zero all the dropped bytes.
9352 assert(NumEvenDrops <= 3 &&
9353 "No support for dropping even elements more than 3 times.");
9354 // We use the mask type to pick which bytes are preserved based on how many
9355 // elements are dropped.
9356 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9357 SDValue ByteClearMask = DAG.getBitcast(
9358 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9359 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9361 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9363 // Now pack things back together.
9364 V1 = DAG.getBitcast(MVT::v8i16, V1);
9365 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9366 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9367 for (int i = 1; i < NumEvenDrops; ++i) {
9368 Result = DAG.getBitcast(MVT::v8i16, Result);
9369 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9375 // Handle multi-input cases by blending single-input shuffles.
9376 if (NumV2Elements > 0)
9377 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9380 // The fallback path for single-input shuffles widens this into two v8i16
9381 // vectors with unpacks, shuffles those, and then pulls them back together
9385 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9386 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9387 for (int i = 0; i < 16; ++i)
9389 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9391 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9393 SDValue VLoHalf, VHiHalf;
9394 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9395 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9397 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9398 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9399 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9400 [](int M) { return M >= 0 && M % 2 == 1; })) {
9401 // Use a mask to drop the high bytes.
9402 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9403 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9404 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9406 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9407 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9409 // Squash the masks to point directly into VLoHalf.
9410 for (int &M : LoBlendMask)
9413 for (int &M : HiBlendMask)
9417 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9418 // VHiHalf so that we can blend them as i16s.
9419 VLoHalf = DAG.getBitcast(
9420 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9421 VHiHalf = DAG.getBitcast(
9422 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9425 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9426 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9428 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9431 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9433 /// This routine breaks down the specific type of 128-bit shuffle and
9434 /// dispatches to the lowering routines accordingly.
9435 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9436 MVT VT, const X86Subtarget *Subtarget,
9437 SelectionDAG &DAG) {
9438 switch (VT.SimpleTy) {
9440 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9442 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9444 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9446 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9448 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9450 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9453 llvm_unreachable("Unimplemented!");
9457 /// \brief Helper function to test whether a shuffle mask could be
9458 /// simplified by widening the elements being shuffled.
9460 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9461 /// leaves it in an unspecified state.
9463 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9464 /// shuffle masks. The latter have the special property of a '-2' representing
9465 /// a zero-ed lane of a vector.
9466 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9467 SmallVectorImpl<int> &WidenedMask) {
9468 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9469 // If both elements are undef, its trivial.
9470 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9471 WidenedMask.push_back(SM_SentinelUndef);
9475 // Check for an undef mask and a mask value properly aligned to fit with
9476 // a pair of values. If we find such a case, use the non-undef mask's value.
9477 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9478 WidenedMask.push_back(Mask[i + 1] / 2);
9481 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9482 WidenedMask.push_back(Mask[i] / 2);
9486 // When zeroing, we need to spread the zeroing across both lanes to widen.
9487 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9488 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9489 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9490 WidenedMask.push_back(SM_SentinelZero);
9496 // Finally check if the two mask values are adjacent and aligned with
9498 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9499 WidenedMask.push_back(Mask[i] / 2);
9503 // Otherwise we can't safely widen the elements used in this shuffle.
9506 assert(WidenedMask.size() == Mask.size() / 2 &&
9507 "Incorrect size of mask after widening the elements!");
9512 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9514 /// This routine just extracts two subvectors, shuffles them independently, and
9515 /// then concatenates them back together. This should work effectively with all
9516 /// AVX vector shuffle types.
9517 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9518 SDValue V2, ArrayRef<int> Mask,
9519 SelectionDAG &DAG) {
9520 assert(VT.getSizeInBits() >= 256 &&
9521 "Only for 256-bit or wider vector shuffles!");
9522 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9523 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9525 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9526 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9528 int NumElements = VT.getVectorNumElements();
9529 int SplitNumElements = NumElements / 2;
9530 MVT ScalarVT = VT.getScalarType();
9531 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9533 // Rather than splitting build-vectors, just build two narrower build
9534 // vectors. This helps shuffling with splats and zeros.
9535 auto SplitVector = [&](SDValue V) {
9536 while (V.getOpcode() == ISD::BITCAST)
9537 V = V->getOperand(0);
9539 MVT OrigVT = V.getSimpleValueType();
9540 int OrigNumElements = OrigVT.getVectorNumElements();
9541 int OrigSplitNumElements = OrigNumElements / 2;
9542 MVT OrigScalarVT = OrigVT.getScalarType();
9543 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9547 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9549 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9550 DAG.getIntPtrConstant(0, DL));
9551 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9552 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9555 SmallVector<SDValue, 16> LoOps, HiOps;
9556 for (int i = 0; i < OrigSplitNumElements; ++i) {
9557 LoOps.push_back(BV->getOperand(i));
9558 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9560 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9561 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9563 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9564 DAG.getBitcast(SplitVT, HiV));
9567 SDValue LoV1, HiV1, LoV2, HiV2;
9568 std::tie(LoV1, HiV1) = SplitVector(V1);
9569 std::tie(LoV2, HiV2) = SplitVector(V2);
9571 // Now create two 4-way blends of these half-width vectors.
9572 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9573 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9574 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9575 for (int i = 0; i < SplitNumElements; ++i) {
9576 int M = HalfMask[i];
9577 if (M >= NumElements) {
9578 if (M >= NumElements + SplitNumElements)
9582 V2BlendMask.push_back(M - NumElements);
9583 V1BlendMask.push_back(-1);
9584 BlendMask.push_back(SplitNumElements + i);
9585 } else if (M >= 0) {
9586 if (M >= SplitNumElements)
9590 V2BlendMask.push_back(-1);
9591 V1BlendMask.push_back(M);
9592 BlendMask.push_back(i);
9594 V2BlendMask.push_back(-1);
9595 V1BlendMask.push_back(-1);
9596 BlendMask.push_back(-1);
9600 // Because the lowering happens after all combining takes place, we need to
9601 // manually combine these blend masks as much as possible so that we create
9602 // a minimal number of high-level vector shuffle nodes.
9604 // First try just blending the halves of V1 or V2.
9605 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9606 return DAG.getUNDEF(SplitVT);
9607 if (!UseLoV2 && !UseHiV2)
9608 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9609 if (!UseLoV1 && !UseHiV1)
9610 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9612 SDValue V1Blend, V2Blend;
9613 if (UseLoV1 && UseHiV1) {
9615 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9617 // We only use half of V1 so map the usage down into the final blend mask.
9618 V1Blend = UseLoV1 ? LoV1 : HiV1;
9619 for (int i = 0; i < SplitNumElements; ++i)
9620 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9621 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9623 if (UseLoV2 && UseHiV2) {
9625 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9627 // We only use half of V2 so map the usage down into the final blend mask.
9628 V2Blend = UseLoV2 ? LoV2 : HiV2;
9629 for (int i = 0; i < SplitNumElements; ++i)
9630 if (BlendMask[i] >= SplitNumElements)
9631 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9633 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9635 SDValue Lo = HalfBlend(LoMask);
9636 SDValue Hi = HalfBlend(HiMask);
9637 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9640 /// \brief Either split a vector in halves or decompose the shuffles and the
9643 /// This is provided as a good fallback for many lowerings of non-single-input
9644 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9645 /// between splitting the shuffle into 128-bit components and stitching those
9646 /// back together vs. extracting the single-input shuffles and blending those
9648 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9649 SDValue V2, ArrayRef<int> Mask,
9650 SelectionDAG &DAG) {
9651 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9652 "lower single-input shuffles as it "
9653 "could then recurse on itself.");
9654 int Size = Mask.size();
9656 // If this can be modeled as a broadcast of two elements followed by a blend,
9657 // prefer that lowering. This is especially important because broadcasts can
9658 // often fold with memory operands.
9659 auto DoBothBroadcast = [&] {
9660 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9663 if (V2BroadcastIdx == -1)
9664 V2BroadcastIdx = M - Size;
9665 else if (M - Size != V2BroadcastIdx)
9667 } else if (M >= 0) {
9668 if (V1BroadcastIdx == -1)
9670 else if (M != V1BroadcastIdx)
9675 if (DoBothBroadcast())
9676 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9679 // If the inputs all stem from a single 128-bit lane of each input, then we
9680 // split them rather than blending because the split will decompose to
9681 // unusually few instructions.
9682 int LaneCount = VT.getSizeInBits() / 128;
9683 int LaneSize = Size / LaneCount;
9684 SmallBitVector LaneInputs[2];
9685 LaneInputs[0].resize(LaneCount, false);
9686 LaneInputs[1].resize(LaneCount, false);
9687 for (int i = 0; i < Size; ++i)
9689 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9690 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9691 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9693 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9694 // that the decomposed single-input shuffles don't end up here.
9695 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9698 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9699 /// a permutation and blend of those lanes.
9701 /// This essentially blends the out-of-lane inputs to each lane into the lane
9702 /// from a permuted copy of the vector. This lowering strategy results in four
9703 /// instructions in the worst case for a single-input cross lane shuffle which
9704 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9705 /// of. Special cases for each particular shuffle pattern should be handled
9706 /// prior to trying this lowering.
9707 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9708 SDValue V1, SDValue V2,
9710 SelectionDAG &DAG) {
9711 // FIXME: This should probably be generalized for 512-bit vectors as well.
9712 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9713 int LaneSize = Mask.size() / 2;
9715 // If there are only inputs from one 128-bit lane, splitting will in fact be
9716 // less expensive. The flags track whether the given lane contains an element
9717 // that crosses to another lane.
9718 bool LaneCrossing[2] = {false, false};
9719 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9720 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9721 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9722 if (!LaneCrossing[0] || !LaneCrossing[1])
9723 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9725 if (isSingleInputShuffleMask(Mask)) {
9726 SmallVector<int, 32> FlippedBlendMask;
9727 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9728 FlippedBlendMask.push_back(
9729 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9731 : Mask[i] % LaneSize +
9732 (i / LaneSize) * LaneSize + Size));
9734 // Flip the vector, and blend the results which should now be in-lane. The
9735 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9736 // 5 for the high source. The value 3 selects the high half of source 2 and
9737 // the value 2 selects the low half of source 2. We only use source 2 to
9738 // allow folding it into a memory operand.
9739 unsigned PERMMask = 3 | 2 << 4;
9740 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9741 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9742 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9745 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9746 // will be handled by the above logic and a blend of the results, much like
9747 // other patterns in AVX.
9748 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9751 /// \brief Handle lowering 2-lane 128-bit shuffles.
9752 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9753 SDValue V2, ArrayRef<int> Mask,
9754 const X86Subtarget *Subtarget,
9755 SelectionDAG &DAG) {
9756 // TODO: If minimizing size and one of the inputs is a zero vector and the
9757 // the zero vector has only one use, we could use a VPERM2X128 to save the
9758 // instruction bytes needed to explicitly generate the zero vector.
9760 // Blends are faster and handle all the non-lane-crossing cases.
9761 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9765 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9766 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9768 // If either input operand is a zero vector, use VPERM2X128 because its mask
9769 // allows us to replace the zero input with an implicit zero.
9770 if (!IsV1Zero && !IsV2Zero) {
9771 // Check for patterns which can be matched with a single insert of a 128-bit
9773 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9774 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9775 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9776 VT.getVectorNumElements() / 2);
9777 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9778 DAG.getIntPtrConstant(0, DL));
9779 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9780 OnlyUsesV1 ? V1 : V2,
9781 DAG.getIntPtrConstant(0, DL));
9782 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9786 // Otherwise form a 128-bit permutation. After accounting for undefs,
9787 // convert the 64-bit shuffle mask selection values into 128-bit
9788 // selection bits by dividing the indexes by 2 and shifting into positions
9789 // defined by a vperm2*128 instruction's immediate control byte.
9791 // The immediate permute control byte looks like this:
9792 // [1:0] - select 128 bits from sources for low half of destination
9794 // [3] - zero low half of destination
9795 // [5:4] - select 128 bits from sources for high half of destination
9797 // [7] - zero high half of destination
9799 int MaskLO = Mask[0];
9800 if (MaskLO == SM_SentinelUndef)
9801 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9803 int MaskHI = Mask[2];
9804 if (MaskHI == SM_SentinelUndef)
9805 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9807 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9809 // If either input is a zero vector, replace it with an undef input.
9810 // Shuffle mask values < 4 are selecting elements of V1.
9811 // Shuffle mask values >= 4 are selecting elements of V2.
9812 // Adjust each half of the permute mask by clearing the half that was
9813 // selecting the zero vector and setting the zero mask bit.
9815 V1 = DAG.getUNDEF(VT);
9817 PermMask = (PermMask & 0xf0) | 0x08;
9819 PermMask = (PermMask & 0x0f) | 0x80;
9822 V2 = DAG.getUNDEF(VT);
9824 PermMask = (PermMask & 0xf0) | 0x08;
9826 PermMask = (PermMask & 0x0f) | 0x80;
9829 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9830 DAG.getConstant(PermMask, DL, MVT::i8));
9833 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9834 /// shuffling each lane.
9836 /// This will only succeed when the result of fixing the 128-bit lanes results
9837 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9838 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9839 /// the lane crosses early and then use simpler shuffles within each lane.
9841 /// FIXME: It might be worthwhile at some point to support this without
9842 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9843 /// in x86 only floating point has interesting non-repeating shuffles, and even
9844 /// those are still *marginally* more expensive.
9845 static SDValue lowerVectorShuffleByMerging128BitLanes(
9846 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9847 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9848 assert(!isSingleInputShuffleMask(Mask) &&
9849 "This is only useful with multiple inputs.");
9851 int Size = Mask.size();
9852 int LaneSize = 128 / VT.getScalarSizeInBits();
9853 int NumLanes = Size / LaneSize;
9854 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9856 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9857 // check whether the in-128-bit lane shuffles share a repeating pattern.
9858 SmallVector<int, 4> Lanes;
9859 Lanes.resize(NumLanes, -1);
9860 SmallVector<int, 4> InLaneMask;
9861 InLaneMask.resize(LaneSize, -1);
9862 for (int i = 0; i < Size; ++i) {
9866 int j = i / LaneSize;
9869 // First entry we've seen for this lane.
9870 Lanes[j] = Mask[i] / LaneSize;
9871 } else if (Lanes[j] != Mask[i] / LaneSize) {
9872 // This doesn't match the lane selected previously!
9876 // Check that within each lane we have a consistent shuffle mask.
9877 int k = i % LaneSize;
9878 if (InLaneMask[k] < 0) {
9879 InLaneMask[k] = Mask[i] % LaneSize;
9880 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9881 // This doesn't fit a repeating in-lane mask.
9886 // First shuffle the lanes into place.
9887 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9888 VT.getSizeInBits() / 64);
9889 SmallVector<int, 8> LaneMask;
9890 LaneMask.resize(NumLanes * 2, -1);
9891 for (int i = 0; i < NumLanes; ++i)
9892 if (Lanes[i] >= 0) {
9893 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9894 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9897 V1 = DAG.getBitcast(LaneVT, V1);
9898 V2 = DAG.getBitcast(LaneVT, V2);
9899 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9901 // Cast it back to the type we actually want.
9902 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9904 // Now do a simple shuffle that isn't lane crossing.
9905 SmallVector<int, 8> NewMask;
9906 NewMask.resize(Size, -1);
9907 for (int i = 0; i < Size; ++i)
9909 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9910 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9911 "Must not introduce lane crosses at this point!");
9913 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9916 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9919 /// This returns true if the elements from a particular input are already in the
9920 /// slot required by the given mask and require no permutation.
9921 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9922 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9923 int Size = Mask.size();
9924 for (int i = 0; i < Size; ++i)
9925 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9931 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9932 ArrayRef<int> Mask, SDValue V1,
9933 SDValue V2, SelectionDAG &DAG) {
9935 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9936 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9937 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9938 int NumElts = VT.getVectorNumElements();
9939 bool ShufpdMask = true;
9940 bool CommutableMask = true;
9941 unsigned Immediate = 0;
9942 for (int i = 0; i < NumElts; ++i) {
9945 int Val = (i & 6) + NumElts * (i & 1);
9946 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9947 if (Mask[i] < Val || Mask[i] > Val + 1)
9949 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9950 CommutableMask = false;
9951 Immediate |= (Mask[i] % 2) << i;
9954 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9955 DAG.getConstant(Immediate, DL, MVT::i8));
9957 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9958 DAG.getConstant(Immediate, DL, MVT::i8));
9962 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9964 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9965 /// isn't available.
9966 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9967 const X86Subtarget *Subtarget,
9968 SelectionDAG &DAG) {
9970 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9971 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9972 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9973 ArrayRef<int> Mask = SVOp->getMask();
9974 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9976 SmallVector<int, 4> WidenedMask;
9977 if (canWidenShuffleElements(Mask, WidenedMask))
9978 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9981 if (isSingleInputShuffleMask(Mask)) {
9982 // Check for being able to broadcast a single element.
9983 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9984 Mask, Subtarget, DAG))
9987 // Use low duplicate instructions for masks that match their pattern.
9988 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9989 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9991 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9992 // Non-half-crossing single input shuffles can be lowerid with an
9993 // interleaved permutation.
9994 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9995 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9996 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9997 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10000 // With AVX2 we have direct support for this permutation.
10001 if (Subtarget->hasAVX2())
10002 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10003 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10005 // Otherwise, fall back.
10006 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10010 // X86 has dedicated unpack instructions that can handle specific blend
10011 // operations: UNPCKH and UNPCKL.
10012 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10013 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10014 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10015 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10016 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10017 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10018 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10019 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10021 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10025 // Check if the blend happens to exactly fit that of SHUFPD.
10027 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10030 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10031 // shuffle. However, if we have AVX2 and either inputs are already in place,
10032 // we will be able to shuffle even across lanes the other input in a single
10033 // instruction so skip this pattern.
10034 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10035 isShuffleMaskInputInPlace(1, Mask))))
10036 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10037 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10040 // If we have AVX2 then we always want to lower with a blend because an v4 we
10041 // can fully permute the elements.
10042 if (Subtarget->hasAVX2())
10043 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10046 // Otherwise fall back on generic lowering.
10047 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10050 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10052 /// This routine is only called when we have AVX2 and thus a reasonable
10053 /// instruction set for v4i64 shuffling..
10054 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10055 const X86Subtarget *Subtarget,
10056 SelectionDAG &DAG) {
10058 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10059 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10060 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10061 ArrayRef<int> Mask = SVOp->getMask();
10062 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10063 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10065 SmallVector<int, 4> WidenedMask;
10066 if (canWidenShuffleElements(Mask, WidenedMask))
10067 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10070 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10074 // Check for being able to broadcast a single element.
10075 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10076 Mask, Subtarget, DAG))
10079 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10080 // use lower latency instructions that will operate on both 128-bit lanes.
10081 SmallVector<int, 2> RepeatedMask;
10082 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10083 if (isSingleInputShuffleMask(Mask)) {
10084 int PSHUFDMask[] = {-1, -1, -1, -1};
10085 for (int i = 0; i < 2; ++i)
10086 if (RepeatedMask[i] >= 0) {
10087 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10088 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10090 return DAG.getBitcast(
10092 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10093 DAG.getBitcast(MVT::v8i32, V1),
10094 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10098 // AVX2 provides a direct instruction for permuting a single input across
10100 if (isSingleInputShuffleMask(Mask))
10101 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10102 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10104 // Try to use shift instructions.
10105 if (SDValue Shift =
10106 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10109 // Use dedicated unpack instructions for masks that match their pattern.
10110 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10111 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10112 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10113 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10114 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10115 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10116 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10117 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10119 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10120 // shuffle. However, if we have AVX2 and either inputs are already in place,
10121 // we will be able to shuffle even across lanes the other input in a single
10122 // instruction so skip this pattern.
10123 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10124 isShuffleMaskInputInPlace(1, Mask))))
10125 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10126 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10129 // Otherwise fall back on generic blend lowering.
10130 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10134 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10136 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10137 /// isn't available.
10138 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10139 const X86Subtarget *Subtarget,
10140 SelectionDAG &DAG) {
10142 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10143 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10144 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10145 ArrayRef<int> Mask = SVOp->getMask();
10146 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10148 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10152 // Check for being able to broadcast a single element.
10153 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10154 Mask, Subtarget, DAG))
10157 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10158 // options to efficiently lower the shuffle.
10159 SmallVector<int, 4> RepeatedMask;
10160 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10161 assert(RepeatedMask.size() == 4 &&
10162 "Repeated masks must be half the mask width!");
10164 // Use even/odd duplicate instructions for masks that match their pattern.
10165 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10166 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10167 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10168 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10170 if (isSingleInputShuffleMask(Mask))
10171 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10172 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10174 // Use dedicated unpack instructions for masks that match their pattern.
10175 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10176 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10177 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10178 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10179 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10180 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10181 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10182 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10184 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10185 // have already handled any direct blends. We also need to squash the
10186 // repeated mask into a simulated v4f32 mask.
10187 for (int i = 0; i < 4; ++i)
10188 if (RepeatedMask[i] >= 8)
10189 RepeatedMask[i] -= 4;
10190 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10193 // If we have a single input shuffle with different shuffle patterns in the
10194 // two 128-bit lanes use the variable mask to VPERMILPS.
10195 if (isSingleInputShuffleMask(Mask)) {
10196 SDValue VPermMask[8];
10197 for (int i = 0; i < 8; ++i)
10198 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10199 : DAG.getConstant(Mask[i], DL, MVT::i32);
10200 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10201 return DAG.getNode(
10202 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10203 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10205 if (Subtarget->hasAVX2())
10206 return DAG.getNode(
10207 X86ISD::VPERMV, DL, MVT::v8f32,
10208 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10209 MVT::v8i32, VPermMask)),
10212 // Otherwise, fall back.
10213 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10217 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10219 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10220 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10223 // If we have AVX2 then we always want to lower with a blend because at v8 we
10224 // can fully permute the elements.
10225 if (Subtarget->hasAVX2())
10226 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10229 // Otherwise fall back on generic lowering.
10230 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10233 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10235 /// This routine is only called when we have AVX2 and thus a reasonable
10236 /// instruction set for v8i32 shuffling..
10237 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10238 const X86Subtarget *Subtarget,
10239 SelectionDAG &DAG) {
10241 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10242 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10243 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10244 ArrayRef<int> Mask = SVOp->getMask();
10245 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10246 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10248 // Whenever we can lower this as a zext, that instruction is strictly faster
10249 // than any alternative. It also allows us to fold memory operands into the
10250 // shuffle in many cases.
10251 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10252 Mask, Subtarget, DAG))
10255 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10259 // Check for being able to broadcast a single element.
10260 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10261 Mask, Subtarget, DAG))
10264 // If the shuffle mask is repeated in each 128-bit lane we can use more
10265 // efficient instructions that mirror the shuffles across the two 128-bit
10267 SmallVector<int, 4> RepeatedMask;
10268 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10269 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10270 if (isSingleInputShuffleMask(Mask))
10271 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10272 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10274 // Use dedicated unpack instructions for masks that match their pattern.
10275 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10276 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10277 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10278 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10279 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10280 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10281 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10282 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10285 // Try to use shift instructions.
10286 if (SDValue Shift =
10287 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10290 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10291 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10294 // If the shuffle patterns aren't repeated but it is a single input, directly
10295 // generate a cross-lane VPERMD instruction.
10296 if (isSingleInputShuffleMask(Mask)) {
10297 SDValue VPermMask[8];
10298 for (int i = 0; i < 8; ++i)
10299 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10300 : DAG.getConstant(Mask[i], DL, MVT::i32);
10301 return DAG.getNode(
10302 X86ISD::VPERMV, DL, MVT::v8i32,
10303 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10306 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10308 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10309 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10312 // Otherwise fall back on generic blend lowering.
10313 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10317 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10319 /// This routine is only called when we have AVX2 and thus a reasonable
10320 /// instruction set for v16i16 shuffling..
10321 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10322 const X86Subtarget *Subtarget,
10323 SelectionDAG &DAG) {
10325 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10326 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10327 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10328 ArrayRef<int> Mask = SVOp->getMask();
10329 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10330 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10332 // Whenever we can lower this as a zext, that instruction is strictly faster
10333 // than any alternative. It also allows us to fold memory operands into the
10334 // shuffle in many cases.
10335 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10336 Mask, Subtarget, DAG))
10339 // Check for being able to broadcast a single element.
10340 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10341 Mask, Subtarget, DAG))
10344 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10348 // Use dedicated unpack instructions for masks that match their pattern.
10349 if (isShuffleEquivalent(V1, V2, Mask,
10350 {// First 128-bit lane:
10351 0, 16, 1, 17, 2, 18, 3, 19,
10352 // Second 128-bit lane:
10353 8, 24, 9, 25, 10, 26, 11, 27}))
10354 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10355 if (isShuffleEquivalent(V1, V2, Mask,
10356 {// First 128-bit lane:
10357 4, 20, 5, 21, 6, 22, 7, 23,
10358 // Second 128-bit lane:
10359 12, 28, 13, 29, 14, 30, 15, 31}))
10360 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10362 // Try to use shift instructions.
10363 if (SDValue Shift =
10364 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10367 // Try to use byte rotation instructions.
10368 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10369 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10372 if (isSingleInputShuffleMask(Mask)) {
10373 // There are no generalized cross-lane shuffle operations available on i16
10375 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10376 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10379 SmallVector<int, 8> RepeatedMask;
10380 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10381 // As this is a single-input shuffle, the repeated mask should be
10382 // a strictly valid v8i16 mask that we can pass through to the v8i16
10383 // lowering to handle even the v16 case.
10384 return lowerV8I16GeneralSingleInputVectorShuffle(
10385 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10388 SDValue PSHUFBMask[32];
10389 for (int i = 0; i < 16; ++i) {
10390 if (Mask[i] == -1) {
10391 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10395 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10396 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10397 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10398 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10400 return DAG.getBitcast(MVT::v16i16,
10401 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10402 DAG.getBitcast(MVT::v32i8, V1),
10403 DAG.getNode(ISD::BUILD_VECTOR, DL,
10404 MVT::v32i8, PSHUFBMask)));
10407 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10409 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10410 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10413 // Otherwise fall back on generic lowering.
10414 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10417 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10419 /// This routine is only called when we have AVX2 and thus a reasonable
10420 /// instruction set for v32i8 shuffling..
10421 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10422 const X86Subtarget *Subtarget,
10423 SelectionDAG &DAG) {
10425 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10426 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10427 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10428 ArrayRef<int> Mask = SVOp->getMask();
10429 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10430 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10432 // Whenever we can lower this as a zext, that instruction is strictly faster
10433 // than any alternative. It also allows us to fold memory operands into the
10434 // shuffle in many cases.
10435 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10436 Mask, Subtarget, DAG))
10439 // Check for being able to broadcast a single element.
10440 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10441 Mask, Subtarget, DAG))
10444 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10448 // Use dedicated unpack instructions for masks that match their pattern.
10449 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10451 if (isShuffleEquivalent(
10453 {// First 128-bit lane:
10454 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10455 // Second 128-bit lane:
10456 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10457 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10458 if (isShuffleEquivalent(
10460 {// First 128-bit lane:
10461 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10462 // Second 128-bit lane:
10463 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10464 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10466 // Try to use shift instructions.
10467 if (SDValue Shift =
10468 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10471 // Try to use byte rotation instructions.
10472 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10473 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10476 if (isSingleInputShuffleMask(Mask)) {
10477 // There are no generalized cross-lane shuffle operations available on i8
10479 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10480 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10483 SDValue PSHUFBMask[32];
10484 for (int i = 0; i < 32; ++i)
10487 ? DAG.getUNDEF(MVT::i8)
10488 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10491 return DAG.getNode(
10492 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10493 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10496 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10498 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10499 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10502 // Otherwise fall back on generic lowering.
10503 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10506 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10508 /// This routine either breaks down the specific type of a 256-bit x86 vector
10509 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10510 /// together based on the available instructions.
10511 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10512 MVT VT, const X86Subtarget *Subtarget,
10513 SelectionDAG &DAG) {
10515 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10516 ArrayRef<int> Mask = SVOp->getMask();
10518 // If we have a single input to the zero element, insert that into V1 if we
10519 // can do so cheaply.
10520 int NumElts = VT.getVectorNumElements();
10521 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10522 return M >= NumElts;
10525 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10526 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10527 DL, VT, V1, V2, Mask, Subtarget, DAG))
10530 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10531 // check for those subtargets here and avoid much of the subtarget querying in
10532 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10533 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10534 // floating point types there eventually, just immediately cast everything to
10535 // a float and operate entirely in that domain.
10536 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10537 int ElementBits = VT.getScalarSizeInBits();
10538 if (ElementBits < 32)
10539 // No floating point type available, decompose into 128-bit vectors.
10540 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10542 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10543 VT.getVectorNumElements());
10544 V1 = DAG.getBitcast(FpVT, V1);
10545 V2 = DAG.getBitcast(FpVT, V2);
10546 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10549 switch (VT.SimpleTy) {
10551 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10553 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10555 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10557 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10559 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10561 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10564 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10568 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10569 ArrayRef<int> Mask, SDValue V1,
10570 SDValue V2, SelectionDAG &DAG) {
10572 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10574 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10575 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10577 SmallVector<SDValue, 32> VPermMask;
10578 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10579 VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10580 DAG.getConstant(Mask[i], DL, MaskEltVT));
10581 SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10583 if (isSingleInputShuffleMask(Mask))
10584 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10586 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10589 // X86 has dedicated unpack instructions that can handle specific blend
10590 // operations: UNPCKH and UNPCKL.
10591 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT,
10592 ArrayRef<int> Mask, SDValue V1,
10593 SDValue V2, SelectionDAG &DAG) {
10594 int NumElts = VT.getVectorNumElements();
10595 bool Unpckl = true;
10596 bool Unpckh = true;
10597 bool UnpcklSwapped = true;
10598 bool UnpckhSwapped = true;
10599 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
10601 for (int i = 0; i < NumElts ; ++i) {
10602 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
10604 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
10605 int HiPos = LoPos + NumEltsInLane / 2;
10606 int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
10607 int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
10611 if (Mask[i] != LoPos)
10613 if (Mask[i] != HiPos)
10615 if (Mask[i] != LoPosSwapped)
10616 UnpcklSwapped = false;
10617 if (Mask[i] != HiPosSwapped)
10618 UnpckhSwapped = false;
10619 if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
10623 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10625 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10627 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10629 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10631 llvm_unreachable("Unexpected result of UNPCK mask analysis");
10635 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10636 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10637 const X86Subtarget *Subtarget,
10638 SelectionDAG &DAG) {
10640 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10641 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10642 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10643 ArrayRef<int> Mask = SVOp->getMask();
10644 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10646 SDValue UnpckNode =
10647 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG);
10651 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10654 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10655 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10656 const X86Subtarget *Subtarget,
10657 SelectionDAG &DAG) {
10659 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10660 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10661 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10662 ArrayRef<int> Mask = SVOp->getMask();
10663 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10665 SDValue UnpckNode =
10666 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG);
10670 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10673 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10674 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10675 const X86Subtarget *Subtarget,
10676 SelectionDAG &DAG) {
10678 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10679 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10680 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10681 ArrayRef<int> Mask = SVOp->getMask();
10682 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10684 SDValue UnpckNode =
10685 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG);
10689 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10692 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10693 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10694 const X86Subtarget *Subtarget,
10695 SelectionDAG &DAG) {
10697 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10698 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10699 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10700 ArrayRef<int> Mask = SVOp->getMask();
10701 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10703 SDValue UnpckNode =
10704 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG);
10708 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10711 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10712 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10713 const X86Subtarget *Subtarget,
10714 SelectionDAG &DAG) {
10716 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10717 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10718 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10719 ArrayRef<int> Mask = SVOp->getMask();
10720 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10721 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10723 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10726 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10727 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10728 const X86Subtarget *Subtarget,
10729 SelectionDAG &DAG) {
10731 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10732 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10733 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10734 ArrayRef<int> Mask = SVOp->getMask();
10735 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10736 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10738 // FIXME: Implement direct support for this type!
10739 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10742 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10744 /// This routine either breaks down the specific type of a 512-bit x86 vector
10745 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10746 /// together based on the available instructions.
10747 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10748 MVT VT, const X86Subtarget *Subtarget,
10749 SelectionDAG &DAG) {
10751 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10752 ArrayRef<int> Mask = SVOp->getMask();
10753 assert(Subtarget->hasAVX512() &&
10754 "Cannot lower 512-bit vectors w/ basic ISA!");
10756 // Check for being able to broadcast a single element.
10757 if (SDValue Broadcast =
10758 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10761 // Dispatch to each element type for lowering. If we don't have supprot for
10762 // specific element type shuffles at 512 bits, immediately split them and
10763 // lower them. Each lowering routine of a given type is allowed to assume that
10764 // the requisite ISA extensions for that element type are available.
10765 switch (VT.SimpleTy) {
10767 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10769 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10771 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10773 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10775 if (Subtarget->hasBWI())
10776 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10779 if (Subtarget->hasBWI())
10780 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10784 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10787 // Otherwise fall back on splitting.
10788 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10791 /// \brief Top-level lowering for x86 vector shuffles.
10793 /// This handles decomposition, canonicalization, and lowering of all x86
10794 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10795 /// above in helper routines. The canonicalization attempts to widen shuffles
10796 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10797 /// s.t. only one of the two inputs needs to be tested, etc.
10798 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10799 SelectionDAG &DAG) {
10800 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10801 ArrayRef<int> Mask = SVOp->getMask();
10802 SDValue V1 = Op.getOperand(0);
10803 SDValue V2 = Op.getOperand(1);
10804 MVT VT = Op.getSimpleValueType();
10805 int NumElements = VT.getVectorNumElements();
10808 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10810 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10811 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10812 if (V1IsUndef && V2IsUndef)
10813 return DAG.getUNDEF(VT);
10815 // When we create a shuffle node we put the UNDEF node to second operand,
10816 // but in some cases the first operand may be transformed to UNDEF.
10817 // In this case we should just commute the node.
10819 return DAG.getCommutedVectorShuffle(*SVOp);
10821 // Check for non-undef masks pointing at an undef vector and make the masks
10822 // undef as well. This makes it easier to match the shuffle based solely on
10826 if (M >= NumElements) {
10827 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10828 for (int &M : NewMask)
10829 if (M >= NumElements)
10831 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10834 // We actually see shuffles that are entirely re-arrangements of a set of
10835 // zero inputs. This mostly happens while decomposing complex shuffles into
10836 // simple ones. Directly lower these as a buildvector of zeros.
10837 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10838 if (Zeroable.all())
10839 return getZeroVector(VT, Subtarget, DAG, dl);
10841 // Try to collapse shuffles into using a vector type with fewer elements but
10842 // wider element types. We cap this to not form integers or floating point
10843 // elements wider than 64 bits, but it might be interesting to form i128
10844 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10845 SmallVector<int, 16> WidenedMask;
10846 if (VT.getScalarSizeInBits() < 64 &&
10847 canWidenShuffleElements(Mask, WidenedMask)) {
10848 MVT NewEltVT = VT.isFloatingPoint()
10849 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10850 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10851 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10852 // Make sure that the new vector type is legal. For example, v2f64 isn't
10854 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10855 V1 = DAG.getBitcast(NewVT, V1);
10856 V2 = DAG.getBitcast(NewVT, V2);
10857 return DAG.getBitcast(
10858 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10862 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10863 for (int M : SVOp->getMask())
10865 ++NumUndefElements;
10866 else if (M < NumElements)
10871 // Commute the shuffle as needed such that more elements come from V1 than
10872 // V2. This allows us to match the shuffle pattern strictly on how many
10873 // elements come from V1 without handling the symmetric cases.
10874 if (NumV2Elements > NumV1Elements)
10875 return DAG.getCommutedVectorShuffle(*SVOp);
10877 // When the number of V1 and V2 elements are the same, try to minimize the
10878 // number of uses of V2 in the low half of the vector. When that is tied,
10879 // ensure that the sum of indices for V1 is equal to or lower than the sum
10880 // indices for V2. When those are equal, try to ensure that the number of odd
10881 // indices for V1 is lower than the number of odd indices for V2.
10882 if (NumV1Elements == NumV2Elements) {
10883 int LowV1Elements = 0, LowV2Elements = 0;
10884 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10885 if (M >= NumElements)
10889 if (LowV2Elements > LowV1Elements) {
10890 return DAG.getCommutedVectorShuffle(*SVOp);
10891 } else if (LowV2Elements == LowV1Elements) {
10892 int SumV1Indices = 0, SumV2Indices = 0;
10893 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10894 if (SVOp->getMask()[i] >= NumElements)
10896 else if (SVOp->getMask()[i] >= 0)
10898 if (SumV2Indices < SumV1Indices) {
10899 return DAG.getCommutedVectorShuffle(*SVOp);
10900 } else if (SumV2Indices == SumV1Indices) {
10901 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10902 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10903 if (SVOp->getMask()[i] >= NumElements)
10904 NumV2OddIndices += i % 2;
10905 else if (SVOp->getMask()[i] >= 0)
10906 NumV1OddIndices += i % 2;
10907 if (NumV2OddIndices < NumV1OddIndices)
10908 return DAG.getCommutedVectorShuffle(*SVOp);
10913 // For each vector width, delegate to a specialized lowering routine.
10914 if (VT.getSizeInBits() == 128)
10915 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10917 if (VT.getSizeInBits() == 256)
10918 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10920 if (VT.getSizeInBits() == 512)
10921 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10923 llvm_unreachable("Unimplemented!");
10926 // This function assumes its argument is a BUILD_VECTOR of constants or
10927 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10929 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10930 unsigned &MaskValue) {
10932 unsigned NumElems = BuildVector->getNumOperands();
10933 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10934 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10935 unsigned NumElemsInLane = NumElems / NumLanes;
10937 // Blend for v16i16 should be symmetric for the both lanes.
10938 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10939 SDValue EltCond = BuildVector->getOperand(i);
10940 SDValue SndLaneEltCond =
10941 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10943 int Lane1Cond = -1, Lane2Cond = -1;
10944 if (isa<ConstantSDNode>(EltCond))
10945 Lane1Cond = !isZero(EltCond);
10946 if (isa<ConstantSDNode>(SndLaneEltCond))
10947 Lane2Cond = !isZero(SndLaneEltCond);
10949 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10950 // Lane1Cond != 0, means we want the first argument.
10951 // Lane1Cond == 0, means we want the second argument.
10952 // The encoding of this argument is 0 for the first argument, 1
10953 // for the second. Therefore, invert the condition.
10954 MaskValue |= !Lane1Cond << i;
10955 else if (Lane1Cond < 0)
10956 MaskValue |= !Lane2Cond << i;
10963 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10964 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10965 const X86Subtarget *Subtarget,
10966 SelectionDAG &DAG) {
10967 SDValue Cond = Op.getOperand(0);
10968 SDValue LHS = Op.getOperand(1);
10969 SDValue RHS = Op.getOperand(2);
10971 MVT VT = Op.getSimpleValueType();
10973 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10975 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10977 // Only non-legal VSELECTs reach this lowering, convert those into generic
10978 // shuffles and re-use the shuffle lowering path for blends.
10979 SmallVector<int, 32> Mask;
10980 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10981 SDValue CondElt = CondBV->getOperand(i);
10983 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10985 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10988 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10989 // A vselect where all conditions and data are constants can be optimized into
10990 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10991 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10992 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10993 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10996 // Try to lower this to a blend-style vector shuffle. This can handle all
10997 // constant condition cases.
10998 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11001 // Variable blends are only legal from SSE4.1 onward.
11002 if (!Subtarget->hasSSE41())
11005 // Only some types will be legal on some subtargets. If we can emit a legal
11006 // VSELECT-matching blend, return Op, and but if we need to expand, return
11008 switch (Op.getSimpleValueType().SimpleTy) {
11010 // Most of the vector types have blends past SSE4.1.
11014 // The byte blends for AVX vectors were introduced only in AVX2.
11015 if (Subtarget->hasAVX2())
11022 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11023 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11026 // FIXME: We should custom lower this by fixing the condition and using i8
11032 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11033 MVT VT = Op.getSimpleValueType();
11036 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11039 if (VT.getSizeInBits() == 8) {
11040 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11041 Op.getOperand(0), Op.getOperand(1));
11042 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11043 DAG.getValueType(VT));
11044 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11047 if (VT.getSizeInBits() == 16) {
11048 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11049 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11051 return DAG.getNode(
11052 ISD::TRUNCATE, dl, MVT::i16,
11053 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11054 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11055 Op.getOperand(1)));
11056 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11057 Op.getOperand(0), Op.getOperand(1));
11058 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11059 DAG.getValueType(VT));
11060 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11063 if (VT == MVT::f32) {
11064 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11065 // the result back to FR32 register. It's only worth matching if the
11066 // result has a single use which is a store or a bitcast to i32. And in
11067 // the case of a store, it's not worth it if the index is a constant 0,
11068 // because a MOVSSmr can be used instead, which is smaller and faster.
11069 if (!Op.hasOneUse())
11071 SDNode *User = *Op.getNode()->use_begin();
11072 if ((User->getOpcode() != ISD::STORE ||
11073 (isa<ConstantSDNode>(Op.getOperand(1)) &&
11074 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11075 (User->getOpcode() != ISD::BITCAST ||
11076 User->getValueType(0) != MVT::i32))
11078 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11079 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11081 return DAG.getBitcast(MVT::f32, Extract);
11084 if (VT == MVT::i32 || VT == MVT::i64) {
11085 // ExtractPS/pextrq works with constant index.
11086 if (isa<ConstantSDNode>(Op.getOperand(1)))
11092 /// Extract one bit from mask vector, like v16i1 or v8i1.
11093 /// AVX-512 feature.
11095 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11096 SDValue Vec = Op.getOperand(0);
11098 MVT VecVT = Vec.getSimpleValueType();
11099 SDValue Idx = Op.getOperand(1);
11100 MVT EltVT = Op.getSimpleValueType();
11102 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11103 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11104 "Unexpected vector type in ExtractBitFromMaskVector");
11106 // variable index can't be handled in mask registers,
11107 // extend vector to VR512
11108 if (!isa<ConstantSDNode>(Idx)) {
11109 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11110 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11111 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11112 ExtVT.getVectorElementType(), Ext, Idx);
11113 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11116 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11117 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11118 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11119 rc = getRegClassFor(MVT::v16i1);
11120 unsigned MaxSift = rc->getSize()*8 - 1;
11121 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11122 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11123 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11124 DAG.getConstant(MaxSift, dl, MVT::i8));
11125 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11126 DAG.getIntPtrConstant(0, dl));
11130 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11131 SelectionDAG &DAG) const {
11133 SDValue Vec = Op.getOperand(0);
11134 MVT VecVT = Vec.getSimpleValueType();
11135 SDValue Idx = Op.getOperand(1);
11137 if (Op.getSimpleValueType() == MVT::i1)
11138 return ExtractBitFromMaskVector(Op, DAG);
11140 if (!isa<ConstantSDNode>(Idx)) {
11141 if (VecVT.is512BitVector() ||
11142 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11143 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11146 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11147 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11148 MaskEltVT.getSizeInBits());
11150 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11151 auto PtrVT = getPointerTy(DAG.getDataLayout());
11152 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11153 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11154 DAG.getConstant(0, dl, PtrVT));
11155 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11156 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11157 DAG.getConstant(0, dl, PtrVT));
11162 // If this is a 256-bit vector result, first extract the 128-bit vector and
11163 // then extract the element from the 128-bit vector.
11164 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11166 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11167 // Get the 128-bit vector.
11168 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11169 MVT EltVT = VecVT.getVectorElementType();
11171 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11173 //if (IdxVal >= NumElems/2)
11174 // IdxVal -= NumElems/2;
11175 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11176 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11177 DAG.getConstant(IdxVal, dl, MVT::i32));
11180 assert(VecVT.is128BitVector() && "Unexpected vector length");
11182 if (Subtarget->hasSSE41())
11183 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11186 MVT VT = Op.getSimpleValueType();
11187 // TODO: handle v16i8.
11188 if (VT.getSizeInBits() == 16) {
11189 SDValue Vec = Op.getOperand(0);
11190 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11192 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11193 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11194 DAG.getBitcast(MVT::v4i32, Vec),
11195 Op.getOperand(1)));
11196 // Transform it so it match pextrw which produces a 32-bit result.
11197 MVT EltVT = MVT::i32;
11198 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11199 Op.getOperand(0), Op.getOperand(1));
11200 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11201 DAG.getValueType(VT));
11202 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11205 if (VT.getSizeInBits() == 32) {
11206 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11210 // SHUFPS the element to the lowest double word, then movss.
11211 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11212 MVT VVT = Op.getOperand(0).getSimpleValueType();
11213 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11214 DAG.getUNDEF(VVT), Mask);
11215 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11216 DAG.getIntPtrConstant(0, dl));
11219 if (VT.getSizeInBits() == 64) {
11220 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11221 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11222 // to match extract_elt for f64.
11223 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11227 // UNPCKHPD the element to the lowest double word, then movsd.
11228 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11229 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11230 int Mask[2] = { 1, -1 };
11231 MVT VVT = Op.getOperand(0).getSimpleValueType();
11232 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11233 DAG.getUNDEF(VVT), Mask);
11234 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11235 DAG.getIntPtrConstant(0, dl));
11241 /// Insert one bit to mask vector, like v16i1 or v8i1.
11242 /// AVX-512 feature.
11244 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11246 SDValue Vec = Op.getOperand(0);
11247 SDValue Elt = Op.getOperand(1);
11248 SDValue Idx = Op.getOperand(2);
11249 MVT VecVT = Vec.getSimpleValueType();
11251 if (!isa<ConstantSDNode>(Idx)) {
11252 // Non constant index. Extend source and destination,
11253 // insert element and then truncate the result.
11254 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11255 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11256 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11257 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11258 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11259 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11262 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11263 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11265 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11266 DAG.getConstant(IdxVal, dl, MVT::i8));
11267 if (Vec.getOpcode() == ISD::UNDEF)
11269 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11272 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11273 SelectionDAG &DAG) const {
11274 MVT VT = Op.getSimpleValueType();
11275 MVT EltVT = VT.getVectorElementType();
11277 if (EltVT == MVT::i1)
11278 return InsertBitToMaskVector(Op, DAG);
11281 SDValue N0 = Op.getOperand(0);
11282 SDValue N1 = Op.getOperand(1);
11283 SDValue N2 = Op.getOperand(2);
11284 if (!isa<ConstantSDNode>(N2))
11286 auto *N2C = cast<ConstantSDNode>(N2);
11287 unsigned IdxVal = N2C->getZExtValue();
11289 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11290 // into that, and then insert the subvector back into the result.
11291 if (VT.is256BitVector() || VT.is512BitVector()) {
11292 // With a 256-bit vector, we can insert into the zero element efficiently
11293 // using a blend if we have AVX or AVX2 and the right data type.
11294 if (VT.is256BitVector() && IdxVal == 0) {
11295 // TODO: It is worthwhile to cast integer to floating point and back
11296 // and incur a domain crossing penalty if that's what we'll end up
11297 // doing anyway after extracting to a 128-bit vector.
11298 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11299 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11300 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11301 N2 = DAG.getIntPtrConstant(1, dl);
11302 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11306 // Get the desired 128-bit vector chunk.
11307 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11309 // Insert the element into the desired chunk.
11310 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11311 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11313 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11314 DAG.getConstant(IdxIn128, dl, MVT::i32));
11316 // Insert the changed part back into the bigger vector
11317 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11319 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11321 if (Subtarget->hasSSE41()) {
11322 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11324 if (VT == MVT::v8i16) {
11325 Opc = X86ISD::PINSRW;
11327 assert(VT == MVT::v16i8);
11328 Opc = X86ISD::PINSRB;
11331 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11333 if (N1.getValueType() != MVT::i32)
11334 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11335 if (N2.getValueType() != MVT::i32)
11336 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11337 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11340 if (EltVT == MVT::f32) {
11341 // Bits [7:6] of the constant are the source select. This will always be
11342 // zero here. The DAG Combiner may combine an extract_elt index into
11343 // these bits. For example (insert (extract, 3), 2) could be matched by
11344 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11345 // Bits [5:4] of the constant are the destination select. This is the
11346 // value of the incoming immediate.
11347 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11348 // combine either bitwise AND or insert of float 0.0 to set these bits.
11350 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11351 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11352 // If this is an insertion of 32-bits into the low 32-bits of
11353 // a vector, we prefer to generate a blend with immediate rather
11354 // than an insertps. Blends are simpler operations in hardware and so
11355 // will always have equal or better performance than insertps.
11356 // But if optimizing for size and there's a load folding opportunity,
11357 // generate insertps because blendps does not have a 32-bit memory
11359 N2 = DAG.getIntPtrConstant(1, dl);
11360 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11361 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11363 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11364 // Create this as a scalar to vector..
11365 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11366 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11369 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11370 // PINSR* works with constant index.
11375 if (EltVT == MVT::i8)
11378 if (EltVT.getSizeInBits() == 16) {
11379 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11380 // as its second argument.
11381 if (N1.getValueType() != MVT::i32)
11382 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11383 if (N2.getValueType() != MVT::i32)
11384 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11385 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11390 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11392 MVT OpVT = Op.getSimpleValueType();
11394 // If this is a 256-bit vector result, first insert into a 128-bit
11395 // vector and then insert into the 256-bit vector.
11396 if (!OpVT.is128BitVector()) {
11397 // Insert into a 128-bit vector.
11398 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11399 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11400 OpVT.getVectorNumElements() / SizeFactor);
11402 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11404 // Insert the 128-bit vector.
11405 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11408 if (OpVT == MVT::v1i64 &&
11409 Op.getOperand(0).getValueType() == MVT::i64)
11410 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11412 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11413 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11414 return DAG.getBitcast(
11415 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11418 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11419 // a simple subregister reference or explicit instructions to grab
11420 // upper bits of a vector.
11421 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11422 SelectionDAG &DAG) {
11424 SDValue In = Op.getOperand(0);
11425 SDValue Idx = Op.getOperand(1);
11426 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11427 MVT ResVT = Op.getSimpleValueType();
11428 MVT InVT = In.getSimpleValueType();
11430 if (Subtarget->hasFp256()) {
11431 if (ResVT.is128BitVector() &&
11432 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11433 isa<ConstantSDNode>(Idx)) {
11434 return Extract128BitVector(In, IdxVal, DAG, dl);
11436 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11437 isa<ConstantSDNode>(Idx)) {
11438 return Extract256BitVector(In, IdxVal, DAG, dl);
11444 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11445 // simple superregister reference or explicit instructions to insert
11446 // the upper bits of a vector.
11447 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11448 SelectionDAG &DAG) {
11449 if (!Subtarget->hasAVX())
11453 SDValue Vec = Op.getOperand(0);
11454 SDValue SubVec = Op.getOperand(1);
11455 SDValue Idx = Op.getOperand(2);
11457 if (!isa<ConstantSDNode>(Idx))
11460 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11461 MVT OpVT = Op.getSimpleValueType();
11462 MVT SubVecVT = SubVec.getSimpleValueType();
11464 // Fold two 16-byte subvector loads into one 32-byte load:
11465 // (insert_subvector (insert_subvector undef, (load addr), 0),
11466 // (load addr + 16), Elts/2)
11468 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11469 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11470 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11471 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11472 if (Idx2 && Idx2->getZExtValue() == 0) {
11473 SDValue SubVec2 = Vec.getOperand(1);
11474 // If needed, look through a bitcast to get to the load.
11475 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11476 SubVec2 = SubVec2.getOperand(0);
11478 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11480 unsigned Alignment = FirstLd->getAlignment();
11481 unsigned AS = FirstLd->getAddressSpace();
11482 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11483 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11484 OpVT, AS, Alignment, &Fast) && Fast) {
11485 SDValue Ops[] = { SubVec2, SubVec };
11486 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11493 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11494 SubVecVT.is128BitVector())
11495 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11497 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11498 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11500 if (OpVT.getVectorElementType() == MVT::i1) {
11501 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11503 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11504 SDValue Undef = DAG.getUNDEF(OpVT);
11505 unsigned NumElems = OpVT.getVectorNumElements();
11506 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11508 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11509 // Zero upper bits of the Vec
11510 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11511 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11513 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11515 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11516 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11519 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11521 // Zero upper bits of the Vec2
11522 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11523 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11524 // Zero lower bits of the Vec
11525 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11526 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11527 // Merge them together
11528 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11534 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11535 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11536 // one of the above mentioned nodes. It has to be wrapped because otherwise
11537 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11538 // be used to form addressing mode. These wrapped nodes will be selected
11541 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11542 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11544 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11545 // global base reg.
11546 unsigned char OpFlag = 0;
11547 unsigned WrapperKind = X86ISD::Wrapper;
11548 CodeModel::Model M = DAG.getTarget().getCodeModel();
11550 if (Subtarget->isPICStyleRIPRel() &&
11551 (M == CodeModel::Small || M == CodeModel::Kernel))
11552 WrapperKind = X86ISD::WrapperRIP;
11553 else if (Subtarget->isPICStyleGOT())
11554 OpFlag = X86II::MO_GOTOFF;
11555 else if (Subtarget->isPICStyleStubPIC())
11556 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11558 auto PtrVT = getPointerTy(DAG.getDataLayout());
11559 SDValue Result = DAG.getTargetConstantPool(
11560 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11562 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11563 // With PIC, the address is actually $g + Offset.
11566 DAG.getNode(ISD::ADD, DL, PtrVT,
11567 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11573 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11574 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11576 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11577 // global base reg.
11578 unsigned char OpFlag = 0;
11579 unsigned WrapperKind = X86ISD::Wrapper;
11580 CodeModel::Model M = DAG.getTarget().getCodeModel();
11582 if (Subtarget->isPICStyleRIPRel() &&
11583 (M == CodeModel::Small || M == CodeModel::Kernel))
11584 WrapperKind = X86ISD::WrapperRIP;
11585 else if (Subtarget->isPICStyleGOT())
11586 OpFlag = X86II::MO_GOTOFF;
11587 else if (Subtarget->isPICStyleStubPIC())
11588 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11590 auto PtrVT = getPointerTy(DAG.getDataLayout());
11591 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11593 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11595 // With PIC, the address is actually $g + Offset.
11598 DAG.getNode(ISD::ADD, DL, PtrVT,
11599 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11605 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11606 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11608 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11609 // global base reg.
11610 unsigned char OpFlag = 0;
11611 unsigned WrapperKind = X86ISD::Wrapper;
11612 CodeModel::Model M = DAG.getTarget().getCodeModel();
11614 if (Subtarget->isPICStyleRIPRel() &&
11615 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11616 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11617 OpFlag = X86II::MO_GOTPCREL;
11618 WrapperKind = X86ISD::WrapperRIP;
11619 } else if (Subtarget->isPICStyleGOT()) {
11620 OpFlag = X86II::MO_GOT;
11621 } else if (Subtarget->isPICStyleStubPIC()) {
11622 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11623 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11624 OpFlag = X86II::MO_DARWIN_NONLAZY;
11627 auto PtrVT = getPointerTy(DAG.getDataLayout());
11628 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11631 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11633 // With PIC, the address is actually $g + Offset.
11634 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11635 !Subtarget->is64Bit()) {
11637 DAG.getNode(ISD::ADD, DL, PtrVT,
11638 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11641 // For symbols that require a load from a stub to get the address, emit the
11643 if (isGlobalStubReference(OpFlag))
11644 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11645 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11646 false, false, false, 0);
11652 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11653 // Create the TargetBlockAddressAddress node.
11654 unsigned char OpFlags =
11655 Subtarget->ClassifyBlockAddressReference();
11656 CodeModel::Model M = DAG.getTarget().getCodeModel();
11657 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11658 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11660 auto PtrVT = getPointerTy(DAG.getDataLayout());
11661 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11663 if (Subtarget->isPICStyleRIPRel() &&
11664 (M == CodeModel::Small || M == CodeModel::Kernel))
11665 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11667 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11669 // With PIC, the address is actually $g + Offset.
11670 if (isGlobalRelativeToPICBase(OpFlags)) {
11671 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11672 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11679 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11680 int64_t Offset, SelectionDAG &DAG) const {
11681 // Create the TargetGlobalAddress node, folding in the constant
11682 // offset if it is legal.
11683 unsigned char OpFlags =
11684 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11685 CodeModel::Model M = DAG.getTarget().getCodeModel();
11686 auto PtrVT = getPointerTy(DAG.getDataLayout());
11688 if (OpFlags == X86II::MO_NO_FLAG &&
11689 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11690 // A direct static reference to a global.
11691 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11694 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11697 if (Subtarget->isPICStyleRIPRel() &&
11698 (M == CodeModel::Small || M == CodeModel::Kernel))
11699 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11701 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11703 // With PIC, the address is actually $g + Offset.
11704 if (isGlobalRelativeToPICBase(OpFlags)) {
11705 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11706 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11709 // For globals that require a load from a stub to get the address, emit the
11711 if (isGlobalStubReference(OpFlags))
11712 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11713 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11714 false, false, false, 0);
11716 // If there was a non-zero offset that we didn't fold, create an explicit
11717 // addition for it.
11719 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11720 DAG.getConstant(Offset, dl, PtrVT));
11726 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11727 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11728 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11729 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11733 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11734 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11735 unsigned char OperandFlags, bool LocalDynamic = false) {
11736 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11737 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11739 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11740 GA->getValueType(0),
11744 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11748 SDValue Ops[] = { Chain, TGA, *InFlag };
11749 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11751 SDValue Ops[] = { Chain, TGA };
11752 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11755 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11756 MFI->setAdjustsStack(true);
11757 MFI->setHasCalls(true);
11759 SDValue Flag = Chain.getValue(1);
11760 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11763 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11765 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11768 SDLoc dl(GA); // ? function entry point might be better
11769 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11770 DAG.getNode(X86ISD::GlobalBaseReg,
11771 SDLoc(), PtrVT), InFlag);
11772 InFlag = Chain.getValue(1);
11774 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11777 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11779 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11781 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11782 X86::RAX, X86II::MO_TLSGD);
11785 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11791 // Get the start address of the TLS block for this module.
11792 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11793 .getInfo<X86MachineFunctionInfo>();
11794 MFI->incNumLocalDynamicTLSAccesses();
11798 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11799 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11802 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11803 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11804 InFlag = Chain.getValue(1);
11805 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11806 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11809 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11813 unsigned char OperandFlags = X86II::MO_DTPOFF;
11814 unsigned WrapperKind = X86ISD::Wrapper;
11815 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11816 GA->getValueType(0),
11817 GA->getOffset(), OperandFlags);
11818 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11820 // Add x@dtpoff with the base.
11821 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11824 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11825 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11826 const EVT PtrVT, TLSModel::Model model,
11827 bool is64Bit, bool isPIC) {
11830 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11831 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11832 is64Bit ? 257 : 256));
11834 SDValue ThreadPointer =
11835 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11836 MachinePointerInfo(Ptr), false, false, false, 0);
11838 unsigned char OperandFlags = 0;
11839 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11841 unsigned WrapperKind = X86ISD::Wrapper;
11842 if (model == TLSModel::LocalExec) {
11843 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11844 } else if (model == TLSModel::InitialExec) {
11846 OperandFlags = X86II::MO_GOTTPOFF;
11847 WrapperKind = X86ISD::WrapperRIP;
11849 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11852 llvm_unreachable("Unexpected model");
11855 // emit "addl x@ntpoff,%eax" (local exec)
11856 // or "addl x@indntpoff,%eax" (initial exec)
11857 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11859 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11860 GA->getOffset(), OperandFlags);
11861 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11863 if (model == TLSModel::InitialExec) {
11864 if (isPIC && !is64Bit) {
11865 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11866 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11870 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11871 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11872 false, false, false, 0);
11875 // The address of the thread local variable is the add of the thread
11876 // pointer with the offset of the variable.
11877 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11881 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11883 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11884 const GlobalValue *GV = GA->getGlobal();
11885 auto PtrVT = getPointerTy(DAG.getDataLayout());
11887 if (Subtarget->isTargetELF()) {
11888 if (DAG.getTarget().Options.EmulatedTLS)
11889 return LowerToTLSEmulatedModel(GA, DAG);
11890 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11892 case TLSModel::GeneralDynamic:
11893 if (Subtarget->is64Bit())
11894 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11895 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11896 case TLSModel::LocalDynamic:
11897 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11898 Subtarget->is64Bit());
11899 case TLSModel::InitialExec:
11900 case TLSModel::LocalExec:
11901 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11902 DAG.getTarget().getRelocationModel() ==
11905 llvm_unreachable("Unknown TLS model.");
11908 if (Subtarget->isTargetDarwin()) {
11909 // Darwin only has one model of TLS. Lower to that.
11910 unsigned char OpFlag = 0;
11911 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11912 X86ISD::WrapperRIP : X86ISD::Wrapper;
11914 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11915 // global base reg.
11916 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11917 !Subtarget->is64Bit();
11919 OpFlag = X86II::MO_TLVP_PIC_BASE;
11921 OpFlag = X86II::MO_TLVP;
11923 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11924 GA->getValueType(0),
11925 GA->getOffset(), OpFlag);
11926 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11928 // With PIC32, the address is actually $g + Offset.
11930 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11931 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11934 // Lowering the machine isd will make sure everything is in the right
11936 SDValue Chain = DAG.getEntryNode();
11937 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11938 SDValue Args[] = { Chain, Offset };
11939 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11941 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11942 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11943 MFI->setAdjustsStack(true);
11945 // And our return value (tls address) is in the standard call return value
11947 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11948 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11951 if (Subtarget->isTargetKnownWindowsMSVC() ||
11952 Subtarget->isTargetWindowsGNU()) {
11953 // Just use the implicit TLS architecture
11954 // Need to generate someting similar to:
11955 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11957 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11958 // mov rcx, qword [rdx+rcx*8]
11959 // mov eax, .tls$:tlsvar
11960 // [rax+rcx] contains the address
11961 // Windows 64bit: gs:0x58
11962 // Windows 32bit: fs:__tls_array
11965 SDValue Chain = DAG.getEntryNode();
11967 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11968 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11969 // use its literal value of 0x2C.
11970 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11971 ? Type::getInt8PtrTy(*DAG.getContext(),
11973 : Type::getInt32PtrTy(*DAG.getContext(),
11976 SDValue TlsArray = Subtarget->is64Bit()
11977 ? DAG.getIntPtrConstant(0x58, dl)
11978 : (Subtarget->isTargetWindowsGNU()
11979 ? DAG.getIntPtrConstant(0x2C, dl)
11980 : DAG.getExternalSymbol("_tls_array", PtrVT));
11982 SDValue ThreadPointer =
11983 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11987 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11988 res = ThreadPointer;
11990 // Load the _tls_index variable
11991 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11992 if (Subtarget->is64Bit())
11993 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11994 MachinePointerInfo(), MVT::i32, false, false,
11997 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12000 auto &DL = DAG.getDataLayout();
12002 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12003 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12005 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12008 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12011 // Get the offset of start of .tls section
12012 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12013 GA->getValueType(0),
12014 GA->getOffset(), X86II::MO_SECREL);
12015 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12017 // The address of the thread local variable is the add of the thread
12018 // pointer with the offset of the variable.
12019 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12022 llvm_unreachable("TLS not implemented for this target.");
12025 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12026 /// and take a 2 x i32 value to shift plus a shift amount.
12027 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12028 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12029 MVT VT = Op.getSimpleValueType();
12030 unsigned VTBits = VT.getSizeInBits();
12032 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12033 SDValue ShOpLo = Op.getOperand(0);
12034 SDValue ShOpHi = Op.getOperand(1);
12035 SDValue ShAmt = Op.getOperand(2);
12036 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12037 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12039 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12040 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12041 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12042 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12043 : DAG.getConstant(0, dl, VT);
12045 SDValue Tmp2, Tmp3;
12046 if (Op.getOpcode() == ISD::SHL_PARTS) {
12047 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12048 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12050 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12051 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12054 // If the shift amount is larger or equal than the width of a part we can't
12055 // rely on the results of shld/shrd. Insert a test and select the appropriate
12056 // values for large shift amounts.
12057 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12058 DAG.getConstant(VTBits, dl, MVT::i8));
12059 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12060 AndNode, DAG.getConstant(0, dl, MVT::i8));
12063 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12064 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12065 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12067 if (Op.getOpcode() == ISD::SHL_PARTS) {
12068 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12069 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12071 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12072 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12075 SDValue Ops[2] = { Lo, Hi };
12076 return DAG.getMergeValues(Ops, dl);
12079 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12080 SelectionDAG &DAG) const {
12081 SDValue Src = Op.getOperand(0);
12082 MVT SrcVT = Src.getSimpleValueType();
12083 MVT VT = Op.getSimpleValueType();
12086 if (SrcVT.isVector()) {
12087 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12088 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12089 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12090 DAG.getUNDEF(SrcVT)));
12092 if (SrcVT.getVectorElementType() == MVT::i1) {
12093 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12094 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12095 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12100 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12101 "Unknown SINT_TO_FP to lower!");
12103 // These are really Legal; return the operand so the caller accepts it as
12105 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12107 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12108 Subtarget->is64Bit()) {
12112 unsigned Size = SrcVT.getSizeInBits()/8;
12113 MachineFunction &MF = DAG.getMachineFunction();
12114 auto PtrVT = getPointerTy(MF.getDataLayout());
12115 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12116 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12117 SDValue Chain = DAG.getStore(
12118 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12119 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12121 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12124 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12126 SelectionDAG &DAG) const {
12130 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12132 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12134 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12136 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12138 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12139 MachineMemOperand *MMO;
12141 int SSFI = FI->getIndex();
12142 MMO = DAG.getMachineFunction().getMachineMemOperand(
12143 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12144 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12146 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12147 StackSlot = StackSlot.getOperand(1);
12149 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12150 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12152 Tys, Ops, SrcVT, MMO);
12155 Chain = Result.getValue(1);
12156 SDValue InFlag = Result.getValue(2);
12158 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12159 // shouldn't be necessary except that RFP cannot be live across
12160 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12161 MachineFunction &MF = DAG.getMachineFunction();
12162 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12163 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12164 auto PtrVT = getPointerTy(MF.getDataLayout());
12165 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12166 Tys = DAG.getVTList(MVT::Other);
12168 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12170 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12171 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12172 MachineMemOperand::MOStore, SSFISize, SSFISize);
12174 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12175 Ops, Op.getValueType(), MMO);
12176 Result = DAG.getLoad(
12177 Op.getValueType(), DL, Chain, StackSlot,
12178 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12179 false, false, false, 0);
12185 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12186 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12187 SelectionDAG &DAG) const {
12188 // This algorithm is not obvious. Here it is what we're trying to output:
12191 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12192 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12194 haddpd %xmm0, %xmm0
12196 pshufd $0x4e, %xmm0, %xmm1
12202 LLVMContext *Context = DAG.getContext();
12204 // Build some magic constants.
12205 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12206 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12207 auto PtrVT = getPointerTy(DAG.getDataLayout());
12208 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12210 SmallVector<Constant*,2> CV1;
12212 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12213 APInt(64, 0x4330000000000000ULL))));
12215 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12216 APInt(64, 0x4530000000000000ULL))));
12217 Constant *C1 = ConstantVector::get(CV1);
12218 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12220 // Load the 64-bit value into an XMM register.
12221 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12224 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12225 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12226 false, false, false, 16);
12228 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12231 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12232 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12233 false, false, false, 16);
12234 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12235 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12238 if (Subtarget->hasSSE3()) {
12239 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12240 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12242 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12243 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12245 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12246 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12249 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12250 DAG.getIntPtrConstant(0, dl));
12253 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12254 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12255 SelectionDAG &DAG) const {
12257 // FP constant to bias correct the final result.
12258 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12261 // Load the 32-bit value into an XMM register.
12262 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12265 // Zero out the upper parts of the register.
12266 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12268 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12269 DAG.getBitcast(MVT::v2f64, Load),
12270 DAG.getIntPtrConstant(0, dl));
12272 // Or the load with the bias.
12273 SDValue Or = DAG.getNode(
12274 ISD::OR, dl, MVT::v2i64,
12275 DAG.getBitcast(MVT::v2i64,
12276 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12277 DAG.getBitcast(MVT::v2i64,
12278 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12280 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12281 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12283 // Subtract the bias.
12284 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12286 // Handle final rounding.
12287 EVT DestVT = Op.getValueType();
12289 if (DestVT.bitsLT(MVT::f64))
12290 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12291 DAG.getIntPtrConstant(0, dl));
12292 if (DestVT.bitsGT(MVT::f64))
12293 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12295 // Handle final rounding.
12299 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12300 const X86Subtarget &Subtarget) {
12301 // The algorithm is the following:
12302 // #ifdef __SSE4_1__
12303 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12304 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12305 // (uint4) 0x53000000, 0xaa);
12307 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12308 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12310 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12311 // return (float4) lo + fhi;
12314 SDValue V = Op->getOperand(0);
12315 EVT VecIntVT = V.getValueType();
12316 bool Is128 = VecIntVT == MVT::v4i32;
12317 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12318 // If we convert to something else than the supported type, e.g., to v4f64,
12320 if (VecFloatVT != Op->getValueType(0))
12323 unsigned NumElts = VecIntVT.getVectorNumElements();
12324 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12325 "Unsupported custom type");
12326 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12328 // In the #idef/#else code, we have in common:
12329 // - The vector of constants:
12335 // Create the splat vector for 0x4b000000.
12336 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12337 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12338 CstLow, CstLow, CstLow, CstLow};
12339 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12340 makeArrayRef(&CstLowArray[0], NumElts));
12341 // Create the splat vector for 0x53000000.
12342 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12343 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12344 CstHigh, CstHigh, CstHigh, CstHigh};
12345 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12346 makeArrayRef(&CstHighArray[0], NumElts));
12348 // Create the right shift.
12349 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12350 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12351 CstShift, CstShift, CstShift, CstShift};
12352 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12353 makeArrayRef(&CstShiftArray[0], NumElts));
12354 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12357 if (Subtarget.hasSSE41()) {
12358 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12359 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12360 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12361 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12362 // Low will be bitcasted right away, so do not bother bitcasting back to its
12364 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12365 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12366 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12367 // (uint4) 0x53000000, 0xaa);
12368 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12369 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12370 // High will be bitcasted right away, so do not bother bitcasting back to
12371 // its original type.
12372 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12373 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12375 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12376 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12377 CstMask, CstMask, CstMask);
12378 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12379 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12380 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12382 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12383 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12386 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12387 SDValue CstFAdd = DAG.getConstantFP(
12388 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12389 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12390 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12391 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12392 makeArrayRef(&CstFAddArray[0], NumElts));
12394 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12395 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12397 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12398 // return (float4) lo + fhi;
12399 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12400 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12403 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12404 SelectionDAG &DAG) const {
12405 SDValue N0 = Op.getOperand(0);
12406 MVT SVT = N0.getSimpleValueType();
12409 switch (SVT.SimpleTy) {
12411 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12416 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12417 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12418 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12422 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12425 if (Subtarget->hasAVX512())
12426 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12427 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12429 llvm_unreachable(nullptr);
12432 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12433 SelectionDAG &DAG) const {
12434 SDValue N0 = Op.getOperand(0);
12436 auto PtrVT = getPointerTy(DAG.getDataLayout());
12438 if (Op.getValueType().isVector())
12439 return lowerUINT_TO_FP_vec(Op, DAG);
12441 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12442 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12443 // the optimization here.
12444 if (DAG.SignBitIsZero(N0))
12445 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12447 MVT SrcVT = N0.getSimpleValueType();
12448 MVT DstVT = Op.getSimpleValueType();
12449 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12450 return LowerUINT_TO_FP_i64(Op, DAG);
12451 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12452 return LowerUINT_TO_FP_i32(Op, DAG);
12453 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12456 // Make a 64-bit buffer, and use it to build an FILD.
12457 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12458 if (SrcVT == MVT::i32) {
12459 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12460 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12461 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12462 StackSlot, MachinePointerInfo(),
12464 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12465 OffsetSlot, MachinePointerInfo(),
12467 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12471 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12472 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12473 StackSlot, MachinePointerInfo(),
12475 // For i64 source, we need to add the appropriate power of 2 if the input
12476 // was negative. This is the same as the optimization in
12477 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12478 // we must be careful to do the computation in x87 extended precision, not
12479 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12480 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12481 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12482 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12483 MachineMemOperand::MOLoad, 8, 8);
12485 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12486 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12487 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12490 APInt FF(32, 0x5F800000ULL);
12492 // Check whether the sign bit is set.
12493 SDValue SignSet = DAG.getSetCC(
12494 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12495 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12497 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12498 SDValue FudgePtr = DAG.getConstantPool(
12499 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12501 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12502 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12503 SDValue Four = DAG.getIntPtrConstant(4, dl);
12504 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12506 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12508 // Load the value out, extending it from f32 to f80.
12509 // FIXME: Avoid the extend by constructing the right constant pool?
12510 SDValue Fudge = DAG.getExtLoad(
12511 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12512 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12513 false, false, false, 4);
12514 // Extend everything to 80 bits to force it to be done on x87.
12515 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12516 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12517 DAG.getIntPtrConstant(0, dl));
12520 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12521 // is legal, or has an f16 source (which needs to be promoted to f32),
12522 // just return an <SDValue(), SDValue()> pair.
12523 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12524 // to i16, i32 or i64, and we lower it to a legal sequence.
12525 // If lowered to the final integer result we return a <result, SDValue()> pair.
12526 // Otherwise we lower it to a sequence ending with a FIST, return a
12527 // <FIST, StackSlot> pair, and the caller is responsible for loading
12528 // the final integer result from StackSlot.
12529 std::pair<SDValue,SDValue>
12530 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12531 bool IsSigned, bool IsReplace) const {
12534 EVT DstTy = Op.getValueType();
12535 EVT TheVT = Op.getOperand(0).getValueType();
12536 auto PtrVT = getPointerTy(DAG.getDataLayout());
12538 if (TheVT == MVT::f16)
12539 // We need to promote the f16 to f32 before using the lowering
12540 // in this routine.
12541 return std::make_pair(SDValue(), SDValue());
12543 assert((TheVT == MVT::f32 ||
12544 TheVT == MVT::f64 ||
12545 TheVT == MVT::f80) &&
12546 "Unexpected FP operand type in FP_TO_INTHelper");
12548 // If using FIST to compute an unsigned i64, we'll need some fixup
12549 // to handle values above the maximum signed i64. A FIST is always
12550 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12551 bool UnsignedFixup = !IsSigned &&
12552 DstTy == MVT::i64 &&
12553 (!Subtarget->is64Bit() ||
12554 !isScalarFPTypeInSSEReg(TheVT));
12556 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12557 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12558 // The low 32 bits of the fist result will have the correct uint32 result.
12559 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12563 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12564 DstTy.getSimpleVT() >= MVT::i16 &&
12565 "Unknown FP_TO_INT to lower!");
12567 // These are really Legal.
12568 if (DstTy == MVT::i32 &&
12569 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12570 return std::make_pair(SDValue(), SDValue());
12571 if (Subtarget->is64Bit() &&
12572 DstTy == MVT::i64 &&
12573 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12574 return std::make_pair(SDValue(), SDValue());
12576 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12578 MachineFunction &MF = DAG.getMachineFunction();
12579 unsigned MemSize = DstTy.getSizeInBits()/8;
12580 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12581 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12584 switch (DstTy.getSimpleVT().SimpleTy) {
12585 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12586 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12587 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12588 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12591 SDValue Chain = DAG.getEntryNode();
12592 SDValue Value = Op.getOperand(0);
12593 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12595 if (UnsignedFixup) {
12597 // Conversion to unsigned i64 is implemented with a select,
12598 // depending on whether the source value fits in the range
12599 // of a signed i64. Let Thresh be the FP equivalent of
12600 // 0x8000000000000000ULL.
12602 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12603 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12604 // Fist-to-mem64 FistSrc
12605 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12606 // to XOR'ing the high 32 bits with Adjust.
12608 // Being a power of 2, Thresh is exactly representable in all FP formats.
12609 // For X87 we'd like to use the smallest FP type for this constant, but
12610 // for DAG type consistency we have to match the FP operand type.
12612 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12613 APFloat::opStatus Status = APFloat::opOK;
12614 bool LosesInfo = false;
12615 if (TheVT == MVT::f64)
12616 // The rounding mode is irrelevant as the conversion should be exact.
12617 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12619 else if (TheVT == MVT::f80)
12620 Status = Thresh.convert(APFloat::x87DoubleExtended,
12621 APFloat::rmNearestTiesToEven, &LosesInfo);
12623 assert(Status == APFloat::opOK && !LosesInfo &&
12624 "FP conversion should have been exact");
12626 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12628 SDValue Cmp = DAG.getSetCC(DL,
12629 getSetCCResultType(DAG.getDataLayout(),
12630 *DAG.getContext(), TheVT),
12631 Value, ThreshVal, ISD::SETLT);
12632 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12633 DAG.getConstant(0, DL, MVT::i32),
12634 DAG.getConstant(0x80000000, DL, MVT::i32));
12635 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12636 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12637 *DAG.getContext(), TheVT),
12638 Value, ThreshVal, ISD::SETLT);
12639 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12642 // FIXME This causes a redundant load/store if the SSE-class value is already
12643 // in memory, such as if it is on the callstack.
12644 if (isScalarFPTypeInSSEReg(TheVT)) {
12645 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12646 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12647 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12649 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12651 Chain, StackSlot, DAG.getValueType(TheVT)
12654 MachineMemOperand *MMO =
12655 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12656 MachineMemOperand::MOLoad, MemSize, MemSize);
12657 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12658 Chain = Value.getValue(1);
12659 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12660 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12663 MachineMemOperand *MMO =
12664 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12665 MachineMemOperand::MOStore, MemSize, MemSize);
12667 if (UnsignedFixup) {
12669 // Insert the FIST, load its result as two i32's,
12670 // and XOR the high i32 with Adjust.
12672 SDValue FistOps[] = { Chain, Value, StackSlot };
12673 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12674 FistOps, DstTy, MMO);
12676 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12677 MachinePointerInfo(),
12678 false, false, false, 0);
12679 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12680 DAG.getConstant(4, DL, PtrVT));
12682 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12683 MachinePointerInfo(),
12684 false, false, false, 0);
12685 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12687 if (Subtarget->is64Bit()) {
12688 // Join High32 and Low32 into a 64-bit result.
12689 // (High32 << 32) | Low32
12690 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12691 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12692 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12693 DAG.getConstant(32, DL, MVT::i8));
12694 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12695 return std::make_pair(Result, SDValue());
12698 SDValue ResultOps[] = { Low32, High32 };
12700 SDValue pair = IsReplace
12701 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12702 : DAG.getMergeValues(ResultOps, DL);
12703 return std::make_pair(pair, SDValue());
12705 // Build the FP_TO_INT*_IN_MEM
12706 SDValue Ops[] = { Chain, Value, StackSlot };
12707 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12709 return std::make_pair(FIST, StackSlot);
12713 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12714 const X86Subtarget *Subtarget) {
12715 MVT VT = Op->getSimpleValueType(0);
12716 SDValue In = Op->getOperand(0);
12717 MVT InVT = In.getSimpleValueType();
12720 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12721 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12723 // Optimize vectors in AVX mode:
12726 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12727 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12728 // Concat upper and lower parts.
12731 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12732 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12733 // Concat upper and lower parts.
12736 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12737 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12738 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12741 if (Subtarget->hasInt256())
12742 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12744 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12745 SDValue Undef = DAG.getUNDEF(InVT);
12746 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12747 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12748 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12750 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12751 VT.getVectorNumElements()/2);
12753 OpLo = DAG.getBitcast(HVT, OpLo);
12754 OpHi = DAG.getBitcast(HVT, OpHi);
12756 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12759 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12760 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12761 MVT VT = Op->getSimpleValueType(0);
12762 SDValue In = Op->getOperand(0);
12763 MVT InVT = In.getSimpleValueType();
12765 unsigned int NumElts = VT.getVectorNumElements();
12766 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12769 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12770 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12772 assert(InVT.getVectorElementType() == MVT::i1);
12773 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12775 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12777 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12779 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12780 if (VT.is512BitVector())
12782 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12785 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12786 SelectionDAG &DAG) {
12787 if (Subtarget->hasFp256())
12788 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12794 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12795 SelectionDAG &DAG) {
12797 MVT VT = Op.getSimpleValueType();
12798 SDValue In = Op.getOperand(0);
12799 MVT SVT = In.getSimpleValueType();
12801 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12802 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12804 if (Subtarget->hasFp256())
12805 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12808 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12809 VT.getVectorNumElements() != SVT.getVectorNumElements());
12813 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12815 MVT VT = Op.getSimpleValueType();
12816 SDValue In = Op.getOperand(0);
12817 MVT InVT = In.getSimpleValueType();
12819 if (VT == MVT::i1) {
12820 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12821 "Invalid scalar TRUNCATE operation");
12822 if (InVT.getSizeInBits() >= 32)
12824 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12825 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12827 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12828 "Invalid TRUNCATE operation");
12830 // move vector to mask - truncate solution for SKX
12831 if (VT.getVectorElementType() == MVT::i1) {
12832 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12833 Subtarget->hasBWI())
12834 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12835 if ((InVT.is256BitVector() || InVT.is128BitVector())
12836 && InVT.getScalarSizeInBits() <= 16 &&
12837 Subtarget->hasBWI() && Subtarget->hasVLX())
12838 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12839 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12840 Subtarget->hasDQI())
12841 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12842 if ((InVT.is256BitVector() || InVT.is128BitVector())
12843 && InVT.getScalarSizeInBits() >= 32 &&
12844 Subtarget->hasDQI() && Subtarget->hasVLX())
12845 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12848 if (VT.getVectorElementType() == MVT::i1) {
12849 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12850 unsigned NumElts = InVT.getVectorNumElements();
12851 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12852 if (InVT.getSizeInBits() < 512) {
12853 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12854 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12859 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12860 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12861 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12864 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12865 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12866 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12867 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12869 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12870 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12871 if (Subtarget->hasInt256()) {
12872 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12873 In = DAG.getBitcast(MVT::v8i32, In);
12874 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12876 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12877 DAG.getIntPtrConstant(0, DL));
12880 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12881 DAG.getIntPtrConstant(0, DL));
12882 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12883 DAG.getIntPtrConstant(2, DL));
12884 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12885 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12886 static const int ShufMask[] = {0, 2, 4, 6};
12887 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12890 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12891 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12892 if (Subtarget->hasInt256()) {
12893 In = DAG.getBitcast(MVT::v32i8, In);
12895 SmallVector<SDValue,32> pshufbMask;
12896 for (unsigned i = 0; i < 2; ++i) {
12897 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12898 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12899 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12900 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12901 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12902 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12903 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12904 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12905 for (unsigned j = 0; j < 8; ++j)
12906 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12908 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12909 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12910 In = DAG.getBitcast(MVT::v4i64, In);
12912 static const int ShufMask[] = {0, 2, -1, -1};
12913 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12915 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12916 DAG.getIntPtrConstant(0, DL));
12917 return DAG.getBitcast(VT, In);
12920 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12921 DAG.getIntPtrConstant(0, DL));
12923 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12924 DAG.getIntPtrConstant(4, DL));
12926 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12927 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12929 // The PSHUFB mask:
12930 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12931 -1, -1, -1, -1, -1, -1, -1, -1};
12933 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12934 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12935 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12937 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12938 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12940 // The MOVLHPS Mask:
12941 static const int ShufMask2[] = {0, 1, 4, 5};
12942 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12943 return DAG.getBitcast(MVT::v8i16, res);
12946 // Handle truncation of V256 to V128 using shuffles.
12947 if (!VT.is128BitVector() || !InVT.is256BitVector())
12950 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12952 unsigned NumElems = VT.getVectorNumElements();
12953 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12955 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12956 // Prepare truncation shuffle mask
12957 for (unsigned i = 0; i != NumElems; ++i)
12958 MaskVec[i] = i * 2;
12959 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12960 DAG.getUNDEF(NVT), &MaskVec[0]);
12961 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12962 DAG.getIntPtrConstant(0, DL));
12965 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12966 SelectionDAG &DAG) const {
12967 assert(!Op.getSimpleValueType().isVector());
12969 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12970 /*IsSigned=*/ true, /*IsReplace=*/ false);
12971 SDValue FIST = Vals.first, StackSlot = Vals.second;
12972 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12973 if (!FIST.getNode())
12976 if (StackSlot.getNode())
12977 // Load the result.
12978 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12979 FIST, StackSlot, MachinePointerInfo(),
12980 false, false, false, 0);
12982 // The node is the result.
12986 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12987 SelectionDAG &DAG) const {
12988 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12989 /*IsSigned=*/ false, /*IsReplace=*/ false);
12990 SDValue FIST = Vals.first, StackSlot = Vals.second;
12991 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12992 if (!FIST.getNode())
12995 if (StackSlot.getNode())
12996 // Load the result.
12997 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12998 FIST, StackSlot, MachinePointerInfo(),
12999 false, false, false, 0);
13001 // The node is the result.
13005 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13007 MVT VT = Op.getSimpleValueType();
13008 SDValue In = Op.getOperand(0);
13009 MVT SVT = In.getSimpleValueType();
13011 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13013 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13014 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13015 In, DAG.getUNDEF(SVT)));
13018 /// The only differences between FABS and FNEG are the mask and the logic op.
13019 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13020 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13021 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13022 "Wrong opcode for lowering FABS or FNEG.");
13024 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13026 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13027 // into an FNABS. We'll lower the FABS after that if it is still in use.
13029 for (SDNode *User : Op->uses())
13030 if (User->getOpcode() == ISD::FNEG)
13034 MVT VT = Op.getSimpleValueType();
13036 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13037 // decide if we should generate a 16-byte constant mask when we only need 4 or
13038 // 8 bytes for the scalar case.
13044 if (VT.isVector()) {
13046 EltVT = VT.getVectorElementType();
13047 NumElts = VT.getVectorNumElements();
13049 // There are no scalar bitwise logical SSE/AVX instructions, so we
13050 // generate a 16-byte vector constant and logic op even for the scalar case.
13051 // Using a 16-byte mask allows folding the load of the mask with
13052 // the logic op, so it can save (~4 bytes) on code size.
13053 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13055 NumElts = (VT == MVT::f64) ? 2 : 4;
13058 unsigned EltBits = EltVT.getSizeInBits();
13059 LLVMContext *Context = DAG.getContext();
13060 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13062 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13063 Constant *C = ConstantInt::get(*Context, MaskElt);
13064 C = ConstantVector::getSplat(NumElts, C);
13065 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13066 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13067 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13069 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13070 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13071 false, false, false, Alignment);
13073 SDValue Op0 = Op.getOperand(0);
13074 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13076 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13077 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13080 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13082 // For the scalar case extend to a 128-bit vector, perform the logic op,
13083 // and extract the scalar result back out.
13084 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13085 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13086 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13087 DAG.getIntPtrConstant(0, dl));
13090 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13091 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13092 LLVMContext *Context = DAG.getContext();
13093 SDValue Op0 = Op.getOperand(0);
13094 SDValue Op1 = Op.getOperand(1);
13096 MVT VT = Op.getSimpleValueType();
13097 MVT SrcVT = Op1.getSimpleValueType();
13099 // If second operand is smaller, extend it first.
13100 if (SrcVT.bitsLT(VT)) {
13101 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13104 // And if it is bigger, shrink it first.
13105 if (SrcVT.bitsGT(VT)) {
13106 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13110 // At this point the operands and the result should have the same
13111 // type, and that won't be f80 since that is not custom lowered.
13113 const fltSemantics &Sem =
13114 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13115 const unsigned SizeInBits = VT.getSizeInBits();
13117 SmallVector<Constant *, 4> CV(
13118 VT == MVT::f64 ? 2 : 4,
13119 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13121 // First, clear all bits but the sign bit from the second operand (sign).
13122 CV[0] = ConstantFP::get(*Context,
13123 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13124 Constant *C = ConstantVector::get(CV);
13125 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13126 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13128 // Perform all logic operations as 16-byte vectors because there are no
13129 // scalar FP logic instructions in SSE. This allows load folding of the
13130 // constants into the logic instructions.
13131 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13133 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13134 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13135 false, false, false, 16);
13136 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13137 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13139 // Next, clear the sign bit from the first operand (magnitude).
13140 // If it's a constant, we can clear it here.
13141 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13142 APFloat APF = Op0CN->getValueAPF();
13143 // If the magnitude is a positive zero, the sign bit alone is enough.
13144 if (APF.isPosZero())
13145 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13146 DAG.getIntPtrConstant(0, dl));
13148 CV[0] = ConstantFP::get(*Context, APF);
13150 CV[0] = ConstantFP::get(
13152 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13154 C = ConstantVector::get(CV);
13155 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13157 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13158 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13159 false, false, false, 16);
13160 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13161 if (!isa<ConstantFPSDNode>(Op0)) {
13162 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13163 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13165 // OR the magnitude value with the sign bit.
13166 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13167 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13168 DAG.getIntPtrConstant(0, dl));
13171 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13172 SDValue N0 = Op.getOperand(0);
13174 MVT VT = Op.getSimpleValueType();
13176 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13177 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13178 DAG.getConstant(1, dl, VT));
13179 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13182 // Check whether an OR'd tree is PTEST-able.
13183 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13184 SelectionDAG &DAG) {
13185 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13187 if (!Subtarget->hasSSE41())
13190 if (!Op->hasOneUse())
13193 SDNode *N = Op.getNode();
13196 SmallVector<SDValue, 8> Opnds;
13197 DenseMap<SDValue, unsigned> VecInMap;
13198 SmallVector<SDValue, 8> VecIns;
13199 EVT VT = MVT::Other;
13201 // Recognize a special case where a vector is casted into wide integer to
13203 Opnds.push_back(N->getOperand(0));
13204 Opnds.push_back(N->getOperand(1));
13206 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13207 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13208 // BFS traverse all OR'd operands.
13209 if (I->getOpcode() == ISD::OR) {
13210 Opnds.push_back(I->getOperand(0));
13211 Opnds.push_back(I->getOperand(1));
13212 // Re-evaluate the number of nodes to be traversed.
13213 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13217 // Quit if a non-EXTRACT_VECTOR_ELT
13218 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13221 // Quit if without a constant index.
13222 SDValue Idx = I->getOperand(1);
13223 if (!isa<ConstantSDNode>(Idx))
13226 SDValue ExtractedFromVec = I->getOperand(0);
13227 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13228 if (M == VecInMap.end()) {
13229 VT = ExtractedFromVec.getValueType();
13230 // Quit if not 128/256-bit vector.
13231 if (!VT.is128BitVector() && !VT.is256BitVector())
13233 // Quit if not the same type.
13234 if (VecInMap.begin() != VecInMap.end() &&
13235 VT != VecInMap.begin()->first.getValueType())
13237 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13238 VecIns.push_back(ExtractedFromVec);
13240 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13243 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13244 "Not extracted from 128-/256-bit vector.");
13246 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13248 for (DenseMap<SDValue, unsigned>::const_iterator
13249 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13250 // Quit if not all elements are used.
13251 if (I->second != FullMask)
13255 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13257 // Cast all vectors into TestVT for PTEST.
13258 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13259 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13261 // If more than one full vectors are evaluated, OR them first before PTEST.
13262 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13263 // Each iteration will OR 2 nodes and append the result until there is only
13264 // 1 node left, i.e. the final OR'd value of all vectors.
13265 SDValue LHS = VecIns[Slot];
13266 SDValue RHS = VecIns[Slot + 1];
13267 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13270 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13271 VecIns.back(), VecIns.back());
13274 /// \brief return true if \c Op has a use that doesn't just read flags.
13275 static bool hasNonFlagsUse(SDValue Op) {
13276 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13278 SDNode *User = *UI;
13279 unsigned UOpNo = UI.getOperandNo();
13280 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13281 // Look pass truncate.
13282 UOpNo = User->use_begin().getOperandNo();
13283 User = *User->use_begin();
13286 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13287 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13293 /// Emit nodes that will be selected as "test Op0,Op0", or something
13295 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13296 SelectionDAG &DAG) const {
13297 if (Op.getValueType() == MVT::i1) {
13298 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13299 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13300 DAG.getConstant(0, dl, MVT::i8));
13302 // CF and OF aren't always set the way we want. Determine which
13303 // of these we need.
13304 bool NeedCF = false;
13305 bool NeedOF = false;
13308 case X86::COND_A: case X86::COND_AE:
13309 case X86::COND_B: case X86::COND_BE:
13312 case X86::COND_G: case X86::COND_GE:
13313 case X86::COND_L: case X86::COND_LE:
13314 case X86::COND_O: case X86::COND_NO: {
13315 // Check if we really need to set the
13316 // Overflow flag. If NoSignedWrap is present
13317 // that is not actually needed.
13318 switch (Op->getOpcode()) {
13323 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13324 if (BinNode->Flags.hasNoSignedWrap())
13334 // See if we can use the EFLAGS value from the operand instead of
13335 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13336 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13337 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13338 // Emit a CMP with 0, which is the TEST pattern.
13339 //if (Op.getValueType() == MVT::i1)
13340 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13341 // DAG.getConstant(0, MVT::i1));
13342 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13343 DAG.getConstant(0, dl, Op.getValueType()));
13345 unsigned Opcode = 0;
13346 unsigned NumOperands = 0;
13348 // Truncate operations may prevent the merge of the SETCC instruction
13349 // and the arithmetic instruction before it. Attempt to truncate the operands
13350 // of the arithmetic instruction and use a reduced bit-width instruction.
13351 bool NeedTruncation = false;
13352 SDValue ArithOp = Op;
13353 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13354 SDValue Arith = Op->getOperand(0);
13355 // Both the trunc and the arithmetic op need to have one user each.
13356 if (Arith->hasOneUse())
13357 switch (Arith.getOpcode()) {
13364 NeedTruncation = true;
13370 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13371 // which may be the result of a CAST. We use the variable 'Op', which is the
13372 // non-casted variable when we check for possible users.
13373 switch (ArithOp.getOpcode()) {
13375 // Due to an isel shortcoming, be conservative if this add is likely to be
13376 // selected as part of a load-modify-store instruction. When the root node
13377 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13378 // uses of other nodes in the match, such as the ADD in this case. This
13379 // leads to the ADD being left around and reselected, with the result being
13380 // two adds in the output. Alas, even if none our users are stores, that
13381 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13382 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13383 // climbing the DAG back to the root, and it doesn't seem to be worth the
13385 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13386 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13387 if (UI->getOpcode() != ISD::CopyToReg &&
13388 UI->getOpcode() != ISD::SETCC &&
13389 UI->getOpcode() != ISD::STORE)
13392 if (ConstantSDNode *C =
13393 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13394 // An add of one will be selected as an INC.
13395 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13396 Opcode = X86ISD::INC;
13401 // An add of negative one (subtract of one) will be selected as a DEC.
13402 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13403 Opcode = X86ISD::DEC;
13409 // Otherwise use a regular EFLAGS-setting add.
13410 Opcode = X86ISD::ADD;
13415 // If we have a constant logical shift that's only used in a comparison
13416 // against zero turn it into an equivalent AND. This allows turning it into
13417 // a TEST instruction later.
13418 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13419 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13420 EVT VT = Op.getValueType();
13421 unsigned BitWidth = VT.getSizeInBits();
13422 unsigned ShAmt = Op->getConstantOperandVal(1);
13423 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13425 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13426 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13427 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13428 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13430 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13431 DAG.getConstant(Mask, dl, VT));
13432 DAG.ReplaceAllUsesWith(Op, New);
13438 // If the primary and result isn't used, don't bother using X86ISD::AND,
13439 // because a TEST instruction will be better.
13440 if (!hasNonFlagsUse(Op))
13446 // Due to the ISEL shortcoming noted above, be conservative if this op is
13447 // likely to be selected as part of a load-modify-store instruction.
13448 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13449 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13450 if (UI->getOpcode() == ISD::STORE)
13453 // Otherwise use a regular EFLAGS-setting instruction.
13454 switch (ArithOp.getOpcode()) {
13455 default: llvm_unreachable("unexpected operator!");
13456 case ISD::SUB: Opcode = X86ISD::SUB; break;
13457 case ISD::XOR: Opcode = X86ISD::XOR; break;
13458 case ISD::AND: Opcode = X86ISD::AND; break;
13460 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13461 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13462 if (EFLAGS.getNode())
13465 Opcode = X86ISD::OR;
13479 return SDValue(Op.getNode(), 1);
13485 // If we found that truncation is beneficial, perform the truncation and
13487 if (NeedTruncation) {
13488 EVT VT = Op.getValueType();
13489 SDValue WideVal = Op->getOperand(0);
13490 EVT WideVT = WideVal.getValueType();
13491 unsigned ConvertedOp = 0;
13492 // Use a target machine opcode to prevent further DAGCombine
13493 // optimizations that may separate the arithmetic operations
13494 // from the setcc node.
13495 switch (WideVal.getOpcode()) {
13497 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13498 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13499 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13500 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13501 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13505 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13506 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13507 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13508 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13509 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13515 // Emit a CMP with 0, which is the TEST pattern.
13516 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13517 DAG.getConstant(0, dl, Op.getValueType()));
13519 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13520 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13522 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13523 DAG.ReplaceAllUsesWith(Op, New);
13524 return SDValue(New.getNode(), 1);
13527 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13529 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13530 SDLoc dl, SelectionDAG &DAG) const {
13531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13532 if (C->getAPIntValue() == 0)
13533 return EmitTest(Op0, X86CC, dl, DAG);
13535 if (Op0.getValueType() == MVT::i1)
13536 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13539 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13540 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13541 // Do the comparison at i32 if it's smaller, besides the Atom case.
13542 // This avoids subregister aliasing issues. Keep the smaller reference
13543 // if we're optimizing for size, however, as that'll allow better folding
13544 // of memory operations.
13545 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13546 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13547 !Subtarget->isAtom()) {
13548 unsigned ExtendOp =
13549 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13550 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13551 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13553 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13554 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13555 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13557 return SDValue(Sub.getNode(), 1);
13559 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13562 /// Convert a comparison if required by the subtarget.
13563 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13564 SelectionDAG &DAG) const {
13565 // If the subtarget does not support the FUCOMI instruction, floating-point
13566 // comparisons have to be converted.
13567 if (Subtarget->hasCMov() ||
13568 Cmp.getOpcode() != X86ISD::CMP ||
13569 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13570 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13573 // The instruction selector will select an FUCOM instruction instead of
13574 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13575 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13576 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13578 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13579 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13580 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13581 DAG.getConstant(8, dl, MVT::i8));
13582 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13583 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13586 /// The minimum architected relative accuracy is 2^-12. We need one
13587 /// Newton-Raphson step to have a good float result (24 bits of precision).
13588 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13589 DAGCombinerInfo &DCI,
13590 unsigned &RefinementSteps,
13591 bool &UseOneConstNR) const {
13592 EVT VT = Op.getValueType();
13593 const char *RecipOp;
13595 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13596 // TODO: Add support for AVX512 (v16f32).
13597 // It is likely not profitable to do this for f64 because a double-precision
13598 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13599 // instructions: convert to single, rsqrtss, convert back to double, refine
13600 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13601 // along with FMA, this could be a throughput win.
13602 if (VT == MVT::f32 && Subtarget->hasSSE1())
13604 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13605 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13606 RecipOp = "vec-sqrtf";
13610 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13611 if (!Recips.isEnabled(RecipOp))
13614 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13615 UseOneConstNR = false;
13616 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13619 /// The minimum architected relative accuracy is 2^-12. We need one
13620 /// Newton-Raphson step to have a good float result (24 bits of precision).
13621 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13622 DAGCombinerInfo &DCI,
13623 unsigned &RefinementSteps) const {
13624 EVT VT = Op.getValueType();
13625 const char *RecipOp;
13627 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13628 // TODO: Add support for AVX512 (v16f32).
13629 // It is likely not profitable to do this for f64 because a double-precision
13630 // reciprocal estimate with refinement on x86 prior to FMA requires
13631 // 15 instructions: convert to single, rcpss, convert back to double, refine
13632 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13633 // along with FMA, this could be a throughput win.
13634 if (VT == MVT::f32 && Subtarget->hasSSE1())
13636 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13637 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13638 RecipOp = "vec-divf";
13642 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13643 if (!Recips.isEnabled(RecipOp))
13646 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13647 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13650 /// If we have at least two divisions that use the same divisor, convert to
13651 /// multplication by a reciprocal. This may need to be adjusted for a given
13652 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13653 /// This is because we still need one division to calculate the reciprocal and
13654 /// then we need two multiplies by that reciprocal as replacements for the
13655 /// original divisions.
13656 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13660 static bool isAllOnes(SDValue V) {
13661 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13662 return C && C->isAllOnesValue();
13665 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13666 /// if it's possible.
13667 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13668 SDLoc dl, SelectionDAG &DAG) const {
13669 SDValue Op0 = And.getOperand(0);
13670 SDValue Op1 = And.getOperand(1);
13671 if (Op0.getOpcode() == ISD::TRUNCATE)
13672 Op0 = Op0.getOperand(0);
13673 if (Op1.getOpcode() == ISD::TRUNCATE)
13674 Op1 = Op1.getOperand(0);
13677 if (Op1.getOpcode() == ISD::SHL)
13678 std::swap(Op0, Op1);
13679 if (Op0.getOpcode() == ISD::SHL) {
13680 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13681 if (And00C->getZExtValue() == 1) {
13682 // If we looked past a truncate, check that it's only truncating away
13684 unsigned BitWidth = Op0.getValueSizeInBits();
13685 unsigned AndBitWidth = And.getValueSizeInBits();
13686 if (BitWidth > AndBitWidth) {
13688 DAG.computeKnownBits(Op0, Zeros, Ones);
13689 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13693 RHS = Op0.getOperand(1);
13695 } else if (Op1.getOpcode() == ISD::Constant) {
13696 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13697 uint64_t AndRHSVal = AndRHS->getZExtValue();
13698 SDValue AndLHS = Op0;
13700 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13701 LHS = AndLHS.getOperand(0);
13702 RHS = AndLHS.getOperand(1);
13705 // Use BT if the immediate can't be encoded in a TEST instruction.
13706 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13708 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13712 if (LHS.getNode()) {
13713 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13714 // instruction. Since the shift amount is in-range-or-undefined, we know
13715 // that doing a bittest on the i32 value is ok. We extend to i32 because
13716 // the encoding for the i16 version is larger than the i32 version.
13717 // Also promote i16 to i32 for performance / code size reason.
13718 if (LHS.getValueType() == MVT::i8 ||
13719 LHS.getValueType() == MVT::i16)
13720 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13722 // If the operand types disagree, extend the shift amount to match. Since
13723 // BT ignores high bits (like shifts) we can use anyextend.
13724 if (LHS.getValueType() != RHS.getValueType())
13725 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13727 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13728 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13729 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13730 DAG.getConstant(Cond, dl, MVT::i8), BT);
13736 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13738 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13743 // SSE Condition code mapping:
13752 switch (SetCCOpcode) {
13753 default: llvm_unreachable("Unexpected SETCC condition");
13755 case ISD::SETEQ: SSECC = 0; break;
13757 case ISD::SETGT: Swap = true; // Fallthrough
13759 case ISD::SETOLT: SSECC = 1; break;
13761 case ISD::SETGE: Swap = true; // Fallthrough
13763 case ISD::SETOLE: SSECC = 2; break;
13764 case ISD::SETUO: SSECC = 3; break;
13766 case ISD::SETNE: SSECC = 4; break;
13767 case ISD::SETULE: Swap = true; // Fallthrough
13768 case ISD::SETUGE: SSECC = 5; break;
13769 case ISD::SETULT: Swap = true; // Fallthrough
13770 case ISD::SETUGT: SSECC = 6; break;
13771 case ISD::SETO: SSECC = 7; break;
13773 case ISD::SETONE: SSECC = 8; break;
13776 std::swap(Op0, Op1);
13781 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13782 // ones, and then concatenate the result back.
13783 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13784 MVT VT = Op.getSimpleValueType();
13786 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13787 "Unsupported value type for operation");
13789 unsigned NumElems = VT.getVectorNumElements();
13791 SDValue CC = Op.getOperand(2);
13793 // Extract the LHS vectors
13794 SDValue LHS = Op.getOperand(0);
13795 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13796 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13798 // Extract the RHS vectors
13799 SDValue RHS = Op.getOperand(1);
13800 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13801 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13803 // Issue the operation on the smaller types and concatenate the result back
13804 MVT EltVT = VT.getVectorElementType();
13805 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13806 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13807 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13808 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13811 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13812 SDValue Op0 = Op.getOperand(0);
13813 SDValue Op1 = Op.getOperand(1);
13814 SDValue CC = Op.getOperand(2);
13815 MVT VT = Op.getSimpleValueType();
13818 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13819 "Unexpected type for boolean compare operation");
13820 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13821 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13822 DAG.getConstant(-1, dl, VT));
13823 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13824 DAG.getConstant(-1, dl, VT));
13825 switch (SetCCOpcode) {
13826 default: llvm_unreachable("Unexpected SETCC condition");
13828 // (x == y) -> ~(x ^ y)
13829 return DAG.getNode(ISD::XOR, dl, VT,
13830 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13831 DAG.getConstant(-1, dl, VT));
13833 // (x != y) -> (x ^ y)
13834 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13837 // (x > y) -> (x & ~y)
13838 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13841 // (x < y) -> (~x & y)
13842 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13845 // (x <= y) -> (~x | y)
13846 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13849 // (x >=y) -> (x | ~y)
13850 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13854 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13855 const X86Subtarget *Subtarget) {
13856 SDValue Op0 = Op.getOperand(0);
13857 SDValue Op1 = Op.getOperand(1);
13858 SDValue CC = Op.getOperand(2);
13859 MVT VT = Op.getSimpleValueType();
13862 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13863 Op.getValueType().getScalarType() == MVT::i1 &&
13864 "Cannot set masked compare for this operation");
13866 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13868 bool Unsigned = false;
13871 switch (SetCCOpcode) {
13872 default: llvm_unreachable("Unexpected SETCC condition");
13873 case ISD::SETNE: SSECC = 4; break;
13874 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13875 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13876 case ISD::SETLT: Swap = true; //fall-through
13877 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13878 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13879 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13880 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13881 case ISD::SETULE: Unsigned = true; //fall-through
13882 case ISD::SETLE: SSECC = 2; break;
13886 std::swap(Op0, Op1);
13888 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13889 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13890 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13891 DAG.getConstant(SSECC, dl, MVT::i8));
13894 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13895 /// operand \p Op1. If non-trivial (for example because it's not constant)
13896 /// return an empty value.
13897 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13899 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13903 MVT VT = Op1.getSimpleValueType();
13904 MVT EVT = VT.getVectorElementType();
13905 unsigned n = VT.getVectorNumElements();
13906 SmallVector<SDValue, 8> ULTOp1;
13908 for (unsigned i = 0; i < n; ++i) {
13909 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13910 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13913 // Avoid underflow.
13914 APInt Val = Elt->getAPIntValue();
13918 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13921 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13924 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13925 SelectionDAG &DAG) {
13926 SDValue Op0 = Op.getOperand(0);
13927 SDValue Op1 = Op.getOperand(1);
13928 SDValue CC = Op.getOperand(2);
13929 MVT VT = Op.getSimpleValueType();
13930 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13931 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13936 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13937 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13940 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13941 unsigned Opc = X86ISD::CMPP;
13942 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13943 assert(VT.getVectorNumElements() <= 16);
13944 Opc = X86ISD::CMPM;
13946 // In the two special cases we can't handle, emit two comparisons.
13949 unsigned CombineOpc;
13950 if (SetCCOpcode == ISD::SETUEQ) {
13951 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13953 assert(SetCCOpcode == ISD::SETONE);
13954 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13957 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13958 DAG.getConstant(CC0, dl, MVT::i8));
13959 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13960 DAG.getConstant(CC1, dl, MVT::i8));
13961 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13963 // Handle all other FP comparisons here.
13964 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13965 DAG.getConstant(SSECC, dl, MVT::i8));
13968 // Break 256-bit integer vector compare into smaller ones.
13969 if (VT.is256BitVector() && !Subtarget->hasInt256())
13970 return Lower256IntVSETCC(Op, DAG);
13972 EVT OpVT = Op1.getValueType();
13973 if (OpVT.getVectorElementType() == MVT::i1)
13974 return LowerBoolVSETCC_AVX512(Op, DAG);
13976 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13977 if (Subtarget->hasAVX512()) {
13978 if (Op1.getValueType().is512BitVector() ||
13979 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13980 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13981 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13983 // In AVX-512 architecture setcc returns mask with i1 elements,
13984 // But there is no compare instruction for i8 and i16 elements in KNL.
13985 // We are not talking about 512-bit operands in this case, these
13986 // types are illegal.
13988 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13989 OpVT.getVectorElementType().getSizeInBits() >= 8))
13990 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13991 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13994 // We are handling one of the integer comparisons here. Since SSE only has
13995 // GT and EQ comparisons for integer, swapping operands and multiple
13996 // operations may be required for some comparisons.
13998 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13999 bool Subus = false;
14001 switch (SetCCOpcode) {
14002 default: llvm_unreachable("Unexpected SETCC condition");
14003 case ISD::SETNE: Invert = true;
14004 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14005 case ISD::SETLT: Swap = true;
14006 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14007 case ISD::SETGE: Swap = true;
14008 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14009 Invert = true; break;
14010 case ISD::SETULT: Swap = true;
14011 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14012 FlipSigns = true; break;
14013 case ISD::SETUGE: Swap = true;
14014 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14015 FlipSigns = true; Invert = true; break;
14018 // Special case: Use min/max operations for SETULE/SETUGE
14019 MVT VET = VT.getVectorElementType();
14021 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14022 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14025 switch (SetCCOpcode) {
14027 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14028 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14031 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14034 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14035 if (!MinMax && hasSubus) {
14036 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14038 // t = psubus Op0, Op1
14039 // pcmpeq t, <0..0>
14040 switch (SetCCOpcode) {
14042 case ISD::SETULT: {
14043 // If the comparison is against a constant we can turn this into a
14044 // setule. With psubus, setule does not require a swap. This is
14045 // beneficial because the constant in the register is no longer
14046 // destructed as the destination so it can be hoisted out of a loop.
14047 // Only do this pre-AVX since vpcmp* is no longer destructive.
14048 if (Subtarget->hasAVX())
14050 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14051 if (ULEOp1.getNode()) {
14053 Subus = true; Invert = false; Swap = false;
14057 // Psubus is better than flip-sign because it requires no inversion.
14058 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14059 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14063 Opc = X86ISD::SUBUS;
14069 std::swap(Op0, Op1);
14071 // Check that the operation in question is available (most are plain SSE2,
14072 // but PCMPGTQ and PCMPEQQ have different requirements).
14073 if (VT == MVT::v2i64) {
14074 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14075 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14077 // First cast everything to the right type.
14078 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14079 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14081 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14082 // bits of the inputs before performing those operations. The lower
14083 // compare is always unsigned.
14086 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14088 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14089 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14090 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14091 Sign, Zero, Sign, Zero);
14093 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14094 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14096 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14097 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14098 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14100 // Create masks for only the low parts/high parts of the 64 bit integers.
14101 static const int MaskHi[] = { 1, 1, 3, 3 };
14102 static const int MaskLo[] = { 0, 0, 2, 2 };
14103 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14104 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14105 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14107 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14108 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14111 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14113 return DAG.getBitcast(VT, Result);
14116 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14117 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14118 // pcmpeqd + pshufd + pand.
14119 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14121 // First cast everything to the right type.
14122 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14123 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14126 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14128 // Make sure the lower and upper halves are both all-ones.
14129 static const int Mask[] = { 1, 0, 3, 2 };
14130 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14131 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14134 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14136 return DAG.getBitcast(VT, Result);
14140 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14141 // bits of the inputs before performing those operations.
14143 EVT EltVT = VT.getVectorElementType();
14144 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14146 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14147 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14150 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14152 // If the logical-not of the result is required, perform that now.
14154 Result = DAG.getNOT(dl, Result, VT);
14157 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14160 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14161 getZeroVector(VT, Subtarget, DAG, dl));
14166 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14168 MVT VT = Op.getSimpleValueType();
14170 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14172 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14173 && "SetCC type must be 8-bit or 1-bit integer");
14174 SDValue Op0 = Op.getOperand(0);
14175 SDValue Op1 = Op.getOperand(1);
14177 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14179 // Optimize to BT if possible.
14180 // Lower (X & (1 << N)) == 0 to BT(X, N).
14181 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14182 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14183 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14184 Op1.getOpcode() == ISD::Constant &&
14185 cast<ConstantSDNode>(Op1)->isNullValue() &&
14186 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14187 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14188 if (NewSetCC.getNode()) {
14190 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14195 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14197 if (Op1.getOpcode() == ISD::Constant &&
14198 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14199 cast<ConstantSDNode>(Op1)->isNullValue()) &&
14200 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14202 // If the input is a setcc, then reuse the input setcc or use a new one with
14203 // the inverted condition.
14204 if (Op0.getOpcode() == X86ISD::SETCC) {
14205 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14206 bool Invert = (CC == ISD::SETNE) ^
14207 cast<ConstantSDNode>(Op1)->isNullValue();
14211 CCode = X86::GetOppositeBranchCondition(CCode);
14212 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14213 DAG.getConstant(CCode, dl, MVT::i8),
14214 Op0.getOperand(1));
14216 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14220 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14221 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14222 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14224 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14225 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14228 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14229 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14230 if (X86CC == X86::COND_INVALID)
14233 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14234 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14235 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14236 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14238 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14242 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14243 static bool isX86LogicalCmp(SDValue Op) {
14244 unsigned Opc = Op.getNode()->getOpcode();
14245 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14246 Opc == X86ISD::SAHF)
14248 if (Op.getResNo() == 1 &&
14249 (Opc == X86ISD::ADD ||
14250 Opc == X86ISD::SUB ||
14251 Opc == X86ISD::ADC ||
14252 Opc == X86ISD::SBB ||
14253 Opc == X86ISD::SMUL ||
14254 Opc == X86ISD::UMUL ||
14255 Opc == X86ISD::INC ||
14256 Opc == X86ISD::DEC ||
14257 Opc == X86ISD::OR ||
14258 Opc == X86ISD::XOR ||
14259 Opc == X86ISD::AND))
14262 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14268 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14269 if (V.getOpcode() != ISD::TRUNCATE)
14272 SDValue VOp0 = V.getOperand(0);
14273 unsigned InBits = VOp0.getValueSizeInBits();
14274 unsigned Bits = V.getValueSizeInBits();
14275 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14278 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14279 bool addTest = true;
14280 SDValue Cond = Op.getOperand(0);
14281 SDValue Op1 = Op.getOperand(1);
14282 SDValue Op2 = Op.getOperand(2);
14284 EVT VT = Op1.getValueType();
14287 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14288 // are available or VBLENDV if AVX is available.
14289 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14290 if (Cond.getOpcode() == ISD::SETCC &&
14291 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14292 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14293 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14294 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14295 int SSECC = translateX86FSETCC(
14296 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14299 if (Subtarget->hasAVX512()) {
14300 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14301 DAG.getConstant(SSECC, DL, MVT::i8));
14302 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14305 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14306 DAG.getConstant(SSECC, DL, MVT::i8));
14308 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14309 // of 3 logic instructions for size savings and potentially speed.
14310 // Unfortunately, there is no scalar form of VBLENDV.
14312 // If either operand is a constant, don't try this. We can expect to
14313 // optimize away at least one of the logic instructions later in that
14314 // case, so that sequence would be faster than a variable blend.
14316 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14317 // uses XMM0 as the selection register. That may need just as many
14318 // instructions as the AND/ANDN/OR sequence due to register moves, so
14321 if (Subtarget->hasAVX() &&
14322 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14324 // Convert to vectors, do a VSELECT, and convert back to scalar.
14325 // All of the conversions should be optimized away.
14327 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14328 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14329 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14330 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14332 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14333 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14335 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14337 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14338 VSel, DAG.getIntPtrConstant(0, DL));
14340 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14341 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14342 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14346 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14348 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14349 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14350 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14351 Op1Scalar = Op1.getOperand(0);
14353 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14354 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14355 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14356 Op2Scalar = Op2.getOperand(0);
14357 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14358 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14359 Op1Scalar.getValueType(),
14360 Cond, Op1Scalar, Op2Scalar);
14361 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14362 return DAG.getBitcast(VT, newSelect);
14363 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14364 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14365 DAG.getIntPtrConstant(0, DL));
14369 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14370 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14371 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14372 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14373 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14374 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14375 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14377 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14380 if (Cond.getOpcode() == ISD::SETCC) {
14381 SDValue NewCond = LowerSETCC(Cond, DAG);
14382 if (NewCond.getNode())
14386 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14387 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14388 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14389 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14390 if (Cond.getOpcode() == X86ISD::SETCC &&
14391 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14392 isZero(Cond.getOperand(1).getOperand(1))) {
14393 SDValue Cmp = Cond.getOperand(1);
14395 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14397 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14398 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14399 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14401 SDValue CmpOp0 = Cmp.getOperand(0);
14402 // Apply further optimizations for special cases
14403 // (select (x != 0), -1, 0) -> neg & sbb
14404 // (select (x == 0), 0, -1) -> neg & sbb
14405 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14406 if (YC->isNullValue() &&
14407 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14408 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14409 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14410 DAG.getConstant(0, DL,
14411 CmpOp0.getValueType()),
14413 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14414 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14415 SDValue(Neg.getNode(), 1));
14419 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14420 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14421 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14423 SDValue Res = // Res = 0 or -1.
14424 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14425 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14427 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14428 Res = DAG.getNOT(DL, Res, Res.getValueType());
14430 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14431 if (!N2C || !N2C->isNullValue())
14432 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14437 // Look past (and (setcc_carry (cmp ...)), 1).
14438 if (Cond.getOpcode() == ISD::AND &&
14439 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14440 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14441 if (C && C->getAPIntValue() == 1)
14442 Cond = Cond.getOperand(0);
14445 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14446 // setting operand in place of the X86ISD::SETCC.
14447 unsigned CondOpcode = Cond.getOpcode();
14448 if (CondOpcode == X86ISD::SETCC ||
14449 CondOpcode == X86ISD::SETCC_CARRY) {
14450 CC = Cond.getOperand(0);
14452 SDValue Cmp = Cond.getOperand(1);
14453 unsigned Opc = Cmp.getOpcode();
14454 MVT VT = Op.getSimpleValueType();
14456 bool IllegalFPCMov = false;
14457 if (VT.isFloatingPoint() && !VT.isVector() &&
14458 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14459 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14461 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14462 Opc == X86ISD::BT) { // FIXME
14466 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14467 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14468 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14469 Cond.getOperand(0).getValueType() != MVT::i8)) {
14470 SDValue LHS = Cond.getOperand(0);
14471 SDValue RHS = Cond.getOperand(1);
14472 unsigned X86Opcode;
14475 switch (CondOpcode) {
14476 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14477 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14478 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14479 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14480 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14481 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14482 default: llvm_unreachable("unexpected overflowing operator");
14484 if (CondOpcode == ISD::UMULO)
14485 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14488 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14490 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14492 if (CondOpcode == ISD::UMULO)
14493 Cond = X86Op.getValue(2);
14495 Cond = X86Op.getValue(1);
14497 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14502 // Look past the truncate if the high bits are known zero.
14503 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14504 Cond = Cond.getOperand(0);
14506 // We know the result of AND is compared against zero. Try to match
14508 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14509 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14510 if (NewSetCC.getNode()) {
14511 CC = NewSetCC.getOperand(0);
14512 Cond = NewSetCC.getOperand(1);
14519 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14520 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14523 // a < b ? -1 : 0 -> RES = ~setcc_carry
14524 // a < b ? 0 : -1 -> RES = setcc_carry
14525 // a >= b ? -1 : 0 -> RES = setcc_carry
14526 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14527 if (Cond.getOpcode() == X86ISD::SUB) {
14528 Cond = ConvertCmpIfNecessary(Cond, DAG);
14529 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14531 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14532 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14533 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14534 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14536 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14537 return DAG.getNOT(DL, Res, Res.getValueType());
14542 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14543 // widen the cmov and push the truncate through. This avoids introducing a new
14544 // branch during isel and doesn't add any extensions.
14545 if (Op.getValueType() == MVT::i8 &&
14546 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14547 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14548 if (T1.getValueType() == T2.getValueType() &&
14549 // Blacklist CopyFromReg to avoid partial register stalls.
14550 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14551 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14552 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14553 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14557 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14558 // condition is true.
14559 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14560 SDValue Ops[] = { Op2, Op1, CC, Cond };
14561 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14564 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14565 const X86Subtarget *Subtarget,
14566 SelectionDAG &DAG) {
14567 MVT VT = Op->getSimpleValueType(0);
14568 SDValue In = Op->getOperand(0);
14569 MVT InVT = In.getSimpleValueType();
14570 MVT VTElt = VT.getVectorElementType();
14571 MVT InVTElt = InVT.getVectorElementType();
14575 if ((InVTElt == MVT::i1) &&
14576 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14577 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14579 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14580 VTElt.getSizeInBits() <= 16)) ||
14582 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14583 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14585 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14586 VTElt.getSizeInBits() >= 32))))
14587 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14589 unsigned int NumElts = VT.getVectorNumElements();
14591 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14594 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14595 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14596 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14597 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14600 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14601 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14603 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14606 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14608 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14609 if (VT.is512BitVector())
14611 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14614 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14615 const X86Subtarget *Subtarget,
14616 SelectionDAG &DAG) {
14617 SDValue In = Op->getOperand(0);
14618 MVT VT = Op->getSimpleValueType(0);
14619 MVT InVT = In.getSimpleValueType();
14620 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14622 MVT InSVT = InVT.getScalarType();
14623 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14625 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14627 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14632 // SSE41 targets can use the pmovsx* instructions directly.
14633 if (Subtarget->hasSSE41())
14634 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14636 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14640 // As SRAI is only available on i16/i32 types, we expand only up to i32
14641 // and handle i64 separately.
14642 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14643 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14644 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14645 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14646 Curr = DAG.getBitcast(CurrVT, Curr);
14649 SDValue SignExt = Curr;
14650 if (CurrVT != InVT) {
14651 unsigned SignExtShift =
14652 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14653 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14654 DAG.getConstant(SignExtShift, dl, MVT::i8));
14660 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14661 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14662 DAG.getConstant(31, dl, MVT::i8));
14663 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14664 return DAG.getBitcast(VT, Ext);
14670 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14671 SelectionDAG &DAG) {
14672 MVT VT = Op->getSimpleValueType(0);
14673 SDValue In = Op->getOperand(0);
14674 MVT InVT = In.getSimpleValueType();
14677 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14678 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14680 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14681 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14682 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14685 if (Subtarget->hasInt256())
14686 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14688 // Optimize vectors in AVX mode
14689 // Sign extend v8i16 to v8i32 and
14692 // Divide input vector into two parts
14693 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14694 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14695 // concat the vectors to original VT
14697 unsigned NumElems = InVT.getVectorNumElements();
14698 SDValue Undef = DAG.getUNDEF(InVT);
14700 SmallVector<int,8> ShufMask1(NumElems, -1);
14701 for (unsigned i = 0; i != NumElems/2; ++i)
14704 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14706 SmallVector<int,8> ShufMask2(NumElems, -1);
14707 for (unsigned i = 0; i != NumElems/2; ++i)
14708 ShufMask2[i] = i + NumElems/2;
14710 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14712 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14713 VT.getVectorNumElements()/2);
14715 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14716 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14718 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14721 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14722 // may emit an illegal shuffle but the expansion is still better than scalar
14723 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14724 // we'll emit a shuffle and a arithmetic shift.
14725 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14726 // TODO: It is possible to support ZExt by zeroing the undef values during
14727 // the shuffle phase or after the shuffle.
14728 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14729 SelectionDAG &DAG) {
14730 MVT RegVT = Op.getSimpleValueType();
14731 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14732 assert(RegVT.isInteger() &&
14733 "We only custom lower integer vector sext loads.");
14735 // Nothing useful we can do without SSE2 shuffles.
14736 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14738 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14740 EVT MemVT = Ld->getMemoryVT();
14741 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14742 unsigned RegSz = RegVT.getSizeInBits();
14744 ISD::LoadExtType Ext = Ld->getExtensionType();
14746 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14747 && "Only anyext and sext are currently implemented.");
14748 assert(MemVT != RegVT && "Cannot extend to the same type");
14749 assert(MemVT.isVector() && "Must load a vector from memory");
14751 unsigned NumElems = RegVT.getVectorNumElements();
14752 unsigned MemSz = MemVT.getSizeInBits();
14753 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14755 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14756 // The only way in which we have a legal 256-bit vector result but not the
14757 // integer 256-bit operations needed to directly lower a sextload is if we
14758 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14759 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14760 // correctly legalized. We do this late to allow the canonical form of
14761 // sextload to persist throughout the rest of the DAG combiner -- it wants
14762 // to fold together any extensions it can, and so will fuse a sign_extend
14763 // of an sextload into a sextload targeting a wider value.
14765 if (MemSz == 128) {
14766 // Just switch this to a normal load.
14767 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14768 "it must be a legal 128-bit vector "
14770 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14771 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14772 Ld->isInvariant(), Ld->getAlignment());
14774 assert(MemSz < 128 &&
14775 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14776 // Do an sext load to a 128-bit vector type. We want to use the same
14777 // number of elements, but elements half as wide. This will end up being
14778 // recursively lowered by this routine, but will succeed as we definitely
14779 // have all the necessary features if we're using AVX1.
14781 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14782 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14784 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14785 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14786 Ld->isNonTemporal(), Ld->isInvariant(),
14787 Ld->getAlignment());
14790 // Replace chain users with the new chain.
14791 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14792 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14794 // Finally, do a normal sign-extend to the desired register.
14795 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14798 // All sizes must be a power of two.
14799 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14800 "Non-power-of-two elements are not custom lowered!");
14802 // Attempt to load the original value using scalar loads.
14803 // Find the largest scalar type that divides the total loaded size.
14804 MVT SclrLoadTy = MVT::i8;
14805 for (MVT Tp : MVT::integer_valuetypes()) {
14806 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14811 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14812 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14814 SclrLoadTy = MVT::f64;
14816 // Calculate the number of scalar loads that we need to perform
14817 // in order to load our vector from memory.
14818 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14820 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14821 "Can only lower sext loads with a single scalar load!");
14823 unsigned loadRegZize = RegSz;
14824 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14827 // Represent our vector as a sequence of elements which are the
14828 // largest scalar that we can load.
14829 EVT LoadUnitVecVT = EVT::getVectorVT(
14830 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14832 // Represent the data using the same element type that is stored in
14833 // memory. In practice, we ''widen'' MemVT.
14835 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14836 loadRegZize / MemVT.getScalarType().getSizeInBits());
14838 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14839 "Invalid vector type");
14841 // We can't shuffle using an illegal type.
14842 assert(TLI.isTypeLegal(WideVecVT) &&
14843 "We only lower types that form legal widened vector types");
14845 SmallVector<SDValue, 8> Chains;
14846 SDValue Ptr = Ld->getBasePtr();
14847 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14848 TLI.getPointerTy(DAG.getDataLayout()));
14849 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14851 for (unsigned i = 0; i < NumLoads; ++i) {
14852 // Perform a single load.
14853 SDValue ScalarLoad =
14854 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14855 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14856 Ld->getAlignment());
14857 Chains.push_back(ScalarLoad.getValue(1));
14858 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14859 // another round of DAGCombining.
14861 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14863 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14864 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14866 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14869 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14871 // Bitcast the loaded value to a vector of the original element type, in
14872 // the size of the target vector type.
14873 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14874 unsigned SizeRatio = RegSz / MemSz;
14876 if (Ext == ISD::SEXTLOAD) {
14877 // If we have SSE4.1, we can directly emit a VSEXT node.
14878 if (Subtarget->hasSSE41()) {
14879 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14880 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14884 // Otherwise we'll shuffle the small elements in the high bits of the
14885 // larger type and perform an arithmetic shift. If the shift is not legal
14886 // it's better to scalarize.
14887 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14888 "We can't implement a sext load without an arithmetic right shift!");
14890 // Redistribute the loaded elements into the different locations.
14891 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14892 for (unsigned i = 0; i != NumElems; ++i)
14893 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14895 SDValue Shuff = DAG.getVectorShuffle(
14896 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14898 Shuff = DAG.getBitcast(RegVT, Shuff);
14900 // Build the arithmetic shift.
14901 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14902 MemVT.getVectorElementType().getSizeInBits();
14904 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14905 DAG.getConstant(Amt, dl, RegVT));
14907 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14911 // Redistribute the loaded elements into the different locations.
14912 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14913 for (unsigned i = 0; i != NumElems; ++i)
14914 ShuffleVec[i * SizeRatio] = i;
14916 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14917 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14919 // Bitcast to the requested type.
14920 Shuff = DAG.getBitcast(RegVT, Shuff);
14921 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14925 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14926 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14927 // from the AND / OR.
14928 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14929 Opc = Op.getOpcode();
14930 if (Opc != ISD::OR && Opc != ISD::AND)
14932 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14933 Op.getOperand(0).hasOneUse() &&
14934 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14935 Op.getOperand(1).hasOneUse());
14938 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14939 // 1 and that the SETCC node has a single use.
14940 static bool isXor1OfSetCC(SDValue Op) {
14941 if (Op.getOpcode() != ISD::XOR)
14943 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14944 if (N1C && N1C->getAPIntValue() == 1) {
14945 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14946 Op.getOperand(0).hasOneUse();
14951 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14952 bool addTest = true;
14953 SDValue Chain = Op.getOperand(0);
14954 SDValue Cond = Op.getOperand(1);
14955 SDValue Dest = Op.getOperand(2);
14958 bool Inverted = false;
14960 if (Cond.getOpcode() == ISD::SETCC) {
14961 // Check for setcc([su]{add,sub,mul}o == 0).
14962 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14963 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14964 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14965 Cond.getOperand(0).getResNo() == 1 &&
14966 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14967 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14968 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14969 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14970 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14971 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14973 Cond = Cond.getOperand(0);
14975 SDValue NewCond = LowerSETCC(Cond, DAG);
14976 if (NewCond.getNode())
14981 // FIXME: LowerXALUO doesn't handle these!!
14982 else if (Cond.getOpcode() == X86ISD::ADD ||
14983 Cond.getOpcode() == X86ISD::SUB ||
14984 Cond.getOpcode() == X86ISD::SMUL ||
14985 Cond.getOpcode() == X86ISD::UMUL)
14986 Cond = LowerXALUO(Cond, DAG);
14989 // Look pass (and (setcc_carry (cmp ...)), 1).
14990 if (Cond.getOpcode() == ISD::AND &&
14991 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14992 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14993 if (C && C->getAPIntValue() == 1)
14994 Cond = Cond.getOperand(0);
14997 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14998 // setting operand in place of the X86ISD::SETCC.
14999 unsigned CondOpcode = Cond.getOpcode();
15000 if (CondOpcode == X86ISD::SETCC ||
15001 CondOpcode == X86ISD::SETCC_CARRY) {
15002 CC = Cond.getOperand(0);
15004 SDValue Cmp = Cond.getOperand(1);
15005 unsigned Opc = Cmp.getOpcode();
15006 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15007 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15011 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15015 // These can only come from an arithmetic instruction with overflow,
15016 // e.g. SADDO, UADDO.
15017 Cond = Cond.getNode()->getOperand(1);
15023 CondOpcode = Cond.getOpcode();
15024 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15025 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15026 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15027 Cond.getOperand(0).getValueType() != MVT::i8)) {
15028 SDValue LHS = Cond.getOperand(0);
15029 SDValue RHS = Cond.getOperand(1);
15030 unsigned X86Opcode;
15033 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15034 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15036 switch (CondOpcode) {
15037 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15039 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15041 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15044 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15045 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15047 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15049 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15052 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15053 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15054 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15055 default: llvm_unreachable("unexpected overflowing operator");
15058 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15059 if (CondOpcode == ISD::UMULO)
15060 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15063 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15065 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15067 if (CondOpcode == ISD::UMULO)
15068 Cond = X86Op.getValue(2);
15070 Cond = X86Op.getValue(1);
15072 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15076 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15077 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15078 if (CondOpc == ISD::OR) {
15079 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15080 // two branches instead of an explicit OR instruction with a
15082 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15083 isX86LogicalCmp(Cmp)) {
15084 CC = Cond.getOperand(0).getOperand(0);
15085 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15086 Chain, Dest, CC, Cmp);
15087 CC = Cond.getOperand(1).getOperand(0);
15091 } else { // ISD::AND
15092 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15093 // two branches instead of an explicit AND instruction with a
15094 // separate test. However, we only do this if this block doesn't
15095 // have a fall-through edge, because this requires an explicit
15096 // jmp when the condition is false.
15097 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15098 isX86LogicalCmp(Cmp) &&
15099 Op.getNode()->hasOneUse()) {
15100 X86::CondCode CCode =
15101 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15102 CCode = X86::GetOppositeBranchCondition(CCode);
15103 CC = DAG.getConstant(CCode, dl, MVT::i8);
15104 SDNode *User = *Op.getNode()->use_begin();
15105 // Look for an unconditional branch following this conditional branch.
15106 // We need this because we need to reverse the successors in order
15107 // to implement FCMP_OEQ.
15108 if (User->getOpcode() == ISD::BR) {
15109 SDValue FalseBB = User->getOperand(1);
15111 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15112 assert(NewBR == User);
15116 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15117 Chain, Dest, CC, Cmp);
15118 X86::CondCode CCode =
15119 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15120 CCode = X86::GetOppositeBranchCondition(CCode);
15121 CC = DAG.getConstant(CCode, dl, MVT::i8);
15127 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15128 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15129 // It should be transformed during dag combiner except when the condition
15130 // is set by a arithmetics with overflow node.
15131 X86::CondCode CCode =
15132 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15133 CCode = X86::GetOppositeBranchCondition(CCode);
15134 CC = DAG.getConstant(CCode, dl, MVT::i8);
15135 Cond = Cond.getOperand(0).getOperand(1);
15137 } else if (Cond.getOpcode() == ISD::SETCC &&
15138 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15139 // For FCMP_OEQ, we can emit
15140 // two branches instead of an explicit AND instruction with a
15141 // separate test. However, we only do this if this block doesn't
15142 // have a fall-through edge, because this requires an explicit
15143 // jmp when the condition is false.
15144 if (Op.getNode()->hasOneUse()) {
15145 SDNode *User = *Op.getNode()->use_begin();
15146 // Look for an unconditional branch following this conditional branch.
15147 // We need this because we need to reverse the successors in order
15148 // to implement FCMP_OEQ.
15149 if (User->getOpcode() == ISD::BR) {
15150 SDValue FalseBB = User->getOperand(1);
15152 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15153 assert(NewBR == User);
15157 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15158 Cond.getOperand(0), Cond.getOperand(1));
15159 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15160 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15161 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15162 Chain, Dest, CC, Cmp);
15163 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15168 } else if (Cond.getOpcode() == ISD::SETCC &&
15169 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15170 // For FCMP_UNE, we can emit
15171 // two branches instead of an explicit AND instruction with a
15172 // separate test. However, we only do this if this block doesn't
15173 // have a fall-through edge, because this requires an explicit
15174 // jmp when the condition is false.
15175 if (Op.getNode()->hasOneUse()) {
15176 SDNode *User = *Op.getNode()->use_begin();
15177 // Look for an unconditional branch following this conditional branch.
15178 // We need this because we need to reverse the successors in order
15179 // to implement FCMP_UNE.
15180 if (User->getOpcode() == ISD::BR) {
15181 SDValue FalseBB = User->getOperand(1);
15183 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15184 assert(NewBR == User);
15187 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15188 Cond.getOperand(0), Cond.getOperand(1));
15189 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15190 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15191 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15192 Chain, Dest, CC, Cmp);
15193 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15203 // Look pass the truncate if the high bits are known zero.
15204 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15205 Cond = Cond.getOperand(0);
15207 // We know the result of AND is compared against zero. Try to match
15209 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15210 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15211 if (NewSetCC.getNode()) {
15212 CC = NewSetCC.getOperand(0);
15213 Cond = NewSetCC.getOperand(1);
15220 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15221 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15222 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15224 Cond = ConvertCmpIfNecessary(Cond, DAG);
15225 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15226 Chain, Dest, CC, Cond);
15229 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15230 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15231 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15232 // that the guard pages used by the OS virtual memory manager are allocated in
15233 // correct sequence.
15235 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15236 SelectionDAG &DAG) const {
15237 MachineFunction &MF = DAG.getMachineFunction();
15238 bool SplitStack = MF.shouldSplitStack();
15239 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15244 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15245 SDNode* Node = Op.getNode();
15247 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15248 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15249 " not tell us which reg is the stack pointer!");
15250 EVT VT = Node->getValueType(0);
15251 SDValue Tmp1 = SDValue(Node, 0);
15252 SDValue Tmp2 = SDValue(Node, 1);
15253 SDValue Tmp3 = Node->getOperand(2);
15254 SDValue Chain = Tmp1.getOperand(0);
15256 // Chain the dynamic stack allocation so that it doesn't modify the stack
15257 // pointer when other instructions are using the stack.
15258 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15261 SDValue Size = Tmp2.getOperand(1);
15262 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15263 Chain = SP.getValue(1);
15264 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15265 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15266 unsigned StackAlign = TFI.getStackAlignment();
15267 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15268 if (Align > StackAlign)
15269 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15270 DAG.getConstant(-(uint64_t)Align, dl, VT));
15271 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15273 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15274 DAG.getIntPtrConstant(0, dl, true), SDValue(),
15277 SDValue Ops[2] = { Tmp1, Tmp2 };
15278 return DAG.getMergeValues(Ops, dl);
15282 SDValue Chain = Op.getOperand(0);
15283 SDValue Size = Op.getOperand(1);
15284 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15285 EVT VT = Op.getNode()->getValueType(0);
15287 bool Is64Bit = Subtarget->is64Bit();
15288 MVT SPTy = getPointerTy(DAG.getDataLayout());
15291 MachineRegisterInfo &MRI = MF.getRegInfo();
15294 // The 64 bit implementation of segmented stacks needs to clobber both r10
15295 // r11. This makes it impossible to use it along with nested parameters.
15296 const Function *F = MF.getFunction();
15298 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15300 if (I->hasNestAttr())
15301 report_fatal_error("Cannot use segmented stacks with functions that "
15302 "have nested arguments.");
15305 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15306 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15307 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15308 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15309 DAG.getRegister(Vreg, SPTy));
15310 SDValue Ops1[2] = { Value, Chain };
15311 return DAG.getMergeValues(Ops1, dl);
15314 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15316 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15317 Flag = Chain.getValue(1);
15318 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15320 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15322 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15323 unsigned SPReg = RegInfo->getStackRegister();
15324 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15325 Chain = SP.getValue(1);
15328 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15329 DAG.getConstant(-(uint64_t)Align, dl, VT));
15330 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15333 SDValue Ops1[2] = { SP, Chain };
15334 return DAG.getMergeValues(Ops1, dl);
15338 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15339 MachineFunction &MF = DAG.getMachineFunction();
15340 auto PtrVT = getPointerTy(MF.getDataLayout());
15341 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15343 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15346 if (!Subtarget->is64Bit() ||
15347 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15348 // vastart just stores the address of the VarArgsFrameIndex slot into the
15349 // memory location argument.
15350 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15351 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15352 MachinePointerInfo(SV), false, false, 0);
15356 // gp_offset (0 - 6 * 8)
15357 // fp_offset (48 - 48 + 8 * 16)
15358 // overflow_arg_area (point to parameters coming in memory).
15360 SmallVector<SDValue, 8> MemOps;
15361 SDValue FIN = Op.getOperand(1);
15363 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15364 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15366 FIN, MachinePointerInfo(SV), false, false, 0);
15367 MemOps.push_back(Store);
15370 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15371 Store = DAG.getStore(Op.getOperand(0), DL,
15372 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15374 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15375 MemOps.push_back(Store);
15377 // Store ptr to overflow_arg_area
15378 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15379 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15380 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15381 MachinePointerInfo(SV, 8),
15383 MemOps.push_back(Store);
15385 // Store ptr to reg_save_area.
15386 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15387 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15388 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15389 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15390 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15391 MemOps.push_back(Store);
15392 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15395 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15396 assert(Subtarget->is64Bit() &&
15397 "LowerVAARG only handles 64-bit va_arg!");
15398 assert(Op.getNode()->getNumOperands() == 4);
15400 MachineFunction &MF = DAG.getMachineFunction();
15401 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15402 // The Win64 ABI uses char* instead of a structure.
15403 return DAG.expandVAArg(Op.getNode());
15405 SDValue Chain = Op.getOperand(0);
15406 SDValue SrcPtr = Op.getOperand(1);
15407 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15408 unsigned Align = Op.getConstantOperandVal(3);
15411 EVT ArgVT = Op.getNode()->getValueType(0);
15412 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15413 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15416 // Decide which area this value should be read from.
15417 // TODO: Implement the AMD64 ABI in its entirety. This simple
15418 // selection mechanism works only for the basic types.
15419 if (ArgVT == MVT::f80) {
15420 llvm_unreachable("va_arg for f80 not yet implemented");
15421 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15422 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15423 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15424 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15426 llvm_unreachable("Unhandled argument type in LowerVAARG");
15429 if (ArgMode == 2) {
15430 // Sanity Check: Make sure using fp_offset makes sense.
15431 assert(!Subtarget->useSoftFloat() &&
15432 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15433 Subtarget->hasSSE1());
15436 // Insert VAARG_64 node into the DAG
15437 // VAARG_64 returns two values: Variable Argument Address, Chain
15438 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15439 DAG.getConstant(ArgMode, dl, MVT::i8),
15440 DAG.getConstant(Align, dl, MVT::i32)};
15441 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15442 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15443 VTs, InstOps, MVT::i64,
15444 MachinePointerInfo(SV),
15446 /*Volatile=*/false,
15448 /*WriteMem=*/true);
15449 Chain = VAARG.getValue(1);
15451 // Load the next argument and return it
15452 return DAG.getLoad(ArgVT, dl,
15455 MachinePointerInfo(),
15456 false, false, false, 0);
15459 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15460 SelectionDAG &DAG) {
15461 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15462 // where a va_list is still an i8*.
15463 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15464 if (Subtarget->isCallingConvWin64(
15465 DAG.getMachineFunction().getFunction()->getCallingConv()))
15466 // Probably a Win64 va_copy.
15467 return DAG.expandVACopy(Op.getNode());
15469 SDValue Chain = Op.getOperand(0);
15470 SDValue DstPtr = Op.getOperand(1);
15471 SDValue SrcPtr = Op.getOperand(2);
15472 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15473 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15476 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15477 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15479 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15482 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15483 // amount is a constant. Takes immediate version of shift as input.
15484 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15485 SDValue SrcOp, uint64_t ShiftAmt,
15486 SelectionDAG &DAG) {
15487 MVT ElementType = VT.getVectorElementType();
15489 // Fold this packed shift into its first operand if ShiftAmt is 0.
15493 // Check for ShiftAmt >= element width
15494 if (ShiftAmt >= ElementType.getSizeInBits()) {
15495 if (Opc == X86ISD::VSRAI)
15496 ShiftAmt = ElementType.getSizeInBits() - 1;
15498 return DAG.getConstant(0, dl, VT);
15501 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15502 && "Unknown target vector shift-by-constant node");
15504 // Fold this packed vector shift into a build vector if SrcOp is a
15505 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15506 if (VT == SrcOp.getSimpleValueType() &&
15507 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15508 SmallVector<SDValue, 8> Elts;
15509 unsigned NumElts = SrcOp->getNumOperands();
15510 ConstantSDNode *ND;
15513 default: llvm_unreachable(nullptr);
15514 case X86ISD::VSHLI:
15515 for (unsigned i=0; i!=NumElts; ++i) {
15516 SDValue CurrentOp = SrcOp->getOperand(i);
15517 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15518 Elts.push_back(CurrentOp);
15521 ND = cast<ConstantSDNode>(CurrentOp);
15522 const APInt &C = ND->getAPIntValue();
15523 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15526 case X86ISD::VSRLI:
15527 for (unsigned i=0; i!=NumElts; ++i) {
15528 SDValue CurrentOp = SrcOp->getOperand(i);
15529 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15530 Elts.push_back(CurrentOp);
15533 ND = cast<ConstantSDNode>(CurrentOp);
15534 const APInt &C = ND->getAPIntValue();
15535 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15538 case X86ISD::VSRAI:
15539 for (unsigned i=0; i!=NumElts; ++i) {
15540 SDValue CurrentOp = SrcOp->getOperand(i);
15541 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15542 Elts.push_back(CurrentOp);
15545 ND = cast<ConstantSDNode>(CurrentOp);
15546 const APInt &C = ND->getAPIntValue();
15547 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15552 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15555 return DAG.getNode(Opc, dl, VT, SrcOp,
15556 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15559 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15560 // may or may not be a constant. Takes immediate version of shift as input.
15561 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15562 SDValue SrcOp, SDValue ShAmt,
15563 SelectionDAG &DAG) {
15564 MVT SVT = ShAmt.getSimpleValueType();
15565 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15567 // Catch shift-by-constant.
15568 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15569 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15570 CShAmt->getZExtValue(), DAG);
15572 // Change opcode to non-immediate version
15574 default: llvm_unreachable("Unknown target vector shift node");
15575 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15576 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15577 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15580 const X86Subtarget &Subtarget =
15581 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15582 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15583 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15584 // Let the shuffle legalizer expand this shift amount node.
15585 SDValue Op0 = ShAmt.getOperand(0);
15586 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15587 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15589 // Need to build a vector containing shift amount.
15590 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15591 SmallVector<SDValue, 4> ShOps;
15592 ShOps.push_back(ShAmt);
15593 if (SVT == MVT::i32) {
15594 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15595 ShOps.push_back(DAG.getUNDEF(SVT));
15597 ShOps.push_back(DAG.getUNDEF(SVT));
15599 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15600 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15603 // The return type has to be a 128-bit type with the same element
15604 // type as the input type.
15605 MVT EltVT = VT.getVectorElementType();
15606 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15608 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15609 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15612 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15613 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15614 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15615 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15616 SDValue PreservedSrc,
15617 const X86Subtarget *Subtarget,
15618 SelectionDAG &DAG) {
15619 EVT VT = Op.getValueType();
15620 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15621 MVT::i1, VT.getVectorNumElements());
15622 SDValue VMask = SDValue();
15623 unsigned OpcodeSelect = ISD::VSELECT;
15626 assert(MaskVT.isSimple() && "invalid mask type");
15628 if (isAllOnes(Mask))
15631 if (MaskVT.bitsGT(Mask.getValueType())) {
15632 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15633 MaskVT.getSizeInBits());
15634 VMask = DAG.getBitcast(MaskVT,
15635 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15637 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15638 Mask.getValueType().getSizeInBits());
15639 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15640 // are extracted by EXTRACT_SUBVECTOR.
15641 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15642 DAG.getBitcast(BitcastVT, Mask),
15643 DAG.getIntPtrConstant(0, dl));
15646 switch (Op.getOpcode()) {
15648 case X86ISD::PCMPEQM:
15649 case X86ISD::PCMPGTM:
15651 case X86ISD::CMPMU:
15652 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15653 case X86ISD::VTRUNC:
15654 case X86ISD::VTRUNCS:
15655 case X86ISD::VTRUNCUS:
15656 // We can't use ISD::VSELECT here because it is not always "Legal"
15657 // for the destination type. For example vpmovqb require only AVX512
15658 // and vselect that can operate on byte element type require BWI
15659 OpcodeSelect = X86ISD::SELECT;
15662 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15663 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15664 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15667 /// \brief Creates an SDNode for a predicated scalar operation.
15668 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15669 /// The mask is coming as MVT::i8 and it should be truncated
15670 /// to MVT::i1 while lowering masking intrinsics.
15671 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15672 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15673 /// for a scalar instruction.
15674 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15675 SDValue PreservedSrc,
15676 const X86Subtarget *Subtarget,
15677 SelectionDAG &DAG) {
15678 if (isAllOnes(Mask))
15681 EVT VT = Op.getValueType();
15683 // The mask should be of type MVT::i1
15684 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15686 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15687 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15688 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15691 static int getSEHRegistrationNodeSize(const Function *Fn) {
15692 if (!Fn->hasPersonalityFn())
15693 report_fatal_error(
15694 "querying registration node size for function without personality");
15695 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15696 // WinEHStatePass for the full struct definition.
15697 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15698 case EHPersonality::MSVC_X86SEH: return 24;
15699 case EHPersonality::MSVC_CXX: return 16;
15702 report_fatal_error("can only recover FP for MSVC EH personality functions");
15705 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15706 /// function or when returning to a parent frame after catching an exception, we
15707 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15708 /// Here's the math:
15709 /// RegNodeBase = EntryEBP - RegNodeSize
15710 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15711 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15712 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15713 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15714 SDValue EntryEBP) {
15715 MachineFunction &MF = DAG.getMachineFunction();
15718 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15719 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15721 // It's possible that the parent function no longer has a personality function
15722 // if the exceptional code was optimized away, in which case we just return
15723 // the incoming EBP.
15724 if (!Fn->hasPersonalityFn())
15727 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15729 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15731 MCSymbol *OffsetSym =
15732 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15733 GlobalValue::getRealLinkageName(Fn->getName()));
15734 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15735 SDValue RegNodeFrameOffset =
15736 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15738 // RegNodeBase = EntryEBP - RegNodeSize
15739 // ParentFP = RegNodeBase - RegNodeFrameOffset
15740 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15741 DAG.getConstant(RegNodeSize, dl, PtrVT));
15742 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15745 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15746 SelectionDAG &DAG) {
15748 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15749 EVT VT = Op.getValueType();
15750 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15752 switch(IntrData->Type) {
15753 case INTR_TYPE_1OP:
15754 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15755 case INTR_TYPE_2OP:
15756 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15758 case INTR_TYPE_2OP_IMM8:
15759 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15760 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15761 case INTR_TYPE_3OP:
15762 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15763 Op.getOperand(2), Op.getOperand(3));
15764 case INTR_TYPE_4OP:
15765 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15766 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15767 case INTR_TYPE_1OP_MASK_RM: {
15768 SDValue Src = Op.getOperand(1);
15769 SDValue PassThru = Op.getOperand(2);
15770 SDValue Mask = Op.getOperand(3);
15771 SDValue RoundingMode;
15772 // We allways add rounding mode to the Node.
15773 // If the rounding mode is not specified, we add the
15774 // "current direction" mode.
15775 if (Op.getNumOperands() == 4)
15777 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15779 RoundingMode = Op.getOperand(4);
15780 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15781 if (IntrWithRoundingModeOpcode != 0)
15782 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15783 X86::STATIC_ROUNDING::CUR_DIRECTION)
15784 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15785 dl, Op.getValueType(), Src, RoundingMode),
15786 Mask, PassThru, Subtarget, DAG);
15787 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15789 Mask, PassThru, Subtarget, DAG);
15791 case INTR_TYPE_1OP_MASK: {
15792 SDValue Src = Op.getOperand(1);
15793 SDValue PassThru = Op.getOperand(2);
15794 SDValue Mask = Op.getOperand(3);
15795 // We add rounding mode to the Node when
15796 // - RM Opcode is specified and
15797 // - RM is not "current direction".
15798 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15799 if (IntrWithRoundingModeOpcode != 0) {
15800 SDValue Rnd = Op.getOperand(4);
15801 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15802 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15803 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15804 dl, Op.getValueType(),
15806 Mask, PassThru, Subtarget, DAG);
15809 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15810 Mask, PassThru, Subtarget, DAG);
15812 case INTR_TYPE_SCALAR_MASK_RM: {
15813 SDValue Src1 = Op.getOperand(1);
15814 SDValue Src2 = Op.getOperand(2);
15815 SDValue Src0 = Op.getOperand(3);
15816 SDValue Mask = Op.getOperand(4);
15817 // There are 2 kinds of intrinsics in this group:
15818 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15819 // (2) With rounding mode and sae - 7 operands.
15820 if (Op.getNumOperands() == 6) {
15821 SDValue Sae = Op.getOperand(5);
15822 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15823 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15825 Mask, Src0, Subtarget, DAG);
15827 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15828 SDValue RoundingMode = Op.getOperand(5);
15829 SDValue Sae = Op.getOperand(6);
15830 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15831 RoundingMode, Sae),
15832 Mask, Src0, Subtarget, DAG);
15834 case INTR_TYPE_2OP_MASK: {
15835 SDValue Src1 = Op.getOperand(1);
15836 SDValue Src2 = Op.getOperand(2);
15837 SDValue PassThru = Op.getOperand(3);
15838 SDValue Mask = Op.getOperand(4);
15839 // We specify 2 possible opcodes for intrinsics with rounding modes.
15840 // First, we check if the intrinsic may have non-default rounding mode,
15841 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15842 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15843 if (IntrWithRoundingModeOpcode != 0) {
15844 SDValue Rnd = Op.getOperand(5);
15845 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15846 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15847 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15848 dl, Op.getValueType(),
15850 Mask, PassThru, Subtarget, DAG);
15853 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15855 Mask, PassThru, Subtarget, DAG);
15857 case INTR_TYPE_2OP_MASK_RM: {
15858 SDValue Src1 = Op.getOperand(1);
15859 SDValue Src2 = Op.getOperand(2);
15860 SDValue PassThru = Op.getOperand(3);
15861 SDValue Mask = Op.getOperand(4);
15862 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15863 // First, we check if the intrinsic have rounding mode (6 operands),
15864 // if not, we set rounding mode to "current".
15866 if (Op.getNumOperands() == 6)
15867 Rnd = Op.getOperand(5);
15869 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15870 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15872 Mask, PassThru, Subtarget, DAG);
15874 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15875 SDValue Src1 = Op.getOperand(1);
15876 SDValue Src2 = Op.getOperand(2);
15877 SDValue Src3 = Op.getOperand(3);
15878 SDValue PassThru = Op.getOperand(4);
15879 SDValue Mask = Op.getOperand(5);
15880 SDValue Sae = Op.getOperand(6);
15882 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15884 Mask, PassThru, Subtarget, DAG);
15886 case INTR_TYPE_3OP_MASK_RM: {
15887 SDValue Src1 = Op.getOperand(1);
15888 SDValue Src2 = Op.getOperand(2);
15889 SDValue Imm = Op.getOperand(3);
15890 SDValue PassThru = Op.getOperand(4);
15891 SDValue Mask = Op.getOperand(5);
15892 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15893 // First, we check if the intrinsic have rounding mode (7 operands),
15894 // if not, we set rounding mode to "current".
15896 if (Op.getNumOperands() == 7)
15897 Rnd = Op.getOperand(6);
15899 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15900 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15901 Src1, Src2, Imm, Rnd),
15902 Mask, PassThru, Subtarget, DAG);
15904 case INTR_TYPE_3OP_IMM8_MASK:
15905 case INTR_TYPE_3OP_MASK: {
15906 SDValue Src1 = Op.getOperand(1);
15907 SDValue Src2 = Op.getOperand(2);
15908 SDValue Src3 = Op.getOperand(3);
15909 SDValue PassThru = Op.getOperand(4);
15910 SDValue Mask = Op.getOperand(5);
15912 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15913 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15914 // We specify 2 possible opcodes for intrinsics with rounding modes.
15915 // First, we check if the intrinsic may have non-default rounding mode,
15916 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15917 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15918 if (IntrWithRoundingModeOpcode != 0) {
15919 SDValue Rnd = Op.getOperand(6);
15920 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15921 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15922 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15923 dl, Op.getValueType(),
15924 Src1, Src2, Src3, Rnd),
15925 Mask, PassThru, Subtarget, DAG);
15928 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15930 Mask, PassThru, Subtarget, DAG);
15932 case VPERM_3OP_MASKZ:
15933 case VPERM_3OP_MASK:
15936 case FMA_OP_MASK: {
15937 SDValue Src1 = Op.getOperand(1);
15938 SDValue Src2 = Op.getOperand(2);
15939 SDValue Src3 = Op.getOperand(3);
15940 SDValue Mask = Op.getOperand(4);
15941 EVT VT = Op.getValueType();
15942 SDValue PassThru = SDValue();
15944 // set PassThru element
15945 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15946 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15947 else if (IntrData->Type == FMA_OP_MASK3)
15952 // We specify 2 possible opcodes for intrinsics with rounding modes.
15953 // First, we check if the intrinsic may have non-default rounding mode,
15954 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15955 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15956 if (IntrWithRoundingModeOpcode != 0) {
15957 SDValue Rnd = Op.getOperand(5);
15958 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15959 X86::STATIC_ROUNDING::CUR_DIRECTION)
15960 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15961 dl, Op.getValueType(),
15962 Src1, Src2, Src3, Rnd),
15963 Mask, PassThru, Subtarget, DAG);
15965 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15966 dl, Op.getValueType(),
15968 Mask, PassThru, Subtarget, DAG);
15971 case CMP_MASK_CC: {
15972 // Comparison intrinsics with masks.
15973 // Example of transformation:
15974 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15975 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15977 // (v8i1 (insert_subvector undef,
15978 // (v2i1 (and (PCMPEQM %a, %b),
15979 // (extract_subvector
15980 // (v8i1 (bitcast %mask)), 0))), 0))))
15981 EVT VT = Op.getOperand(1).getValueType();
15982 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15983 VT.getVectorNumElements());
15984 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15985 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15986 Mask.getValueType().getSizeInBits());
15988 if (IntrData->Type == CMP_MASK_CC) {
15989 SDValue CC = Op.getOperand(3);
15990 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15991 // We specify 2 possible opcodes for intrinsics with rounding modes.
15992 // First, we check if the intrinsic may have non-default rounding mode,
15993 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15994 if (IntrData->Opc1 != 0) {
15995 SDValue Rnd = Op.getOperand(5);
15996 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15997 X86::STATIC_ROUNDING::CUR_DIRECTION)
15998 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15999 Op.getOperand(2), CC, Rnd);
16001 //default rounding mode
16003 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16004 Op.getOperand(2), CC);
16007 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16008 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16011 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16012 DAG.getTargetConstant(0, dl,
16015 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16016 DAG.getUNDEF(BitcastVT), CmpMask,
16017 DAG.getIntPtrConstant(0, dl));
16018 return DAG.getBitcast(Op.getValueType(), Res);
16020 case COMI: { // Comparison intrinsics
16021 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16022 SDValue LHS = Op.getOperand(1);
16023 SDValue RHS = Op.getOperand(2);
16024 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16025 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16026 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16027 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16028 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16029 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16032 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16033 Op.getOperand(1), Op.getOperand(2), DAG);
16035 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16036 Op.getSimpleValueType(),
16038 Op.getOperand(2), DAG),
16039 Op.getOperand(4), Op.getOperand(3), Subtarget,
16041 case COMPRESS_EXPAND_IN_REG: {
16042 SDValue Mask = Op.getOperand(3);
16043 SDValue DataToCompress = Op.getOperand(1);
16044 SDValue PassThru = Op.getOperand(2);
16045 if (isAllOnes(Mask)) // return data as is
16046 return Op.getOperand(1);
16048 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16050 Mask, PassThru, Subtarget, DAG);
16053 SDValue Mask = Op.getOperand(3);
16054 EVT VT = Op.getValueType();
16055 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16056 VT.getVectorNumElements());
16057 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16058 Mask.getValueType().getSizeInBits());
16060 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16061 DAG.getBitcast(BitcastVT, Mask),
16062 DAG.getIntPtrConstant(0, dl));
16063 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16072 default: return SDValue(); // Don't custom lower most intrinsics.
16074 case Intrinsic::x86_avx2_permd:
16075 case Intrinsic::x86_avx2_permps:
16076 // Operands intentionally swapped. Mask is last operand to intrinsic,
16077 // but second operand for node/instruction.
16078 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16079 Op.getOperand(2), Op.getOperand(1));
16081 // ptest and testp intrinsics. The intrinsic these come from are designed to
16082 // return an integer value, not just an instruction so lower it to the ptest
16083 // or testp pattern and a setcc for the result.
16084 case Intrinsic::x86_sse41_ptestz:
16085 case Intrinsic::x86_sse41_ptestc:
16086 case Intrinsic::x86_sse41_ptestnzc:
16087 case Intrinsic::x86_avx_ptestz_256:
16088 case Intrinsic::x86_avx_ptestc_256:
16089 case Intrinsic::x86_avx_ptestnzc_256:
16090 case Intrinsic::x86_avx_vtestz_ps:
16091 case Intrinsic::x86_avx_vtestc_ps:
16092 case Intrinsic::x86_avx_vtestnzc_ps:
16093 case Intrinsic::x86_avx_vtestz_pd:
16094 case Intrinsic::x86_avx_vtestc_pd:
16095 case Intrinsic::x86_avx_vtestnzc_pd:
16096 case Intrinsic::x86_avx_vtestz_ps_256:
16097 case Intrinsic::x86_avx_vtestc_ps_256:
16098 case Intrinsic::x86_avx_vtestnzc_ps_256:
16099 case Intrinsic::x86_avx_vtestz_pd_256:
16100 case Intrinsic::x86_avx_vtestc_pd_256:
16101 case Intrinsic::x86_avx_vtestnzc_pd_256: {
16102 bool IsTestPacked = false;
16105 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16106 case Intrinsic::x86_avx_vtestz_ps:
16107 case Intrinsic::x86_avx_vtestz_pd:
16108 case Intrinsic::x86_avx_vtestz_ps_256:
16109 case Intrinsic::x86_avx_vtestz_pd_256:
16110 IsTestPacked = true; // Fallthrough
16111 case Intrinsic::x86_sse41_ptestz:
16112 case Intrinsic::x86_avx_ptestz_256:
16114 X86CC = X86::COND_E;
16116 case Intrinsic::x86_avx_vtestc_ps:
16117 case Intrinsic::x86_avx_vtestc_pd:
16118 case Intrinsic::x86_avx_vtestc_ps_256:
16119 case Intrinsic::x86_avx_vtestc_pd_256:
16120 IsTestPacked = true; // Fallthrough
16121 case Intrinsic::x86_sse41_ptestc:
16122 case Intrinsic::x86_avx_ptestc_256:
16124 X86CC = X86::COND_B;
16126 case Intrinsic::x86_avx_vtestnzc_ps:
16127 case Intrinsic::x86_avx_vtestnzc_pd:
16128 case Intrinsic::x86_avx_vtestnzc_ps_256:
16129 case Intrinsic::x86_avx_vtestnzc_pd_256:
16130 IsTestPacked = true; // Fallthrough
16131 case Intrinsic::x86_sse41_ptestnzc:
16132 case Intrinsic::x86_avx_ptestnzc_256:
16134 X86CC = X86::COND_A;
16138 SDValue LHS = Op.getOperand(1);
16139 SDValue RHS = Op.getOperand(2);
16140 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16141 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16142 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16143 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16144 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16146 case Intrinsic::x86_avx512_kortestz_w:
16147 case Intrinsic::x86_avx512_kortestc_w: {
16148 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16149 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16150 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16151 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16152 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16153 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16154 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16157 case Intrinsic::x86_sse42_pcmpistria128:
16158 case Intrinsic::x86_sse42_pcmpestria128:
16159 case Intrinsic::x86_sse42_pcmpistric128:
16160 case Intrinsic::x86_sse42_pcmpestric128:
16161 case Intrinsic::x86_sse42_pcmpistrio128:
16162 case Intrinsic::x86_sse42_pcmpestrio128:
16163 case Intrinsic::x86_sse42_pcmpistris128:
16164 case Intrinsic::x86_sse42_pcmpestris128:
16165 case Intrinsic::x86_sse42_pcmpistriz128:
16166 case Intrinsic::x86_sse42_pcmpestriz128: {
16170 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16171 case Intrinsic::x86_sse42_pcmpistria128:
16172 Opcode = X86ISD::PCMPISTRI;
16173 X86CC = X86::COND_A;
16175 case Intrinsic::x86_sse42_pcmpestria128:
16176 Opcode = X86ISD::PCMPESTRI;
16177 X86CC = X86::COND_A;
16179 case Intrinsic::x86_sse42_pcmpistric128:
16180 Opcode = X86ISD::PCMPISTRI;
16181 X86CC = X86::COND_B;
16183 case Intrinsic::x86_sse42_pcmpestric128:
16184 Opcode = X86ISD::PCMPESTRI;
16185 X86CC = X86::COND_B;
16187 case Intrinsic::x86_sse42_pcmpistrio128:
16188 Opcode = X86ISD::PCMPISTRI;
16189 X86CC = X86::COND_O;
16191 case Intrinsic::x86_sse42_pcmpestrio128:
16192 Opcode = X86ISD::PCMPESTRI;
16193 X86CC = X86::COND_O;
16195 case Intrinsic::x86_sse42_pcmpistris128:
16196 Opcode = X86ISD::PCMPISTRI;
16197 X86CC = X86::COND_S;
16199 case Intrinsic::x86_sse42_pcmpestris128:
16200 Opcode = X86ISD::PCMPESTRI;
16201 X86CC = X86::COND_S;
16203 case Intrinsic::x86_sse42_pcmpistriz128:
16204 Opcode = X86ISD::PCMPISTRI;
16205 X86CC = X86::COND_E;
16207 case Intrinsic::x86_sse42_pcmpestriz128:
16208 Opcode = X86ISD::PCMPESTRI;
16209 X86CC = X86::COND_E;
16212 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16213 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16214 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16215 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16216 DAG.getConstant(X86CC, dl, MVT::i8),
16217 SDValue(PCMP.getNode(), 1));
16218 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16221 case Intrinsic::x86_sse42_pcmpistri128:
16222 case Intrinsic::x86_sse42_pcmpestri128: {
16224 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16225 Opcode = X86ISD::PCMPISTRI;
16227 Opcode = X86ISD::PCMPESTRI;
16229 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16230 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16231 return DAG.getNode(Opcode, dl, VTs, NewOps);
16234 case Intrinsic::x86_seh_lsda: {
16235 // Compute the symbol for the LSDA. We know it'll get emitted later.
16236 MachineFunction &MF = DAG.getMachineFunction();
16237 SDValue Op1 = Op.getOperand(1);
16238 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16239 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16240 GlobalValue::getRealLinkageName(Fn->getName()));
16242 // Generate a simple absolute symbol reference. This intrinsic is only
16243 // supported on 32-bit Windows, which isn't PIC.
16244 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16245 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16248 case Intrinsic::x86_seh_recoverfp: {
16249 SDValue FnOp = Op.getOperand(1);
16250 SDValue IncomingFPOp = Op.getOperand(2);
16251 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16252 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16254 report_fatal_error(
16255 "llvm.x86.seh.recoverfp must take a function as the first argument");
16256 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16259 case Intrinsic::localaddress: {
16260 // Returns one of the stack, base, or frame pointer registers, depending on
16261 // which is used to reference local variables.
16262 MachineFunction &MF = DAG.getMachineFunction();
16263 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16265 if (RegInfo->hasBasePointer(MF))
16266 Reg = RegInfo->getBaseRegister();
16267 else // This function handles the SP or FP case.
16268 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16269 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16274 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16275 SDValue Src, SDValue Mask, SDValue Base,
16276 SDValue Index, SDValue ScaleOp, SDValue Chain,
16277 const X86Subtarget * Subtarget) {
16279 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16281 llvm_unreachable("Invalid scale type");
16282 unsigned ScaleVal = C->getZExtValue();
16283 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16284 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16286 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16287 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16288 Index.getSimpleValueType().getVectorNumElements());
16290 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16292 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16294 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16295 Mask.getValueType().getSizeInBits());
16297 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16298 // are extracted by EXTRACT_SUBVECTOR.
16299 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16300 DAG.getBitcast(BitcastVT, Mask),
16301 DAG.getIntPtrConstant(0, dl));
16303 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16304 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16305 SDValue Segment = DAG.getRegister(0, MVT::i32);
16306 if (Src.getOpcode() == ISD::UNDEF)
16307 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16308 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16309 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16310 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16311 return DAG.getMergeValues(RetOps, dl);
16314 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16315 SDValue Src, SDValue Mask, SDValue Base,
16316 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16318 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16320 llvm_unreachable("Invalid scale type");
16321 unsigned ScaleVal = C->getZExtValue();
16322 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16323 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16325 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16326 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16327 SDValue Segment = DAG.getRegister(0, MVT::i32);
16328 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16329 Index.getSimpleValueType().getVectorNumElements());
16331 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16333 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16335 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16336 Mask.getValueType().getSizeInBits());
16338 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16339 // are extracted by EXTRACT_SUBVECTOR.
16340 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16341 DAG.getBitcast(BitcastVT, Mask),
16342 DAG.getIntPtrConstant(0, dl));
16344 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16345 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16346 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16347 return SDValue(Res, 1);
16350 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16351 SDValue Mask, SDValue Base, SDValue Index,
16352 SDValue ScaleOp, SDValue Chain) {
16354 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16355 assert(C && "Invalid scale type");
16356 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16357 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16358 SDValue Segment = DAG.getRegister(0, MVT::i32);
16360 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16362 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16364 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16366 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16367 //SDVTList VTs = DAG.getVTList(MVT::Other);
16368 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16369 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16370 return SDValue(Res, 0);
16373 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16374 // read performance monitor counters (x86_rdpmc).
16375 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16376 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16377 SmallVectorImpl<SDValue> &Results) {
16378 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16379 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16382 // The ECX register is used to select the index of the performance counter
16384 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16386 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16388 // Reads the content of a 64-bit performance counter and returns it in the
16389 // registers EDX:EAX.
16390 if (Subtarget->is64Bit()) {
16391 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16392 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16395 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16396 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16399 Chain = HI.getValue(1);
16401 if (Subtarget->is64Bit()) {
16402 // The EAX register is loaded with the low-order 32 bits. The EDX register
16403 // is loaded with the supported high-order bits of the counter.
16404 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16405 DAG.getConstant(32, DL, MVT::i8));
16406 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16407 Results.push_back(Chain);
16411 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16412 SDValue Ops[] = { LO, HI };
16413 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16414 Results.push_back(Pair);
16415 Results.push_back(Chain);
16418 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16419 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16420 // also used to custom lower READCYCLECOUNTER nodes.
16421 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16422 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16423 SmallVectorImpl<SDValue> &Results) {
16424 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16425 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16428 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16429 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16430 // and the EAX register is loaded with the low-order 32 bits.
16431 if (Subtarget->is64Bit()) {
16432 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16433 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16436 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16437 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16440 SDValue Chain = HI.getValue(1);
16442 if (Opcode == X86ISD::RDTSCP_DAG) {
16443 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16445 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16446 // the ECX register. Add 'ecx' explicitly to the chain.
16447 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16449 // Explicitly store the content of ECX at the location passed in input
16450 // to the 'rdtscp' intrinsic.
16451 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16452 MachinePointerInfo(), false, false, 0);
16455 if (Subtarget->is64Bit()) {
16456 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16457 // the EAX register is loaded with the low-order 32 bits.
16458 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16459 DAG.getConstant(32, DL, MVT::i8));
16460 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16461 Results.push_back(Chain);
16465 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16466 SDValue Ops[] = { LO, HI };
16467 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16468 Results.push_back(Pair);
16469 Results.push_back(Chain);
16472 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16473 SelectionDAG &DAG) {
16474 SmallVector<SDValue, 2> Results;
16476 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16478 return DAG.getMergeValues(Results, DL);
16481 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16482 SelectionDAG &DAG) {
16483 MachineFunction &MF = DAG.getMachineFunction();
16484 const Function *Fn = MF.getFunction();
16486 SDValue Chain = Op.getOperand(0);
16488 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16489 "using llvm.x86.seh.restoreframe requires a frame pointer");
16491 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16492 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16494 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16495 unsigned FrameReg =
16496 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16497 unsigned SPReg = RegInfo->getStackRegister();
16498 unsigned SlotSize = RegInfo->getSlotSize();
16500 // Get incoming EBP.
16501 SDValue IncomingEBP =
16502 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16504 // SP is saved in the first field of every registration node, so load
16505 // [EBP-RegNodeSize] into SP.
16506 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16507 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16508 DAG.getConstant(-RegNodeSize, dl, VT));
16510 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16511 false, VT.getScalarSizeInBits() / 8);
16512 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16514 if (!RegInfo->needsStackRealignment(MF)) {
16515 // Adjust EBP to point back to the original frame position.
16516 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16517 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16519 assert(RegInfo->hasBasePointer(MF) &&
16520 "functions with Win32 EH must use frame or base pointer register");
16522 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16523 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16524 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16526 // Reload the spilled EBP value, now that the stack and base pointers are
16528 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16529 X86FI->setHasSEHFramePtrSave(true);
16530 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16531 X86FI->setSEHFramePtrSaveIndex(FI);
16532 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16533 MachinePointerInfo(), false, false, false,
16534 VT.getScalarSizeInBits() / 8);
16535 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16541 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16542 /// return truncate Store/MaskedStore Node
16543 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16547 SDValue Mask = Op.getOperand(4);
16548 SDValue DataToTruncate = Op.getOperand(3);
16549 SDValue Addr = Op.getOperand(2);
16550 SDValue Chain = Op.getOperand(0);
16552 EVT VT = DataToTruncate.getValueType();
16553 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16554 ElementType, VT.getVectorNumElements());
16556 if (isAllOnes(Mask)) // return just a truncate store
16557 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16558 MachinePointerInfo(), SVT, false, false,
16559 SVT.getScalarSizeInBits()/8);
16561 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16562 MVT::i1, VT.getVectorNumElements());
16563 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16564 Mask.getValueType().getSizeInBits());
16565 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16566 // are extracted by EXTRACT_SUBVECTOR.
16567 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16568 DAG.getBitcast(BitcastVT, Mask),
16569 DAG.getIntPtrConstant(0, dl));
16571 MachineMemOperand *MMO = DAG.getMachineFunction().
16572 getMachineMemOperand(MachinePointerInfo(),
16573 MachineMemOperand::MOStore, SVT.getStoreSize(),
16574 SVT.getScalarSizeInBits()/8);
16576 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16577 VMask, SVT, MMO, true);
16580 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16581 SelectionDAG &DAG) {
16582 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16584 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16586 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16587 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16592 switch(IntrData->Type) {
16594 llvm_unreachable("Unknown Intrinsic Type");
16598 // Emit the node with the right value type.
16599 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16600 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16602 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16603 // Otherwise return the value from Rand, which is always 0, casted to i32.
16604 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16605 DAG.getConstant(1, dl, Op->getValueType(1)),
16606 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16607 SDValue(Result.getNode(), 1) };
16608 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16609 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16612 // Return { result, isValid, chain }.
16613 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16614 SDValue(Result.getNode(), 2));
16617 //gather(v1, mask, index, base, scale);
16618 SDValue Chain = Op.getOperand(0);
16619 SDValue Src = Op.getOperand(2);
16620 SDValue Base = Op.getOperand(3);
16621 SDValue Index = Op.getOperand(4);
16622 SDValue Mask = Op.getOperand(5);
16623 SDValue Scale = Op.getOperand(6);
16624 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16628 //scatter(base, mask, index, v1, scale);
16629 SDValue Chain = Op.getOperand(0);
16630 SDValue Base = Op.getOperand(2);
16631 SDValue Mask = Op.getOperand(3);
16632 SDValue Index = Op.getOperand(4);
16633 SDValue Src = Op.getOperand(5);
16634 SDValue Scale = Op.getOperand(6);
16635 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16639 SDValue Hint = Op.getOperand(6);
16640 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16641 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16642 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16643 SDValue Chain = Op.getOperand(0);
16644 SDValue Mask = Op.getOperand(2);
16645 SDValue Index = Op.getOperand(3);
16646 SDValue Base = Op.getOperand(4);
16647 SDValue Scale = Op.getOperand(5);
16648 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16650 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16652 SmallVector<SDValue, 2> Results;
16653 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16655 return DAG.getMergeValues(Results, dl);
16657 // Read Performance Monitoring Counters.
16659 SmallVector<SDValue, 2> Results;
16660 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16661 return DAG.getMergeValues(Results, dl);
16663 // XTEST intrinsics.
16665 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16666 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16667 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16668 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16670 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16671 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16672 Ret, SDValue(InTrans.getNode(), 1));
16676 SmallVector<SDValue, 2> Results;
16677 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16678 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16679 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16680 DAG.getConstant(-1, dl, MVT::i8));
16681 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16682 Op.getOperand(4), GenCF.getValue(1));
16683 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16684 Op.getOperand(5), MachinePointerInfo(),
16686 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16687 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16689 Results.push_back(SetCC);
16690 Results.push_back(Store);
16691 return DAG.getMergeValues(Results, dl);
16693 case COMPRESS_TO_MEM: {
16695 SDValue Mask = Op.getOperand(4);
16696 SDValue DataToCompress = Op.getOperand(3);
16697 SDValue Addr = Op.getOperand(2);
16698 SDValue Chain = Op.getOperand(0);
16700 EVT VT = DataToCompress.getValueType();
16701 if (isAllOnes(Mask)) // return just a store
16702 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16703 MachinePointerInfo(), false, false,
16704 VT.getScalarSizeInBits()/8);
16706 SDValue Compressed =
16707 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16708 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16709 return DAG.getStore(Chain, dl, Compressed, Addr,
16710 MachinePointerInfo(), false, false,
16711 VT.getScalarSizeInBits()/8);
16713 case TRUNCATE_TO_MEM_VI8:
16714 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16715 case TRUNCATE_TO_MEM_VI16:
16716 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16717 case TRUNCATE_TO_MEM_VI32:
16718 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16719 case EXPAND_FROM_MEM: {
16721 SDValue Mask = Op.getOperand(4);
16722 SDValue PassThru = Op.getOperand(3);
16723 SDValue Addr = Op.getOperand(2);
16724 SDValue Chain = Op.getOperand(0);
16725 EVT VT = Op.getValueType();
16727 if (isAllOnes(Mask)) // return just a load
16728 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16729 false, VT.getScalarSizeInBits()/8);
16731 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16732 false, false, false,
16733 VT.getScalarSizeInBits()/8);
16735 SDValue Results[] = {
16736 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16737 Mask, PassThru, Subtarget, DAG), Chain};
16738 return DAG.getMergeValues(Results, dl);
16743 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16744 SelectionDAG &DAG) const {
16745 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16746 MFI->setReturnAddressIsTaken(true);
16748 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16751 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16753 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16756 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16757 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16758 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16759 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16760 DAG.getNode(ISD::ADD, dl, PtrVT,
16761 FrameAddr, Offset),
16762 MachinePointerInfo(), false, false, false, 0);
16765 // Just load the return address.
16766 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16767 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16768 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16771 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16772 MachineFunction &MF = DAG.getMachineFunction();
16773 MachineFrameInfo *MFI = MF.getFrameInfo();
16774 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16775 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16776 EVT VT = Op.getValueType();
16778 MFI->setFrameAddressIsTaken(true);
16780 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16781 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16782 // is not possible to crawl up the stack without looking at the unwind codes
16784 int FrameAddrIndex = FuncInfo->getFAIndex();
16785 if (!FrameAddrIndex) {
16786 // Set up a frame object for the return address.
16787 unsigned SlotSize = RegInfo->getSlotSize();
16788 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16789 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16790 FuncInfo->setFAIndex(FrameAddrIndex);
16792 return DAG.getFrameIndex(FrameAddrIndex, VT);
16795 unsigned FrameReg =
16796 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16797 SDLoc dl(Op); // FIXME probably not meaningful
16798 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16799 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16800 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16801 "Invalid Frame Register!");
16802 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16804 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16805 MachinePointerInfo(),
16806 false, false, false, 0);
16810 // FIXME? Maybe this could be a TableGen attribute on some registers and
16811 // this table could be generated automatically from RegInfo.
16812 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16813 SelectionDAG &DAG) const {
16814 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16815 const MachineFunction &MF = DAG.getMachineFunction();
16817 unsigned Reg = StringSwitch<unsigned>(RegName)
16818 .Case("esp", X86::ESP)
16819 .Case("rsp", X86::RSP)
16820 .Case("ebp", X86::EBP)
16821 .Case("rbp", X86::RBP)
16824 if (Reg == X86::EBP || Reg == X86::RBP) {
16825 if (!TFI.hasFP(MF))
16826 report_fatal_error("register " + StringRef(RegName) +
16827 " is allocatable: function has no frame pointer");
16830 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16831 unsigned FrameReg =
16832 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16833 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16834 "Invalid Frame Register!");
16842 report_fatal_error("Invalid register name global variable");
16845 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16846 SelectionDAG &DAG) const {
16847 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16848 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16851 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16852 SDValue Chain = Op.getOperand(0);
16853 SDValue Offset = Op.getOperand(1);
16854 SDValue Handler = Op.getOperand(2);
16857 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16858 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16859 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16860 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16861 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16862 "Invalid Frame Register!");
16863 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16864 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16866 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16867 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16869 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16870 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16872 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16874 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16875 DAG.getRegister(StoreAddrReg, PtrVT));
16878 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16879 SDValue Chain = Op.getOperand(0);
16880 SDValue Dest = Op.getOperand(1);
16883 MVT PtrVT = getPointerTy(DAG.getDataLayout());
16885 MachineFunction &MF = DAG.getMachineFunction();
16886 if (isAsynchronousEHPersonality(
16887 classifyEHPersonality(MF.getFunction()->getPersonalityFn()))) {
16888 // For SEH, codegen catchret as a branch for now.
16889 // FIXME: Insert something to restore the frame.
16890 return DAG.getNode(ISD::BR, DL, MVT::Other, Chain, Dest);
16893 unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16895 // Load the address of the destination block.
16896 // FIXME: Do this without creating a BlockAddress.
16897 MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16899 BlockAddress::get(const_cast<Function *>(MF.getFunction()),
16900 const_cast<BasicBlock *>(DestMBB->getBasicBlock()));
16901 DestMBB->setHasAddressTaken();
16902 SDValue BlockPtr = DAG.getBlockAddress(BA, PtrVT);
16903 Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, BlockPtr);
16904 return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16905 DAG.getRegister(ReturnReg, PtrVT));
16908 SDValue X86TargetLowering::LowerCLEANUPRET(SDValue Op, SelectionDAG &DAG) const {
16909 return DAG.getNode(X86ISD::CLEANUPRET, SDLoc(Op), MVT::Other,
16913 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16914 SelectionDAG &DAG) const {
16916 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16917 DAG.getVTList(MVT::i32, MVT::Other),
16918 Op.getOperand(0), Op.getOperand(1));
16921 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16922 SelectionDAG &DAG) const {
16924 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16925 Op.getOperand(0), Op.getOperand(1));
16928 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16929 return Op.getOperand(0);
16932 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16933 SelectionDAG &DAG) const {
16934 SDValue Root = Op.getOperand(0);
16935 SDValue Trmp = Op.getOperand(1); // trampoline
16936 SDValue FPtr = Op.getOperand(2); // nested function
16937 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16940 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16941 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16943 if (Subtarget->is64Bit()) {
16944 SDValue OutChains[6];
16946 // Large code-model.
16947 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16948 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16950 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16951 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16953 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16955 // Load the pointer to the nested function into R11.
16956 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16957 SDValue Addr = Trmp;
16958 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16959 Addr, MachinePointerInfo(TrmpAddr),
16962 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16963 DAG.getConstant(2, dl, MVT::i64));
16964 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16965 MachinePointerInfo(TrmpAddr, 2),
16968 // Load the 'nest' parameter value into R10.
16969 // R10 is specified in X86CallingConv.td
16970 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16971 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16972 DAG.getConstant(10, dl, MVT::i64));
16973 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16974 Addr, MachinePointerInfo(TrmpAddr, 10),
16977 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16978 DAG.getConstant(12, dl, MVT::i64));
16979 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16980 MachinePointerInfo(TrmpAddr, 12),
16983 // Jump to the nested function.
16984 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16985 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16986 DAG.getConstant(20, dl, MVT::i64));
16987 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16988 Addr, MachinePointerInfo(TrmpAddr, 20),
16991 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16992 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16993 DAG.getConstant(22, dl, MVT::i64));
16994 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16995 Addr, MachinePointerInfo(TrmpAddr, 22),
16998 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17000 const Function *Func =
17001 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17002 CallingConv::ID CC = Func->getCallingConv();
17007 llvm_unreachable("Unsupported calling convention");
17008 case CallingConv::C:
17009 case CallingConv::X86_StdCall: {
17010 // Pass 'nest' parameter in ECX.
17011 // Must be kept in sync with X86CallingConv.td
17012 NestReg = X86::ECX;
17014 // Check that ECX wasn't needed by an 'inreg' parameter.
17015 FunctionType *FTy = Func->getFunctionType();
17016 const AttributeSet &Attrs = Func->getAttributes();
17018 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17019 unsigned InRegCount = 0;
17022 for (FunctionType::param_iterator I = FTy->param_begin(),
17023 E = FTy->param_end(); I != E; ++I, ++Idx)
17024 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17025 auto &DL = DAG.getDataLayout();
17026 // FIXME: should only count parameters that are lowered to integers.
17027 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17030 if (InRegCount > 2) {
17031 report_fatal_error("Nest register in use - reduce number of inreg"
17037 case CallingConv::X86_FastCall:
17038 case CallingConv::X86_ThisCall:
17039 case CallingConv::Fast:
17040 // Pass 'nest' parameter in EAX.
17041 // Must be kept in sync with X86CallingConv.td
17042 NestReg = X86::EAX;
17046 SDValue OutChains[4];
17047 SDValue Addr, Disp;
17049 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17050 DAG.getConstant(10, dl, MVT::i32));
17051 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17053 // This is storing the opcode for MOV32ri.
17054 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17055 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17056 OutChains[0] = DAG.getStore(Root, dl,
17057 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17058 Trmp, MachinePointerInfo(TrmpAddr),
17061 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17062 DAG.getConstant(1, dl, MVT::i32));
17063 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17064 MachinePointerInfo(TrmpAddr, 1),
17067 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17068 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17069 DAG.getConstant(5, dl, MVT::i32));
17070 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17071 Addr, MachinePointerInfo(TrmpAddr, 5),
17074 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17075 DAG.getConstant(6, dl, MVT::i32));
17076 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17077 MachinePointerInfo(TrmpAddr, 6),
17080 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17084 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17085 SelectionDAG &DAG) const {
17087 The rounding mode is in bits 11:10 of FPSR, and has the following
17089 00 Round to nearest
17094 FLT_ROUNDS, on the other hand, expects the following:
17101 To perform the conversion, we do:
17102 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17105 MachineFunction &MF = DAG.getMachineFunction();
17106 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17107 unsigned StackAlignment = TFI.getStackAlignment();
17108 MVT VT = Op.getSimpleValueType();
17111 // Save FP Control Word to stack slot
17112 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17113 SDValue StackSlot =
17114 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17116 MachineMemOperand *MMO =
17117 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17118 MachineMemOperand::MOStore, 2, 2);
17120 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17121 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17122 DAG.getVTList(MVT::Other),
17123 Ops, MVT::i16, MMO);
17125 // Load FP Control Word from stack slot
17126 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17127 MachinePointerInfo(), false, false, false, 0);
17129 // Transform as necessary
17131 DAG.getNode(ISD::SRL, DL, MVT::i16,
17132 DAG.getNode(ISD::AND, DL, MVT::i16,
17133 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17134 DAG.getConstant(11, DL, MVT::i8));
17136 DAG.getNode(ISD::SRL, DL, MVT::i16,
17137 DAG.getNode(ISD::AND, DL, MVT::i16,
17138 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17139 DAG.getConstant(9, DL, MVT::i8));
17142 DAG.getNode(ISD::AND, DL, MVT::i16,
17143 DAG.getNode(ISD::ADD, DL, MVT::i16,
17144 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17145 DAG.getConstant(1, DL, MVT::i16)),
17146 DAG.getConstant(3, DL, MVT::i16));
17148 return DAG.getNode((VT.getSizeInBits() < 16 ?
17149 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17152 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17153 MVT VT = Op.getSimpleValueType();
17155 unsigned NumBits = VT.getSizeInBits();
17158 Op = Op.getOperand(0);
17159 if (VT == MVT::i8) {
17160 // Zero extend to i32 since there is not an i8 bsr.
17162 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17165 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17166 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17167 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17169 // If src is zero (i.e. bsr sets ZF), returns NumBits.
17172 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17173 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17176 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17178 // Finally xor with NumBits-1.
17179 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17180 DAG.getConstant(NumBits - 1, dl, OpVT));
17183 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17187 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17188 MVT VT = Op.getSimpleValueType();
17190 unsigned NumBits = VT.getSizeInBits();
17193 Op = Op.getOperand(0);
17194 if (VT == MVT::i8) {
17195 // Zero extend to i32 since there is not an i8 bsr.
17197 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17200 // Issue a bsr (scan bits in reverse).
17201 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17202 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17204 // And xor with NumBits-1.
17205 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17206 DAG.getConstant(NumBits - 1, dl, OpVT));
17209 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17213 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17214 MVT VT = Op.getSimpleValueType();
17215 unsigned NumBits = VT.getSizeInBits();
17217 Op = Op.getOperand(0);
17219 // Issue a bsf (scan bits forward) which also sets EFLAGS.
17220 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17221 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17223 // If src is zero (i.e. bsf sets ZF), returns NumBits.
17226 DAG.getConstant(NumBits, dl, VT),
17227 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17230 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17233 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17234 // ones, and then concatenate the result back.
17235 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17236 MVT VT = Op.getSimpleValueType();
17238 assert(VT.is256BitVector() && VT.isInteger() &&
17239 "Unsupported value type for operation");
17241 unsigned NumElems = VT.getVectorNumElements();
17244 // Extract the LHS vectors
17245 SDValue LHS = Op.getOperand(0);
17246 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17247 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17249 // Extract the RHS vectors
17250 SDValue RHS = Op.getOperand(1);
17251 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17252 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17254 MVT EltVT = VT.getVectorElementType();
17255 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17257 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17258 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17259 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17262 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17263 if (Op.getValueType() == MVT::i1)
17264 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17265 Op.getOperand(0), Op.getOperand(1));
17266 assert(Op.getSimpleValueType().is256BitVector() &&
17267 Op.getSimpleValueType().isInteger() &&
17268 "Only handle AVX 256-bit vector integer operation");
17269 return Lower256IntArith(Op, DAG);
17272 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17273 if (Op.getValueType() == MVT::i1)
17274 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17275 Op.getOperand(0), Op.getOperand(1));
17276 assert(Op.getSimpleValueType().is256BitVector() &&
17277 Op.getSimpleValueType().isInteger() &&
17278 "Only handle AVX 256-bit vector integer operation");
17279 return Lower256IntArith(Op, DAG);
17282 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17283 assert(Op.getSimpleValueType().is256BitVector() &&
17284 Op.getSimpleValueType().isInteger() &&
17285 "Only handle AVX 256-bit vector integer operation");
17286 return Lower256IntArith(Op, DAG);
17289 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17290 SelectionDAG &DAG) {
17292 MVT VT = Op.getSimpleValueType();
17295 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17297 // Decompose 256-bit ops into smaller 128-bit ops.
17298 if (VT.is256BitVector() && !Subtarget->hasInt256())
17299 return Lower256IntArith(Op, DAG);
17301 SDValue A = Op.getOperand(0);
17302 SDValue B = Op.getOperand(1);
17304 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17305 // pairs, multiply and truncate.
17306 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17307 if (Subtarget->hasInt256()) {
17308 if (VT == MVT::v32i8) {
17309 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17310 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17311 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17312 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17313 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17314 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17315 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17316 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17317 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17318 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17321 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17322 return DAG.getNode(
17323 ISD::TRUNCATE, dl, VT,
17324 DAG.getNode(ISD::MUL, dl, ExVT,
17325 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17326 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17329 assert(VT == MVT::v16i8 &&
17330 "Pre-AVX2 support only supports v16i8 multiplication");
17331 MVT ExVT = MVT::v8i16;
17333 // Extract the lo parts and sign extend to i16
17335 if (Subtarget->hasSSE41()) {
17336 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17337 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17339 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17340 -1, 4, -1, 5, -1, 6, -1, 7};
17341 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17342 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17343 ALo = DAG.getBitcast(ExVT, ALo);
17344 BLo = DAG.getBitcast(ExVT, BLo);
17345 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17346 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17349 // Extract the hi parts and sign extend to i16
17351 if (Subtarget->hasSSE41()) {
17352 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
17353 -1, -1, -1, -1, -1, -1, -1, -1};
17354 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17355 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17356 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17357 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17359 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
17360 -1, 12, -1, 13, -1, 14, -1, 15};
17361 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17362 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17363 AHi = DAG.getBitcast(ExVT, AHi);
17364 BHi = DAG.getBitcast(ExVT, BHi);
17365 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17366 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17369 // Multiply, mask the lower 8bits of the lo/hi results and pack
17370 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17371 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17372 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17373 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17374 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17377 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17378 if (VT == MVT::v4i32) {
17379 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17380 "Should not custom lower when pmuldq is available!");
17382 // Extract the odd parts.
17383 static const int UnpackMask[] = { 1, -1, 3, -1 };
17384 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17385 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17387 // Multiply the even parts.
17388 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17389 // Now multiply odd parts.
17390 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17392 Evens = DAG.getBitcast(VT, Evens);
17393 Odds = DAG.getBitcast(VT, Odds);
17395 // Merge the two vectors back together with a shuffle. This expands into 2
17397 static const int ShufMask[] = { 0, 4, 2, 6 };
17398 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17401 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17402 "Only know how to lower V2I64/V4I64/V8I64 multiply");
17404 // Ahi = psrlqi(a, 32);
17405 // Bhi = psrlqi(b, 32);
17407 // AloBlo = pmuludq(a, b);
17408 // AloBhi = pmuludq(a, Bhi);
17409 // AhiBlo = pmuludq(Ahi, b);
17411 // AloBhi = psllqi(AloBhi, 32);
17412 // AhiBlo = psllqi(AhiBlo, 32);
17413 // return AloBlo + AloBhi + AhiBlo;
17415 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17416 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17418 SDValue AhiBlo = Ahi;
17419 SDValue AloBhi = Bhi;
17420 // Bit cast to 32-bit vectors for MULUDQ
17421 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17422 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17423 A = DAG.getBitcast(MulVT, A);
17424 B = DAG.getBitcast(MulVT, B);
17425 Ahi = DAG.getBitcast(MulVT, Ahi);
17426 Bhi = DAG.getBitcast(MulVT, Bhi);
17428 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17429 // After shifting right const values the result may be all-zero.
17430 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17431 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17432 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17434 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17435 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17436 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17439 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17440 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17443 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17444 assert(Subtarget->isTargetWin64() && "Unexpected target");
17445 EVT VT = Op.getValueType();
17446 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17447 "Unexpected return type for lowering");
17451 switch (Op->getOpcode()) {
17452 default: llvm_unreachable("Unexpected request for libcall!");
17453 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17454 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17455 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17456 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17457 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17458 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17462 SDValue InChain = DAG.getEntryNode();
17464 TargetLowering::ArgListTy Args;
17465 TargetLowering::ArgListEntry Entry;
17466 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17467 EVT ArgVT = Op->getOperand(i).getValueType();
17468 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17469 "Unexpected argument type for lowering");
17470 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17471 Entry.Node = StackPtr;
17472 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17474 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17475 Entry.Ty = PointerType::get(ArgTy,0);
17476 Entry.isSExt = false;
17477 Entry.isZExt = false;
17478 Args.push_back(Entry);
17481 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17482 getPointerTy(DAG.getDataLayout()));
17484 TargetLowering::CallLoweringInfo CLI(DAG);
17485 CLI.setDebugLoc(dl).setChain(InChain)
17486 .setCallee(getLibcallCallingConv(LC),
17487 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17488 Callee, std::move(Args), 0)
17489 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17491 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17492 return DAG.getBitcast(VT, CallInfo.first);
17495 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17496 SelectionDAG &DAG) {
17497 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17498 EVT VT = Op0.getValueType();
17501 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17502 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17504 // PMULxD operations multiply each even value (starting at 0) of LHS with
17505 // the related value of RHS and produce a widen result.
17506 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17507 // => <2 x i64> <ae|cg>
17509 // In other word, to have all the results, we need to perform two PMULxD:
17510 // 1. one with the even values.
17511 // 2. one with the odd values.
17512 // To achieve #2, with need to place the odd values at an even position.
17514 // Place the odd value at an even position (basically, shift all values 1
17515 // step to the left):
17516 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17517 // <a|b|c|d> => <b|undef|d|undef>
17518 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17519 // <e|f|g|h> => <f|undef|h|undef>
17520 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17522 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17524 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17525 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17527 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17528 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17529 // => <2 x i64> <ae|cg>
17530 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17531 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17532 // => <2 x i64> <bf|dh>
17533 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17535 // Shuffle it back into the right order.
17536 SDValue Highs, Lows;
17537 if (VT == MVT::v8i32) {
17538 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17539 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17540 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17541 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17543 const int HighMask[] = {1, 5, 3, 7};
17544 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17545 const int LowMask[] = {0, 4, 2, 6};
17546 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17549 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17550 // unsigned multiply.
17551 if (IsSigned && !Subtarget->hasSSE41()) {
17552 SDValue ShAmt = DAG.getConstant(
17554 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17555 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17556 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17557 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17558 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17560 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17561 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17564 // The first result of MUL_LOHI is actually the low value, followed by the
17566 SDValue Ops[] = {Lows, Highs};
17567 return DAG.getMergeValues(Ops, dl);
17570 // Return true if the required (according to Opcode) shift-imm form is natively
17571 // supported by the Subtarget
17572 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17574 if (VT.getScalarSizeInBits() < 16)
17577 if (VT.is512BitVector() &&
17578 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17581 bool LShift = VT.is128BitVector() ||
17582 (VT.is256BitVector() && Subtarget->hasInt256());
17584 bool AShift = LShift && (Subtarget->hasVLX() ||
17585 (VT != MVT::v2i64 && VT != MVT::v4i64));
17586 return (Opcode == ISD::SRA) ? AShift : LShift;
17589 // The shift amount is a variable, but it is the same for all vector lanes.
17590 // These instructions are defined together with shift-immediate.
17592 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17594 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17597 // Return true if the required (according to Opcode) variable-shift form is
17598 // natively supported by the Subtarget
17599 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17602 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17605 // vXi16 supported only on AVX-512, BWI
17606 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17609 if (VT.is512BitVector() || Subtarget->hasVLX())
17612 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17613 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17614 return (Opcode == ISD::SRA) ? AShift : LShift;
17617 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17618 const X86Subtarget *Subtarget) {
17619 MVT VT = Op.getSimpleValueType();
17621 SDValue R = Op.getOperand(0);
17622 SDValue Amt = Op.getOperand(1);
17624 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17625 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17627 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17628 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17629 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17630 SDValue Ex = DAG.getBitcast(ExVT, R);
17632 if (ShiftAmt >= 32) {
17633 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17635 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17636 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17637 ShiftAmt - 32, DAG);
17638 if (VT == MVT::v2i64)
17639 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17640 if (VT == MVT::v4i64)
17641 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17642 {9, 1, 11, 3, 13, 5, 15, 7});
17644 // SRA upper i32, SHL whole i64 and select lower i32.
17645 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17648 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17649 Lower = DAG.getBitcast(ExVT, Lower);
17650 if (VT == MVT::v2i64)
17651 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17652 if (VT == MVT::v4i64)
17653 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17654 {8, 1, 10, 3, 12, 5, 14, 7});
17656 return DAG.getBitcast(VT, Ex);
17659 // Optimize shl/srl/sra with constant shift amount.
17660 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17661 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17662 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17664 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17665 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17667 // i64 SRA needs to be performed as partial shifts.
17668 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17669 Op.getOpcode() == ISD::SRA)
17670 return ArithmeticShiftRight64(ShiftAmt);
17672 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17673 unsigned NumElts = VT.getVectorNumElements();
17674 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17676 if (Op.getOpcode() == ISD::SHL) {
17677 // Simple i8 add case
17679 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17681 // Make a large shift.
17682 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17684 SHL = DAG.getBitcast(VT, SHL);
17685 // Zero out the rightmost bits.
17686 SmallVector<SDValue, 32> V(
17687 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17688 return DAG.getNode(ISD::AND, dl, VT, SHL,
17689 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17691 if (Op.getOpcode() == ISD::SRL) {
17692 // Make a large shift.
17693 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17695 SRL = DAG.getBitcast(VT, SRL);
17696 // Zero out the leftmost bits.
17697 SmallVector<SDValue, 32> V(
17698 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17699 return DAG.getNode(ISD::AND, dl, VT, SRL,
17700 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17702 if (Op.getOpcode() == ISD::SRA) {
17703 if (ShiftAmt == 7) {
17704 // ashr(R, 7) === cmp_slt(R, 0)
17705 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17706 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17709 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17710 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17711 SmallVector<SDValue, 32> V(NumElts,
17712 DAG.getConstant(128 >> ShiftAmt, dl,
17714 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17715 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17716 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17719 llvm_unreachable("Unknown shift opcode.");
17724 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17725 if (!Subtarget->is64Bit() &&
17726 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17728 // Peek through any splat that was introduced for i64 shift vectorization.
17729 int SplatIndex = -1;
17730 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17731 if (SVN->isSplat()) {
17732 SplatIndex = SVN->getSplatIndex();
17733 Amt = Amt.getOperand(0);
17734 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17735 "Splat shuffle referencing second operand");
17738 if (Amt.getOpcode() != ISD::BITCAST ||
17739 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17742 Amt = Amt.getOperand(0);
17743 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17744 VT.getVectorNumElements();
17745 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17746 uint64_t ShiftAmt = 0;
17747 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17748 for (unsigned i = 0; i != Ratio; ++i) {
17749 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17753 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17756 // Check remaining shift amounts (if not a splat).
17757 if (SplatIndex < 0) {
17758 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17759 uint64_t ShAmt = 0;
17760 for (unsigned j = 0; j != Ratio; ++j) {
17761 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17765 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17767 if (ShAmt != ShiftAmt)
17772 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17773 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17775 if (Op.getOpcode() == ISD::SRA)
17776 return ArithmeticShiftRight64(ShiftAmt);
17782 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17783 const X86Subtarget* Subtarget) {
17784 MVT VT = Op.getSimpleValueType();
17786 SDValue R = Op.getOperand(0);
17787 SDValue Amt = Op.getOperand(1);
17789 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17790 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17792 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17793 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17795 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17797 EVT EltVT = VT.getVectorElementType();
17799 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17800 // Check if this build_vector node is doing a splat.
17801 // If so, then set BaseShAmt equal to the splat value.
17802 BaseShAmt = BV->getSplatValue();
17803 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17804 BaseShAmt = SDValue();
17806 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17807 Amt = Amt.getOperand(0);
17809 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17810 if (SVN && SVN->isSplat()) {
17811 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17812 SDValue InVec = Amt.getOperand(0);
17813 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17814 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17815 "Unexpected shuffle index found!");
17816 BaseShAmt = InVec.getOperand(SplatIdx);
17817 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17818 if (ConstantSDNode *C =
17819 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17820 if (C->getZExtValue() == SplatIdx)
17821 BaseShAmt = InVec.getOperand(1);
17826 // Avoid introducing an extract element from a shuffle.
17827 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17828 DAG.getIntPtrConstant(SplatIdx, dl));
17832 if (BaseShAmt.getNode()) {
17833 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17834 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17835 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17836 else if (EltVT.bitsLT(MVT::i32))
17837 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17839 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17843 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17844 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17845 Amt.getOpcode() == ISD::BITCAST &&
17846 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17847 Amt = Amt.getOperand(0);
17848 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17849 VT.getVectorNumElements();
17850 std::vector<SDValue> Vals(Ratio);
17851 for (unsigned i = 0; i != Ratio; ++i)
17852 Vals[i] = Amt.getOperand(i);
17853 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17854 for (unsigned j = 0; j != Ratio; ++j)
17855 if (Vals[j] != Amt.getOperand(i + j))
17859 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17860 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17865 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17866 SelectionDAG &DAG) {
17867 MVT VT = Op.getSimpleValueType();
17869 SDValue R = Op.getOperand(0);
17870 SDValue Amt = Op.getOperand(1);
17872 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17873 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17875 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17878 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17881 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17884 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17885 // shifts per-lane and then shuffle the partial results back together.
17886 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17887 // Splat the shift amounts so the scalar shifts above will catch it.
17888 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17889 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17890 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17891 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17892 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17895 // i64 vector arithmetic shift can be emulated with the transform:
17896 // M = lshr(SIGN_BIT, Amt)
17897 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17898 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17899 Op.getOpcode() == ISD::SRA) {
17900 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17901 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17902 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17903 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17904 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17908 // If possible, lower this packed shift into a vector multiply instead of
17909 // expanding it into a sequence of scalar shifts.
17910 // Do this only if the vector shift count is a constant build_vector.
17911 if (Op.getOpcode() == ISD::SHL &&
17912 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17913 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17914 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17915 SmallVector<SDValue, 8> Elts;
17916 EVT SVT = VT.getScalarType();
17917 unsigned SVTBits = SVT.getSizeInBits();
17918 const APInt &One = APInt(SVTBits, 1);
17919 unsigned NumElems = VT.getVectorNumElements();
17921 for (unsigned i=0; i !=NumElems; ++i) {
17922 SDValue Op = Amt->getOperand(i);
17923 if (Op->getOpcode() == ISD::UNDEF) {
17924 Elts.push_back(Op);
17928 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17929 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17930 uint64_t ShAmt = C.getZExtValue();
17931 if (ShAmt >= SVTBits) {
17932 Elts.push_back(DAG.getUNDEF(SVT));
17935 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17937 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17938 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17941 // Lower SHL with variable shift amount.
17942 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17943 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17945 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17946 DAG.getConstant(0x3f800000U, dl, VT));
17947 Op = DAG.getBitcast(MVT::v4f32, Op);
17948 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17949 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17952 // If possible, lower this shift as a sequence of two shifts by
17953 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17955 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17957 // Could be rewritten as:
17958 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17960 // The advantage is that the two shifts from the example would be
17961 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17962 // the vector shift into four scalar shifts plus four pairs of vector
17964 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17965 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17966 unsigned TargetOpcode = X86ISD::MOVSS;
17967 bool CanBeSimplified;
17968 // The splat value for the first packed shift (the 'X' from the example).
17969 SDValue Amt1 = Amt->getOperand(0);
17970 // The splat value for the second packed shift (the 'Y' from the example).
17971 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17972 Amt->getOperand(2);
17974 // See if it is possible to replace this node with a sequence of
17975 // two shifts followed by a MOVSS/MOVSD
17976 if (VT == MVT::v4i32) {
17977 // Check if it is legal to use a MOVSS.
17978 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17979 Amt2 == Amt->getOperand(3);
17980 if (!CanBeSimplified) {
17981 // Otherwise, check if we can still simplify this node using a MOVSD.
17982 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17983 Amt->getOperand(2) == Amt->getOperand(3);
17984 TargetOpcode = X86ISD::MOVSD;
17985 Amt2 = Amt->getOperand(2);
17988 // Do similar checks for the case where the machine value type
17990 CanBeSimplified = Amt1 == Amt->getOperand(1);
17991 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17992 CanBeSimplified = Amt2 == Amt->getOperand(i);
17994 if (!CanBeSimplified) {
17995 TargetOpcode = X86ISD::MOVSD;
17996 CanBeSimplified = true;
17997 Amt2 = Amt->getOperand(4);
17998 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17999 CanBeSimplified = Amt1 == Amt->getOperand(i);
18000 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18001 CanBeSimplified = Amt2 == Amt->getOperand(j);
18005 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18006 isa<ConstantSDNode>(Amt2)) {
18007 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18008 EVT CastVT = MVT::v4i32;
18010 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18011 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18013 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18014 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18015 if (TargetOpcode == X86ISD::MOVSD)
18016 CastVT = MVT::v2i64;
18017 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18018 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18019 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18021 return DAG.getBitcast(VT, Result);
18025 // v4i32 Non Uniform Shifts.
18026 // If the shift amount is constant we can shift each lane using the SSE2
18027 // immediate shifts, else we need to zero-extend each lane to the lower i64
18028 // and shift using the SSE2 variable shifts.
18029 // The separate results can then be blended together.
18030 if (VT == MVT::v4i32) {
18031 unsigned Opc = Op.getOpcode();
18032 SDValue Amt0, Amt1, Amt2, Amt3;
18033 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18034 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18035 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18036 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18037 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18039 // ISD::SHL is handled above but we include it here for completeness.
18042 llvm_unreachable("Unknown target vector shift node");
18044 Opc = X86ISD::VSHL;
18047 Opc = X86ISD::VSRL;
18050 Opc = X86ISD::VSRA;
18053 // The SSE2 shifts use the lower i64 as the same shift amount for
18054 // all lanes and the upper i64 is ignored. These shuffle masks
18055 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18056 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18057 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18058 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18059 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18060 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18063 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18064 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18065 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18066 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18067 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18068 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18069 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18072 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18073 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18074 unsigned ShiftOpcode = Op->getOpcode();
18076 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18077 // On SSE41 targets we make use of the fact that VSELECT lowers
18078 // to PBLENDVB which selects bytes based just on the sign bit.
18079 if (Subtarget->hasSSE41()) {
18080 V0 = DAG.getBitcast(VT, V0);
18081 V1 = DAG.getBitcast(VT, V1);
18082 Sel = DAG.getBitcast(VT, Sel);
18083 return DAG.getBitcast(SelVT,
18084 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18086 // On pre-SSE41 targets we test for the sign bit by comparing to
18087 // zero - a negative value will set all bits of the lanes to true
18088 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18089 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18090 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18091 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18094 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18095 // We can safely do this using i16 shifts as we're only interested in
18096 // the 3 lower bits of each byte.
18097 Amt = DAG.getBitcast(ExtVT, Amt);
18098 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18099 Amt = DAG.getBitcast(VT, Amt);
18101 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18102 // r = VSELECT(r, shift(r, 4), a);
18104 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18105 R = SignBitSelect(VT, Amt, M, R);
18108 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18110 // r = VSELECT(r, shift(r, 2), a);
18111 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18112 R = SignBitSelect(VT, Amt, M, R);
18115 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18117 // return VSELECT(r, shift(r, 1), a);
18118 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18119 R = SignBitSelect(VT, Amt, M, R);
18123 if (Op->getOpcode() == ISD::SRA) {
18124 // For SRA we need to unpack each byte to the higher byte of a i16 vector
18125 // so we can correctly sign extend. We don't care what happens to the
18127 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18128 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18129 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18130 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18131 ALo = DAG.getBitcast(ExtVT, ALo);
18132 AHi = DAG.getBitcast(ExtVT, AHi);
18133 RLo = DAG.getBitcast(ExtVT, RLo);
18134 RHi = DAG.getBitcast(ExtVT, RHi);
18136 // r = VSELECT(r, shift(r, 4), a);
18137 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18138 DAG.getConstant(4, dl, ExtVT));
18139 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18140 DAG.getConstant(4, dl, ExtVT));
18141 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18142 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18145 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18146 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18148 // r = VSELECT(r, shift(r, 2), a);
18149 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18150 DAG.getConstant(2, dl, ExtVT));
18151 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18152 DAG.getConstant(2, dl, ExtVT));
18153 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18154 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18157 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18158 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18160 // r = VSELECT(r, shift(r, 1), a);
18161 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18162 DAG.getConstant(1, dl, ExtVT));
18163 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18164 DAG.getConstant(1, dl, ExtVT));
18165 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18166 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18168 // Logical shift the result back to the lower byte, leaving a zero upper
18170 // meaning that we can safely pack with PACKUSWB.
18172 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18174 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18175 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18179 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18180 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18181 // solution better.
18182 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18183 MVT ExtVT = MVT::v8i32;
18185 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18186 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18187 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18188 return DAG.getNode(ISD::TRUNCATE, dl, VT,
18189 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18192 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18193 MVT ExtVT = MVT::v8i32;
18194 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18195 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18196 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18197 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18198 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18199 ALo = DAG.getBitcast(ExtVT, ALo);
18200 AHi = DAG.getBitcast(ExtVT, AHi);
18201 RLo = DAG.getBitcast(ExtVT, RLo);
18202 RHi = DAG.getBitcast(ExtVT, RHi);
18203 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18204 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18205 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18206 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18207 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18210 if (VT == MVT::v8i16) {
18211 unsigned ShiftOpcode = Op->getOpcode();
18213 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18214 // On SSE41 targets we make use of the fact that VSELECT lowers
18215 // to PBLENDVB which selects bytes based just on the sign bit.
18216 if (Subtarget->hasSSE41()) {
18217 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18218 V0 = DAG.getBitcast(ExtVT, V0);
18219 V1 = DAG.getBitcast(ExtVT, V1);
18220 Sel = DAG.getBitcast(ExtVT, Sel);
18221 return DAG.getBitcast(
18222 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18224 // On pre-SSE41 targets we splat the sign bit - a negative value will
18225 // set all bits of the lanes to true and VSELECT uses that in
18226 // its OR(AND(V0,C),AND(V1,~C)) lowering.
18228 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18229 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18232 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18233 if (Subtarget->hasSSE41()) {
18234 // On SSE41 targets we need to replicate the shift mask in both
18235 // bytes for PBLENDVB.
18238 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18239 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18241 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18244 // r = VSELECT(r, shift(r, 8), a);
18245 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18246 R = SignBitSelect(Amt, M, R);
18249 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18251 // r = VSELECT(r, shift(r, 4), a);
18252 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18253 R = SignBitSelect(Amt, M, R);
18256 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18258 // r = VSELECT(r, shift(r, 2), a);
18259 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18260 R = SignBitSelect(Amt, M, R);
18263 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18265 // return VSELECT(r, shift(r, 1), a);
18266 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18267 R = SignBitSelect(Amt, M, R);
18271 // Decompose 256-bit shifts into smaller 128-bit shifts.
18272 if (VT.is256BitVector()) {
18273 unsigned NumElems = VT.getVectorNumElements();
18274 MVT EltVT = VT.getVectorElementType();
18275 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18277 // Extract the two vectors
18278 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18279 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18281 // Recreate the shift amount vectors
18282 SDValue Amt1, Amt2;
18283 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18284 // Constant shift amount
18285 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18286 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18287 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18289 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18290 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18292 // Variable shift amount
18293 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18294 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18297 // Issue new vector shifts for the smaller types
18298 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18299 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18301 // Concatenate the result back
18302 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18308 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18309 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18310 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18311 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18312 // has only one use.
18313 SDNode *N = Op.getNode();
18314 SDValue LHS = N->getOperand(0);
18315 SDValue RHS = N->getOperand(1);
18316 unsigned BaseOp = 0;
18319 switch (Op.getOpcode()) {
18320 default: llvm_unreachable("Unknown ovf instruction!");
18322 // A subtract of one will be selected as a INC. Note that INC doesn't
18323 // set CF, so we can't do this for UADDO.
18324 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18326 BaseOp = X86ISD::INC;
18327 Cond = X86::COND_O;
18330 BaseOp = X86ISD::ADD;
18331 Cond = X86::COND_O;
18334 BaseOp = X86ISD::ADD;
18335 Cond = X86::COND_B;
18338 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18339 // set CF, so we can't do this for USUBO.
18340 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18342 BaseOp = X86ISD::DEC;
18343 Cond = X86::COND_O;
18346 BaseOp = X86ISD::SUB;
18347 Cond = X86::COND_O;
18350 BaseOp = X86ISD::SUB;
18351 Cond = X86::COND_B;
18354 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18355 Cond = X86::COND_O;
18357 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18358 if (N->getValueType(0) == MVT::i8) {
18359 BaseOp = X86ISD::UMUL8;
18360 Cond = X86::COND_O;
18363 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18365 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18368 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18369 DAG.getConstant(X86::COND_O, DL, MVT::i32),
18370 SDValue(Sum.getNode(), 2));
18372 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18376 // Also sets EFLAGS.
18377 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18378 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18381 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18382 DAG.getConstant(Cond, DL, MVT::i32),
18383 SDValue(Sum.getNode(), 1));
18385 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18388 /// Returns true if the operand type is exactly twice the native width, and
18389 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18390 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18391 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18392 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18393 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18396 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18397 else if (OpWidth == 128)
18398 return Subtarget->hasCmpxchg16b();
18403 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18404 return needsCmpXchgNb(SI->getValueOperand()->getType());
18407 // Note: this turns large loads into lock cmpxchg8b/16b.
18408 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18409 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18410 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18411 return needsCmpXchgNb(PTy->getElementType());
18414 TargetLoweringBase::AtomicRMWExpansionKind
18415 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18416 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18417 Type *MemType = AI->getType();
18419 // If the operand is too big, we must see if cmpxchg8/16b is available
18420 // and default to library calls otherwise.
18421 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18422 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18423 : AtomicRMWExpansionKind::None;
18426 AtomicRMWInst::BinOp Op = AI->getOperation();
18429 llvm_unreachable("Unknown atomic operation");
18430 case AtomicRMWInst::Xchg:
18431 case AtomicRMWInst::Add:
18432 case AtomicRMWInst::Sub:
18433 // It's better to use xadd, xsub or xchg for these in all cases.
18434 return AtomicRMWExpansionKind::None;
18435 case AtomicRMWInst::Or:
18436 case AtomicRMWInst::And:
18437 case AtomicRMWInst::Xor:
18438 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18439 // prefix to a normal instruction for these operations.
18440 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18441 : AtomicRMWExpansionKind::None;
18442 case AtomicRMWInst::Nand:
18443 case AtomicRMWInst::Max:
18444 case AtomicRMWInst::Min:
18445 case AtomicRMWInst::UMax:
18446 case AtomicRMWInst::UMin:
18447 // These always require a non-trivial set of data operations on x86. We must
18448 // use a cmpxchg loop.
18449 return AtomicRMWExpansionKind::CmpXChg;
18453 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18454 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18455 // no-sse2). There isn't any reason to disable it if the target processor
18457 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18461 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18462 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18463 Type *MemType = AI->getType();
18464 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18465 // there is no benefit in turning such RMWs into loads, and it is actually
18466 // harmful as it introduces a mfence.
18467 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18470 auto Builder = IRBuilder<>(AI);
18471 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18472 auto SynchScope = AI->getSynchScope();
18473 // We must restrict the ordering to avoid generating loads with Release or
18474 // ReleaseAcquire orderings.
18475 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18476 auto Ptr = AI->getPointerOperand();
18478 // Before the load we need a fence. Here is an example lifted from
18479 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18482 // x.store(1, relaxed);
18483 // r1 = y.fetch_add(0, release);
18485 // y.fetch_add(42, acquire);
18486 // r2 = x.load(relaxed);
18487 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18488 // lowered to just a load without a fence. A mfence flushes the store buffer,
18489 // making the optimization clearly correct.
18490 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18491 // otherwise, we might be able to be more aggressive on relaxed idempotent
18492 // rmw. In practice, they do not look useful, so we don't try to be
18493 // especially clever.
18494 if (SynchScope == SingleThread)
18495 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18496 // the IR level, so we must wrap it in an intrinsic.
18499 if (!hasMFENCE(*Subtarget))
18500 // FIXME: it might make sense to use a locked operation here but on a
18501 // different cache-line to prevent cache-line bouncing. In practice it
18502 // is probably a small win, and x86 processors without mfence are rare
18503 // enough that we do not bother.
18507 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18508 Builder.CreateCall(MFence, {});
18510 // Finally we can emit the atomic load.
18511 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18512 AI->getType()->getPrimitiveSizeInBits());
18513 Loaded->setAtomic(Order, SynchScope);
18514 AI->replaceAllUsesWith(Loaded);
18515 AI->eraseFromParent();
18519 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18520 SelectionDAG &DAG) {
18522 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18523 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18524 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18525 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18527 // The only fence that needs an instruction is a sequentially-consistent
18528 // cross-thread fence.
18529 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18530 if (hasMFENCE(*Subtarget))
18531 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18533 SDValue Chain = Op.getOperand(0);
18534 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18536 DAG.getRegister(X86::ESP, MVT::i32), // Base
18537 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18538 DAG.getRegister(0, MVT::i32), // Index
18539 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18540 DAG.getRegister(0, MVT::i32), // Segment.
18544 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18545 return SDValue(Res, 0);
18548 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18549 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18552 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18553 SelectionDAG &DAG) {
18554 MVT T = Op.getSimpleValueType();
18558 switch(T.SimpleTy) {
18559 default: llvm_unreachable("Invalid value type!");
18560 case MVT::i8: Reg = X86::AL; size = 1; break;
18561 case MVT::i16: Reg = X86::AX; size = 2; break;
18562 case MVT::i32: Reg = X86::EAX; size = 4; break;
18564 assert(Subtarget->is64Bit() && "Node not type legal!");
18565 Reg = X86::RAX; size = 8;
18568 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18569 Op.getOperand(2), SDValue());
18570 SDValue Ops[] = { cpIn.getValue(0),
18573 DAG.getTargetConstant(size, DL, MVT::i8),
18574 cpIn.getValue(1) };
18575 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18576 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18577 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18581 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18582 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18583 MVT::i32, cpOut.getValue(2));
18584 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18585 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18588 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18589 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18590 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18594 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18595 SelectionDAG &DAG) {
18596 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18597 MVT DstVT = Op.getSimpleValueType();
18599 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18600 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18601 if (DstVT != MVT::f64)
18602 // This conversion needs to be expanded.
18605 SDValue InVec = Op->getOperand(0);
18607 unsigned NumElts = SrcVT.getVectorNumElements();
18608 EVT SVT = SrcVT.getVectorElementType();
18610 // Widen the vector in input in the case of MVT::v2i32.
18611 // Example: from MVT::v2i32 to MVT::v4i32.
18612 SmallVector<SDValue, 16> Elts;
18613 for (unsigned i = 0, e = NumElts; i != e; ++i)
18614 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18615 DAG.getIntPtrConstant(i, dl)));
18617 // Explicitly mark the extra elements as Undef.
18618 Elts.append(NumElts, DAG.getUNDEF(SVT));
18620 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18621 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18622 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18623 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18624 DAG.getIntPtrConstant(0, dl));
18627 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18628 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18629 assert((DstVT == MVT::i64 ||
18630 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18631 "Unexpected custom BITCAST");
18632 // i64 <=> MMX conversions are Legal.
18633 if (SrcVT==MVT::i64 && DstVT.isVector())
18635 if (DstVT==MVT::i64 && SrcVT.isVector())
18637 // MMX <=> MMX conversions are Legal.
18638 if (SrcVT.isVector() && DstVT.isVector())
18640 // All other conversions need to be expanded.
18644 /// Compute the horizontal sum of bytes in V for the elements of VT.
18646 /// Requires V to be a byte vector and VT to be an integer vector type with
18647 /// wider elements than V's type. The width of the elements of VT determines
18648 /// how many bytes of V are summed horizontally to produce each element of the
18650 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18651 const X86Subtarget *Subtarget,
18652 SelectionDAG &DAG) {
18654 MVT ByteVecVT = V.getSimpleValueType();
18655 MVT EltVT = VT.getVectorElementType();
18656 int NumElts = VT.getVectorNumElements();
18657 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18658 "Expected value to have byte element type.");
18659 assert(EltVT != MVT::i8 &&
18660 "Horizontal byte sum only makes sense for wider elements!");
18661 unsigned VecSize = VT.getSizeInBits();
18662 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18664 // PSADBW instruction horizontally add all bytes and leave the result in i64
18665 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18666 if (EltVT == MVT::i64) {
18667 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18668 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18669 return DAG.getBitcast(VT, V);
18672 if (EltVT == MVT::i32) {
18673 // We unpack the low half and high half into i32s interleaved with zeros so
18674 // that we can use PSADBW to horizontally sum them. The most useful part of
18675 // this is that it lines up the results of two PSADBW instructions to be
18676 // two v2i64 vectors which concatenated are the 4 population counts. We can
18677 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18678 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18679 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18680 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18682 // Do the horizontal sums into two v2i64s.
18683 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18684 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18685 DAG.getBitcast(ByteVecVT, Low), Zeros);
18686 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18687 DAG.getBitcast(ByteVecVT, High), Zeros);
18689 // Merge them together.
18690 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18691 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18692 DAG.getBitcast(ShortVecVT, Low),
18693 DAG.getBitcast(ShortVecVT, High));
18695 return DAG.getBitcast(VT, V);
18698 // The only element type left is i16.
18699 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18701 // To obtain pop count for each i16 element starting from the pop count for
18702 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18703 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18704 // directly supported.
18705 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18706 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18707 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18708 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18709 DAG.getBitcast(ByteVecVT, V));
18710 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18713 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18714 const X86Subtarget *Subtarget,
18715 SelectionDAG &DAG) {
18716 MVT VT = Op.getSimpleValueType();
18717 MVT EltVT = VT.getVectorElementType();
18718 unsigned VecSize = VT.getSizeInBits();
18720 // Implement a lookup table in register by using an algorithm based on:
18721 // http://wm.ite.pl/articles/sse-popcount.html
18723 // The general idea is that every lower byte nibble in the input vector is an
18724 // index into a in-register pre-computed pop count table. We then split up the
18725 // input vector in two new ones: (1) a vector with only the shifted-right
18726 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18727 // masked out higher ones) for each byte. PSHUB is used separately with both
18728 // to index the in-register table. Next, both are added and the result is a
18729 // i8 vector where each element contains the pop count for input byte.
18731 // To obtain the pop count for elements != i8, we follow up with the same
18732 // approach and use additional tricks as described below.
18734 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18735 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18736 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18737 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18739 int NumByteElts = VecSize / 8;
18740 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18741 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18742 SmallVector<SDValue, 16> LUTVec;
18743 for (int i = 0; i < NumByteElts; ++i)
18744 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18745 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18746 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18747 DAG.getConstant(0x0F, DL, MVT::i8));
18748 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18751 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18752 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18753 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18756 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18758 // The input vector is used as the shuffle mask that index elements into the
18759 // LUT. After counting low and high nibbles, add the vector to obtain the
18760 // final pop count per i8 element.
18761 SDValue HighPopCnt =
18762 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18763 SDValue LowPopCnt =
18764 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18765 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18767 if (EltVT == MVT::i8)
18770 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18773 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18774 const X86Subtarget *Subtarget,
18775 SelectionDAG &DAG) {
18776 MVT VT = Op.getSimpleValueType();
18777 assert(VT.is128BitVector() &&
18778 "Only 128-bit vector bitmath lowering supported.");
18780 int VecSize = VT.getSizeInBits();
18781 MVT EltVT = VT.getVectorElementType();
18782 int Len = EltVT.getSizeInBits();
18784 // This is the vectorized version of the "best" algorithm from
18785 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18786 // with a minor tweak to use a series of adds + shifts instead of vector
18787 // multiplications. Implemented for all integer vector types. We only use
18788 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18789 // much faster, even faster than using native popcnt instructions.
18791 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18792 MVT VT = V.getSimpleValueType();
18793 SmallVector<SDValue, 32> Shifters(
18794 VT.getVectorNumElements(),
18795 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18796 return DAG.getNode(OpCode, DL, VT, V,
18797 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18799 auto GetMask = [&](SDValue V, APInt Mask) {
18800 MVT VT = V.getSimpleValueType();
18801 SmallVector<SDValue, 32> Masks(
18802 VT.getVectorNumElements(),
18803 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18804 return DAG.getNode(ISD::AND, DL, VT, V,
18805 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18808 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18809 // x86, so set the SRL type to have elements at least i16 wide. This is
18810 // correct because all of our SRLs are followed immediately by a mask anyways
18811 // that handles any bits that sneak into the high bits of the byte elements.
18812 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18816 // v = v - ((v >> 1) & 0x55555555...)
18818 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18819 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18820 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18822 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18823 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18824 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18825 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18826 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18828 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18829 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18830 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18831 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18833 // At this point, V contains the byte-wise population count, and we are
18834 // merely doing a horizontal sum if necessary to get the wider element
18836 if (EltVT == MVT::i8)
18839 return LowerHorizontalByteSum(
18840 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18844 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18845 SelectionDAG &DAG) {
18846 MVT VT = Op.getSimpleValueType();
18847 // FIXME: Need to add AVX-512 support here!
18848 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18849 "Unknown CTPOP type to handle");
18850 SDLoc DL(Op.getNode());
18851 SDValue Op0 = Op.getOperand(0);
18853 if (!Subtarget->hasSSSE3()) {
18854 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18855 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18856 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18859 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18860 unsigned NumElems = VT.getVectorNumElements();
18862 // Extract each 128-bit vector, compute pop count and concat the result.
18863 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18864 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18866 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18867 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18868 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18871 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18874 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18875 SelectionDAG &DAG) {
18876 assert(Op.getValueType().isVector() &&
18877 "We only do custom lowering for vector population count.");
18878 return LowerVectorCTPOP(Op, Subtarget, DAG);
18881 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18882 SDNode *Node = Op.getNode();
18884 EVT T = Node->getValueType(0);
18885 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18886 DAG.getConstant(0, dl, T), Node->getOperand(2));
18887 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18888 cast<AtomicSDNode>(Node)->getMemoryVT(),
18889 Node->getOperand(0),
18890 Node->getOperand(1), negOp,
18891 cast<AtomicSDNode>(Node)->getMemOperand(),
18892 cast<AtomicSDNode>(Node)->getOrdering(),
18893 cast<AtomicSDNode>(Node)->getSynchScope());
18896 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18897 SDNode *Node = Op.getNode();
18899 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18901 // Convert seq_cst store -> xchg
18902 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18903 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18904 // (The only way to get a 16-byte store is cmpxchg16b)
18905 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18906 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18907 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18908 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18909 cast<AtomicSDNode>(Node)->getMemoryVT(),
18910 Node->getOperand(0),
18911 Node->getOperand(1), Node->getOperand(2),
18912 cast<AtomicSDNode>(Node)->getMemOperand(),
18913 cast<AtomicSDNode>(Node)->getOrdering(),
18914 cast<AtomicSDNode>(Node)->getSynchScope());
18915 return Swap.getValue(1);
18917 // Other atomic stores have a simple pattern.
18921 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18922 EVT VT = Op.getNode()->getSimpleValueType(0);
18924 // Let legalize expand this if it isn't a legal type yet.
18925 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18928 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18931 bool ExtraOp = false;
18932 switch (Op.getOpcode()) {
18933 default: llvm_unreachable("Invalid code");
18934 case ISD::ADDC: Opc = X86ISD::ADD; break;
18935 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18936 case ISD::SUBC: Opc = X86ISD::SUB; break;
18937 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18941 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18943 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18944 Op.getOperand(1), Op.getOperand(2));
18947 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18948 SelectionDAG &DAG) {
18949 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18951 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18952 // which returns the values as { float, float } (in XMM0) or
18953 // { double, double } (which is returned in XMM0, XMM1).
18955 SDValue Arg = Op.getOperand(0);
18956 EVT ArgVT = Arg.getValueType();
18957 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18959 TargetLowering::ArgListTy Args;
18960 TargetLowering::ArgListEntry Entry;
18964 Entry.isSExt = false;
18965 Entry.isZExt = false;
18966 Args.push_back(Entry);
18968 bool isF64 = ArgVT == MVT::f64;
18969 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18970 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18971 // the results are returned via SRet in memory.
18972 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18973 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18975 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18977 Type *RetTy = isF64
18978 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18979 : (Type*)VectorType::get(ArgTy, 4);
18981 TargetLowering::CallLoweringInfo CLI(DAG);
18982 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18983 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18985 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18988 // Returned in xmm0 and xmm1.
18989 return CallResult.first;
18991 // Returned in bits 0:31 and 32:64 xmm0.
18992 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18993 CallResult.first, DAG.getIntPtrConstant(0, dl));
18994 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18995 CallResult.first, DAG.getIntPtrConstant(1, dl));
18996 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18997 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19000 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19001 SelectionDAG &DAG) {
19002 assert(Subtarget->hasAVX512() &&
19003 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19005 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19006 EVT VT = N->getValue().getValueType();
19007 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19010 // X86 scatter kills mask register, so its type should be added to
19011 // the list of return values
19012 if (N->getNumValues() == 1) {
19013 SDValue Index = N->getIndex();
19014 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19015 !Index.getValueType().is512BitVector())
19016 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19018 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19019 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19020 N->getOperand(3), Index };
19022 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19023 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19024 return SDValue(NewScatter.getNode(), 0);
19029 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19030 SelectionDAG &DAG) {
19031 assert(Subtarget->hasAVX512() &&
19032 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19034 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19035 EVT VT = Op.getValueType();
19036 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19039 SDValue Index = N->getIndex();
19040 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19041 !Index.getValueType().is512BitVector()) {
19042 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19043 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19044 N->getOperand(3), Index };
19045 DAG.UpdateNodeOperands(N, Ops);
19050 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19051 SelectionDAG &DAG) const {
19052 // TODO: Eventually, the lowering of these nodes should be informed by or
19053 // deferred to the GC strategy for the function in which they appear. For
19054 // now, however, they must be lowered to something. Since they are logically
19055 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19056 // require special handling for these nodes), lower them as literal NOOPs for
19058 SmallVector<SDValue, 2> Ops;
19060 Ops.push_back(Op.getOperand(0));
19061 if (Op->getGluedNode())
19062 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19065 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19066 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19071 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19072 SelectionDAG &DAG) const {
19073 // TODO: Eventually, the lowering of these nodes should be informed by or
19074 // deferred to the GC strategy for the function in which they appear. For
19075 // now, however, they must be lowered to something. Since they are logically
19076 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19077 // require special handling for these nodes), lower them as literal NOOPs for
19079 SmallVector<SDValue, 2> Ops;
19081 Ops.push_back(Op.getOperand(0));
19082 if (Op->getGluedNode())
19083 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19086 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19087 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19092 /// LowerOperation - Provide custom lowering hooks for some operations.
19094 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19095 switch (Op.getOpcode()) {
19096 default: llvm_unreachable("Should not custom lower this!");
19097 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19098 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19099 return LowerCMP_SWAP(Op, Subtarget, DAG);
19100 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
19101 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
19102 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
19103 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
19104 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19105 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
19106 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
19107 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19108 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
19109 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19110 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19111 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
19112 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
19113 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
19114 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
19115 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
19116 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
19117 case ISD::SHL_PARTS:
19118 case ISD::SRA_PARTS:
19119 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
19120 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
19121 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
19122 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
19123 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
19124 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19125 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
19126 case ISD::SIGN_EXTEND_VECTOR_INREG:
19127 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19128 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
19129 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
19130 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
19131 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
19133 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
19134 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
19135 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
19136 case ISD::SETCC: return LowerSETCC(Op, DAG);
19137 case ISD::SELECT: return LowerSELECT(Op, DAG);
19138 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
19139 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
19140 case ISD::VASTART: return LowerVASTART(Op, DAG);
19141 case ISD::VAARG: return LowerVAARG(Op, DAG);
19142 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
19143 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19144 case ISD::INTRINSIC_VOID:
19145 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19146 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
19147 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
19148 case ISD::FRAME_TO_ARGS_OFFSET:
19149 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19150 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19151 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
19152 case ISD::CLEANUPRET: return LowerCLEANUPRET(Op, DAG);
19153 case ISD::CATCHRET: return LowerCATCHRET(Op, DAG);
19154 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
19155 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
19156 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
19157 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
19158 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
19159 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
19160 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19161 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
19162 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
19163 case ISD::UMUL_LOHI:
19164 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
19167 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
19173 case ISD::UMULO: return LowerXALUO(Op, DAG);
19174 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19175 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
19179 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19180 case ISD::ADD: return LowerADD(Op, DAG);
19181 case ISD::SUB: return LowerSUB(Op, DAG);
19185 case ISD::UMIN: return LowerMINMAX(Op, DAG);
19186 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
19187 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
19188 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
19189 case ISD::GC_TRANSITION_START:
19190 return LowerGC_TRANSITION_START(Op, DAG);
19191 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
19195 /// ReplaceNodeResults - Replace a node with an illegal result type
19196 /// with a new node built out of custom code.
19197 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19198 SmallVectorImpl<SDValue>&Results,
19199 SelectionDAG &DAG) const {
19201 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19202 switch (N->getOpcode()) {
19204 llvm_unreachable("Do not know how to custom type legalize this operation!");
19205 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19206 case X86ISD::FMINC:
19208 case X86ISD::FMAXC:
19209 case X86ISD::FMAX: {
19210 EVT VT = N->getValueType(0);
19211 if (VT != MVT::v2f32)
19212 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19213 SDValue UNDEF = DAG.getUNDEF(VT);
19214 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19215 N->getOperand(0), UNDEF);
19216 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19217 N->getOperand(1), UNDEF);
19218 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19221 case ISD::SIGN_EXTEND_INREG:
19226 // We don't want to expand or promote these.
19233 case ISD::UDIVREM: {
19234 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19235 Results.push_back(V);
19238 case ISD::FP_TO_SINT:
19239 case ISD::FP_TO_UINT: {
19240 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19242 std::pair<SDValue,SDValue> Vals =
19243 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19244 SDValue FIST = Vals.first, StackSlot = Vals.second;
19245 if (FIST.getNode()) {
19246 EVT VT = N->getValueType(0);
19247 // Return a load from the stack slot.
19248 if (StackSlot.getNode())
19249 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19250 MachinePointerInfo(),
19251 false, false, false, 0));
19253 Results.push_back(FIST);
19257 case ISD::UINT_TO_FP: {
19258 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19259 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19260 N->getValueType(0) != MVT::v2f32)
19262 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19264 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19266 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19267 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19268 DAG.getBitcast(MVT::v2i64, VBias));
19269 Or = DAG.getBitcast(MVT::v2f64, Or);
19270 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19271 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19274 case ISD::FP_ROUND: {
19275 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19277 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19278 Results.push_back(V);
19281 case ISD::FP_EXTEND: {
19282 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19283 // No other ValueType for FP_EXTEND should reach this point.
19284 assert(N->getValueType(0) == MVT::v2f32 &&
19285 "Do not know how to legalize this Node");
19288 case ISD::INTRINSIC_W_CHAIN: {
19289 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19291 default : llvm_unreachable("Do not know how to custom type "
19292 "legalize this intrinsic operation!");
19293 case Intrinsic::x86_rdtsc:
19294 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19296 case Intrinsic::x86_rdtscp:
19297 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19299 case Intrinsic::x86_rdpmc:
19300 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19303 case ISD::READCYCLECOUNTER: {
19304 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19307 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19308 EVT T = N->getValueType(0);
19309 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19310 bool Regs64bit = T == MVT::i128;
19311 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19312 SDValue cpInL, cpInH;
19313 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19314 DAG.getConstant(0, dl, HalfT));
19315 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19316 DAG.getConstant(1, dl, HalfT));
19317 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19318 Regs64bit ? X86::RAX : X86::EAX,
19320 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19321 Regs64bit ? X86::RDX : X86::EDX,
19322 cpInH, cpInL.getValue(1));
19323 SDValue swapInL, swapInH;
19324 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19325 DAG.getConstant(0, dl, HalfT));
19326 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19327 DAG.getConstant(1, dl, HalfT));
19328 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19329 Regs64bit ? X86::RBX : X86::EBX,
19330 swapInL, cpInH.getValue(1));
19331 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19332 Regs64bit ? X86::RCX : X86::ECX,
19333 swapInH, swapInL.getValue(1));
19334 SDValue Ops[] = { swapInH.getValue(0),
19336 swapInH.getValue(1) };
19337 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19338 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19339 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19340 X86ISD::LCMPXCHG8_DAG;
19341 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19342 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19343 Regs64bit ? X86::RAX : X86::EAX,
19344 HalfT, Result.getValue(1));
19345 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19346 Regs64bit ? X86::RDX : X86::EDX,
19347 HalfT, cpOutL.getValue(2));
19348 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19350 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19351 MVT::i32, cpOutH.getValue(2));
19353 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19354 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19355 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19357 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19358 Results.push_back(Success);
19359 Results.push_back(EFLAGS.getValue(1));
19362 case ISD::ATOMIC_SWAP:
19363 case ISD::ATOMIC_LOAD_ADD:
19364 case ISD::ATOMIC_LOAD_SUB:
19365 case ISD::ATOMIC_LOAD_AND:
19366 case ISD::ATOMIC_LOAD_OR:
19367 case ISD::ATOMIC_LOAD_XOR:
19368 case ISD::ATOMIC_LOAD_NAND:
19369 case ISD::ATOMIC_LOAD_MIN:
19370 case ISD::ATOMIC_LOAD_MAX:
19371 case ISD::ATOMIC_LOAD_UMIN:
19372 case ISD::ATOMIC_LOAD_UMAX:
19373 case ISD::ATOMIC_LOAD: {
19374 // Delegate to generic TypeLegalization. Situations we can really handle
19375 // should have already been dealt with by AtomicExpandPass.cpp.
19378 case ISD::BITCAST: {
19379 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19380 EVT DstVT = N->getValueType(0);
19381 EVT SrcVT = N->getOperand(0)->getValueType(0);
19383 if (SrcVT != MVT::f64 ||
19384 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19387 unsigned NumElts = DstVT.getVectorNumElements();
19388 EVT SVT = DstVT.getVectorElementType();
19389 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19390 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19391 MVT::v2f64, N->getOperand(0));
19392 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19394 if (ExperimentalVectorWideningLegalization) {
19395 // If we are legalizing vectors by widening, we already have the desired
19396 // legal vector type, just return it.
19397 Results.push_back(ToVecInt);
19401 SmallVector<SDValue, 8> Elts;
19402 for (unsigned i = 0, e = NumElts; i != e; ++i)
19403 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19404 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19406 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19411 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19412 switch ((X86ISD::NodeType)Opcode) {
19413 case X86ISD::FIRST_NUMBER: break;
19414 case X86ISD::BSF: return "X86ISD::BSF";
19415 case X86ISD::BSR: return "X86ISD::BSR";
19416 case X86ISD::SHLD: return "X86ISD::SHLD";
19417 case X86ISD::SHRD: return "X86ISD::SHRD";
19418 case X86ISD::FAND: return "X86ISD::FAND";
19419 case X86ISD::FANDN: return "X86ISD::FANDN";
19420 case X86ISD::FOR: return "X86ISD::FOR";
19421 case X86ISD::FXOR: return "X86ISD::FXOR";
19422 case X86ISD::FILD: return "X86ISD::FILD";
19423 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19424 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19425 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19426 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19427 case X86ISD::FLD: return "X86ISD::FLD";
19428 case X86ISD::FST: return "X86ISD::FST";
19429 case X86ISD::CALL: return "X86ISD::CALL";
19430 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19431 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19432 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19433 case X86ISD::BT: return "X86ISD::BT";
19434 case X86ISD::CMP: return "X86ISD::CMP";
19435 case X86ISD::COMI: return "X86ISD::COMI";
19436 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19437 case X86ISD::CMPM: return "X86ISD::CMPM";
19438 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19439 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19440 case X86ISD::SETCC: return "X86ISD::SETCC";
19441 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19442 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19443 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19444 case X86ISD::CMOV: return "X86ISD::CMOV";
19445 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19446 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19447 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19448 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19449 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19450 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19451 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19452 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19453 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19454 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19455 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19456 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19457 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19458 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19459 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19460 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19461 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19462 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19463 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19464 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19465 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19466 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19467 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19468 case X86ISD::HADD: return "X86ISD::HADD";
19469 case X86ISD::HSUB: return "X86ISD::HSUB";
19470 case X86ISD::FHADD: return "X86ISD::FHADD";
19471 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19472 case X86ISD::ABS: return "X86ISD::ABS";
19473 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
19474 case X86ISD::FMAX: return "X86ISD::FMAX";
19475 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19476 case X86ISD::FMIN: return "X86ISD::FMIN";
19477 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19478 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19479 case X86ISD::FMINC: return "X86ISD::FMINC";
19480 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19481 case X86ISD::FRCP: return "X86ISD::FRCP";
19482 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19483 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19484 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19485 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19486 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19487 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19488 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19489 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19490 case X86ISD::CATCHRET: return "X86ISD::CATCHRET";
19491 case X86ISD::CLEANUPRET: return "X86ISD::CLEANUPRET";
19492 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19493 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19494 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19495 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19496 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19497 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19498 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19499 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19500 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19501 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19502 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19503 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19504 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19505 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19506 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19507 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19508 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19509 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19510 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19511 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19512 case X86ISD::VSHL: return "X86ISD::VSHL";
19513 case X86ISD::VSRL: return "X86ISD::VSRL";
19514 case X86ISD::VSRA: return "X86ISD::VSRA";
19515 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19516 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19517 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19518 case X86ISD::CMPP: return "X86ISD::CMPP";
19519 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19520 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19521 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19522 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19523 case X86ISD::ADD: return "X86ISD::ADD";
19524 case X86ISD::SUB: return "X86ISD::SUB";
19525 case X86ISD::ADC: return "X86ISD::ADC";
19526 case X86ISD::SBB: return "X86ISD::SBB";
19527 case X86ISD::SMUL: return "X86ISD::SMUL";
19528 case X86ISD::UMUL: return "X86ISD::UMUL";
19529 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19530 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19531 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19532 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19533 case X86ISD::INC: return "X86ISD::INC";
19534 case X86ISD::DEC: return "X86ISD::DEC";
19535 case X86ISD::OR: return "X86ISD::OR";
19536 case X86ISD::XOR: return "X86ISD::XOR";
19537 case X86ISD::AND: return "X86ISD::AND";
19538 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19539 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19540 case X86ISD::PTEST: return "X86ISD::PTEST";
19541 case X86ISD::TESTP: return "X86ISD::TESTP";
19542 case X86ISD::TESTM: return "X86ISD::TESTM";
19543 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19544 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19545 case X86ISD::KTEST: return "X86ISD::KTEST";
19546 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19547 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19548 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19549 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19550 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19551 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19552 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19553 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19554 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19555 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19556 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19557 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19558 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19559 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19560 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19561 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19562 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19563 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19564 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19565 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19566 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19567 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19568 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19569 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19570 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19571 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19572 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19573 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19574 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19575 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19576 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19577 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19578 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19579 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19580 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19581 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19582 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
19583 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19584 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19585 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19586 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19587 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19588 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19589 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19590 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19591 case X86ISD::SAHF: return "X86ISD::SAHF";
19592 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19593 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19594 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19595 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19596 case X86ISD::FMADD: return "X86ISD::FMADD";
19597 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19598 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19599 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19600 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19601 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19602 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19603 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19604 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19605 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19606 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19607 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19608 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19609 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19610 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
19611 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19612 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19613 case X86ISD::XTEST: return "X86ISD::XTEST";
19614 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19615 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19616 case X86ISD::SELECT: return "X86ISD::SELECT";
19617 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19618 case X86ISD::RCP28: return "X86ISD::RCP28";
19619 case X86ISD::EXP2: return "X86ISD::EXP2";
19620 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19621 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19622 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19623 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19624 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19625 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19626 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19627 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19628 case X86ISD::ADDS: return "X86ISD::ADDS";
19629 case X86ISD::SUBS: return "X86ISD::SUBS";
19630 case X86ISD::AVG: return "X86ISD::AVG";
19631 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19632 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19633 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19634 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19635 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19640 // isLegalAddressingMode - Return true if the addressing mode represented
19641 // by AM is legal for this target, for a load/store of the specified type.
19642 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19643 const AddrMode &AM, Type *Ty,
19644 unsigned AS) const {
19645 // X86 supports extremely general addressing modes.
19646 CodeModel::Model M = getTargetMachine().getCodeModel();
19647 Reloc::Model R = getTargetMachine().getRelocationModel();
19649 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19650 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19655 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19657 // If a reference to this global requires an extra load, we can't fold it.
19658 if (isGlobalStubReference(GVFlags))
19661 // If BaseGV requires a register for the PIC base, we cannot also have a
19662 // BaseReg specified.
19663 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19666 // If lower 4G is not available, then we must use rip-relative addressing.
19667 if ((M != CodeModel::Small || R != Reloc::Static) &&
19668 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19672 switch (AM.Scale) {
19678 // These scales always work.
19683 // These scales are formed with basereg+scalereg. Only accept if there is
19688 default: // Other stuff never works.
19695 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19696 unsigned Bits = Ty->getScalarSizeInBits();
19698 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19699 // particularly cheaper than those without.
19703 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19704 // variable shifts just as cheap as scalar ones.
19705 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19708 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19709 // fully general vector.
19713 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19714 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19716 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19717 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19718 return NumBits1 > NumBits2;
19721 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19722 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19725 if (!isTypeLegal(EVT::getEVT(Ty1)))
19728 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19730 // Assuming the caller doesn't have a zeroext or signext return parameter,
19731 // truncation all the way down to i1 is valid.
19735 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19736 return isInt<32>(Imm);
19739 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19740 // Can also use sub to handle negated immediates.
19741 return isInt<32>(Imm);
19744 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19745 if (!VT1.isInteger() || !VT2.isInteger())
19747 unsigned NumBits1 = VT1.getSizeInBits();
19748 unsigned NumBits2 = VT2.getSizeInBits();
19749 return NumBits1 > NumBits2;
19752 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19753 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19754 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19757 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19758 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19759 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19762 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19763 EVT VT1 = Val.getValueType();
19764 if (isZExtFree(VT1, VT2))
19767 if (Val.getOpcode() != ISD::LOAD)
19770 if (!VT1.isSimple() || !VT1.isInteger() ||
19771 !VT2.isSimple() || !VT2.isInteger())
19774 switch (VT1.getSimpleVT().SimpleTy) {
19779 // X86 has 8, 16, and 32-bit zero-extending loads.
19786 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19789 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19790 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19793 VT = VT.getScalarType();
19795 if (!VT.isSimple())
19798 switch (VT.getSimpleVT().SimpleTy) {
19809 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19810 // i16 instructions are longer (0x66 prefix) and potentially slower.
19811 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19814 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19815 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19816 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19817 /// are assumed to be legal.
19819 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19821 if (!VT.isSimple())
19824 // Not for i1 vectors
19825 if (VT.getScalarType() == MVT::i1)
19828 // Very little shuffling can be done for 64-bit vectors right now.
19829 if (VT.getSizeInBits() == 64)
19832 // We only care that the types being shuffled are legal. The lowering can
19833 // handle any possible shuffle mask that results.
19834 return isTypeLegal(VT.getSimpleVT());
19838 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19840 // Just delegate to the generic legality, clear masks aren't special.
19841 return isShuffleMaskLegal(Mask, VT);
19844 //===----------------------------------------------------------------------===//
19845 // X86 Scheduler Hooks
19846 //===----------------------------------------------------------------------===//
19848 /// Utility function to emit xbegin specifying the start of an RTM region.
19849 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19850 const TargetInstrInfo *TII) {
19851 DebugLoc DL = MI->getDebugLoc();
19853 const BasicBlock *BB = MBB->getBasicBlock();
19854 MachineFunction::iterator I = MBB;
19857 // For the v = xbegin(), we generate
19868 MachineBasicBlock *thisMBB = MBB;
19869 MachineFunction *MF = MBB->getParent();
19870 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19871 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19872 MF->insert(I, mainMBB);
19873 MF->insert(I, sinkMBB);
19875 // Transfer the remainder of BB and its successor edges to sinkMBB.
19876 sinkMBB->splice(sinkMBB->begin(), MBB,
19877 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19878 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19882 // # fallthrough to mainMBB
19883 // # abortion to sinkMBB
19884 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19885 thisMBB->addSuccessor(mainMBB);
19886 thisMBB->addSuccessor(sinkMBB);
19890 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19891 mainMBB->addSuccessor(sinkMBB);
19894 // EAX is live into the sinkMBB
19895 sinkMBB->addLiveIn(X86::EAX);
19896 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19897 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19900 MI->eraseFromParent();
19904 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19905 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19906 // in the .td file.
19907 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19908 const TargetInstrInfo *TII) {
19910 switch (MI->getOpcode()) {
19911 default: llvm_unreachable("illegal opcode!");
19912 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19913 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19914 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19915 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19916 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19917 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19918 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19919 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19922 DebugLoc dl = MI->getDebugLoc();
19923 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19925 unsigned NumArgs = MI->getNumOperands();
19926 for (unsigned i = 1; i < NumArgs; ++i) {
19927 MachineOperand &Op = MI->getOperand(i);
19928 if (!(Op.isReg() && Op.isImplicit()))
19929 MIB.addOperand(Op);
19931 if (MI->hasOneMemOperand())
19932 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19934 BuildMI(*BB, MI, dl,
19935 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19936 .addReg(X86::XMM0);
19938 MI->eraseFromParent();
19942 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19943 // defs in an instruction pattern
19944 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19945 const TargetInstrInfo *TII) {
19947 switch (MI->getOpcode()) {
19948 default: llvm_unreachable("illegal opcode!");
19949 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19950 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19951 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19952 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19953 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19954 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19955 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19956 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19959 DebugLoc dl = MI->getDebugLoc();
19960 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19962 unsigned NumArgs = MI->getNumOperands(); // remove the results
19963 for (unsigned i = 1; i < NumArgs; ++i) {
19964 MachineOperand &Op = MI->getOperand(i);
19965 if (!(Op.isReg() && Op.isImplicit()))
19966 MIB.addOperand(Op);
19968 if (MI->hasOneMemOperand())
19969 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19971 BuildMI(*BB, MI, dl,
19972 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19975 MI->eraseFromParent();
19979 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19980 const X86Subtarget *Subtarget) {
19981 DebugLoc dl = MI->getDebugLoc();
19982 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19983 // Address into RAX/EAX, other two args into ECX, EDX.
19984 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19985 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19986 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19987 for (int i = 0; i < X86::AddrNumOperands; ++i)
19988 MIB.addOperand(MI->getOperand(i));
19990 unsigned ValOps = X86::AddrNumOperands;
19991 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19992 .addReg(MI->getOperand(ValOps).getReg());
19993 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19994 .addReg(MI->getOperand(ValOps+1).getReg());
19996 // The instruction doesn't actually take any operands though.
19997 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19999 MI->eraseFromParent(); // The pseudo is gone now.
20003 MachineBasicBlock *
20004 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20005 MachineBasicBlock *MBB) const {
20006 // Emit va_arg instruction on X86-64.
20008 // Operands to this pseudo-instruction:
20009 // 0 ) Output : destination address (reg)
20010 // 1-5) Input : va_list address (addr, i64mem)
20011 // 6 ) ArgSize : Size (in bytes) of vararg type
20012 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20013 // 8 ) Align : Alignment of type
20014 // 9 ) EFLAGS (implicit-def)
20016 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20017 static_assert(X86::AddrNumOperands == 5,
20018 "VAARG_64 assumes 5 address operands");
20020 unsigned DestReg = MI->getOperand(0).getReg();
20021 MachineOperand &Base = MI->getOperand(1);
20022 MachineOperand &Scale = MI->getOperand(2);
20023 MachineOperand &Index = MI->getOperand(3);
20024 MachineOperand &Disp = MI->getOperand(4);
20025 MachineOperand &Segment = MI->getOperand(5);
20026 unsigned ArgSize = MI->getOperand(6).getImm();
20027 unsigned ArgMode = MI->getOperand(7).getImm();
20028 unsigned Align = MI->getOperand(8).getImm();
20030 // Memory Reference
20031 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20032 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20033 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20035 // Machine Information
20036 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20037 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20038 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20039 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20040 DebugLoc DL = MI->getDebugLoc();
20042 // struct va_list {
20045 // i64 overflow_area (address)
20046 // i64 reg_save_area (address)
20048 // sizeof(va_list) = 24
20049 // alignment(va_list) = 8
20051 unsigned TotalNumIntRegs = 6;
20052 unsigned TotalNumXMMRegs = 8;
20053 bool UseGPOffset = (ArgMode == 1);
20054 bool UseFPOffset = (ArgMode == 2);
20055 unsigned MaxOffset = TotalNumIntRegs * 8 +
20056 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20058 /* Align ArgSize to a multiple of 8 */
20059 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20060 bool NeedsAlign = (Align > 8);
20062 MachineBasicBlock *thisMBB = MBB;
20063 MachineBasicBlock *overflowMBB;
20064 MachineBasicBlock *offsetMBB;
20065 MachineBasicBlock *endMBB;
20067 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
20068 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
20069 unsigned OffsetReg = 0;
20071 if (!UseGPOffset && !UseFPOffset) {
20072 // If we only pull from the overflow region, we don't create a branch.
20073 // We don't need to alter control flow.
20074 OffsetDestReg = 0; // unused
20075 OverflowDestReg = DestReg;
20077 offsetMBB = nullptr;
20078 overflowMBB = thisMBB;
20081 // First emit code to check if gp_offset (or fp_offset) is below the bound.
20082 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20083 // If not, pull from overflow_area. (branch to overflowMBB)
20088 // offsetMBB overflowMBB
20093 // Registers for the PHI in endMBB
20094 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20095 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20097 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20098 MachineFunction *MF = MBB->getParent();
20099 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20100 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20101 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20103 MachineFunction::iterator MBBIter = MBB;
20106 // Insert the new basic blocks
20107 MF->insert(MBBIter, offsetMBB);
20108 MF->insert(MBBIter, overflowMBB);
20109 MF->insert(MBBIter, endMBB);
20111 // Transfer the remainder of MBB and its successor edges to endMBB.
20112 endMBB->splice(endMBB->begin(), thisMBB,
20113 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20114 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20116 // Make offsetMBB and overflowMBB successors of thisMBB
20117 thisMBB->addSuccessor(offsetMBB);
20118 thisMBB->addSuccessor(overflowMBB);
20120 // endMBB is a successor of both offsetMBB and overflowMBB
20121 offsetMBB->addSuccessor(endMBB);
20122 overflowMBB->addSuccessor(endMBB);
20124 // Load the offset value into a register
20125 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20126 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20130 .addDisp(Disp, UseFPOffset ? 4 : 0)
20131 .addOperand(Segment)
20132 .setMemRefs(MMOBegin, MMOEnd);
20134 // Check if there is enough room left to pull this argument.
20135 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20137 .addImm(MaxOffset + 8 - ArgSizeA8);
20139 // Branch to "overflowMBB" if offset >= max
20140 // Fall through to "offsetMBB" otherwise
20141 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20142 .addMBB(overflowMBB);
20145 // In offsetMBB, emit code to use the reg_save_area.
20147 assert(OffsetReg != 0);
20149 // Read the reg_save_area address.
20150 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20151 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20156 .addOperand(Segment)
20157 .setMemRefs(MMOBegin, MMOEnd);
20159 // Zero-extend the offset
20160 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20161 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20164 .addImm(X86::sub_32bit);
20166 // Add the offset to the reg_save_area to get the final address.
20167 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20168 .addReg(OffsetReg64)
20169 .addReg(RegSaveReg);
20171 // Compute the offset for the next argument
20172 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20173 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20175 .addImm(UseFPOffset ? 16 : 8);
20177 // Store it back into the va_list.
20178 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20182 .addDisp(Disp, UseFPOffset ? 4 : 0)
20183 .addOperand(Segment)
20184 .addReg(NextOffsetReg)
20185 .setMemRefs(MMOBegin, MMOEnd);
20188 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20193 // Emit code to use overflow area
20196 // Load the overflow_area address into a register.
20197 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20198 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20203 .addOperand(Segment)
20204 .setMemRefs(MMOBegin, MMOEnd);
20206 // If we need to align it, do so. Otherwise, just copy the address
20207 // to OverflowDestReg.
20209 // Align the overflow address
20210 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20211 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20213 // aligned_addr = (addr + (align-1)) & ~(align-1)
20214 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20215 .addReg(OverflowAddrReg)
20218 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20220 .addImm(~(uint64_t)(Align-1));
20222 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20223 .addReg(OverflowAddrReg);
20226 // Compute the next overflow address after this argument.
20227 // (the overflow address should be kept 8-byte aligned)
20228 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20229 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20230 .addReg(OverflowDestReg)
20231 .addImm(ArgSizeA8);
20233 // Store the new overflow address.
20234 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20239 .addOperand(Segment)
20240 .addReg(NextAddrReg)
20241 .setMemRefs(MMOBegin, MMOEnd);
20243 // If we branched, emit the PHI to the front of endMBB.
20245 BuildMI(*endMBB, endMBB->begin(), DL,
20246 TII->get(X86::PHI), DestReg)
20247 .addReg(OffsetDestReg).addMBB(offsetMBB)
20248 .addReg(OverflowDestReg).addMBB(overflowMBB);
20251 // Erase the pseudo instruction
20252 MI->eraseFromParent();
20257 MachineBasicBlock *
20258 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20260 MachineBasicBlock *MBB) const {
20261 // Emit code to save XMM registers to the stack. The ABI says that the
20262 // number of registers to save is given in %al, so it's theoretically
20263 // possible to do an indirect jump trick to avoid saving all of them,
20264 // however this code takes a simpler approach and just executes all
20265 // of the stores if %al is non-zero. It's less code, and it's probably
20266 // easier on the hardware branch predictor, and stores aren't all that
20267 // expensive anyway.
20269 // Create the new basic blocks. One block contains all the XMM stores,
20270 // and one block is the final destination regardless of whether any
20271 // stores were performed.
20272 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20273 MachineFunction *F = MBB->getParent();
20274 MachineFunction::iterator MBBIter = MBB;
20276 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20277 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20278 F->insert(MBBIter, XMMSaveMBB);
20279 F->insert(MBBIter, EndMBB);
20281 // Transfer the remainder of MBB and its successor edges to EndMBB.
20282 EndMBB->splice(EndMBB->begin(), MBB,
20283 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20284 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20286 // The original block will now fall through to the XMM save block.
20287 MBB->addSuccessor(XMMSaveMBB);
20288 // The XMMSaveMBB will fall through to the end block.
20289 XMMSaveMBB->addSuccessor(EndMBB);
20291 // Now add the instructions.
20292 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20293 DebugLoc DL = MI->getDebugLoc();
20295 unsigned CountReg = MI->getOperand(0).getReg();
20296 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20297 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20299 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20300 // If %al is 0, branch around the XMM save block.
20301 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20302 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20303 MBB->addSuccessor(EndMBB);
20306 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20307 // that was just emitted, but clearly shouldn't be "saved".
20308 assert((MI->getNumOperands() <= 3 ||
20309 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20310 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20311 && "Expected last argument to be EFLAGS");
20312 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20313 // In the XMM save block, save all the XMM argument registers.
20314 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20315 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20316 MachineMemOperand *MMO = F->getMachineMemOperand(
20317 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20318 MachineMemOperand::MOStore,
20319 /*Size=*/16, /*Align=*/16);
20320 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20321 .addFrameIndex(RegSaveFrameIndex)
20322 .addImm(/*Scale=*/1)
20323 .addReg(/*IndexReg=*/0)
20324 .addImm(/*Disp=*/Offset)
20325 .addReg(/*Segment=*/0)
20326 .addReg(MI->getOperand(i).getReg())
20327 .addMemOperand(MMO);
20330 MI->eraseFromParent(); // The pseudo instruction is gone now.
20335 // The EFLAGS operand of SelectItr might be missing a kill marker
20336 // because there were multiple uses of EFLAGS, and ISel didn't know
20337 // which to mark. Figure out whether SelectItr should have had a
20338 // kill marker, and set it if it should. Returns the correct kill
20340 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20341 MachineBasicBlock* BB,
20342 const TargetRegisterInfo* TRI) {
20343 // Scan forward through BB for a use/def of EFLAGS.
20344 MachineBasicBlock::iterator miI(std::next(SelectItr));
20345 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20346 const MachineInstr& mi = *miI;
20347 if (mi.readsRegister(X86::EFLAGS))
20349 if (mi.definesRegister(X86::EFLAGS))
20350 break; // Should have kill-flag - update below.
20353 // If we hit the end of the block, check whether EFLAGS is live into a
20355 if (miI == BB->end()) {
20356 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20357 sEnd = BB->succ_end();
20358 sItr != sEnd; ++sItr) {
20359 MachineBasicBlock* succ = *sItr;
20360 if (succ->isLiveIn(X86::EFLAGS))
20365 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20366 // out. SelectMI should have a kill flag on EFLAGS.
20367 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20371 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20372 // together with other CMOV pseudo-opcodes into a single basic-block with
20373 // conditional jump around it.
20374 static bool isCMOVPseudo(MachineInstr *MI) {
20375 switch (MI->getOpcode()) {
20376 case X86::CMOV_FR32:
20377 case X86::CMOV_FR64:
20378 case X86::CMOV_GR8:
20379 case X86::CMOV_GR16:
20380 case X86::CMOV_GR32:
20381 case X86::CMOV_RFP32:
20382 case X86::CMOV_RFP64:
20383 case X86::CMOV_RFP80:
20384 case X86::CMOV_V2F64:
20385 case X86::CMOV_V2I64:
20386 case X86::CMOV_V4F32:
20387 case X86::CMOV_V4F64:
20388 case X86::CMOV_V4I64:
20389 case X86::CMOV_V16F32:
20390 case X86::CMOV_V8F32:
20391 case X86::CMOV_V8F64:
20392 case X86::CMOV_V8I64:
20393 case X86::CMOV_V8I1:
20394 case X86::CMOV_V16I1:
20395 case X86::CMOV_V32I1:
20396 case X86::CMOV_V64I1:
20404 MachineBasicBlock *
20405 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20406 MachineBasicBlock *BB) const {
20407 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20408 DebugLoc DL = MI->getDebugLoc();
20410 // To "insert" a SELECT_CC instruction, we actually have to insert the
20411 // diamond control-flow pattern. The incoming instruction knows the
20412 // destination vreg to set, the condition code register to branch on, the
20413 // true/false values to select between, and a branch opcode to use.
20414 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20415 MachineFunction::iterator It = BB;
20421 // cmpTY ccX, r1, r2
20423 // fallthrough --> copy0MBB
20424 MachineBasicBlock *thisMBB = BB;
20425 MachineFunction *F = BB->getParent();
20427 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20428 // as described above, by inserting a BB, and then making a PHI at the join
20429 // point to select the true and false operands of the CMOV in the PHI.
20431 // The code also handles two different cases of multiple CMOV opcodes
20435 // In this case, there are multiple CMOVs in a row, all which are based on
20436 // the same condition setting (or the exact opposite condition setting).
20437 // In this case we can lower all the CMOVs using a single inserted BB, and
20438 // then make a number of PHIs at the join point to model the CMOVs. The only
20439 // trickiness here, is that in a case like:
20441 // t2 = CMOV cond1 t1, f1
20442 // t3 = CMOV cond1 t2, f2
20444 // when rewriting this into PHIs, we have to perform some renaming on the
20445 // temps since you cannot have a PHI operand refer to a PHI result earlier
20446 // in the same block. The "simple" but wrong lowering would be:
20448 // t2 = PHI t1(BB1), f1(BB2)
20449 // t3 = PHI t2(BB1), f2(BB2)
20451 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20452 // renaming is to note that on the path through BB1, t2 is really just a
20453 // copy of t1, and do that renaming, properly generating:
20455 // t2 = PHI t1(BB1), f1(BB2)
20456 // t3 = PHI t1(BB1), f2(BB2)
20458 // Case 2, we lower cascaded CMOVs such as
20460 // (CMOV (CMOV F, T, cc1), T, cc2)
20462 // to two successives branches. For that, we look for another CMOV as the
20463 // following instruction.
20465 // Without this, we would add a PHI between the two jumps, which ends up
20466 // creating a few copies all around. For instance, for
20468 // (sitofp (zext (fcmp une)))
20470 // we would generate:
20472 // ucomiss %xmm1, %xmm0
20473 // movss <1.0f>, %xmm0
20474 // movaps %xmm0, %xmm1
20476 // xorps %xmm1, %xmm1
20479 // movaps %xmm1, %xmm0
20483 // because this custom-inserter would have generated:
20495 // A: X = ...; Y = ...
20497 // C: Z = PHI [X, A], [Y, B]
20499 // E: PHI [X, C], [Z, D]
20501 // If we lower both CMOVs in a single step, we can instead generate:
20513 // A: X = ...; Y = ...
20515 // E: PHI [X, A], [X, C], [Y, D]
20517 // Which, in our sitofp/fcmp example, gives us something like:
20519 // ucomiss %xmm1, %xmm0
20520 // movss <1.0f>, %xmm0
20523 // xorps %xmm0, %xmm0
20527 MachineInstr *CascadedCMOV = nullptr;
20528 MachineInstr *LastCMOV = MI;
20529 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20530 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20531 MachineBasicBlock::iterator NextMIIt =
20532 std::next(MachineBasicBlock::iterator(MI));
20534 // Check for case 1, where there are multiple CMOVs with the same condition
20535 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20536 // number of jumps the most.
20538 if (isCMOVPseudo(MI)) {
20539 // See if we have a string of CMOVS with the same condition.
20540 while (NextMIIt != BB->end() &&
20541 isCMOVPseudo(NextMIIt) &&
20542 (NextMIIt->getOperand(3).getImm() == CC ||
20543 NextMIIt->getOperand(3).getImm() == OppCC)) {
20544 LastCMOV = &*NextMIIt;
20549 // This checks for case 2, but only do this if we didn't already find
20550 // case 1, as indicated by LastCMOV == MI.
20551 if (LastCMOV == MI &&
20552 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20553 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20554 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20555 CascadedCMOV = &*NextMIIt;
20558 MachineBasicBlock *jcc1MBB = nullptr;
20560 // If we have a cascaded CMOV, we lower it to two successive branches to
20561 // the same block. EFLAGS is used by both, so mark it as live in the second.
20562 if (CascadedCMOV) {
20563 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20564 F->insert(It, jcc1MBB);
20565 jcc1MBB->addLiveIn(X86::EFLAGS);
20568 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20569 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20570 F->insert(It, copy0MBB);
20571 F->insert(It, sinkMBB);
20573 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20574 // live into the sink and copy blocks.
20575 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20577 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20578 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20579 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20580 copy0MBB->addLiveIn(X86::EFLAGS);
20581 sinkMBB->addLiveIn(X86::EFLAGS);
20584 // Transfer the remainder of BB and its successor edges to sinkMBB.
20585 sinkMBB->splice(sinkMBB->begin(), BB,
20586 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20587 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20589 // Add the true and fallthrough blocks as its successors.
20590 if (CascadedCMOV) {
20591 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20592 BB->addSuccessor(jcc1MBB);
20594 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20595 // jump to the sinkMBB.
20596 jcc1MBB->addSuccessor(copy0MBB);
20597 jcc1MBB->addSuccessor(sinkMBB);
20599 BB->addSuccessor(copy0MBB);
20602 // The true block target of the first (or only) branch is always sinkMBB.
20603 BB->addSuccessor(sinkMBB);
20605 // Create the conditional branch instruction.
20606 unsigned Opc = X86::GetCondBranchFromCond(CC);
20607 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20609 if (CascadedCMOV) {
20610 unsigned Opc2 = X86::GetCondBranchFromCond(
20611 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20612 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20616 // %FalseValue = ...
20617 // # fallthrough to sinkMBB
20618 copy0MBB->addSuccessor(sinkMBB);
20621 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20623 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20624 MachineBasicBlock::iterator MIItEnd =
20625 std::next(MachineBasicBlock::iterator(LastCMOV));
20626 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20627 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20628 MachineInstrBuilder MIB;
20630 // As we are creating the PHIs, we have to be careful if there is more than
20631 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20632 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20633 // That also means that PHI construction must work forward from earlier to
20634 // later, and that the code must maintain a mapping from earlier PHI's
20635 // destination registers, and the registers that went into the PHI.
20637 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20638 unsigned DestReg = MIIt->getOperand(0).getReg();
20639 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20640 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20642 // If this CMOV we are generating is the opposite condition from
20643 // the jump we generated, then we have to swap the operands for the
20644 // PHI that is going to be generated.
20645 if (MIIt->getOperand(3).getImm() == OppCC)
20646 std::swap(Op1Reg, Op2Reg);
20648 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20649 Op1Reg = RegRewriteTable[Op1Reg].first;
20651 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20652 Op2Reg = RegRewriteTable[Op2Reg].second;
20654 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20655 TII->get(X86::PHI), DestReg)
20656 .addReg(Op1Reg).addMBB(copy0MBB)
20657 .addReg(Op2Reg).addMBB(thisMBB);
20659 // Add this PHI to the rewrite table.
20660 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20663 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20664 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20665 if (CascadedCMOV) {
20666 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20667 // Copy the PHI result to the register defined by the second CMOV.
20668 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20669 DL, TII->get(TargetOpcode::COPY),
20670 CascadedCMOV->getOperand(0).getReg())
20671 .addReg(MI->getOperand(0).getReg());
20672 CascadedCMOV->eraseFromParent();
20675 // Now remove the CMOV(s).
20676 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20677 (MIIt++)->eraseFromParent();
20682 MachineBasicBlock *
20683 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20684 MachineBasicBlock *BB) const {
20685 // Combine the following atomic floating-point modification pattern:
20686 // a.store(reg OP a.load(acquire), release)
20687 // Transform them into:
20688 // OPss (%gpr), %xmm
20689 // movss %xmm, (%gpr)
20690 // Or sd equivalent for 64-bit operations.
20692 switch (MI->getOpcode()) {
20693 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20694 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20695 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20697 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20698 DebugLoc DL = MI->getDebugLoc();
20699 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20700 unsigned MSrc = MI->getOperand(0).getReg();
20701 unsigned VSrc = MI->getOperand(5).getReg();
20702 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20703 .addReg(/*Base=*/MSrc)
20704 .addImm(/*Scale=*/1)
20705 .addReg(/*Index=*/0)
20708 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20709 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20711 .addReg(/*Base=*/MSrc)
20712 .addImm(/*Scale=*/1)
20713 .addReg(/*Index=*/0)
20714 .addImm(/*Disp=*/0)
20715 .addReg(/*Segment=*/0);
20716 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20717 MI->eraseFromParent(); // The pseudo instruction is gone now.
20721 MachineBasicBlock *
20722 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20723 MachineBasicBlock *BB) const {
20724 MachineFunction *MF = BB->getParent();
20725 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20726 DebugLoc DL = MI->getDebugLoc();
20727 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20729 assert(MF->shouldSplitStack());
20731 const bool Is64Bit = Subtarget->is64Bit();
20732 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20734 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20735 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20738 // ... [Till the alloca]
20739 // If stacklet is not large enough, jump to mallocMBB
20742 // Allocate by subtracting from RSP
20743 // Jump to continueMBB
20746 // Allocate by call to runtime
20750 // [rest of original BB]
20753 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20754 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20755 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20757 MachineRegisterInfo &MRI = MF->getRegInfo();
20758 const TargetRegisterClass *AddrRegClass =
20759 getRegClassFor(getPointerTy(MF->getDataLayout()));
20761 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20762 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20763 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20764 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20765 sizeVReg = MI->getOperand(1).getReg(),
20766 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20768 MachineFunction::iterator MBBIter = BB;
20771 MF->insert(MBBIter, bumpMBB);
20772 MF->insert(MBBIter, mallocMBB);
20773 MF->insert(MBBIter, continueMBB);
20775 continueMBB->splice(continueMBB->begin(), BB,
20776 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20777 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20779 // Add code to the main basic block to check if the stack limit has been hit,
20780 // and if so, jump to mallocMBB otherwise to bumpMBB.
20781 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20782 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20783 .addReg(tmpSPVReg).addReg(sizeVReg);
20784 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20785 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20786 .addReg(SPLimitVReg);
20787 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20789 // bumpMBB simply decreases the stack pointer, since we know the current
20790 // stacklet has enough space.
20791 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20792 .addReg(SPLimitVReg);
20793 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20794 .addReg(SPLimitVReg);
20795 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20797 // Calls into a routine in libgcc to allocate more space from the heap.
20798 const uint32_t *RegMask =
20799 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20801 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20803 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20804 .addExternalSymbol("__morestack_allocate_stack_space")
20805 .addRegMask(RegMask)
20806 .addReg(X86::RDI, RegState::Implicit)
20807 .addReg(X86::RAX, RegState::ImplicitDefine);
20808 } else if (Is64Bit) {
20809 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20811 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20812 .addExternalSymbol("__morestack_allocate_stack_space")
20813 .addRegMask(RegMask)
20814 .addReg(X86::EDI, RegState::Implicit)
20815 .addReg(X86::EAX, RegState::ImplicitDefine);
20817 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20819 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20820 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20821 .addExternalSymbol("__morestack_allocate_stack_space")
20822 .addRegMask(RegMask)
20823 .addReg(X86::EAX, RegState::ImplicitDefine);
20827 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20830 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20831 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20832 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20834 // Set up the CFG correctly.
20835 BB->addSuccessor(bumpMBB);
20836 BB->addSuccessor(mallocMBB);
20837 mallocMBB->addSuccessor(continueMBB);
20838 bumpMBB->addSuccessor(continueMBB);
20840 // Take care of the PHI nodes.
20841 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20842 MI->getOperand(0).getReg())
20843 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20844 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20846 // Delete the original pseudo instruction.
20847 MI->eraseFromParent();
20850 return continueMBB;
20853 MachineBasicBlock *
20854 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20855 MachineBasicBlock *BB) const {
20856 DebugLoc DL = MI->getDebugLoc();
20858 assert(!Subtarget->isTargetMachO());
20860 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20863 MI->eraseFromParent(); // The pseudo instruction is gone now.
20867 MachineBasicBlock *
20868 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20869 MachineBasicBlock *BB) const {
20870 // This is pretty easy. We're taking the value that we received from
20871 // our load from the relocation, sticking it in either RDI (x86-64)
20872 // or EAX and doing an indirect call. The return value will then
20873 // be in the normal return register.
20874 MachineFunction *F = BB->getParent();
20875 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20876 DebugLoc DL = MI->getDebugLoc();
20878 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20879 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20881 // Get a register mask for the lowered call.
20882 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20883 // proper register mask.
20884 const uint32_t *RegMask =
20885 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20886 if (Subtarget->is64Bit()) {
20887 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20888 TII->get(X86::MOV64rm), X86::RDI)
20890 .addImm(0).addReg(0)
20891 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20892 MI->getOperand(3).getTargetFlags())
20894 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20895 addDirectMem(MIB, X86::RDI);
20896 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20897 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20898 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20899 TII->get(X86::MOV32rm), X86::EAX)
20901 .addImm(0).addReg(0)
20902 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20903 MI->getOperand(3).getTargetFlags())
20905 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20906 addDirectMem(MIB, X86::EAX);
20907 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20909 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20910 TII->get(X86::MOV32rm), X86::EAX)
20911 .addReg(TII->getGlobalBaseReg(F))
20912 .addImm(0).addReg(0)
20913 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20914 MI->getOperand(3).getTargetFlags())
20916 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20917 addDirectMem(MIB, X86::EAX);
20918 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20921 MI->eraseFromParent(); // The pseudo instruction is gone now.
20925 MachineBasicBlock *
20926 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20927 MachineBasicBlock *MBB) const {
20928 DebugLoc DL = MI->getDebugLoc();
20929 MachineFunction *MF = MBB->getParent();
20930 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20931 MachineRegisterInfo &MRI = MF->getRegInfo();
20933 const BasicBlock *BB = MBB->getBasicBlock();
20934 MachineFunction::iterator I = MBB;
20937 // Memory Reference
20938 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20939 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20942 unsigned MemOpndSlot = 0;
20944 unsigned CurOp = 0;
20946 DstReg = MI->getOperand(CurOp++).getReg();
20947 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20948 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20949 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20950 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20952 MemOpndSlot = CurOp;
20954 MVT PVT = getPointerTy(MF->getDataLayout());
20955 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20956 "Invalid Pointer Size!");
20958 // For v = setjmp(buf), we generate
20961 // buf[LabelOffset] = restoreMBB
20962 // SjLjSetup restoreMBB
20968 // v = phi(main, restore)
20971 // if base pointer being used, load it from frame
20974 MachineBasicBlock *thisMBB = MBB;
20975 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20976 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20977 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20978 MF->insert(I, mainMBB);
20979 MF->insert(I, sinkMBB);
20980 MF->push_back(restoreMBB);
20982 MachineInstrBuilder MIB;
20984 // Transfer the remainder of BB and its successor edges to sinkMBB.
20985 sinkMBB->splice(sinkMBB->begin(), MBB,
20986 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20987 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20990 unsigned PtrStoreOpc = 0;
20991 unsigned LabelReg = 0;
20992 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20993 Reloc::Model RM = MF->getTarget().getRelocationModel();
20994 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20995 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20997 // Prepare IP either in reg or imm.
20998 if (!UseImmLabel) {
20999 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21000 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21001 LabelReg = MRI.createVirtualRegister(PtrRC);
21002 if (Subtarget->is64Bit()) {
21003 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21007 .addMBB(restoreMBB)
21010 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21011 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21012 .addReg(XII->getGlobalBaseReg(MF))
21015 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21019 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21021 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21022 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21023 if (i == X86::AddrDisp)
21024 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21026 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21029 MIB.addReg(LabelReg);
21031 MIB.addMBB(restoreMBB);
21032 MIB.setMemRefs(MMOBegin, MMOEnd);
21034 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21035 .addMBB(restoreMBB);
21037 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21038 MIB.addRegMask(RegInfo->getNoPreservedMask());
21039 thisMBB->addSuccessor(mainMBB);
21040 thisMBB->addSuccessor(restoreMBB);
21044 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21045 mainMBB->addSuccessor(sinkMBB);
21048 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21049 TII->get(X86::PHI), DstReg)
21050 .addReg(mainDstReg).addMBB(mainMBB)
21051 .addReg(restoreDstReg).addMBB(restoreMBB);
21054 if (RegInfo->hasBasePointer(*MF)) {
21055 const bool Uses64BitFramePtr =
21056 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21057 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21058 X86FI->setRestoreBasePointer(MF);
21059 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21060 unsigned BasePtr = RegInfo->getBaseRegister();
21061 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21062 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21063 FramePtr, true, X86FI->getRestoreBasePointerOffset())
21064 .setMIFlag(MachineInstr::FrameSetup);
21066 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21067 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21068 restoreMBB->addSuccessor(sinkMBB);
21070 MI->eraseFromParent();
21074 MachineBasicBlock *
21075 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21076 MachineBasicBlock *MBB) const {
21077 DebugLoc DL = MI->getDebugLoc();
21078 MachineFunction *MF = MBB->getParent();
21079 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21080 MachineRegisterInfo &MRI = MF->getRegInfo();
21082 // Memory Reference
21083 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21084 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21086 MVT PVT = getPointerTy(MF->getDataLayout());
21087 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21088 "Invalid Pointer Size!");
21090 const TargetRegisterClass *RC =
21091 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21092 unsigned Tmp = MRI.createVirtualRegister(RC);
21093 // Since FP is only updated here but NOT referenced, it's treated as GPR.
21094 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21095 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21096 unsigned SP = RegInfo->getStackRegister();
21098 MachineInstrBuilder MIB;
21100 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21101 const int64_t SPOffset = 2 * PVT.getStoreSize();
21103 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21104 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21107 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21108 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21109 MIB.addOperand(MI->getOperand(i));
21110 MIB.setMemRefs(MMOBegin, MMOEnd);
21112 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21113 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21114 if (i == X86::AddrDisp)
21115 MIB.addDisp(MI->getOperand(i), LabelOffset);
21117 MIB.addOperand(MI->getOperand(i));
21119 MIB.setMemRefs(MMOBegin, MMOEnd);
21121 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21122 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21123 if (i == X86::AddrDisp)
21124 MIB.addDisp(MI->getOperand(i), SPOffset);
21126 MIB.addOperand(MI->getOperand(i));
21128 MIB.setMemRefs(MMOBegin, MMOEnd);
21130 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21132 MI->eraseFromParent();
21136 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21137 // accumulator loops. Writing back to the accumulator allows the coalescer
21138 // to remove extra copies in the loop.
21139 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
21140 MachineBasicBlock *
21141 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21142 MachineBasicBlock *MBB) const {
21143 MachineOperand &AddendOp = MI->getOperand(3);
21145 // Bail out early if the addend isn't a register - we can't switch these.
21146 if (!AddendOp.isReg())
21149 MachineFunction &MF = *MBB->getParent();
21150 MachineRegisterInfo &MRI = MF.getRegInfo();
21152 // Check whether the addend is defined by a PHI:
21153 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21154 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21155 if (!AddendDef.isPHI())
21158 // Look for the following pattern:
21160 // %addend = phi [%entry, 0], [%loop, %result]
21162 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21166 // %addend = phi [%entry, 0], [%loop, %result]
21168 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21170 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21171 assert(AddendDef.getOperand(i).isReg());
21172 MachineOperand PHISrcOp = AddendDef.getOperand(i);
21173 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21174 if (&PHISrcInst == MI) {
21175 // Found a matching instruction.
21176 unsigned NewFMAOpc = 0;
21177 switch (MI->getOpcode()) {
21178 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21179 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21180 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21181 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21182 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21183 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21184 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21185 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21186 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21187 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21188 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21189 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21190 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21191 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21192 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21193 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21194 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21195 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21196 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21197 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21199 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21200 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21201 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21202 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21203 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21204 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21205 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21206 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21207 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21208 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21209 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21210 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21211 default: llvm_unreachable("Unrecognized FMA variant.");
21214 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21215 MachineInstrBuilder MIB =
21216 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21217 .addOperand(MI->getOperand(0))
21218 .addOperand(MI->getOperand(3))
21219 .addOperand(MI->getOperand(2))
21220 .addOperand(MI->getOperand(1));
21221 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21222 MI->eraseFromParent();
21229 MachineBasicBlock *
21230 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21231 MachineBasicBlock *BB) const {
21232 switch (MI->getOpcode()) {
21233 default: llvm_unreachable("Unexpected instr type to insert");
21234 case X86::TAILJMPd64:
21235 case X86::TAILJMPr64:
21236 case X86::TAILJMPm64:
21237 case X86::TAILJMPd64_REX:
21238 case X86::TAILJMPr64_REX:
21239 case X86::TAILJMPm64_REX:
21240 llvm_unreachable("TAILJMP64 would not be touched here.");
21241 case X86::TCRETURNdi64:
21242 case X86::TCRETURNri64:
21243 case X86::TCRETURNmi64:
21245 case X86::WIN_ALLOCA:
21246 return EmitLoweredWinAlloca(MI, BB);
21247 case X86::SEG_ALLOCA_32:
21248 case X86::SEG_ALLOCA_64:
21249 return EmitLoweredSegAlloca(MI, BB);
21250 case X86::TLSCall_32:
21251 case X86::TLSCall_64:
21252 return EmitLoweredTLSCall(MI, BB);
21253 case X86::CMOV_FR32:
21254 case X86::CMOV_FR64:
21255 case X86::CMOV_GR8:
21256 case X86::CMOV_GR16:
21257 case X86::CMOV_GR32:
21258 case X86::CMOV_RFP32:
21259 case X86::CMOV_RFP64:
21260 case X86::CMOV_RFP80:
21261 case X86::CMOV_V2F64:
21262 case X86::CMOV_V2I64:
21263 case X86::CMOV_V4F32:
21264 case X86::CMOV_V4F64:
21265 case X86::CMOV_V4I64:
21266 case X86::CMOV_V16F32:
21267 case X86::CMOV_V8F32:
21268 case X86::CMOV_V8F64:
21269 case X86::CMOV_V8I64:
21270 case X86::CMOV_V8I1:
21271 case X86::CMOV_V16I1:
21272 case X86::CMOV_V32I1:
21273 case X86::CMOV_V64I1:
21274 return EmitLoweredSelect(MI, BB);
21276 case X86::RELEASE_FADD32mr:
21277 case X86::RELEASE_FADD64mr:
21278 return EmitLoweredAtomicFP(MI, BB);
21280 case X86::FP32_TO_INT16_IN_MEM:
21281 case X86::FP32_TO_INT32_IN_MEM:
21282 case X86::FP32_TO_INT64_IN_MEM:
21283 case X86::FP64_TO_INT16_IN_MEM:
21284 case X86::FP64_TO_INT32_IN_MEM:
21285 case X86::FP64_TO_INT64_IN_MEM:
21286 case X86::FP80_TO_INT16_IN_MEM:
21287 case X86::FP80_TO_INT32_IN_MEM:
21288 case X86::FP80_TO_INT64_IN_MEM: {
21289 MachineFunction *F = BB->getParent();
21290 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21291 DebugLoc DL = MI->getDebugLoc();
21293 // Change the floating point control register to use "round towards zero"
21294 // mode when truncating to an integer value.
21295 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21296 addFrameReference(BuildMI(*BB, MI, DL,
21297 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21299 // Load the old value of the high byte of the control word...
21301 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21302 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21305 // Set the high part to be round to zero...
21306 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21309 // Reload the modified control word now...
21310 addFrameReference(BuildMI(*BB, MI, DL,
21311 TII->get(X86::FLDCW16m)), CWFrameIdx);
21313 // Restore the memory image of control word to original value
21314 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21317 // Get the X86 opcode to use.
21319 switch (MI->getOpcode()) {
21320 default: llvm_unreachable("illegal opcode!");
21321 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21322 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21323 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21324 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21325 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21326 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21327 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21328 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21329 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21333 MachineOperand &Op = MI->getOperand(0);
21335 AM.BaseType = X86AddressMode::RegBase;
21336 AM.Base.Reg = Op.getReg();
21338 AM.BaseType = X86AddressMode::FrameIndexBase;
21339 AM.Base.FrameIndex = Op.getIndex();
21341 Op = MI->getOperand(1);
21343 AM.Scale = Op.getImm();
21344 Op = MI->getOperand(2);
21346 AM.IndexReg = Op.getImm();
21347 Op = MI->getOperand(3);
21348 if (Op.isGlobal()) {
21349 AM.GV = Op.getGlobal();
21351 AM.Disp = Op.getImm();
21353 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21354 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21356 // Reload the original control word now.
21357 addFrameReference(BuildMI(*BB, MI, DL,
21358 TII->get(X86::FLDCW16m)), CWFrameIdx);
21360 MI->eraseFromParent(); // The pseudo instruction is gone now.
21363 // String/text processing lowering.
21364 case X86::PCMPISTRM128REG:
21365 case X86::VPCMPISTRM128REG:
21366 case X86::PCMPISTRM128MEM:
21367 case X86::VPCMPISTRM128MEM:
21368 case X86::PCMPESTRM128REG:
21369 case X86::VPCMPESTRM128REG:
21370 case X86::PCMPESTRM128MEM:
21371 case X86::VPCMPESTRM128MEM:
21372 assert(Subtarget->hasSSE42() &&
21373 "Target must have SSE4.2 or AVX features enabled");
21374 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21376 // String/text processing lowering.
21377 case X86::PCMPISTRIREG:
21378 case X86::VPCMPISTRIREG:
21379 case X86::PCMPISTRIMEM:
21380 case X86::VPCMPISTRIMEM:
21381 case X86::PCMPESTRIREG:
21382 case X86::VPCMPESTRIREG:
21383 case X86::PCMPESTRIMEM:
21384 case X86::VPCMPESTRIMEM:
21385 assert(Subtarget->hasSSE42() &&
21386 "Target must have SSE4.2 or AVX features enabled");
21387 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21389 // Thread synchronization.
21391 return EmitMonitor(MI, BB, Subtarget);
21395 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21397 case X86::VASTART_SAVE_XMM_REGS:
21398 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21400 case X86::VAARG_64:
21401 return EmitVAARG64WithCustomInserter(MI, BB);
21403 case X86::EH_SjLj_SetJmp32:
21404 case X86::EH_SjLj_SetJmp64:
21405 return emitEHSjLjSetJmp(MI, BB);
21407 case X86::EH_SjLj_LongJmp32:
21408 case X86::EH_SjLj_LongJmp64:
21409 return emitEHSjLjLongJmp(MI, BB);
21411 case TargetOpcode::STATEPOINT:
21412 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21413 // this point in the process. We diverge later.
21414 return emitPatchPoint(MI, BB);
21416 case TargetOpcode::STACKMAP:
21417 case TargetOpcode::PATCHPOINT:
21418 return emitPatchPoint(MI, BB);
21420 case X86::VFMADDPDr213r:
21421 case X86::VFMADDPSr213r:
21422 case X86::VFMADDSDr213r:
21423 case X86::VFMADDSSr213r:
21424 case X86::VFMSUBPDr213r:
21425 case X86::VFMSUBPSr213r:
21426 case X86::VFMSUBSDr213r:
21427 case X86::VFMSUBSSr213r:
21428 case X86::VFNMADDPDr213r:
21429 case X86::VFNMADDPSr213r:
21430 case X86::VFNMADDSDr213r:
21431 case X86::VFNMADDSSr213r:
21432 case X86::VFNMSUBPDr213r:
21433 case X86::VFNMSUBPSr213r:
21434 case X86::VFNMSUBSDr213r:
21435 case X86::VFNMSUBSSr213r:
21436 case X86::VFMADDSUBPDr213r:
21437 case X86::VFMADDSUBPSr213r:
21438 case X86::VFMSUBADDPDr213r:
21439 case X86::VFMSUBADDPSr213r:
21440 case X86::VFMADDPDr213rY:
21441 case X86::VFMADDPSr213rY:
21442 case X86::VFMSUBPDr213rY:
21443 case X86::VFMSUBPSr213rY:
21444 case X86::VFNMADDPDr213rY:
21445 case X86::VFNMADDPSr213rY:
21446 case X86::VFNMSUBPDr213rY:
21447 case X86::VFNMSUBPSr213rY:
21448 case X86::VFMADDSUBPDr213rY:
21449 case X86::VFMADDSUBPSr213rY:
21450 case X86::VFMSUBADDPDr213rY:
21451 case X86::VFMSUBADDPSr213rY:
21452 return emitFMA3Instr(MI, BB);
21456 //===----------------------------------------------------------------------===//
21457 // X86 Optimization Hooks
21458 //===----------------------------------------------------------------------===//
21460 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21463 const SelectionDAG &DAG,
21464 unsigned Depth) const {
21465 unsigned BitWidth = KnownZero.getBitWidth();
21466 unsigned Opc = Op.getOpcode();
21467 assert((Opc >= ISD::BUILTIN_OP_END ||
21468 Opc == ISD::INTRINSIC_WO_CHAIN ||
21469 Opc == ISD::INTRINSIC_W_CHAIN ||
21470 Opc == ISD::INTRINSIC_VOID) &&
21471 "Should use MaskedValueIsZero if you don't know whether Op"
21472 " is a target node!");
21474 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21488 // These nodes' second result is a boolean.
21489 if (Op.getResNo() == 0)
21492 case X86ISD::SETCC:
21493 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21495 case ISD::INTRINSIC_WO_CHAIN: {
21496 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21497 unsigned NumLoBits = 0;
21500 case Intrinsic::x86_sse_movmsk_ps:
21501 case Intrinsic::x86_avx_movmsk_ps_256:
21502 case Intrinsic::x86_sse2_movmsk_pd:
21503 case Intrinsic::x86_avx_movmsk_pd_256:
21504 case Intrinsic::x86_mmx_pmovmskb:
21505 case Intrinsic::x86_sse2_pmovmskb_128:
21506 case Intrinsic::x86_avx2_pmovmskb: {
21507 // High bits of movmskp{s|d}, pmovmskb are known zero.
21509 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21510 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21511 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21512 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21513 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21514 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21515 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21516 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21518 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21527 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21529 const SelectionDAG &,
21530 unsigned Depth) const {
21531 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21532 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21533 return Op.getValueType().getScalarType().getSizeInBits();
21539 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21540 /// node is a GlobalAddress + offset.
21541 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21542 const GlobalValue* &GA,
21543 int64_t &Offset) const {
21544 if (N->getOpcode() == X86ISD::Wrapper) {
21545 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21546 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21547 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21551 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21554 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21555 /// same as extracting the high 128-bit part of 256-bit vector and then
21556 /// inserting the result into the low part of a new 256-bit vector
21557 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21558 EVT VT = SVOp->getValueType(0);
21559 unsigned NumElems = VT.getVectorNumElements();
21561 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21562 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21563 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21564 SVOp->getMaskElt(j) >= 0)
21570 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21571 /// same as extracting the low 128-bit part of 256-bit vector and then
21572 /// inserting the result into the high part of a new 256-bit vector
21573 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21574 EVT VT = SVOp->getValueType(0);
21575 unsigned NumElems = VT.getVectorNumElements();
21577 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21578 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21579 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21580 SVOp->getMaskElt(j) >= 0)
21586 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21587 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21588 TargetLowering::DAGCombinerInfo &DCI,
21589 const X86Subtarget* Subtarget) {
21591 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21592 SDValue V1 = SVOp->getOperand(0);
21593 SDValue V2 = SVOp->getOperand(1);
21594 EVT VT = SVOp->getValueType(0);
21595 unsigned NumElems = VT.getVectorNumElements();
21597 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21598 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21602 // V UNDEF BUILD_VECTOR UNDEF
21604 // CONCAT_VECTOR CONCAT_VECTOR
21607 // RESULT: V + zero extended
21609 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21610 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21611 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21614 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21617 // To match the shuffle mask, the first half of the mask should
21618 // be exactly the first vector, and all the rest a splat with the
21619 // first element of the second one.
21620 for (unsigned i = 0; i != NumElems/2; ++i)
21621 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21622 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21625 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21626 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21627 if (Ld->hasNUsesOfValue(1, 0)) {
21628 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21629 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21631 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21633 Ld->getPointerInfo(),
21634 Ld->getAlignment(),
21635 false/*isVolatile*/, true/*ReadMem*/,
21636 false/*WriteMem*/);
21638 // Make sure the newly-created LOAD is in the same position as Ld in
21639 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21640 // and update uses of Ld's output chain to use the TokenFactor.
21641 if (Ld->hasAnyUseOfValue(1)) {
21642 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21643 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21644 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21645 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21646 SDValue(ResNode.getNode(), 1));
21649 return DAG.getBitcast(VT, ResNode);
21653 // Emit a zeroed vector and insert the desired subvector on its
21655 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21656 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21657 return DCI.CombineTo(N, InsV);
21660 //===--------------------------------------------------------------------===//
21661 // Combine some shuffles into subvector extracts and inserts:
21664 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21665 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21666 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21667 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21668 return DCI.CombineTo(N, InsV);
21671 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21672 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21673 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21674 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21675 return DCI.CombineTo(N, InsV);
21681 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21684 /// This is the leaf of the recursive combinine below. When we have found some
21685 /// chain of single-use x86 shuffle instructions and accumulated the combined
21686 /// shuffle mask represented by them, this will try to pattern match that mask
21687 /// into either a single instruction if there is a special purpose instruction
21688 /// for this operation, or into a PSHUFB instruction which is a fully general
21689 /// instruction but should only be used to replace chains over a certain depth.
21690 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21691 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21692 TargetLowering::DAGCombinerInfo &DCI,
21693 const X86Subtarget *Subtarget) {
21694 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21696 // Find the operand that enters the chain. Note that multiple uses are OK
21697 // here, we're not going to remove the operand we find.
21698 SDValue Input = Op.getOperand(0);
21699 while (Input.getOpcode() == ISD::BITCAST)
21700 Input = Input.getOperand(0);
21702 MVT VT = Input.getSimpleValueType();
21703 MVT RootVT = Root.getSimpleValueType();
21706 // Just remove no-op shuffle masks.
21707 if (Mask.size() == 1) {
21708 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21713 // Use the float domain if the operand type is a floating point type.
21714 bool FloatDomain = VT.isFloatingPoint();
21716 // For floating point shuffles, we don't have free copies in the shuffle
21717 // instructions or the ability to load as part of the instruction, so
21718 // canonicalize their shuffles to UNPCK or MOV variants.
21720 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21721 // vectors because it can have a load folded into it that UNPCK cannot. This
21722 // doesn't preclude something switching to the shorter encoding post-RA.
21724 // FIXME: Should teach these routines about AVX vector widths.
21725 if (FloatDomain && VT.getSizeInBits() == 128) {
21726 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21727 bool Lo = Mask.equals({0, 0});
21730 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21731 // is no slower than UNPCKLPD but has the option to fold the input operand
21732 // into even an unaligned memory load.
21733 if (Lo && Subtarget->hasSSE3()) {
21734 Shuffle = X86ISD::MOVDDUP;
21735 ShuffleVT = MVT::v2f64;
21737 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21738 // than the UNPCK variants.
21739 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21740 ShuffleVT = MVT::v4f32;
21742 if (Depth == 1 && Root->getOpcode() == Shuffle)
21743 return false; // Nothing to do!
21744 Op = DAG.getBitcast(ShuffleVT, Input);
21745 DCI.AddToWorklist(Op.getNode());
21746 if (Shuffle == X86ISD::MOVDDUP)
21747 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21749 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21750 DCI.AddToWorklist(Op.getNode());
21751 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21755 if (Subtarget->hasSSE3() &&
21756 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21757 bool Lo = Mask.equals({0, 0, 2, 2});
21758 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21759 MVT ShuffleVT = MVT::v4f32;
21760 if (Depth == 1 && Root->getOpcode() == Shuffle)
21761 return false; // Nothing to do!
21762 Op = DAG.getBitcast(ShuffleVT, Input);
21763 DCI.AddToWorklist(Op.getNode());
21764 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21765 DCI.AddToWorklist(Op.getNode());
21766 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21770 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21771 bool Lo = Mask.equals({0, 0, 1, 1});
21772 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21773 MVT ShuffleVT = MVT::v4f32;
21774 if (Depth == 1 && Root->getOpcode() == Shuffle)
21775 return false; // Nothing to do!
21776 Op = DAG.getBitcast(ShuffleVT, Input);
21777 DCI.AddToWorklist(Op.getNode());
21778 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21779 DCI.AddToWorklist(Op.getNode());
21780 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21786 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21787 // variants as none of these have single-instruction variants that are
21788 // superior to the UNPCK formulation.
21789 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21790 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21791 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21792 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21794 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21795 bool Lo = Mask[0] == 0;
21796 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21797 if (Depth == 1 && Root->getOpcode() == Shuffle)
21798 return false; // Nothing to do!
21800 switch (Mask.size()) {
21802 ShuffleVT = MVT::v8i16;
21805 ShuffleVT = MVT::v16i8;
21808 llvm_unreachable("Impossible mask size!");
21810 Op = DAG.getBitcast(ShuffleVT, Input);
21811 DCI.AddToWorklist(Op.getNode());
21812 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21813 DCI.AddToWorklist(Op.getNode());
21814 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21819 // Don't try to re-form single instruction chains under any circumstances now
21820 // that we've done encoding canonicalization for them.
21824 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21825 // can replace them with a single PSHUFB instruction profitably. Intel's
21826 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21827 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21828 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21829 SmallVector<SDValue, 16> PSHUFBMask;
21830 int NumBytes = VT.getSizeInBits() / 8;
21831 int Ratio = NumBytes / Mask.size();
21832 for (int i = 0; i < NumBytes; ++i) {
21833 if (Mask[i / Ratio] == SM_SentinelUndef) {
21834 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21837 int M = Mask[i / Ratio] != SM_SentinelZero
21838 ? Ratio * Mask[i / Ratio] + i % Ratio
21840 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21842 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21843 Op = DAG.getBitcast(ByteVT, Input);
21844 DCI.AddToWorklist(Op.getNode());
21845 SDValue PSHUFBMaskOp =
21846 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21847 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21848 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21849 DCI.AddToWorklist(Op.getNode());
21850 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21855 // Failed to find any combines.
21859 /// \brief Fully generic combining of x86 shuffle instructions.
21861 /// This should be the last combine run over the x86 shuffle instructions. Once
21862 /// they have been fully optimized, this will recursively consider all chains
21863 /// of single-use shuffle instructions, build a generic model of the cumulative
21864 /// shuffle operation, and check for simpler instructions which implement this
21865 /// operation. We use this primarily for two purposes:
21867 /// 1) Collapse generic shuffles to specialized single instructions when
21868 /// equivalent. In most cases, this is just an encoding size win, but
21869 /// sometimes we will collapse multiple generic shuffles into a single
21870 /// special-purpose shuffle.
21871 /// 2) Look for sequences of shuffle instructions with 3 or more total
21872 /// instructions, and replace them with the slightly more expensive SSSE3
21873 /// PSHUFB instruction if available. We do this as the last combining step
21874 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21875 /// a suitable short sequence of other instructions. The PHUFB will either
21876 /// use a register or have to read from memory and so is slightly (but only
21877 /// slightly) more expensive than the other shuffle instructions.
21879 /// Because this is inherently a quadratic operation (for each shuffle in
21880 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21881 /// This should never be an issue in practice as the shuffle lowering doesn't
21882 /// produce sequences of more than 8 instructions.
21884 /// FIXME: We will currently miss some cases where the redundant shuffling
21885 /// would simplify under the threshold for PSHUFB formation because of
21886 /// combine-ordering. To fix this, we should do the redundant instruction
21887 /// combining in this recursive walk.
21888 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21889 ArrayRef<int> RootMask,
21890 int Depth, bool HasPSHUFB,
21892 TargetLowering::DAGCombinerInfo &DCI,
21893 const X86Subtarget *Subtarget) {
21894 // Bound the depth of our recursive combine because this is ultimately
21895 // quadratic in nature.
21899 // Directly rip through bitcasts to find the underlying operand.
21900 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21901 Op = Op.getOperand(0);
21903 MVT VT = Op.getSimpleValueType();
21904 if (!VT.isVector())
21905 return false; // Bail if we hit a non-vector.
21907 assert(Root.getSimpleValueType().isVector() &&
21908 "Shuffles operate on vector types!");
21909 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21910 "Can only combine shuffles of the same vector register size.");
21912 if (!isTargetShuffle(Op.getOpcode()))
21914 SmallVector<int, 16> OpMask;
21916 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21917 // We only can combine unary shuffles which we can decode the mask for.
21918 if (!HaveMask || !IsUnary)
21921 assert(VT.getVectorNumElements() == OpMask.size() &&
21922 "Different mask size from vector size!");
21923 assert(((RootMask.size() > OpMask.size() &&
21924 RootMask.size() % OpMask.size() == 0) ||
21925 (OpMask.size() > RootMask.size() &&
21926 OpMask.size() % RootMask.size() == 0) ||
21927 OpMask.size() == RootMask.size()) &&
21928 "The smaller number of elements must divide the larger.");
21929 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21930 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21931 assert(((RootRatio == 1 && OpRatio == 1) ||
21932 (RootRatio == 1) != (OpRatio == 1)) &&
21933 "Must not have a ratio for both incoming and op masks!");
21935 SmallVector<int, 16> Mask;
21936 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21938 // Merge this shuffle operation's mask into our accumulated mask. Note that
21939 // this shuffle's mask will be the first applied to the input, followed by the
21940 // root mask to get us all the way to the root value arrangement. The reason
21941 // for this order is that we are recursing up the operation chain.
21942 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21943 int RootIdx = i / RootRatio;
21944 if (RootMask[RootIdx] < 0) {
21945 // This is a zero or undef lane, we're done.
21946 Mask.push_back(RootMask[RootIdx]);
21950 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21951 int OpIdx = RootMaskedIdx / OpRatio;
21952 if (OpMask[OpIdx] < 0) {
21953 // The incoming lanes are zero or undef, it doesn't matter which ones we
21955 Mask.push_back(OpMask[OpIdx]);
21959 // Ok, we have non-zero lanes, map them through.
21960 Mask.push_back(OpMask[OpIdx] * OpRatio +
21961 RootMaskedIdx % OpRatio);
21964 // See if we can recurse into the operand to combine more things.
21965 switch (Op.getOpcode()) {
21966 case X86ISD::PSHUFB:
21968 case X86ISD::PSHUFD:
21969 case X86ISD::PSHUFHW:
21970 case X86ISD::PSHUFLW:
21971 if (Op.getOperand(0).hasOneUse() &&
21972 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21973 HasPSHUFB, DAG, DCI, Subtarget))
21977 case X86ISD::UNPCKL:
21978 case X86ISD::UNPCKH:
21979 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21980 // We can't check for single use, we have to check that this shuffle is the only user.
21981 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21982 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21983 HasPSHUFB, DAG, DCI, Subtarget))
21988 // Minor canonicalization of the accumulated shuffle mask to make it easier
21989 // to match below. All this does is detect masks with squential pairs of
21990 // elements, and shrink them to the half-width mask. It does this in a loop
21991 // so it will reduce the size of the mask to the minimal width mask which
21992 // performs an equivalent shuffle.
21993 SmallVector<int, 16> WidenedMask;
21994 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21995 Mask = std::move(WidenedMask);
21996 WidenedMask.clear();
21999 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22003 /// \brief Get the PSHUF-style mask from PSHUF node.
22005 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22006 /// PSHUF-style masks that can be reused with such instructions.
22007 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22008 MVT VT = N.getSimpleValueType();
22009 SmallVector<int, 4> Mask;
22011 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22015 // If we have more than 128-bits, only the low 128-bits of shuffle mask
22016 // matter. Check that the upper masks are repeats and remove them.
22017 if (VT.getSizeInBits() > 128) {
22018 int LaneElts = 128 / VT.getScalarSizeInBits();
22020 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22021 for (int j = 0; j < LaneElts; ++j)
22022 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22023 "Mask doesn't repeat in high 128-bit lanes!");
22025 Mask.resize(LaneElts);
22028 switch (N.getOpcode()) {
22029 case X86ISD::PSHUFD:
22031 case X86ISD::PSHUFLW:
22034 case X86ISD::PSHUFHW:
22035 Mask.erase(Mask.begin(), Mask.begin() + 4);
22036 for (int &M : Mask)
22040 llvm_unreachable("No valid shuffle instruction found!");
22044 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22046 /// We walk up the chain and look for a combinable shuffle, skipping over
22047 /// shuffles that we could hoist this shuffle's transformation past without
22048 /// altering anything.
22050 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22052 TargetLowering::DAGCombinerInfo &DCI) {
22053 assert(N.getOpcode() == X86ISD::PSHUFD &&
22054 "Called with something other than an x86 128-bit half shuffle!");
22057 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22058 // of the shuffles in the chain so that we can form a fresh chain to replace
22060 SmallVector<SDValue, 8> Chain;
22061 SDValue V = N.getOperand(0);
22062 for (; V.hasOneUse(); V = V.getOperand(0)) {
22063 switch (V.getOpcode()) {
22065 return SDValue(); // Nothing combined!
22068 // Skip bitcasts as we always know the type for the target specific
22072 case X86ISD::PSHUFD:
22073 // Found another dword shuffle.
22076 case X86ISD::PSHUFLW:
22077 // Check that the low words (being shuffled) are the identity in the
22078 // dword shuffle, and the high words are self-contained.
22079 if (Mask[0] != 0 || Mask[1] != 1 ||
22080 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22083 Chain.push_back(V);
22086 case X86ISD::PSHUFHW:
22087 // Check that the high words (being shuffled) are the identity in the
22088 // dword shuffle, and the low words are self-contained.
22089 if (Mask[2] != 2 || Mask[3] != 3 ||
22090 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22093 Chain.push_back(V);
22096 case X86ISD::UNPCKL:
22097 case X86ISD::UNPCKH:
22098 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22099 // shuffle into a preceding word shuffle.
22100 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22101 V.getSimpleValueType().getScalarType() != MVT::i16)
22104 // Search for a half-shuffle which we can combine with.
22105 unsigned CombineOp =
22106 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22107 if (V.getOperand(0) != V.getOperand(1) ||
22108 !V->isOnlyUserOf(V.getOperand(0).getNode()))
22110 Chain.push_back(V);
22111 V = V.getOperand(0);
22113 switch (V.getOpcode()) {
22115 return SDValue(); // Nothing to combine.
22117 case X86ISD::PSHUFLW:
22118 case X86ISD::PSHUFHW:
22119 if (V.getOpcode() == CombineOp)
22122 Chain.push_back(V);
22126 V = V.getOperand(0);
22130 } while (V.hasOneUse());
22133 // Break out of the loop if we break out of the switch.
22137 if (!V.hasOneUse())
22138 // We fell out of the loop without finding a viable combining instruction.
22141 // Merge this node's mask and our incoming mask.
22142 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22143 for (int &M : Mask)
22145 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22146 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22148 // Rebuild the chain around this new shuffle.
22149 while (!Chain.empty()) {
22150 SDValue W = Chain.pop_back_val();
22152 if (V.getValueType() != W.getOperand(0).getValueType())
22153 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22155 switch (W.getOpcode()) {
22157 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22159 case X86ISD::UNPCKL:
22160 case X86ISD::UNPCKH:
22161 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22164 case X86ISD::PSHUFD:
22165 case X86ISD::PSHUFLW:
22166 case X86ISD::PSHUFHW:
22167 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22171 if (V.getValueType() != N.getValueType())
22172 V = DAG.getBitcast(N.getValueType(), V);
22174 // Return the new chain to replace N.
22178 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22180 /// We walk up the chain, skipping shuffles of the other half and looking
22181 /// through shuffles which switch halves trying to find a shuffle of the same
22182 /// pair of dwords.
22183 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22185 TargetLowering::DAGCombinerInfo &DCI) {
22187 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22188 "Called with something other than an x86 128-bit half shuffle!");
22190 unsigned CombineOpcode = N.getOpcode();
22192 // Walk up a single-use chain looking for a combinable shuffle.
22193 SDValue V = N.getOperand(0);
22194 for (; V.hasOneUse(); V = V.getOperand(0)) {
22195 switch (V.getOpcode()) {
22197 return false; // Nothing combined!
22200 // Skip bitcasts as we always know the type for the target specific
22204 case X86ISD::PSHUFLW:
22205 case X86ISD::PSHUFHW:
22206 if (V.getOpcode() == CombineOpcode)
22209 // Other-half shuffles are no-ops.
22212 // Break out of the loop if we break out of the switch.
22216 if (!V.hasOneUse())
22217 // We fell out of the loop without finding a viable combining instruction.
22220 // Combine away the bottom node as its shuffle will be accumulated into
22221 // a preceding shuffle.
22222 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22224 // Record the old value.
22227 // Merge this node's mask and our incoming mask (adjusted to account for all
22228 // the pshufd instructions encountered).
22229 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22230 for (int &M : Mask)
22232 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22233 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22235 // Check that the shuffles didn't cancel each other out. If not, we need to
22236 // combine to the new one.
22238 // Replace the combinable shuffle with the combined one, updating all users
22239 // so that we re-evaluate the chain here.
22240 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22245 /// \brief Try to combine x86 target specific shuffles.
22246 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22247 TargetLowering::DAGCombinerInfo &DCI,
22248 const X86Subtarget *Subtarget) {
22250 MVT VT = N.getSimpleValueType();
22251 SmallVector<int, 4> Mask;
22253 switch (N.getOpcode()) {
22254 case X86ISD::PSHUFD:
22255 case X86ISD::PSHUFLW:
22256 case X86ISD::PSHUFHW:
22257 Mask = getPSHUFShuffleMask(N);
22258 assert(Mask.size() == 4);
22264 // Nuke no-op shuffles that show up after combining.
22265 if (isNoopShuffleMask(Mask))
22266 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22268 // Look for simplifications involving one or two shuffle instructions.
22269 SDValue V = N.getOperand(0);
22270 switch (N.getOpcode()) {
22273 case X86ISD::PSHUFLW:
22274 case X86ISD::PSHUFHW:
22275 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22277 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22278 return SDValue(); // We combined away this shuffle, so we're done.
22280 // See if this reduces to a PSHUFD which is no more expensive and can
22281 // combine with more operations. Note that it has to at least flip the
22282 // dwords as otherwise it would have been removed as a no-op.
22283 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22284 int DMask[] = {0, 1, 2, 3};
22285 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22286 DMask[DOffset + 0] = DOffset + 1;
22287 DMask[DOffset + 1] = DOffset + 0;
22288 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22289 V = DAG.getBitcast(DVT, V);
22290 DCI.AddToWorklist(V.getNode());
22291 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22292 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22293 DCI.AddToWorklist(V.getNode());
22294 return DAG.getBitcast(VT, V);
22297 // Look for shuffle patterns which can be implemented as a single unpack.
22298 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22299 // only works when we have a PSHUFD followed by two half-shuffles.
22300 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22301 (V.getOpcode() == X86ISD::PSHUFLW ||
22302 V.getOpcode() == X86ISD::PSHUFHW) &&
22303 V.getOpcode() != N.getOpcode() &&
22305 SDValue D = V.getOperand(0);
22306 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22307 D = D.getOperand(0);
22308 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22309 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22310 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22311 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22312 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22314 for (int i = 0; i < 4; ++i) {
22315 WordMask[i + NOffset] = Mask[i] + NOffset;
22316 WordMask[i + VOffset] = VMask[i] + VOffset;
22318 // Map the word mask through the DWord mask.
22320 for (int i = 0; i < 8; ++i)
22321 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22322 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22323 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22324 // We can replace all three shuffles with an unpack.
22325 V = DAG.getBitcast(VT, D.getOperand(0));
22326 DCI.AddToWorklist(V.getNode());
22327 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22336 case X86ISD::PSHUFD:
22337 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22346 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22348 /// We combine this directly on the abstract vector shuffle nodes so it is
22349 /// easier to generically match. We also insert dummy vector shuffle nodes for
22350 /// the operands which explicitly discard the lanes which are unused by this
22351 /// operation to try to flow through the rest of the combiner the fact that
22352 /// they're unused.
22353 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22355 EVT VT = N->getValueType(0);
22357 // We only handle target-independent shuffles.
22358 // FIXME: It would be easy and harmless to use the target shuffle mask
22359 // extraction tool to support more.
22360 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22363 auto *SVN = cast<ShuffleVectorSDNode>(N);
22364 ArrayRef<int> Mask = SVN->getMask();
22365 SDValue V1 = N->getOperand(0);
22366 SDValue V2 = N->getOperand(1);
22368 // We require the first shuffle operand to be the SUB node, and the second to
22369 // be the ADD node.
22370 // FIXME: We should support the commuted patterns.
22371 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22374 // If there are other uses of these operations we can't fold them.
22375 if (!V1->hasOneUse() || !V2->hasOneUse())
22378 // Ensure that both operations have the same operands. Note that we can
22379 // commute the FADD operands.
22380 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22381 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22382 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22385 // We're looking for blends between FADD and FSUB nodes. We insist on these
22386 // nodes being lined up in a specific expected pattern.
22387 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22388 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22389 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22392 // Only specific types are legal at this point, assert so we notice if and
22393 // when these change.
22394 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22395 VT == MVT::v4f64) &&
22396 "Unknown vector type encountered!");
22398 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22401 /// PerformShuffleCombine - Performs several different shuffle combines.
22402 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22403 TargetLowering::DAGCombinerInfo &DCI,
22404 const X86Subtarget *Subtarget) {
22406 SDValue N0 = N->getOperand(0);
22407 SDValue N1 = N->getOperand(1);
22408 EVT VT = N->getValueType(0);
22410 // Don't create instructions with illegal types after legalize types has run.
22411 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22412 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22415 // If we have legalized the vector types, look for blends of FADD and FSUB
22416 // nodes that we can fuse into an ADDSUB node.
22417 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22418 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22421 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22422 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22423 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22424 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22426 // During Type Legalization, when promoting illegal vector types,
22427 // the backend might introduce new shuffle dag nodes and bitcasts.
22429 // This code performs the following transformation:
22430 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22431 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22433 // We do this only if both the bitcast and the BINOP dag nodes have
22434 // one use. Also, perform this transformation only if the new binary
22435 // operation is legal. This is to avoid introducing dag nodes that
22436 // potentially need to be further expanded (or custom lowered) into a
22437 // less optimal sequence of dag nodes.
22438 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22439 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22440 N0.getOpcode() == ISD::BITCAST) {
22441 SDValue BC0 = N0.getOperand(0);
22442 EVT SVT = BC0.getValueType();
22443 unsigned Opcode = BC0.getOpcode();
22444 unsigned NumElts = VT.getVectorNumElements();
22446 if (BC0.hasOneUse() && SVT.isVector() &&
22447 SVT.getVectorNumElements() * 2 == NumElts &&
22448 TLI.isOperationLegal(Opcode, VT)) {
22449 bool CanFold = false;
22461 unsigned SVTNumElts = SVT.getVectorNumElements();
22462 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22463 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22464 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22465 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22466 CanFold = SVOp->getMaskElt(i) < 0;
22469 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22470 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22471 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22472 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22477 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22478 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22479 // consecutive, non-overlapping, and in the right order.
22480 SmallVector<SDValue, 16> Elts;
22481 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22482 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22484 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22487 if (isTargetShuffle(N->getOpcode())) {
22489 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22490 if (Shuffle.getNode())
22493 // Try recursively combining arbitrary sequences of x86 shuffle
22494 // instructions into higher-order shuffles. We do this after combining
22495 // specific PSHUF instruction sequences into their minimal form so that we
22496 // can evaluate how many specialized shuffle instructions are involved in
22497 // a particular chain.
22498 SmallVector<int, 1> NonceMask; // Just a placeholder.
22499 NonceMask.push_back(0);
22500 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22501 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22503 return SDValue(); // This routine will use CombineTo to replace N.
22509 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22510 /// specific shuffle of a load can be folded into a single element load.
22511 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22512 /// shuffles have been custom lowered so we need to handle those here.
22513 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22514 TargetLowering::DAGCombinerInfo &DCI) {
22515 if (DCI.isBeforeLegalizeOps())
22518 SDValue InVec = N->getOperand(0);
22519 SDValue EltNo = N->getOperand(1);
22521 if (!isa<ConstantSDNode>(EltNo))
22524 EVT OriginalVT = InVec.getValueType();
22526 if (InVec.getOpcode() == ISD::BITCAST) {
22527 // Don't duplicate a load with other uses.
22528 if (!InVec.hasOneUse())
22530 EVT BCVT = InVec.getOperand(0).getValueType();
22531 if (!BCVT.isVector() ||
22532 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22534 InVec = InVec.getOperand(0);
22537 EVT CurrentVT = InVec.getValueType();
22539 if (!isTargetShuffle(InVec.getOpcode()))
22542 // Don't duplicate a load with other uses.
22543 if (!InVec.hasOneUse())
22546 SmallVector<int, 16> ShuffleMask;
22548 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22549 ShuffleMask, UnaryShuffle))
22552 // Select the input vector, guarding against out of range extract vector.
22553 unsigned NumElems = CurrentVT.getVectorNumElements();
22554 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22555 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22556 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22557 : InVec.getOperand(1);
22559 // If inputs to shuffle are the same for both ops, then allow 2 uses
22560 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22561 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22563 if (LdNode.getOpcode() == ISD::BITCAST) {
22564 // Don't duplicate a load with other uses.
22565 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22568 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22569 LdNode = LdNode.getOperand(0);
22572 if (!ISD::isNormalLoad(LdNode.getNode()))
22575 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22577 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22580 EVT EltVT = N->getValueType(0);
22581 // If there's a bitcast before the shuffle, check if the load type and
22582 // alignment is valid.
22583 unsigned Align = LN0->getAlignment();
22584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22585 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22586 EltVT.getTypeForEVT(*DAG.getContext()));
22588 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22591 // All checks match so transform back to vector_shuffle so that DAG combiner
22592 // can finish the job
22595 // Create shuffle node taking into account the case that its a unary shuffle
22596 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22597 : InVec.getOperand(1);
22598 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22599 InVec.getOperand(0), Shuffle,
22601 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22602 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22606 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22607 /// special and don't usually play with other vector types, it's better to
22608 /// handle them early to be sure we emit efficient code by avoiding
22609 /// store-load conversions.
22610 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22611 if (N->getValueType(0) != MVT::x86mmx ||
22612 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22613 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22616 SDValue V = N->getOperand(0);
22617 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22618 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22619 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22620 N->getValueType(0), V.getOperand(0));
22625 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22626 /// generation and convert it from being a bunch of shuffles and extracts
22627 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22628 /// storing the value and loading scalars back, while for x64 we should
22629 /// use 64-bit extracts and shifts.
22630 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22631 TargetLowering::DAGCombinerInfo &DCI) {
22632 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22635 SDValue InputVector = N->getOperand(0);
22636 SDLoc dl(InputVector);
22637 // Detect mmx to i32 conversion through a v2i32 elt extract.
22638 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22639 N->getValueType(0) == MVT::i32 &&
22640 InputVector.getValueType() == MVT::v2i32) {
22642 // The bitcast source is a direct mmx result.
22643 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22644 if (MMXSrc.getValueType() == MVT::x86mmx)
22645 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22646 N->getValueType(0),
22647 InputVector.getNode()->getOperand(0));
22649 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22650 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22651 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22652 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22653 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22654 MMXSrcOp.getValueType() == MVT::v1i64 &&
22655 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22656 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22657 N->getValueType(0),
22658 MMXSrcOp.getOperand(0));
22661 EVT VT = N->getValueType(0);
22663 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22664 InputVector.getOpcode() == ISD::BITCAST &&
22665 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22666 uint64_t ExtractedElt =
22667 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22668 uint64_t InputValue =
22669 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22670 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22671 return DAG.getConstant(Res, dl, MVT::i1);
22673 // Only operate on vectors of 4 elements, where the alternative shuffling
22674 // gets to be more expensive.
22675 if (InputVector.getValueType() != MVT::v4i32)
22678 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22679 // single use which is a sign-extend or zero-extend, and all elements are
22681 SmallVector<SDNode *, 4> Uses;
22682 unsigned ExtractedElements = 0;
22683 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22684 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22685 if (UI.getUse().getResNo() != InputVector.getResNo())
22688 SDNode *Extract = *UI;
22689 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22692 if (Extract->getValueType(0) != MVT::i32)
22694 if (!Extract->hasOneUse())
22696 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22697 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22699 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22702 // Record which element was extracted.
22703 ExtractedElements |=
22704 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22706 Uses.push_back(Extract);
22709 // If not all the elements were used, this may not be worthwhile.
22710 if (ExtractedElements != 15)
22713 // Ok, we've now decided to do the transformation.
22714 // If 64-bit shifts are legal, use the extract-shift sequence,
22715 // otherwise bounce the vector off the cache.
22716 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22719 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22720 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22721 auto &DL = DAG.getDataLayout();
22722 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22723 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22724 DAG.getConstant(0, dl, VecIdxTy));
22725 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22726 DAG.getConstant(1, dl, VecIdxTy));
22728 SDValue ShAmt = DAG.getConstant(
22729 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22730 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22731 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22732 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22733 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22734 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22735 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22737 // Store the value to a temporary stack slot.
22738 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22739 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22740 MachinePointerInfo(), false, false, 0);
22742 EVT ElementType = InputVector.getValueType().getVectorElementType();
22743 unsigned EltSize = ElementType.getSizeInBits() / 8;
22745 // Replace each use (extract) with a load of the appropriate element.
22746 for (unsigned i = 0; i < 4; ++i) {
22747 uint64_t Offset = EltSize * i;
22748 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22749 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22751 SDValue ScalarAddr =
22752 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22754 // Load the scalar.
22755 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22756 ScalarAddr, MachinePointerInfo(),
22757 false, false, false, 0);
22762 // Replace the extracts
22763 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22764 UE = Uses.end(); UI != UE; ++UI) {
22765 SDNode *Extract = *UI;
22767 SDValue Idx = Extract->getOperand(1);
22768 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22769 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22772 // The replacement was made in place; don't return anything.
22777 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22778 const X86Subtarget *Subtarget) {
22780 SDValue Cond = N->getOperand(0);
22781 SDValue LHS = N->getOperand(1);
22782 SDValue RHS = N->getOperand(2);
22784 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22785 SDValue CondSrc = Cond->getOperand(0);
22786 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22787 Cond = CondSrc->getOperand(0);
22790 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22793 // A vselect where all conditions and data are constants can be optimized into
22794 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22795 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22796 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22799 unsigned MaskValue = 0;
22800 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22803 MVT VT = N->getSimpleValueType(0);
22804 unsigned NumElems = VT.getVectorNumElements();
22805 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22806 for (unsigned i = 0; i < NumElems; ++i) {
22807 // Be sure we emit undef where we can.
22808 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22809 ShuffleMask[i] = -1;
22811 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22814 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22815 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22817 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22820 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22822 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22823 TargetLowering::DAGCombinerInfo &DCI,
22824 const X86Subtarget *Subtarget) {
22826 SDValue Cond = N->getOperand(0);
22827 // Get the LHS/RHS of the select.
22828 SDValue LHS = N->getOperand(1);
22829 SDValue RHS = N->getOperand(2);
22830 EVT VT = LHS.getValueType();
22831 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22833 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22834 // instructions match the semantics of the common C idiom x<y?x:y but not
22835 // x<=y?x:y, because of how they handle negative zero (which can be
22836 // ignored in unsafe-math mode).
22837 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22838 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22839 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22840 (Subtarget->hasSSE2() ||
22841 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22842 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22844 unsigned Opcode = 0;
22845 // Check for x CC y ? x : y.
22846 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22847 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22851 // Converting this to a min would handle NaNs incorrectly, and swapping
22852 // the operands would cause it to handle comparisons between positive
22853 // and negative zero incorrectly.
22854 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22855 if (!DAG.getTarget().Options.UnsafeFPMath &&
22856 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22858 std::swap(LHS, RHS);
22860 Opcode = X86ISD::FMIN;
22863 // Converting this to a min would handle comparisons between positive
22864 // and negative zero incorrectly.
22865 if (!DAG.getTarget().Options.UnsafeFPMath &&
22866 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22868 Opcode = X86ISD::FMIN;
22871 // Converting this to a min would handle both negative zeros and NaNs
22872 // incorrectly, but we can swap the operands to fix both.
22873 std::swap(LHS, RHS);
22877 Opcode = X86ISD::FMIN;
22881 // Converting this to a max would handle comparisons between positive
22882 // and negative zero incorrectly.
22883 if (!DAG.getTarget().Options.UnsafeFPMath &&
22884 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22886 Opcode = X86ISD::FMAX;
22889 // Converting this to a max would handle NaNs incorrectly, and swapping
22890 // the operands would cause it to handle comparisons between positive
22891 // and negative zero incorrectly.
22892 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22893 if (!DAG.getTarget().Options.UnsafeFPMath &&
22894 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22896 std::swap(LHS, RHS);
22898 Opcode = X86ISD::FMAX;
22901 // Converting this to a max would handle both negative zeros and NaNs
22902 // incorrectly, but we can swap the operands to fix both.
22903 std::swap(LHS, RHS);
22907 Opcode = X86ISD::FMAX;
22910 // Check for x CC y ? y : x -- a min/max with reversed arms.
22911 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22912 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22916 // Converting this to a min would handle comparisons between positive
22917 // and negative zero incorrectly, and swapping the operands would
22918 // cause it to handle NaNs incorrectly.
22919 if (!DAG.getTarget().Options.UnsafeFPMath &&
22920 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22921 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22923 std::swap(LHS, RHS);
22925 Opcode = X86ISD::FMIN;
22928 // Converting this to a min would handle NaNs incorrectly.
22929 if (!DAG.getTarget().Options.UnsafeFPMath &&
22930 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22932 Opcode = X86ISD::FMIN;
22935 // Converting this to a min would handle both negative zeros and NaNs
22936 // incorrectly, but we can swap the operands to fix both.
22937 std::swap(LHS, RHS);
22941 Opcode = X86ISD::FMIN;
22945 // Converting this to a max would handle NaNs incorrectly.
22946 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22948 Opcode = X86ISD::FMAX;
22951 // Converting this to a max would handle comparisons between positive
22952 // and negative zero incorrectly, and swapping the operands would
22953 // cause it to handle NaNs incorrectly.
22954 if (!DAG.getTarget().Options.UnsafeFPMath &&
22955 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22956 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22958 std::swap(LHS, RHS);
22960 Opcode = X86ISD::FMAX;
22963 // Converting this to a max would handle both negative zeros and NaNs
22964 // incorrectly, but we can swap the operands to fix both.
22965 std::swap(LHS, RHS);
22969 Opcode = X86ISD::FMAX;
22975 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22978 EVT CondVT = Cond.getValueType();
22979 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22980 CondVT.getVectorElementType() == MVT::i1) {
22981 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22982 // lowering on KNL. In this case we convert it to
22983 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22984 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22985 // Since SKX these selects have a proper lowering.
22986 EVT OpVT = LHS.getValueType();
22987 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22988 (OpVT.getVectorElementType() == MVT::i8 ||
22989 OpVT.getVectorElementType() == MVT::i16) &&
22990 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22991 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22992 DCI.AddToWorklist(Cond.getNode());
22993 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22996 // If this is a select between two integer constants, try to do some
22998 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22999 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23000 // Don't do this for crazy integer types.
23001 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23002 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23003 // so that TrueC (the true value) is larger than FalseC.
23004 bool NeedsCondInvert = false;
23006 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23007 // Efficiently invertible.
23008 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
23009 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
23010 isa<ConstantSDNode>(Cond.getOperand(1))))) {
23011 NeedsCondInvert = true;
23012 std::swap(TrueC, FalseC);
23015 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
23016 if (FalseC->getAPIntValue() == 0 &&
23017 TrueC->getAPIntValue().isPowerOf2()) {
23018 if (NeedsCondInvert) // Invert the condition if needed.
23019 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23020 DAG.getConstant(1, DL, Cond.getValueType()));
23022 // Zero extend the condition if needed.
23023 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23025 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23026 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23027 DAG.getConstant(ShAmt, DL, MVT::i8));
23030 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23031 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23032 if (NeedsCondInvert) // Invert the condition if needed.
23033 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23034 DAG.getConstant(1, DL, Cond.getValueType()));
23036 // Zero extend the condition if needed.
23037 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23038 FalseC->getValueType(0), Cond);
23039 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23040 SDValue(FalseC, 0));
23043 // Optimize cases that will turn into an LEA instruction. This requires
23044 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23045 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23046 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23047 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23049 bool isFastMultiplier = false;
23051 switch ((unsigned char)Diff) {
23053 case 1: // result = add base, cond
23054 case 2: // result = lea base( , cond*2)
23055 case 3: // result = lea base(cond, cond*2)
23056 case 4: // result = lea base( , cond*4)
23057 case 5: // result = lea base(cond, cond*4)
23058 case 8: // result = lea base( , cond*8)
23059 case 9: // result = lea base(cond, cond*8)
23060 isFastMultiplier = true;
23065 if (isFastMultiplier) {
23066 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23067 if (NeedsCondInvert) // Invert the condition if needed.
23068 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23069 DAG.getConstant(1, DL, Cond.getValueType()));
23071 // Zero extend the condition if needed.
23072 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23074 // Scale the condition by the difference.
23076 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23077 DAG.getConstant(Diff, DL,
23078 Cond.getValueType()));
23080 // Add the base if non-zero.
23081 if (FalseC->getAPIntValue() != 0)
23082 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23083 SDValue(FalseC, 0));
23090 // Canonicalize max and min:
23091 // (x > y) ? x : y -> (x >= y) ? x : y
23092 // (x < y) ? x : y -> (x <= y) ? x : y
23093 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23094 // the need for an extra compare
23095 // against zero. e.g.
23096 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23098 // testl %edi, %edi
23100 // cmovgl %edi, %eax
23104 // cmovsl %eax, %edi
23105 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23106 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23107 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23108 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23113 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23114 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23115 Cond.getOperand(0), Cond.getOperand(1), NewCC);
23116 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23121 // Early exit check
23122 if (!TLI.isTypeLegal(VT))
23125 // Match VSELECTs into subs with unsigned saturation.
23126 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23127 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23128 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23129 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23130 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23132 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23133 // left side invert the predicate to simplify logic below.
23135 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23137 CC = ISD::getSetCCInverse(CC, true);
23138 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23142 if (Other.getNode() && Other->getNumOperands() == 2 &&
23143 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23144 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23145 SDValue CondRHS = Cond->getOperand(1);
23147 // Look for a general sub with unsigned saturation first.
23148 // x >= y ? x-y : 0 --> subus x, y
23149 // x > y ? x-y : 0 --> subus x, y
23150 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23151 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23152 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23154 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23155 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23156 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23157 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23158 // If the RHS is a constant we have to reverse the const
23159 // canonicalization.
23160 // x > C-1 ? x+-C : 0 --> subus x, C
23161 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23162 CondRHSConst->getAPIntValue() ==
23163 (-OpRHSConst->getAPIntValue() - 1))
23164 return DAG.getNode(
23165 X86ISD::SUBUS, DL, VT, OpLHS,
23166 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23168 // Another special case: If C was a sign bit, the sub has been
23169 // canonicalized into a xor.
23170 // FIXME: Would it be better to use computeKnownBits to determine
23171 // whether it's safe to decanonicalize the xor?
23172 // x s< 0 ? x^C : 0 --> subus x, C
23173 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23174 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23175 OpRHSConst->getAPIntValue().isSignBit())
23176 // Note that we have to rebuild the RHS constant here to ensure we
23177 // don't rely on particular values of undef lanes.
23178 return DAG.getNode(
23179 X86ISD::SUBUS, DL, VT, OpLHS,
23180 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23185 // Simplify vector selection if condition value type matches vselect
23187 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23188 assert(Cond.getValueType().isVector() &&
23189 "vector select expects a vector selector!");
23191 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23192 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23194 // Try invert the condition if true value is not all 1s and false value
23196 if (!TValIsAllOnes && !FValIsAllZeros &&
23197 // Check if the selector will be produced by CMPP*/PCMP*
23198 Cond.getOpcode() == ISD::SETCC &&
23199 // Check if SETCC has already been promoted
23200 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23202 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23203 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23205 if (TValIsAllZeros || FValIsAllOnes) {
23206 SDValue CC = Cond.getOperand(2);
23207 ISD::CondCode NewCC =
23208 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23209 Cond.getOperand(0).getValueType().isInteger());
23210 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23211 std::swap(LHS, RHS);
23212 TValIsAllOnes = FValIsAllOnes;
23213 FValIsAllZeros = TValIsAllZeros;
23217 if (TValIsAllOnes || FValIsAllZeros) {
23220 if (TValIsAllOnes && FValIsAllZeros)
23222 else if (TValIsAllOnes)
23224 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23225 else if (FValIsAllZeros)
23226 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23227 DAG.getBitcast(CondVT, LHS));
23229 return DAG.getBitcast(VT, Ret);
23233 // We should generate an X86ISD::BLENDI from a vselect if its argument
23234 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23235 // constants. This specific pattern gets generated when we split a
23236 // selector for a 512 bit vector in a machine without AVX512 (but with
23237 // 256-bit vectors), during legalization:
23239 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23241 // Iff we find this pattern and the build_vectors are built from
23242 // constants, we translate the vselect into a shuffle_vector that we
23243 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23244 if ((N->getOpcode() == ISD::VSELECT ||
23245 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23246 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23247 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23248 if (Shuffle.getNode())
23252 // If this is a *dynamic* select (non-constant condition) and we can match
23253 // this node with one of the variable blend instructions, restructure the
23254 // condition so that the blends can use the high bit of each element and use
23255 // SimplifyDemandedBits to simplify the condition operand.
23256 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23257 !DCI.isBeforeLegalize() &&
23258 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23259 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23261 // Don't optimize vector selects that map to mask-registers.
23265 // We can only handle the cases where VSELECT is directly legal on the
23266 // subtarget. We custom lower VSELECT nodes with constant conditions and
23267 // this makes it hard to see whether a dynamic VSELECT will correctly
23268 // lower, so we both check the operation's status and explicitly handle the
23269 // cases where a *dynamic* blend will fail even though a constant-condition
23270 // blend could be custom lowered.
23271 // FIXME: We should find a better way to handle this class of problems.
23272 // Potentially, we should combine constant-condition vselect nodes
23273 // pre-legalization into shuffles and not mark as many types as custom
23275 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23277 // FIXME: We don't support i16-element blends currently. We could and
23278 // should support them by making *all* the bits in the condition be set
23279 // rather than just the high bit and using an i8-element blend.
23280 if (VT.getScalarType() == MVT::i16)
23282 // Dynamic blending was only available from SSE4.1 onward.
23283 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23285 // Byte blends are only available in AVX2
23286 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23287 !Subtarget->hasAVX2())
23290 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23291 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23293 APInt KnownZero, KnownOne;
23294 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23295 DCI.isBeforeLegalizeOps());
23296 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23297 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23299 // If we changed the computation somewhere in the DAG, this change
23300 // will affect all users of Cond.
23301 // Make sure it is fine and update all the nodes so that we do not
23302 // use the generic VSELECT anymore. Otherwise, we may perform
23303 // wrong optimizations as we messed up with the actual expectation
23304 // for the vector boolean values.
23305 if (Cond != TLO.Old) {
23306 // Check all uses of that condition operand to check whether it will be
23307 // consumed by non-BLEND instructions, which may depend on all bits are
23309 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23311 if (I->getOpcode() != ISD::VSELECT)
23312 // TODO: Add other opcodes eventually lowered into BLEND.
23315 // Update all the users of the condition, before committing the change,
23316 // so that the VSELECT optimizations that expect the correct vector
23317 // boolean value will not be triggered.
23318 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23320 DAG.ReplaceAllUsesOfValueWith(
23322 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23323 Cond, I->getOperand(1), I->getOperand(2)));
23324 DCI.CommitTargetLoweringOpt(TLO);
23327 // At this point, only Cond is changed. Change the condition
23328 // just for N to keep the opportunity to optimize all other
23329 // users their own way.
23330 DAG.ReplaceAllUsesOfValueWith(
23332 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23333 TLO.New, N->getOperand(1), N->getOperand(2)));
23341 // Check whether a boolean test is testing a boolean value generated by
23342 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23345 // Simplify the following patterns:
23346 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23347 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23348 // to (Op EFLAGS Cond)
23350 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23351 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23352 // to (Op EFLAGS !Cond)
23354 // where Op could be BRCOND or CMOV.
23356 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23357 // Quit if not CMP and SUB with its value result used.
23358 if (Cmp.getOpcode() != X86ISD::CMP &&
23359 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23362 // Quit if not used as a boolean value.
23363 if (CC != X86::COND_E && CC != X86::COND_NE)
23366 // Check CMP operands. One of them should be 0 or 1 and the other should be
23367 // an SetCC or extended from it.
23368 SDValue Op1 = Cmp.getOperand(0);
23369 SDValue Op2 = Cmp.getOperand(1);
23372 const ConstantSDNode* C = nullptr;
23373 bool needOppositeCond = (CC == X86::COND_E);
23374 bool checkAgainstTrue = false; // Is it a comparison against 1?
23376 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23378 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23380 else // Quit if all operands are not constants.
23383 if (C->getZExtValue() == 1) {
23384 needOppositeCond = !needOppositeCond;
23385 checkAgainstTrue = true;
23386 } else if (C->getZExtValue() != 0)
23387 // Quit if the constant is neither 0 or 1.
23390 bool truncatedToBoolWithAnd = false;
23391 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23392 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23393 SetCC.getOpcode() == ISD::TRUNCATE ||
23394 SetCC.getOpcode() == ISD::AND) {
23395 if (SetCC.getOpcode() == ISD::AND) {
23397 ConstantSDNode *CS;
23398 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23399 CS->getZExtValue() == 1)
23401 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23402 CS->getZExtValue() == 1)
23406 SetCC = SetCC.getOperand(OpIdx);
23407 truncatedToBoolWithAnd = true;
23409 SetCC = SetCC.getOperand(0);
23412 switch (SetCC.getOpcode()) {
23413 case X86ISD::SETCC_CARRY:
23414 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23415 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23416 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23417 // truncated to i1 using 'and'.
23418 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23420 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23421 "Invalid use of SETCC_CARRY!");
23423 case X86ISD::SETCC:
23424 // Set the condition code or opposite one if necessary.
23425 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23426 if (needOppositeCond)
23427 CC = X86::GetOppositeBranchCondition(CC);
23428 return SetCC.getOperand(1);
23429 case X86ISD::CMOV: {
23430 // Check whether false/true value has canonical one, i.e. 0 or 1.
23431 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23432 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23433 // Quit if true value is not a constant.
23436 // Quit if false value is not a constant.
23438 SDValue Op = SetCC.getOperand(0);
23439 // Skip 'zext' or 'trunc' node.
23440 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23441 Op.getOpcode() == ISD::TRUNCATE)
23442 Op = Op.getOperand(0);
23443 // A special case for rdrand/rdseed, where 0 is set if false cond is
23445 if ((Op.getOpcode() != X86ISD::RDRAND &&
23446 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23449 // Quit if false value is not the constant 0 or 1.
23450 bool FValIsFalse = true;
23451 if (FVal && FVal->getZExtValue() != 0) {
23452 if (FVal->getZExtValue() != 1)
23454 // If FVal is 1, opposite cond is needed.
23455 needOppositeCond = !needOppositeCond;
23456 FValIsFalse = false;
23458 // Quit if TVal is not the constant opposite of FVal.
23459 if (FValIsFalse && TVal->getZExtValue() != 1)
23461 if (!FValIsFalse && TVal->getZExtValue() != 0)
23463 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23464 if (needOppositeCond)
23465 CC = X86::GetOppositeBranchCondition(CC);
23466 return SetCC.getOperand(3);
23473 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23475 /// (X86or (X86setcc) (X86setcc))
23476 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23477 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23478 X86::CondCode &CC1, SDValue &Flags,
23480 if (Cond->getOpcode() == X86ISD::CMP) {
23481 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23482 if (!CondOp1C || !CondOp1C->isNullValue())
23485 Cond = Cond->getOperand(0);
23490 SDValue SetCC0, SetCC1;
23491 switch (Cond->getOpcode()) {
23492 default: return false;
23499 SetCC0 = Cond->getOperand(0);
23500 SetCC1 = Cond->getOperand(1);
23504 // Make sure we have SETCC nodes, using the same flags value.
23505 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23506 SetCC1.getOpcode() != X86ISD::SETCC ||
23507 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23510 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23511 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23512 Flags = SetCC0->getOperand(1);
23516 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23517 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23518 TargetLowering::DAGCombinerInfo &DCI,
23519 const X86Subtarget *Subtarget) {
23522 // If the flag operand isn't dead, don't touch this CMOV.
23523 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23526 SDValue FalseOp = N->getOperand(0);
23527 SDValue TrueOp = N->getOperand(1);
23528 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23529 SDValue Cond = N->getOperand(3);
23531 if (CC == X86::COND_E || CC == X86::COND_NE) {
23532 switch (Cond.getOpcode()) {
23536 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23537 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23538 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23544 Flags = checkBoolTestSetCCCombine(Cond, CC);
23545 if (Flags.getNode() &&
23546 // Extra check as FCMOV only supports a subset of X86 cond.
23547 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23548 SDValue Ops[] = { FalseOp, TrueOp,
23549 DAG.getConstant(CC, DL, MVT::i8), Flags };
23550 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23553 // If this is a select between two integer constants, try to do some
23554 // optimizations. Note that the operands are ordered the opposite of SELECT
23556 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23557 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23558 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23559 // larger than FalseC (the false value).
23560 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23561 CC = X86::GetOppositeBranchCondition(CC);
23562 std::swap(TrueC, FalseC);
23563 std::swap(TrueOp, FalseOp);
23566 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23567 // This is efficient for any integer data type (including i8/i16) and
23569 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23570 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23571 DAG.getConstant(CC, DL, MVT::i8), Cond);
23573 // Zero extend the condition if needed.
23574 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23576 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23577 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23578 DAG.getConstant(ShAmt, DL, MVT::i8));
23579 if (N->getNumValues() == 2) // Dead flag value?
23580 return DCI.CombineTo(N, Cond, SDValue());
23584 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23585 // for any integer data type, including i8/i16.
23586 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23587 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23588 DAG.getConstant(CC, DL, MVT::i8), Cond);
23590 // Zero extend the condition if needed.
23591 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23592 FalseC->getValueType(0), Cond);
23593 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23594 SDValue(FalseC, 0));
23596 if (N->getNumValues() == 2) // Dead flag value?
23597 return DCI.CombineTo(N, Cond, SDValue());
23601 // Optimize cases that will turn into an LEA instruction. This requires
23602 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23603 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23604 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23605 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23607 bool isFastMultiplier = false;
23609 switch ((unsigned char)Diff) {
23611 case 1: // result = add base, cond
23612 case 2: // result = lea base( , cond*2)
23613 case 3: // result = lea base(cond, cond*2)
23614 case 4: // result = lea base( , cond*4)
23615 case 5: // result = lea base(cond, cond*4)
23616 case 8: // result = lea base( , cond*8)
23617 case 9: // result = lea base(cond, cond*8)
23618 isFastMultiplier = true;
23623 if (isFastMultiplier) {
23624 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23625 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23626 DAG.getConstant(CC, DL, MVT::i8), Cond);
23627 // Zero extend the condition if needed.
23628 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23630 // Scale the condition by the difference.
23632 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23633 DAG.getConstant(Diff, DL, Cond.getValueType()));
23635 // Add the base if non-zero.
23636 if (FalseC->getAPIntValue() != 0)
23637 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23638 SDValue(FalseC, 0));
23639 if (N->getNumValues() == 2) // Dead flag value?
23640 return DCI.CombineTo(N, Cond, SDValue());
23647 // Handle these cases:
23648 // (select (x != c), e, c) -> select (x != c), e, x),
23649 // (select (x == c), c, e) -> select (x == c), x, e)
23650 // where the c is an integer constant, and the "select" is the combination
23651 // of CMOV and CMP.
23653 // The rationale for this change is that the conditional-move from a constant
23654 // needs two instructions, however, conditional-move from a register needs
23655 // only one instruction.
23657 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23658 // some instruction-combining opportunities. This opt needs to be
23659 // postponed as late as possible.
23661 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23662 // the DCI.xxxx conditions are provided to postpone the optimization as
23663 // late as possible.
23665 ConstantSDNode *CmpAgainst = nullptr;
23666 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23667 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23668 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23670 if (CC == X86::COND_NE &&
23671 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23672 CC = X86::GetOppositeBranchCondition(CC);
23673 std::swap(TrueOp, FalseOp);
23676 if (CC == X86::COND_E &&
23677 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23678 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23679 DAG.getConstant(CC, DL, MVT::i8), Cond };
23680 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23685 // Fold and/or of setcc's to double CMOV:
23686 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23687 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23689 // This combine lets us generate:
23690 // cmovcc1 (jcc1 if we don't have CMOV)
23696 // cmovne (jne if we don't have CMOV)
23697 // When we can't use the CMOV instruction, it might increase branch
23699 // When we can use CMOV, or when there is no mispredict, this improves
23700 // throughput and reduces register pressure.
23702 if (CC == X86::COND_NE) {
23704 X86::CondCode CC0, CC1;
23706 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23708 std::swap(FalseOp, TrueOp);
23709 CC0 = X86::GetOppositeBranchCondition(CC0);
23710 CC1 = X86::GetOppositeBranchCondition(CC1);
23713 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23715 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23716 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23717 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23718 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23726 /// PerformMulCombine - Optimize a single multiply with constant into two
23727 /// in order to implement it with two cheaper instructions, e.g.
23728 /// LEA + SHL, LEA + LEA.
23729 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23730 TargetLowering::DAGCombinerInfo &DCI) {
23731 // An imul is usually smaller than the alternative sequence.
23732 if (DAG.getMachineFunction().getFunction()->optForMinSize())
23735 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23738 EVT VT = N->getValueType(0);
23739 if (VT != MVT::i64 && VT != MVT::i32)
23742 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23745 uint64_t MulAmt = C->getZExtValue();
23746 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23749 uint64_t MulAmt1 = 0;
23750 uint64_t MulAmt2 = 0;
23751 if ((MulAmt % 9) == 0) {
23753 MulAmt2 = MulAmt / 9;
23754 } else if ((MulAmt % 5) == 0) {
23756 MulAmt2 = MulAmt / 5;
23757 } else if ((MulAmt % 3) == 0) {
23759 MulAmt2 = MulAmt / 3;
23762 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23765 if (isPowerOf2_64(MulAmt2) &&
23766 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23767 // If second multiplifer is pow2, issue it first. We want the multiply by
23768 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23770 std::swap(MulAmt1, MulAmt2);
23773 if (isPowerOf2_64(MulAmt1))
23774 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23775 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23777 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23778 DAG.getConstant(MulAmt1, DL, VT));
23780 if (isPowerOf2_64(MulAmt2))
23781 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23782 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23784 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23785 DAG.getConstant(MulAmt2, DL, VT));
23787 // Do not add new nodes to DAG combiner worklist.
23788 DCI.CombineTo(N, NewMul, false);
23793 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23794 SDValue N0 = N->getOperand(0);
23795 SDValue N1 = N->getOperand(1);
23796 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23797 EVT VT = N0.getValueType();
23799 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23800 // since the result of setcc_c is all zero's or all ones.
23801 if (VT.isInteger() && !VT.isVector() &&
23802 N1C && N0.getOpcode() == ISD::AND &&
23803 N0.getOperand(1).getOpcode() == ISD::Constant) {
23804 SDValue N00 = N0.getOperand(0);
23805 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23806 APInt ShAmt = N1C->getAPIntValue();
23807 Mask = Mask.shl(ShAmt);
23808 bool MaskOK = false;
23809 // We can handle cases concerning bit-widening nodes containing setcc_c if
23810 // we carefully interrogate the mask to make sure we are semantics
23812 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23813 // of the underlying setcc_c operation if the setcc_c was zero extended.
23814 // Consider the following example:
23815 // zext(setcc_c) -> i32 0x0000FFFF
23816 // c1 -> i32 0x0000FFFF
23817 // c2 -> i32 0x00000001
23818 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23819 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
23820 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23822 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23823 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23825 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23826 N00.getOpcode() == ISD::ANY_EXTEND) &&
23827 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23828 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23830 if (MaskOK && Mask != 0) {
23832 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23836 // Hardware support for vector shifts is sparse which makes us scalarize the
23837 // vector operations in many cases. Also, on sandybridge ADD is faster than
23839 // (shl V, 1) -> add V,V
23840 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23841 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23842 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23843 // We shift all of the values by one. In many cases we do not have
23844 // hardware support for this operation. This is better expressed as an ADD
23846 if (N1SplatC->getAPIntValue() == 1)
23847 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23853 /// \brief Returns a vector of 0s if the node in input is a vector logical
23854 /// shift by a constant amount which is known to be bigger than or equal
23855 /// to the vector element size in bits.
23856 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23857 const X86Subtarget *Subtarget) {
23858 EVT VT = N->getValueType(0);
23860 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23861 (!Subtarget->hasInt256() ||
23862 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23865 SDValue Amt = N->getOperand(1);
23867 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23868 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23869 APInt ShiftAmt = AmtSplat->getAPIntValue();
23870 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23872 // SSE2/AVX2 logical shifts always return a vector of 0s
23873 // if the shift amount is bigger than or equal to
23874 // the element size. The constant shift amount will be
23875 // encoded as a 8-bit immediate.
23876 if (ShiftAmt.trunc(8).uge(MaxAmount))
23877 return getZeroVector(VT, Subtarget, DAG, DL);
23883 /// PerformShiftCombine - Combine shifts.
23884 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23885 TargetLowering::DAGCombinerInfo &DCI,
23886 const X86Subtarget *Subtarget) {
23887 if (N->getOpcode() == ISD::SHL)
23888 if (SDValue V = PerformSHLCombine(N, DAG))
23891 // Try to fold this logical shift into a zero vector.
23892 if (N->getOpcode() != ISD::SRA)
23893 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23899 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23900 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23901 // and friends. Likewise for OR -> CMPNEQSS.
23902 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23903 TargetLowering::DAGCombinerInfo &DCI,
23904 const X86Subtarget *Subtarget) {
23907 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23908 // we're requiring SSE2 for both.
23909 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23910 SDValue N0 = N->getOperand(0);
23911 SDValue N1 = N->getOperand(1);
23912 SDValue CMP0 = N0->getOperand(1);
23913 SDValue CMP1 = N1->getOperand(1);
23916 // The SETCCs should both refer to the same CMP.
23917 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23920 SDValue CMP00 = CMP0->getOperand(0);
23921 SDValue CMP01 = CMP0->getOperand(1);
23922 EVT VT = CMP00.getValueType();
23924 if (VT == MVT::f32 || VT == MVT::f64) {
23925 bool ExpectingFlags = false;
23926 // Check for any users that want flags:
23927 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23928 !ExpectingFlags && UI != UE; ++UI)
23929 switch (UI->getOpcode()) {
23934 ExpectingFlags = true;
23936 case ISD::CopyToReg:
23937 case ISD::SIGN_EXTEND:
23938 case ISD::ZERO_EXTEND:
23939 case ISD::ANY_EXTEND:
23943 if (!ExpectingFlags) {
23944 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23945 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23947 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23948 X86::CondCode tmp = cc0;
23953 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23954 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23955 // FIXME: need symbolic constants for these magic numbers.
23956 // See X86ATTInstPrinter.cpp:printSSECC().
23957 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23958 if (Subtarget->hasAVX512()) {
23959 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23961 DAG.getConstant(x86cc, DL, MVT::i8));
23962 if (N->getValueType(0) != MVT::i1)
23963 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23967 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23968 CMP00.getValueType(), CMP00, CMP01,
23969 DAG.getConstant(x86cc, DL,
23972 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23973 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23975 if (is64BitFP && !Subtarget->is64Bit()) {
23976 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23977 // 64-bit integer, since that's not a legal type. Since
23978 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23979 // bits, but can do this little dance to extract the lowest 32 bits
23980 // and work with those going forward.
23981 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23983 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23984 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23985 Vector32, DAG.getIntPtrConstant(0, DL));
23989 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23990 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23991 DAG.getConstant(1, DL, IntVT));
23992 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23994 return OneBitOfTruth;
24002 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24003 /// so it can be folded inside ANDNP.
24004 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24005 EVT VT = N->getValueType(0);
24007 // Match direct AllOnes for 128 and 256-bit vectors
24008 if (ISD::isBuildVectorAllOnes(N))
24011 // Look through a bit convert.
24012 if (N->getOpcode() == ISD::BITCAST)
24013 N = N->getOperand(0).getNode();
24015 // Sometimes the operand may come from a insert_subvector building a 256-bit
24017 if (VT.is256BitVector() &&
24018 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24019 SDValue V1 = N->getOperand(0);
24020 SDValue V2 = N->getOperand(1);
24022 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24023 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24024 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24025 ISD::isBuildVectorAllOnes(V2.getNode()))
24032 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24033 // register. In most cases we actually compare or select YMM-sized registers
24034 // and mixing the two types creates horrible code. This method optimizes
24035 // some of the transition sequences.
24036 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24037 TargetLowering::DAGCombinerInfo &DCI,
24038 const X86Subtarget *Subtarget) {
24039 EVT VT = N->getValueType(0);
24040 if (!VT.is256BitVector())
24043 assert((N->getOpcode() == ISD::ANY_EXTEND ||
24044 N->getOpcode() == ISD::ZERO_EXTEND ||
24045 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24047 SDValue Narrow = N->getOperand(0);
24048 EVT NarrowVT = Narrow->getValueType(0);
24049 if (!NarrowVT.is128BitVector())
24052 if (Narrow->getOpcode() != ISD::XOR &&
24053 Narrow->getOpcode() != ISD::AND &&
24054 Narrow->getOpcode() != ISD::OR)
24057 SDValue N0 = Narrow->getOperand(0);
24058 SDValue N1 = Narrow->getOperand(1);
24061 // The Left side has to be a trunc.
24062 if (N0.getOpcode() != ISD::TRUNCATE)
24065 // The type of the truncated inputs.
24066 EVT WideVT = N0->getOperand(0)->getValueType(0);
24070 // The right side has to be a 'trunc' or a constant vector.
24071 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24072 ConstantSDNode *RHSConstSplat = nullptr;
24073 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24074 RHSConstSplat = RHSBV->getConstantSplatNode();
24075 if (!RHSTrunc && !RHSConstSplat)
24078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24080 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24083 // Set N0 and N1 to hold the inputs to the new wide operation.
24084 N0 = N0->getOperand(0);
24085 if (RHSConstSplat) {
24086 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24087 SDValue(RHSConstSplat, 0));
24088 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24089 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24090 } else if (RHSTrunc) {
24091 N1 = N1->getOperand(0);
24094 // Generate the wide operation.
24095 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24096 unsigned Opcode = N->getOpcode();
24098 case ISD::ANY_EXTEND:
24100 case ISD::ZERO_EXTEND: {
24101 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24102 APInt Mask = APInt::getAllOnesValue(InBits);
24103 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24104 return DAG.getNode(ISD::AND, DL, VT,
24105 Op, DAG.getConstant(Mask, DL, VT));
24107 case ISD::SIGN_EXTEND:
24108 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24109 Op, DAG.getValueType(NarrowVT));
24111 llvm_unreachable("Unexpected opcode");
24115 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24116 TargetLowering::DAGCombinerInfo &DCI,
24117 const X86Subtarget *Subtarget) {
24118 SDValue N0 = N->getOperand(0);
24119 SDValue N1 = N->getOperand(1);
24122 // A vector zext_in_reg may be represented as a shuffle,
24123 // feeding into a bitcast (this represents anyext) feeding into
24124 // an and with a mask.
24125 // We'd like to try to combine that into a shuffle with zero
24126 // plus a bitcast, removing the and.
24127 if (N0.getOpcode() != ISD::BITCAST ||
24128 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24131 // The other side of the AND should be a splat of 2^C, where C
24132 // is the number of bits in the source type.
24133 if (N1.getOpcode() == ISD::BITCAST)
24134 N1 = N1.getOperand(0);
24135 if (N1.getOpcode() != ISD::BUILD_VECTOR)
24137 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24139 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24140 EVT SrcType = Shuffle->getValueType(0);
24142 // We expect a single-source shuffle
24143 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24146 unsigned SrcSize = SrcType.getScalarSizeInBits();
24148 APInt SplatValue, SplatUndef;
24149 unsigned SplatBitSize;
24151 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24152 SplatBitSize, HasAnyUndefs))
24155 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24156 // Make sure the splat matches the mask we expect
24157 if (SplatBitSize > ResSize ||
24158 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24161 // Make sure the input and output size make sense
24162 if (SrcSize >= ResSize || ResSize % SrcSize)
24165 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24166 // The number of u's between each two values depends on the ratio between
24167 // the source and dest type.
24168 unsigned ZextRatio = ResSize / SrcSize;
24169 bool IsZext = true;
24170 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24171 if (i % ZextRatio) {
24172 if (Shuffle->getMaskElt(i) > 0) {
24178 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24179 // Expected element number
24189 // Ok, perform the transformation - replace the shuffle with
24190 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24191 // (instead of undef) where the k elements come from the zero vector.
24192 SmallVector<int, 8> Mask;
24193 unsigned NumElems = SrcType.getVectorNumElements();
24194 for (unsigned i = 0; i < NumElems; ++i)
24196 Mask.push_back(NumElems);
24198 Mask.push_back(i / ZextRatio);
24200 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24201 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24202 return DAG.getBitcast(N0.getValueType(), NewShuffle);
24205 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24206 TargetLowering::DAGCombinerInfo &DCI,
24207 const X86Subtarget *Subtarget) {
24208 if (DCI.isBeforeLegalizeOps())
24211 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24214 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24217 EVT VT = N->getValueType(0);
24218 SDValue N0 = N->getOperand(0);
24219 SDValue N1 = N->getOperand(1);
24222 // Create BEXTR instructions
24223 // BEXTR is ((X >> imm) & (2**size-1))
24224 if (VT == MVT::i32 || VT == MVT::i64) {
24225 // Check for BEXTR.
24226 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24227 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24228 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24229 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24230 if (MaskNode && ShiftNode) {
24231 uint64_t Mask = MaskNode->getZExtValue();
24232 uint64_t Shift = ShiftNode->getZExtValue();
24233 if (isMask_64(Mask)) {
24234 uint64_t MaskSize = countPopulation(Mask);
24235 if (Shift + MaskSize <= VT.getSizeInBits())
24236 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24237 DAG.getConstant(Shift | (MaskSize << 8), DL,
24246 // Want to form ANDNP nodes:
24247 // 1) In the hopes of then easily combining them with OR and AND nodes
24248 // to form PBLEND/PSIGN.
24249 // 2) To match ANDN packed intrinsics
24250 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24253 // Check LHS for vnot
24254 if (N0.getOpcode() == ISD::XOR &&
24255 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24256 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24257 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24259 // Check RHS for vnot
24260 if (N1.getOpcode() == ISD::XOR &&
24261 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24262 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24263 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24268 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24269 TargetLowering::DAGCombinerInfo &DCI,
24270 const X86Subtarget *Subtarget) {
24271 if (DCI.isBeforeLegalizeOps())
24274 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24277 SDValue N0 = N->getOperand(0);
24278 SDValue N1 = N->getOperand(1);
24279 EVT VT = N->getValueType(0);
24281 // look for psign/blend
24282 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24283 if (!Subtarget->hasSSSE3() ||
24284 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24287 // Canonicalize pandn to RHS
24288 if (N0.getOpcode() == X86ISD::ANDNP)
24290 // or (and (m, y), (pandn m, x))
24291 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24292 SDValue Mask = N1.getOperand(0);
24293 SDValue X = N1.getOperand(1);
24295 if (N0.getOperand(0) == Mask)
24296 Y = N0.getOperand(1);
24297 if (N0.getOperand(1) == Mask)
24298 Y = N0.getOperand(0);
24300 // Check to see if the mask appeared in both the AND and ANDNP and
24304 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24305 // Look through mask bitcast.
24306 if (Mask.getOpcode() == ISD::BITCAST)
24307 Mask = Mask.getOperand(0);
24308 if (X.getOpcode() == ISD::BITCAST)
24309 X = X.getOperand(0);
24310 if (Y.getOpcode() == ISD::BITCAST)
24311 Y = Y.getOperand(0);
24313 EVT MaskVT = Mask.getValueType();
24315 // Validate that the Mask operand is a vector sra node.
24316 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24317 // there is no psrai.b
24318 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24319 unsigned SraAmt = ~0;
24320 if (Mask.getOpcode() == ISD::SRA) {
24321 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24322 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24323 SraAmt = AmtConst->getZExtValue();
24324 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24325 SDValue SraC = Mask.getOperand(1);
24326 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24328 if ((SraAmt + 1) != EltBits)
24333 // Now we know we at least have a plendvb with the mask val. See if
24334 // we can form a psignb/w/d.
24335 // psign = x.type == y.type == mask.type && y = sub(0, x);
24336 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24337 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24338 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24339 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24340 "Unsupported VT for PSIGN");
24341 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24342 return DAG.getBitcast(VT, Mask);
24344 // PBLENDVB only available on SSE 4.1
24345 if (!Subtarget->hasSSE41())
24348 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24350 X = DAG.getBitcast(BlendVT, X);
24351 Y = DAG.getBitcast(BlendVT, Y);
24352 Mask = DAG.getBitcast(BlendVT, Mask);
24353 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24354 return DAG.getBitcast(VT, Mask);
24358 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24361 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24362 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24364 // SHLD/SHRD instructions have lower register pressure, but on some
24365 // platforms they have higher latency than the equivalent
24366 // series of shifts/or that would otherwise be generated.
24367 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24368 // have higher latencies and we are not optimizing for size.
24369 if (!OptForSize && Subtarget->isSHLDSlow())
24372 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24374 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24376 if (!N0.hasOneUse() || !N1.hasOneUse())
24379 SDValue ShAmt0 = N0.getOperand(1);
24380 if (ShAmt0.getValueType() != MVT::i8)
24382 SDValue ShAmt1 = N1.getOperand(1);
24383 if (ShAmt1.getValueType() != MVT::i8)
24385 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24386 ShAmt0 = ShAmt0.getOperand(0);
24387 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24388 ShAmt1 = ShAmt1.getOperand(0);
24391 unsigned Opc = X86ISD::SHLD;
24392 SDValue Op0 = N0.getOperand(0);
24393 SDValue Op1 = N1.getOperand(0);
24394 if (ShAmt0.getOpcode() == ISD::SUB) {
24395 Opc = X86ISD::SHRD;
24396 std::swap(Op0, Op1);
24397 std::swap(ShAmt0, ShAmt1);
24400 unsigned Bits = VT.getSizeInBits();
24401 if (ShAmt1.getOpcode() == ISD::SUB) {
24402 SDValue Sum = ShAmt1.getOperand(0);
24403 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24404 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24405 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24406 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24407 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24408 return DAG.getNode(Opc, DL, VT,
24410 DAG.getNode(ISD::TRUNCATE, DL,
24413 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24414 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24416 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24417 return DAG.getNode(Opc, DL, VT,
24418 N0.getOperand(0), N1.getOperand(0),
24419 DAG.getNode(ISD::TRUNCATE, DL,
24426 // Generate NEG and CMOV for integer abs.
24427 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24428 EVT VT = N->getValueType(0);
24430 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24431 // 8-bit integer abs to NEG and CMOV.
24432 if (VT.isInteger() && VT.getSizeInBits() == 8)
24435 SDValue N0 = N->getOperand(0);
24436 SDValue N1 = N->getOperand(1);
24439 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24440 // and change it to SUB and CMOV.
24441 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24442 N0.getOpcode() == ISD::ADD &&
24443 N0.getOperand(1) == N1 &&
24444 N1.getOpcode() == ISD::SRA &&
24445 N1.getOperand(0) == N0.getOperand(0))
24446 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24447 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24448 // Generate SUB & CMOV.
24449 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24450 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24452 SDValue Ops[] = { N0.getOperand(0), Neg,
24453 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24454 SDValue(Neg.getNode(), 1) };
24455 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24460 // Try to turn tests against the signbit in the form of:
24461 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24464 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24465 // This is only worth doing if the output type is i8.
24466 if (N->getValueType(0) != MVT::i8)
24469 SDValue N0 = N->getOperand(0);
24470 SDValue N1 = N->getOperand(1);
24472 // We should be performing an xor against a truncated shift.
24473 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24476 // Make sure we are performing an xor against one.
24477 if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24480 // SetCC on x86 zero extends so only act on this if it's a logical shift.
24481 SDValue Shift = N0.getOperand(0);
24482 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24485 // Make sure we are truncating from one of i16, i32 or i64.
24486 EVT ShiftTy = Shift.getValueType();
24487 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24490 // Make sure the shift amount extracts the sign bit.
24491 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24492 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24495 // Create a greater-than comparison against -1.
24496 // N.B. Using SETGE against 0 works but we want a canonical looking
24497 // comparison, using SETGT matches up with what TranslateX86CC.
24499 SDValue ShiftOp = Shift.getOperand(0);
24500 EVT ShiftOpTy = ShiftOp.getValueType();
24501 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24502 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24506 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24507 TargetLowering::DAGCombinerInfo &DCI,
24508 const X86Subtarget *Subtarget) {
24509 if (DCI.isBeforeLegalizeOps())
24512 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24515 if (Subtarget->hasCMov())
24516 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24522 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24523 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24524 TargetLowering::DAGCombinerInfo &DCI,
24525 const X86Subtarget *Subtarget) {
24526 LoadSDNode *Ld = cast<LoadSDNode>(N);
24527 EVT RegVT = Ld->getValueType(0);
24528 EVT MemVT = Ld->getMemoryVT();
24530 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24532 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24533 // into two 16-byte operations.
24534 ISD::LoadExtType Ext = Ld->getExtensionType();
24536 unsigned AddressSpace = Ld->getAddressSpace();
24537 unsigned Alignment = Ld->getAlignment();
24538 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24539 Ext == ISD::NON_EXTLOAD &&
24540 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24541 AddressSpace, Alignment, &Fast) && !Fast) {
24542 unsigned NumElems = RegVT.getVectorNumElements();
24546 SDValue Ptr = Ld->getBasePtr();
24547 SDValue Increment =
24548 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24550 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24552 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24553 Ld->getPointerInfo(), Ld->isVolatile(),
24554 Ld->isNonTemporal(), Ld->isInvariant(),
24556 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24557 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24558 Ld->getPointerInfo(), Ld->isVolatile(),
24559 Ld->isNonTemporal(), Ld->isInvariant(),
24560 std::min(16U, Alignment));
24561 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24563 Load2.getValue(1));
24565 SDValue NewVec = DAG.getUNDEF(RegVT);
24566 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24567 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24568 return DCI.CombineTo(N, NewVec, TF, true);
24574 /// PerformMLOADCombine - Resolve extending loads
24575 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24576 TargetLowering::DAGCombinerInfo &DCI,
24577 const X86Subtarget *Subtarget) {
24578 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24579 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24582 EVT VT = Mld->getValueType(0);
24583 unsigned NumElems = VT.getVectorNumElements();
24584 EVT LdVT = Mld->getMemoryVT();
24587 assert(LdVT != VT && "Cannot extend to the same type");
24588 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24589 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24590 // From, To sizes and ElemCount must be pow of two
24591 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24592 "Unexpected size for extending masked load");
24594 unsigned SizeRatio = ToSz / FromSz;
24595 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24597 // Create a type on which we perform the shuffle
24598 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24599 LdVT.getScalarType(), NumElems*SizeRatio);
24600 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24602 // Convert Src0 value
24603 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24604 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24605 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24606 for (unsigned i = 0; i != NumElems; ++i)
24607 ShuffleVec[i] = i * SizeRatio;
24609 // Can't shuffle using an illegal type.
24610 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24611 && "WideVecVT should be legal");
24612 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24613 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24615 // Prepare the new mask
24617 SDValue Mask = Mld->getMask();
24618 if (Mask.getValueType() == VT) {
24619 // Mask and original value have the same type
24620 NewMask = DAG.getBitcast(WideVecVT, Mask);
24621 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24622 for (unsigned i = 0; i != NumElems; ++i)
24623 ShuffleVec[i] = i * SizeRatio;
24624 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24625 ShuffleVec[i] = NumElems*SizeRatio;
24626 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24627 DAG.getConstant(0, dl, WideVecVT),
24631 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24632 unsigned WidenNumElts = NumElems*SizeRatio;
24633 unsigned MaskNumElts = VT.getVectorNumElements();
24634 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24637 unsigned NumConcat = WidenNumElts / MaskNumElts;
24638 SmallVector<SDValue, 16> Ops(NumConcat);
24639 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24641 for (unsigned i = 1; i != NumConcat; ++i)
24644 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24647 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24648 Mld->getBasePtr(), NewMask, WideSrc0,
24649 Mld->getMemoryVT(), Mld->getMemOperand(),
24651 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24652 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24655 /// PerformMSTORECombine - Resolve truncating stores
24656 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24657 const X86Subtarget *Subtarget) {
24658 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24659 if (!Mst->isTruncatingStore())
24662 EVT VT = Mst->getValue().getValueType();
24663 unsigned NumElems = VT.getVectorNumElements();
24664 EVT StVT = Mst->getMemoryVT();
24667 assert(StVT != VT && "Cannot truncate to the same type");
24668 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24669 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24671 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24673 // The truncating store is legal in some cases. For example
24674 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24675 // are designated for truncate store.
24676 // In this case we don't need any further transformations.
24677 if (TLI.isTruncStoreLegal(VT, StVT))
24680 // From, To sizes and ElemCount must be pow of two
24681 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24682 "Unexpected size for truncating masked store");
24683 // We are going to use the original vector elt for storing.
24684 // Accumulated smaller vector elements must be a multiple of the store size.
24685 assert (((NumElems * FromSz) % ToSz) == 0 &&
24686 "Unexpected ratio for truncating masked store");
24688 unsigned SizeRatio = FromSz / ToSz;
24689 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24691 // Create a type on which we perform the shuffle
24692 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24693 StVT.getScalarType(), NumElems*SizeRatio);
24695 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24697 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24698 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24699 for (unsigned i = 0; i != NumElems; ++i)
24700 ShuffleVec[i] = i * SizeRatio;
24702 // Can't shuffle using an illegal type.
24703 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24704 && "WideVecVT should be legal");
24706 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24707 DAG.getUNDEF(WideVecVT),
24711 SDValue Mask = Mst->getMask();
24712 if (Mask.getValueType() == VT) {
24713 // Mask and original value have the same type
24714 NewMask = DAG.getBitcast(WideVecVT, Mask);
24715 for (unsigned i = 0; i != NumElems; ++i)
24716 ShuffleVec[i] = i * SizeRatio;
24717 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24718 ShuffleVec[i] = NumElems*SizeRatio;
24719 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24720 DAG.getConstant(0, dl, WideVecVT),
24724 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24725 unsigned WidenNumElts = NumElems*SizeRatio;
24726 unsigned MaskNumElts = VT.getVectorNumElements();
24727 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24730 unsigned NumConcat = WidenNumElts / MaskNumElts;
24731 SmallVector<SDValue, 16> Ops(NumConcat);
24732 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24734 for (unsigned i = 1; i != NumConcat; ++i)
24737 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24740 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24741 NewMask, StVT, Mst->getMemOperand(), false);
24743 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24744 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24745 const X86Subtarget *Subtarget) {
24746 StoreSDNode *St = cast<StoreSDNode>(N);
24747 EVT VT = St->getValue().getValueType();
24748 EVT StVT = St->getMemoryVT();
24750 SDValue StoredVal = St->getOperand(1);
24751 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24753 // If we are saving a concatenation of two XMM registers and 32-byte stores
24754 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24756 unsigned AddressSpace = St->getAddressSpace();
24757 unsigned Alignment = St->getAlignment();
24758 if (VT.is256BitVector() && StVT == VT &&
24759 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24760 AddressSpace, Alignment, &Fast) && !Fast) {
24761 unsigned NumElems = VT.getVectorNumElements();
24765 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24766 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24769 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24770 SDValue Ptr0 = St->getBasePtr();
24771 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24773 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24774 St->getPointerInfo(), St->isVolatile(),
24775 St->isNonTemporal(), Alignment);
24776 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24777 St->getPointerInfo(), St->isVolatile(),
24778 St->isNonTemporal(),
24779 std::min(16U, Alignment));
24780 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24783 // Optimize trunc store (of multiple scalars) to shuffle and store.
24784 // First, pack all of the elements in one place. Next, store to memory
24785 // in fewer chunks.
24786 if (St->isTruncatingStore() && VT.isVector()) {
24787 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24788 unsigned NumElems = VT.getVectorNumElements();
24789 assert(StVT != VT && "Cannot truncate to the same type");
24790 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24791 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24793 // The truncating store is legal in some cases. For example
24794 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24795 // are designated for truncate store.
24796 // In this case we don't need any further transformations.
24797 if (TLI.isTruncStoreLegal(VT, StVT))
24800 // From, To sizes and ElemCount must be pow of two
24801 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24802 // We are going to use the original vector elt for storing.
24803 // Accumulated smaller vector elements must be a multiple of the store size.
24804 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24806 unsigned SizeRatio = FromSz / ToSz;
24808 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24810 // Create a type on which we perform the shuffle
24811 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24812 StVT.getScalarType(), NumElems*SizeRatio);
24814 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24816 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24817 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24818 for (unsigned i = 0; i != NumElems; ++i)
24819 ShuffleVec[i] = i * SizeRatio;
24821 // Can't shuffle using an illegal type.
24822 if (!TLI.isTypeLegal(WideVecVT))
24825 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24826 DAG.getUNDEF(WideVecVT),
24828 // At this point all of the data is stored at the bottom of the
24829 // register. We now need to save it to mem.
24831 // Find the largest store unit
24832 MVT StoreType = MVT::i8;
24833 for (MVT Tp : MVT::integer_valuetypes()) {
24834 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24838 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24839 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24840 (64 <= NumElems * ToSz))
24841 StoreType = MVT::f64;
24843 // Bitcast the original vector into a vector of store-size units
24844 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24845 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24846 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24847 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24848 SmallVector<SDValue, 8> Chains;
24849 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24850 TLI.getPointerTy(DAG.getDataLayout()));
24851 SDValue Ptr = St->getBasePtr();
24853 // Perform one or more big stores into memory.
24854 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24855 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24856 StoreType, ShuffWide,
24857 DAG.getIntPtrConstant(i, dl));
24858 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24859 St->getPointerInfo(), St->isVolatile(),
24860 St->isNonTemporal(), St->getAlignment());
24861 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24862 Chains.push_back(Ch);
24865 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24868 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24869 // the FP state in cases where an emms may be missing.
24870 // A preferable solution to the general problem is to figure out the right
24871 // places to insert EMMS. This qualifies as a quick hack.
24873 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24874 if (VT.getSizeInBits() != 64)
24877 const Function *F = DAG.getMachineFunction().getFunction();
24878 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24880 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24881 if ((VT.isVector() ||
24882 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24883 isa<LoadSDNode>(St->getValue()) &&
24884 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24885 St->getChain().hasOneUse() && !St->isVolatile()) {
24886 SDNode* LdVal = St->getValue().getNode();
24887 LoadSDNode *Ld = nullptr;
24888 int TokenFactorIndex = -1;
24889 SmallVector<SDValue, 8> Ops;
24890 SDNode* ChainVal = St->getChain().getNode();
24891 // Must be a store of a load. We currently handle two cases: the load
24892 // is a direct child, and it's under an intervening TokenFactor. It is
24893 // possible to dig deeper under nested TokenFactors.
24894 if (ChainVal == LdVal)
24895 Ld = cast<LoadSDNode>(St->getChain());
24896 else if (St->getValue().hasOneUse() &&
24897 ChainVal->getOpcode() == ISD::TokenFactor) {
24898 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24899 if (ChainVal->getOperand(i).getNode() == LdVal) {
24900 TokenFactorIndex = i;
24901 Ld = cast<LoadSDNode>(St->getValue());
24903 Ops.push_back(ChainVal->getOperand(i));
24907 if (!Ld || !ISD::isNormalLoad(Ld))
24910 // If this is not the MMX case, i.e. we are just turning i64 load/store
24911 // into f64 load/store, avoid the transformation if there are multiple
24912 // uses of the loaded value.
24913 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24918 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24919 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24921 if (Subtarget->is64Bit() || F64IsLegal) {
24922 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24923 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24924 Ld->getPointerInfo(), Ld->isVolatile(),
24925 Ld->isNonTemporal(), Ld->isInvariant(),
24926 Ld->getAlignment());
24927 SDValue NewChain = NewLd.getValue(1);
24928 if (TokenFactorIndex != -1) {
24929 Ops.push_back(NewChain);
24930 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24932 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24933 St->getPointerInfo(),
24934 St->isVolatile(), St->isNonTemporal(),
24935 St->getAlignment());
24938 // Otherwise, lower to two pairs of 32-bit loads / stores.
24939 SDValue LoAddr = Ld->getBasePtr();
24940 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24941 DAG.getConstant(4, LdDL, MVT::i32));
24943 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24944 Ld->getPointerInfo(),
24945 Ld->isVolatile(), Ld->isNonTemporal(),
24946 Ld->isInvariant(), Ld->getAlignment());
24947 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24948 Ld->getPointerInfo().getWithOffset(4),
24949 Ld->isVolatile(), Ld->isNonTemporal(),
24951 MinAlign(Ld->getAlignment(), 4));
24953 SDValue NewChain = LoLd.getValue(1);
24954 if (TokenFactorIndex != -1) {
24955 Ops.push_back(LoLd);
24956 Ops.push_back(HiLd);
24957 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24960 LoAddr = St->getBasePtr();
24961 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24962 DAG.getConstant(4, StDL, MVT::i32));
24964 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24965 St->getPointerInfo(),
24966 St->isVolatile(), St->isNonTemporal(),
24967 St->getAlignment());
24968 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24969 St->getPointerInfo().getWithOffset(4),
24971 St->isNonTemporal(),
24972 MinAlign(St->getAlignment(), 4));
24973 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24976 // This is similar to the above case, but here we handle a scalar 64-bit
24977 // integer store that is extracted from a vector on a 32-bit target.
24978 // If we have SSE2, then we can treat it like a floating-point double
24979 // to get past legalization. The execution dependencies fixup pass will
24980 // choose the optimal machine instruction for the store if this really is
24981 // an integer or v2f32 rather than an f64.
24982 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24983 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24984 SDValue OldExtract = St->getOperand(1);
24985 SDValue ExtOp0 = OldExtract.getOperand(0);
24986 unsigned VecSize = ExtOp0.getValueSizeInBits();
24987 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24988 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24989 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24990 BitCast, OldExtract.getOperand(1));
24991 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24992 St->getPointerInfo(), St->isVolatile(),
24993 St->isNonTemporal(), St->getAlignment());
24999 /// Return 'true' if this vector operation is "horizontal"
25000 /// and return the operands for the horizontal operation in LHS and RHS. A
25001 /// horizontal operation performs the binary operation on successive elements
25002 /// of its first operand, then on successive elements of its second operand,
25003 /// returning the resulting values in a vector. For example, if
25004 /// A = < float a0, float a1, float a2, float a3 >
25006 /// B = < float b0, float b1, float b2, float b3 >
25007 /// then the result of doing a horizontal operation on A and B is
25008 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25009 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25010 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25011 /// set to A, RHS to B, and the routine returns 'true'.
25012 /// Note that the binary operation should have the property that if one of the
25013 /// operands is UNDEF then the result is UNDEF.
25014 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25015 // Look for the following pattern: if
25016 // A = < float a0, float a1, float a2, float a3 >
25017 // B = < float b0, float b1, float b2, float b3 >
25019 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25020 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25021 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25022 // which is A horizontal-op B.
25024 // At least one of the operands should be a vector shuffle.
25025 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25026 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25029 MVT VT = LHS.getSimpleValueType();
25031 assert((VT.is128BitVector() || VT.is256BitVector()) &&
25032 "Unsupported vector type for horizontal add/sub");
25034 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25035 // operate independently on 128-bit lanes.
25036 unsigned NumElts = VT.getVectorNumElements();
25037 unsigned NumLanes = VT.getSizeInBits()/128;
25038 unsigned NumLaneElts = NumElts / NumLanes;
25039 assert((NumLaneElts % 2 == 0) &&
25040 "Vector type should have an even number of elements in each lane");
25041 unsigned HalfLaneElts = NumLaneElts/2;
25043 // View LHS in the form
25044 // LHS = VECTOR_SHUFFLE A, B, LMask
25045 // If LHS is not a shuffle then pretend it is the shuffle
25046 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25047 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25050 SmallVector<int, 16> LMask(NumElts);
25051 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25052 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25053 A = LHS.getOperand(0);
25054 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25055 B = LHS.getOperand(1);
25056 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25057 std::copy(Mask.begin(), Mask.end(), LMask.begin());
25059 if (LHS.getOpcode() != ISD::UNDEF)
25061 for (unsigned i = 0; i != NumElts; ++i)
25065 // Likewise, view RHS in the form
25066 // RHS = VECTOR_SHUFFLE C, D, RMask
25068 SmallVector<int, 16> RMask(NumElts);
25069 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25070 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25071 C = RHS.getOperand(0);
25072 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25073 D = RHS.getOperand(1);
25074 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25075 std::copy(Mask.begin(), Mask.end(), RMask.begin());
25077 if (RHS.getOpcode() != ISD::UNDEF)
25079 for (unsigned i = 0; i != NumElts; ++i)
25083 // Check that the shuffles are both shuffling the same vectors.
25084 if (!(A == C && B == D) && !(A == D && B == C))
25087 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25088 if (!A.getNode() && !B.getNode())
25091 // If A and B occur in reverse order in RHS, then "swap" them (which means
25092 // rewriting the mask).
25094 ShuffleVectorSDNode::commuteMask(RMask);
25096 // At this point LHS and RHS are equivalent to
25097 // LHS = VECTOR_SHUFFLE A, B, LMask
25098 // RHS = VECTOR_SHUFFLE A, B, RMask
25099 // Check that the masks correspond to performing a horizontal operation.
25100 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25101 for (unsigned i = 0; i != NumLaneElts; ++i) {
25102 int LIdx = LMask[i+l], RIdx = RMask[i+l];
25104 // Ignore any UNDEF components.
25105 if (LIdx < 0 || RIdx < 0 ||
25106 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25107 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25110 // Check that successive elements are being operated on. If not, this is
25111 // not a horizontal operation.
25112 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25113 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25114 if (!(LIdx == Index && RIdx == Index + 1) &&
25115 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25120 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25121 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25125 /// Do target-specific dag combines on floating point adds.
25126 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25127 const X86Subtarget *Subtarget) {
25128 EVT VT = N->getValueType(0);
25129 SDValue LHS = N->getOperand(0);
25130 SDValue RHS = N->getOperand(1);
25132 // Try to synthesize horizontal adds from adds of shuffles.
25133 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25134 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25135 isHorizontalBinOp(LHS, RHS, true))
25136 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25140 /// Do target-specific dag combines on floating point subs.
25141 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25142 const X86Subtarget *Subtarget) {
25143 EVT VT = N->getValueType(0);
25144 SDValue LHS = N->getOperand(0);
25145 SDValue RHS = N->getOperand(1);
25147 // Try to synthesize horizontal subs from subs of shuffles.
25148 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25149 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25150 isHorizontalBinOp(LHS, RHS, false))
25151 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25155 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25156 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
25157 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25159 // F[X]OR(0.0, x) -> x
25160 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25161 if (C->getValueAPF().isPosZero())
25162 return N->getOperand(1);
25164 // F[X]OR(x, 0.0) -> x
25165 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25166 if (C->getValueAPF().isPosZero())
25167 return N->getOperand(0);
25171 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25172 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25173 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25175 // Only perform optimizations if UnsafeMath is used.
25176 if (!DAG.getTarget().Options.UnsafeFPMath)
25179 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25180 // into FMINC and FMAXC, which are Commutative operations.
25181 unsigned NewOp = 0;
25182 switch (N->getOpcode()) {
25183 default: llvm_unreachable("unknown opcode");
25184 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
25185 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
25188 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25189 N->getOperand(0), N->getOperand(1));
25192 /// Do target-specific dag combines on X86ISD::FAND nodes.
25193 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25194 // FAND(0.0, x) -> 0.0
25195 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25196 if (C->getValueAPF().isPosZero())
25197 return N->getOperand(0);
25199 // FAND(x, 0.0) -> 0.0
25200 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25201 if (C->getValueAPF().isPosZero())
25202 return N->getOperand(1);
25207 /// Do target-specific dag combines on X86ISD::FANDN nodes
25208 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25209 // FANDN(0.0, x) -> x
25210 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25211 if (C->getValueAPF().isPosZero())
25212 return N->getOperand(1);
25214 // FANDN(x, 0.0) -> 0.0
25215 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25216 if (C->getValueAPF().isPosZero())
25217 return N->getOperand(1);
25222 static SDValue PerformBTCombine(SDNode *N,
25224 TargetLowering::DAGCombinerInfo &DCI) {
25225 // BT ignores high bits in the bit index operand.
25226 SDValue Op1 = N->getOperand(1);
25227 if (Op1.hasOneUse()) {
25228 unsigned BitWidth = Op1.getValueSizeInBits();
25229 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25230 APInt KnownZero, KnownOne;
25231 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25232 !DCI.isBeforeLegalizeOps());
25233 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25234 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25235 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25236 DCI.CommitTargetLoweringOpt(TLO);
25241 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25242 SDValue Op = N->getOperand(0);
25243 if (Op.getOpcode() == ISD::BITCAST)
25244 Op = Op.getOperand(0);
25245 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25246 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25247 VT.getVectorElementType().getSizeInBits() ==
25248 OpVT.getVectorElementType().getSizeInBits()) {
25249 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25254 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25255 const X86Subtarget *Subtarget) {
25256 EVT VT = N->getValueType(0);
25257 if (!VT.isVector())
25260 SDValue N0 = N->getOperand(0);
25261 SDValue N1 = N->getOperand(1);
25262 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25265 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25266 // both SSE and AVX2 since there is no sign-extended shift right
25267 // operation on a vector with 64-bit elements.
25268 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25269 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25270 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25271 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25272 SDValue N00 = N0.getOperand(0);
25274 // EXTLOAD has a better solution on AVX2,
25275 // it may be replaced with X86ISD::VSEXT node.
25276 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25277 if (!ISD::isNormalLoad(N00.getNode()))
25280 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25281 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25283 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25289 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25290 TargetLowering::DAGCombinerInfo &DCI,
25291 const X86Subtarget *Subtarget) {
25292 SDValue N0 = N->getOperand(0);
25293 EVT VT = N->getValueType(0);
25294 EVT SVT = VT.getScalarType();
25295 EVT InVT = N0.getValueType();
25296 EVT InSVT = InVT.getScalarType();
25299 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25300 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25301 // This exposes the sext to the sdivrem lowering, so that it directly extends
25302 // from AH (which we otherwise need to do contortions to access).
25303 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25304 InVT == MVT::i8 && VT == MVT::i32) {
25305 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25306 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25307 N0.getOperand(0), N0.getOperand(1));
25308 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25309 return R.getValue(1);
25312 if (!DCI.isBeforeLegalizeOps()) {
25313 if (InVT == MVT::i1) {
25314 SDValue Zero = DAG.getConstant(0, DL, VT);
25316 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25317 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25322 if (VT.isVector() && Subtarget->hasSSE2()) {
25323 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25324 EVT InVT = N.getValueType();
25325 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25326 Size / InVT.getScalarSizeInBits());
25327 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25328 DAG.getUNDEF(InVT));
25330 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25333 // If target-size is less than 128-bits, extend to a type that would extend
25334 // to 128 bits, extend that and extract the original target vector.
25335 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25336 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25337 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25338 unsigned Scale = 128 / VT.getSizeInBits();
25340 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25341 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25342 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25343 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25344 DAG.getIntPtrConstant(0, DL));
25347 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25348 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25349 if (VT.getSizeInBits() == 128 &&
25350 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25351 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25352 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25353 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25356 // On pre-AVX2 targets, split into 128-bit nodes of
25357 // ISD::SIGN_EXTEND_VECTOR_INREG.
25358 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25359 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25360 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25361 unsigned NumVecs = VT.getSizeInBits() / 128;
25362 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25363 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25364 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25366 SmallVector<SDValue, 8> Opnds;
25367 for (unsigned i = 0, Offset = 0; i != NumVecs;
25368 ++i, Offset += NumSubElts) {
25369 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25370 DAG.getIntPtrConstant(Offset, DL));
25371 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25372 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25373 Opnds.push_back(SrcVec);
25375 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25379 if (!Subtarget->hasFp256())
25382 if (VT.isVector() && VT.getSizeInBits() == 256)
25383 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25389 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25390 const X86Subtarget* Subtarget) {
25392 EVT VT = N->getValueType(0);
25394 // Let legalize expand this if it isn't a legal type yet.
25395 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25398 EVT ScalarVT = VT.getScalarType();
25399 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25400 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25401 !Subtarget->hasAVX512()))
25404 SDValue A = N->getOperand(0);
25405 SDValue B = N->getOperand(1);
25406 SDValue C = N->getOperand(2);
25408 bool NegA = (A.getOpcode() == ISD::FNEG);
25409 bool NegB = (B.getOpcode() == ISD::FNEG);
25410 bool NegC = (C.getOpcode() == ISD::FNEG);
25412 // Negative multiplication when NegA xor NegB
25413 bool NegMul = (NegA != NegB);
25415 A = A.getOperand(0);
25417 B = B.getOperand(0);
25419 C = C.getOperand(0);
25423 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25425 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25427 return DAG.getNode(Opcode, dl, VT, A, B, C);
25430 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25431 TargetLowering::DAGCombinerInfo &DCI,
25432 const X86Subtarget *Subtarget) {
25433 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25434 // (and (i32 x86isd::setcc_carry), 1)
25435 // This eliminates the zext. This transformation is necessary because
25436 // ISD::SETCC is always legalized to i8.
25438 SDValue N0 = N->getOperand(0);
25439 EVT VT = N->getValueType(0);
25441 if (N0.getOpcode() == ISD::AND &&
25443 N0.getOperand(0).hasOneUse()) {
25444 SDValue N00 = N0.getOperand(0);
25445 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25446 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25447 if (!C || C->getZExtValue() != 1)
25449 return DAG.getNode(ISD::AND, dl, VT,
25450 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25451 N00.getOperand(0), N00.getOperand(1)),
25452 DAG.getConstant(1, dl, VT));
25456 if (N0.getOpcode() == ISD::TRUNCATE &&
25458 N0.getOperand(0).hasOneUse()) {
25459 SDValue N00 = N0.getOperand(0);
25460 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25461 return DAG.getNode(ISD::AND, dl, VT,
25462 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25463 N00.getOperand(0), N00.getOperand(1)),
25464 DAG.getConstant(1, dl, VT));
25468 if (VT.is256BitVector())
25469 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25472 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25473 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25474 // This exposes the zext to the udivrem lowering, so that it directly extends
25475 // from AH (which we otherwise need to do contortions to access).
25476 if (N0.getOpcode() == ISD::UDIVREM &&
25477 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25478 (VT == MVT::i32 || VT == MVT::i64)) {
25479 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25480 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25481 N0.getOperand(0), N0.getOperand(1));
25482 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25483 return R.getValue(1);
25489 // Optimize x == -y --> x+y == 0
25490 // x != -y --> x+y != 0
25491 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25492 const X86Subtarget* Subtarget) {
25493 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25494 SDValue LHS = N->getOperand(0);
25495 SDValue RHS = N->getOperand(1);
25496 EVT VT = N->getValueType(0);
25499 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25500 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25501 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25502 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25503 LHS.getOperand(1));
25504 return DAG.getSetCC(DL, N->getValueType(0), addV,
25505 DAG.getConstant(0, DL, addV.getValueType()), CC);
25507 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25508 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25509 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25510 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25511 RHS.getOperand(1));
25512 return DAG.getSetCC(DL, N->getValueType(0), addV,
25513 DAG.getConstant(0, DL, addV.getValueType()), CC);
25516 if (VT.getScalarType() == MVT::i1 &&
25517 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25519 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25520 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25521 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25523 if (!IsSEXT0 || !IsVZero1) {
25524 // Swap the operands and update the condition code.
25525 std::swap(LHS, RHS);
25526 CC = ISD::getSetCCSwappedOperands(CC);
25528 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25529 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25530 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25533 if (IsSEXT0 && IsVZero1) {
25534 assert(VT == LHS.getOperand(0).getValueType() &&
25535 "Uexpected operand type");
25536 if (CC == ISD::SETGT)
25537 return DAG.getConstant(0, DL, VT);
25538 if (CC == ISD::SETLE)
25539 return DAG.getConstant(1, DL, VT);
25540 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25541 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25543 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25544 "Unexpected condition code!");
25545 return LHS.getOperand(0);
25552 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25553 SelectionDAG &DAG) {
25555 MVT VT = Load->getSimpleValueType(0);
25556 MVT EVT = VT.getVectorElementType();
25557 SDValue Addr = Load->getOperand(1);
25558 SDValue NewAddr = DAG.getNode(
25559 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25560 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25561 Addr.getSimpleValueType()));
25564 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25565 DAG.getMachineFunction().getMachineMemOperand(
25566 Load->getMemOperand(), 0, EVT.getStoreSize()));
25570 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25571 const X86Subtarget *Subtarget) {
25573 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25574 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25575 "X86insertps is only defined for v4x32");
25577 SDValue Ld = N->getOperand(1);
25578 if (MayFoldLoad(Ld)) {
25579 // Extract the countS bits from the immediate so we can get the proper
25580 // address when narrowing the vector load to a specific element.
25581 // When the second source op is a memory address, insertps doesn't use
25582 // countS and just gets an f32 from that address.
25583 unsigned DestIndex =
25584 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25586 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25588 // Create this as a scalar to vector to match the instruction pattern.
25589 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25590 // countS bits are ignored when loading from memory on insertps, which
25591 // means we don't need to explicitly set them to 0.
25592 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25593 LoadScalarToVector, N->getOperand(2));
25598 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25599 SDValue V0 = N->getOperand(0);
25600 SDValue V1 = N->getOperand(1);
25602 EVT VT = N->getValueType(0);
25604 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25605 // operands and changing the mask to 1. This saves us a bunch of
25606 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25607 // x86InstrInfo knows how to commute this back after instruction selection
25608 // if it would help register allocation.
25610 // TODO: If optimizing for size or a processor that doesn't suffer from
25611 // partial register update stalls, this should be transformed into a MOVSD
25612 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25614 if (VT == MVT::v2f64)
25615 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25616 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25617 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25618 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25624 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25625 // as "sbb reg,reg", since it can be extended without zext and produces
25626 // an all-ones bit which is more useful than 0/1 in some cases.
25627 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25630 return DAG.getNode(ISD::AND, DL, VT,
25631 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25632 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25634 DAG.getConstant(1, DL, VT));
25635 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25636 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25637 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25638 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25642 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25643 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25644 TargetLowering::DAGCombinerInfo &DCI,
25645 const X86Subtarget *Subtarget) {
25647 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25648 SDValue EFLAGS = N->getOperand(1);
25650 if (CC == X86::COND_A) {
25651 // Try to convert COND_A into COND_B in an attempt to facilitate
25652 // materializing "setb reg".
25654 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25655 // cannot take an immediate as its first operand.
25657 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25658 EFLAGS.getValueType().isInteger() &&
25659 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25660 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25661 EFLAGS.getNode()->getVTList(),
25662 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25663 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25664 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25668 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25669 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25671 if (CC == X86::COND_B)
25672 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25674 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25675 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25676 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25682 // Optimize branch condition evaluation.
25684 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25685 TargetLowering::DAGCombinerInfo &DCI,
25686 const X86Subtarget *Subtarget) {
25688 SDValue Chain = N->getOperand(0);
25689 SDValue Dest = N->getOperand(1);
25690 SDValue EFLAGS = N->getOperand(3);
25691 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25693 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25694 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25695 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25702 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25703 SelectionDAG &DAG) {
25704 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25705 // optimize away operation when it's from a constant.
25707 // The general transformation is:
25708 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25709 // AND(VECTOR_CMP(x,y), constant2)
25710 // constant2 = UNARYOP(constant)
25712 // Early exit if this isn't a vector operation, the operand of the
25713 // unary operation isn't a bitwise AND, or if the sizes of the operations
25714 // aren't the same.
25715 EVT VT = N->getValueType(0);
25716 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25717 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25718 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25721 // Now check that the other operand of the AND is a constant. We could
25722 // make the transformation for non-constant splats as well, but it's unclear
25723 // that would be a benefit as it would not eliminate any operations, just
25724 // perform one more step in scalar code before moving to the vector unit.
25725 if (BuildVectorSDNode *BV =
25726 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25727 // Bail out if the vector isn't a constant.
25728 if (!BV->isConstant())
25731 // Everything checks out. Build up the new and improved node.
25733 EVT IntVT = BV->getValueType(0);
25734 // Create a new constant of the appropriate type for the transformed
25736 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25737 // The AND node needs bitcasts to/from an integer vector type around it.
25738 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25739 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25740 N->getOperand(0)->getOperand(0), MaskConst);
25741 SDValue Res = DAG.getBitcast(VT, NewAnd);
25748 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25749 const X86Subtarget *Subtarget) {
25750 SDValue Op0 = N->getOperand(0);
25751 EVT VT = N->getValueType(0);
25752 EVT InVT = Op0.getValueType();
25753 EVT InSVT = InVT.getScalarType();
25754 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25756 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25757 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25758 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25760 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25761 InVT.getVectorNumElements());
25762 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25764 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25765 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25767 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25773 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25774 const X86Subtarget *Subtarget) {
25775 // First try to optimize away the conversion entirely when it's
25776 // conditionally from a constant. Vectors only.
25777 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25780 // Now move on to more general possibilities.
25781 SDValue Op0 = N->getOperand(0);
25782 EVT VT = N->getValueType(0);
25783 EVT InVT = Op0.getValueType();
25784 EVT InSVT = InVT.getScalarType();
25786 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25787 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25788 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25790 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25791 InVT.getVectorNumElements());
25792 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25793 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25796 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25797 // a 32-bit target where SSE doesn't support i64->FP operations.
25798 if (Op0.getOpcode() == ISD::LOAD) {
25799 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25800 EVT LdVT = Ld->getValueType(0);
25802 // This transformation is not supported if the result type is f16
25803 if (VT == MVT::f16)
25806 if (!Ld->isVolatile() && !VT.isVector() &&
25807 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25808 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25809 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25810 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25811 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25818 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25819 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25820 X86TargetLowering::DAGCombinerInfo &DCI) {
25821 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25822 // the result is either zero or one (depending on the input carry bit).
25823 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25824 if (X86::isZeroNode(N->getOperand(0)) &&
25825 X86::isZeroNode(N->getOperand(1)) &&
25826 // We don't have a good way to replace an EFLAGS use, so only do this when
25828 SDValue(N, 1).use_empty()) {
25830 EVT VT = N->getValueType(0);
25831 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25832 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25833 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25834 DAG.getConstant(X86::COND_B, DL,
25837 DAG.getConstant(1, DL, VT));
25838 return DCI.CombineTo(N, Res1, CarryOut);
25844 // fold (add Y, (sete X, 0)) -> adc 0, Y
25845 // (add Y, (setne X, 0)) -> sbb -1, Y
25846 // (sub (sete X, 0), Y) -> sbb 0, Y
25847 // (sub (setne X, 0), Y) -> adc -1, Y
25848 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25851 // Look through ZExts.
25852 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25853 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25856 SDValue SetCC = Ext.getOperand(0);
25857 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25860 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25861 if (CC != X86::COND_E && CC != X86::COND_NE)
25864 SDValue Cmp = SetCC.getOperand(1);
25865 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25866 !X86::isZeroNode(Cmp.getOperand(1)) ||
25867 !Cmp.getOperand(0).getValueType().isInteger())
25870 SDValue CmpOp0 = Cmp.getOperand(0);
25871 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25872 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25874 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25875 if (CC == X86::COND_NE)
25876 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25877 DL, OtherVal.getValueType(), OtherVal,
25878 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25880 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25881 DL, OtherVal.getValueType(), OtherVal,
25882 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25885 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25886 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25887 const X86Subtarget *Subtarget) {
25888 EVT VT = N->getValueType(0);
25889 SDValue Op0 = N->getOperand(0);
25890 SDValue Op1 = N->getOperand(1);
25892 // Try to synthesize horizontal adds from adds of shuffles.
25893 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25894 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25895 isHorizontalBinOp(Op0, Op1, true))
25896 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25898 return OptimizeConditionalInDecrement(N, DAG);
25901 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25902 const X86Subtarget *Subtarget) {
25903 SDValue Op0 = N->getOperand(0);
25904 SDValue Op1 = N->getOperand(1);
25906 // X86 can't encode an immediate LHS of a sub. See if we can push the
25907 // negation into a preceding instruction.
25908 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25909 // If the RHS of the sub is a XOR with one use and a constant, invert the
25910 // immediate. Then add one to the LHS of the sub so we can turn
25911 // X-Y -> X+~Y+1, saving one register.
25912 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25913 isa<ConstantSDNode>(Op1.getOperand(1))) {
25914 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25915 EVT VT = Op0.getValueType();
25916 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25918 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25919 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25920 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25924 // Try to synthesize horizontal adds from adds of shuffles.
25925 EVT VT = N->getValueType(0);
25926 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25927 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25928 isHorizontalBinOp(Op0, Op1, true))
25929 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25931 return OptimizeConditionalInDecrement(N, DAG);
25934 /// performVZEXTCombine - Performs build vector combines
25935 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25936 TargetLowering::DAGCombinerInfo &DCI,
25937 const X86Subtarget *Subtarget) {
25939 MVT VT = N->getSimpleValueType(0);
25940 SDValue Op = N->getOperand(0);
25941 MVT OpVT = Op.getSimpleValueType();
25942 MVT OpEltVT = OpVT.getVectorElementType();
25943 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25945 // (vzext (bitcast (vzext (x)) -> (vzext x)
25947 while (V.getOpcode() == ISD::BITCAST)
25948 V = V.getOperand(0);
25950 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25951 MVT InnerVT = V.getSimpleValueType();
25952 MVT InnerEltVT = InnerVT.getVectorElementType();
25954 // If the element sizes match exactly, we can just do one larger vzext. This
25955 // is always an exact type match as vzext operates on integer types.
25956 if (OpEltVT == InnerEltVT) {
25957 assert(OpVT == InnerVT && "Types must match for vzext!");
25958 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25961 // The only other way we can combine them is if only a single element of the
25962 // inner vzext is used in the input to the outer vzext.
25963 if (InnerEltVT.getSizeInBits() < InputBits)
25966 // In this case, the inner vzext is completely dead because we're going to
25967 // only look at bits inside of the low element. Just do the outer vzext on
25968 // a bitcast of the input to the inner.
25969 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25972 // Check if we can bypass extracting and re-inserting an element of an input
25973 // vector. Essentially:
25974 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25975 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25976 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25977 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25978 SDValue ExtractedV = V.getOperand(0);
25979 SDValue OrigV = ExtractedV.getOperand(0);
25980 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25981 if (ExtractIdx->getZExtValue() == 0) {
25982 MVT OrigVT = OrigV.getSimpleValueType();
25983 // Extract a subvector if necessary...
25984 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25985 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25986 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25987 OrigVT.getVectorNumElements() / Ratio);
25988 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25989 DAG.getIntPtrConstant(0, DL));
25991 Op = DAG.getBitcast(OpVT, OrigV);
25992 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25999 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26000 DAGCombinerInfo &DCI) const {
26001 SelectionDAG &DAG = DCI.DAG;
26002 switch (N->getOpcode()) {
26004 case ISD::EXTRACT_VECTOR_ELT:
26005 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26008 case X86ISD::SHRUNKBLEND:
26009 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26010 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
26011 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26012 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
26013 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
26014 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
26015 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
26018 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
26019 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
26020 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
26021 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
26022 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
26023 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26024 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
26025 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
26026 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26027 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26028 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
26029 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
26031 case X86ISD::FOR: return PerformFORCombine(N, DAG);
26033 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
26034 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
26035 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
26036 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
26037 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
26038 case ISD::ANY_EXTEND:
26039 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
26040 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
26041 case ISD::SIGN_EXTEND_INREG:
26042 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26043 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
26044 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26045 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26046 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
26047 case X86ISD::SHUFP: // Handle all target specific shuffles
26048 case X86ISD::PALIGNR:
26049 case X86ISD::UNPCKH:
26050 case X86ISD::UNPCKL:
26051 case X86ISD::MOVHLPS:
26052 case X86ISD::MOVLHPS:
26053 case X86ISD::PSHUFB:
26054 case X86ISD::PSHUFD:
26055 case X86ISD::PSHUFHW:
26056 case X86ISD::PSHUFLW:
26057 case X86ISD::MOVSS:
26058 case X86ISD::MOVSD:
26059 case X86ISD::VPERMILPI:
26060 case X86ISD::VPERM2X128:
26061 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26062 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
26063 case X86ISD::INSERTPS: {
26064 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26065 return PerformINSERTPSCombine(N, DAG, Subtarget);
26068 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
26074 /// isTypeDesirableForOp - Return true if the target has native support for
26075 /// the specified value type and it is 'desirable' to use the type for the
26076 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26077 /// instruction encodings are longer and some i16 instructions are slow.
26078 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26079 if (!isTypeLegal(VT))
26081 if (VT != MVT::i16)
26088 case ISD::SIGN_EXTEND:
26089 case ISD::ZERO_EXTEND:
26090 case ISD::ANY_EXTEND:
26103 /// IsDesirableToPromoteOp - This method query the target whether it is
26104 /// beneficial for dag combiner to promote the specified node. If true, it
26105 /// should return the desired promotion type by reference.
26106 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26107 EVT VT = Op.getValueType();
26108 if (VT != MVT::i16)
26111 bool Promote = false;
26112 bool Commute = false;
26113 switch (Op.getOpcode()) {
26116 LoadSDNode *LD = cast<LoadSDNode>(Op);
26117 // If the non-extending load has a single use and it's not live out, then it
26118 // might be folded.
26119 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26120 Op.hasOneUse()*/) {
26121 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26122 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26123 // The only case where we'd want to promote LOAD (rather then it being
26124 // promoted as an operand is when it's only use is liveout.
26125 if (UI->getOpcode() != ISD::CopyToReg)
26132 case ISD::SIGN_EXTEND:
26133 case ISD::ZERO_EXTEND:
26134 case ISD::ANY_EXTEND:
26139 SDValue N0 = Op.getOperand(0);
26140 // Look out for (store (shl (load), x)).
26141 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26154 SDValue N0 = Op.getOperand(0);
26155 SDValue N1 = Op.getOperand(1);
26156 if (!Commute && MayFoldLoad(N1))
26158 // Avoid disabling potential load folding opportunities.
26159 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26161 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26171 //===----------------------------------------------------------------------===//
26172 // X86 Inline Assembly Support
26173 //===----------------------------------------------------------------------===//
26175 // Helper to match a string separated by whitespace.
26176 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26177 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26179 for (StringRef Piece : Pieces) {
26180 if (!S.startswith(Piece)) // Check if the piece matches.
26183 S = S.substr(Piece.size());
26184 StringRef::size_type Pos = S.find_first_not_of(" \t");
26185 if (Pos == 0) // We matched a prefix.
26194 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26196 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26197 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26198 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26199 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26201 if (AsmPieces.size() == 3)
26203 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26210 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26211 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26213 std::string AsmStr = IA->getAsmString();
26215 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26216 if (!Ty || Ty->getBitWidth() % 16 != 0)
26219 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26220 SmallVector<StringRef, 4> AsmPieces;
26221 SplitString(AsmStr, AsmPieces, ";\n");
26223 switch (AsmPieces.size()) {
26224 default: return false;
26226 // FIXME: this should verify that we are targeting a 486 or better. If not,
26227 // we will turn this bswap into something that will be lowered to logical
26228 // ops instead of emitting the bswap asm. For now, we don't support 486 or
26229 // lower so don't worry about this.
26231 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26232 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26233 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26234 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26235 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26236 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26237 // No need to check constraints, nothing other than the equivalent of
26238 // "=r,0" would be valid here.
26239 return IntrinsicLowering::LowerToByteSwap(CI);
26242 // rorw $$8, ${0:w} --> llvm.bswap.i16
26243 if (CI->getType()->isIntegerTy(16) &&
26244 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26245 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26246 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26248 StringRef ConstraintsStr = IA->getConstraintString();
26249 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26250 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26251 if (clobbersFlagRegisters(AsmPieces))
26252 return IntrinsicLowering::LowerToByteSwap(CI);
26256 if (CI->getType()->isIntegerTy(32) &&
26257 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26258 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26259 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26260 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26262 StringRef ConstraintsStr = IA->getConstraintString();
26263 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26264 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26265 if (clobbersFlagRegisters(AsmPieces))
26266 return IntrinsicLowering::LowerToByteSwap(CI);
26269 if (CI->getType()->isIntegerTy(64)) {
26270 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26271 if (Constraints.size() >= 2 &&
26272 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26273 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26274 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
26275 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26276 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26277 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26278 return IntrinsicLowering::LowerToByteSwap(CI);
26286 /// getConstraintType - Given a constraint letter, return the type of
26287 /// constraint it is for this target.
26288 X86TargetLowering::ConstraintType
26289 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26290 if (Constraint.size() == 1) {
26291 switch (Constraint[0]) {
26302 return C_RegisterClass;
26326 return TargetLowering::getConstraintType(Constraint);
26329 /// Examine constraint type and operand type and determine a weight value.
26330 /// This object must already have been set up with the operand type
26331 /// and the current alternative constraint selected.
26332 TargetLowering::ConstraintWeight
26333 X86TargetLowering::getSingleConstraintMatchWeight(
26334 AsmOperandInfo &info, const char *constraint) const {
26335 ConstraintWeight weight = CW_Invalid;
26336 Value *CallOperandVal = info.CallOperandVal;
26337 // If we don't have a value, we can't do a match,
26338 // but allow it at the lowest weight.
26339 if (!CallOperandVal)
26341 Type *type = CallOperandVal->getType();
26342 // Look at the constraint type.
26343 switch (*constraint) {
26345 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26356 if (CallOperandVal->getType()->isIntegerTy())
26357 weight = CW_SpecificReg;
26362 if (type->isFloatingPointTy())
26363 weight = CW_SpecificReg;
26366 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26367 weight = CW_SpecificReg;
26371 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26372 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26373 weight = CW_Register;
26376 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26377 if (C->getZExtValue() <= 31)
26378 weight = CW_Constant;
26382 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26383 if (C->getZExtValue() <= 63)
26384 weight = CW_Constant;
26388 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26389 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26390 weight = CW_Constant;
26394 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26395 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26396 weight = CW_Constant;
26400 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26401 if (C->getZExtValue() <= 3)
26402 weight = CW_Constant;
26406 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26407 if (C->getZExtValue() <= 0xff)
26408 weight = CW_Constant;
26413 if (isa<ConstantFP>(CallOperandVal)) {
26414 weight = CW_Constant;
26418 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26419 if ((C->getSExtValue() >= -0x80000000LL) &&
26420 (C->getSExtValue() <= 0x7fffffffLL))
26421 weight = CW_Constant;
26425 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26426 if (C->getZExtValue() <= 0xffffffff)
26427 weight = CW_Constant;
26434 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26435 /// with another that has more specific requirements based on the type of the
26436 /// corresponding operand.
26437 const char *X86TargetLowering::
26438 LowerXConstraint(EVT ConstraintVT) const {
26439 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26440 // 'f' like normal targets.
26441 if (ConstraintVT.isFloatingPoint()) {
26442 if (Subtarget->hasSSE2())
26444 if (Subtarget->hasSSE1())
26448 return TargetLowering::LowerXConstraint(ConstraintVT);
26451 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26452 /// vector. If it is invalid, don't add anything to Ops.
26453 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26454 std::string &Constraint,
26455 std::vector<SDValue>&Ops,
26456 SelectionDAG &DAG) const {
26459 // Only support length 1 constraints for now.
26460 if (Constraint.length() > 1) return;
26462 char ConstraintLetter = Constraint[0];
26463 switch (ConstraintLetter) {
26466 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26467 if (C->getZExtValue() <= 31) {
26468 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26469 Op.getValueType());
26475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26476 if (C->getZExtValue() <= 63) {
26477 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26478 Op.getValueType());
26484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26485 if (isInt<8>(C->getSExtValue())) {
26486 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26487 Op.getValueType());
26493 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26494 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26495 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26496 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26497 Op.getValueType());
26503 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26504 if (C->getZExtValue() <= 3) {
26505 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26506 Op.getValueType());
26512 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26513 if (C->getZExtValue() <= 255) {
26514 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26515 Op.getValueType());
26521 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26522 if (C->getZExtValue() <= 127) {
26523 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26524 Op.getValueType());
26530 // 32-bit signed value
26531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26532 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26533 C->getSExtValue())) {
26534 // Widen to 64 bits here to get it sign extended.
26535 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26538 // FIXME gcc accepts some relocatable values here too, but only in certain
26539 // memory models; it's complicated.
26544 // 32-bit unsigned value
26545 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26546 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26547 C->getZExtValue())) {
26548 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26549 Op.getValueType());
26553 // FIXME gcc accepts some relocatable values here too, but only in certain
26554 // memory models; it's complicated.
26558 // Literal immediates are always ok.
26559 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26560 // Widen to 64 bits here to get it sign extended.
26561 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26565 // In any sort of PIC mode addresses need to be computed at runtime by
26566 // adding in a register or some sort of table lookup. These can't
26567 // be used as immediates.
26568 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26571 // If we are in non-pic codegen mode, we allow the address of a global (with
26572 // an optional displacement) to be used with 'i'.
26573 GlobalAddressSDNode *GA = nullptr;
26574 int64_t Offset = 0;
26576 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26578 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26579 Offset += GA->getOffset();
26581 } else if (Op.getOpcode() == ISD::ADD) {
26582 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26583 Offset += C->getZExtValue();
26584 Op = Op.getOperand(0);
26587 } else if (Op.getOpcode() == ISD::SUB) {
26588 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26589 Offset += -C->getZExtValue();
26590 Op = Op.getOperand(0);
26595 // Otherwise, this isn't something we can handle, reject it.
26599 const GlobalValue *GV = GA->getGlobal();
26600 // If we require an extra load to get this address, as in PIC mode, we
26601 // can't accept it.
26602 if (isGlobalStubReference(
26603 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26606 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26607 GA->getValueType(0), Offset);
26612 if (Result.getNode()) {
26613 Ops.push_back(Result);
26616 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26619 std::pair<unsigned, const TargetRegisterClass *>
26620 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26621 StringRef Constraint,
26623 // First, see if this is a constraint that directly corresponds to an LLVM
26625 if (Constraint.size() == 1) {
26626 // GCC Constraint Letters
26627 switch (Constraint[0]) {
26629 // TODO: Slight differences here in allocation order and leaving
26630 // RIP in the class. Do they matter any more here than they do
26631 // in the normal allocation?
26632 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26633 if (Subtarget->is64Bit()) {
26634 if (VT == MVT::i32 || VT == MVT::f32)
26635 return std::make_pair(0U, &X86::GR32RegClass);
26636 if (VT == MVT::i16)
26637 return std::make_pair(0U, &X86::GR16RegClass);
26638 if (VT == MVT::i8 || VT == MVT::i1)
26639 return std::make_pair(0U, &X86::GR8RegClass);
26640 if (VT == MVT::i64 || VT == MVT::f64)
26641 return std::make_pair(0U, &X86::GR64RegClass);
26644 // 32-bit fallthrough
26645 case 'Q': // Q_REGS
26646 if (VT == MVT::i32 || VT == MVT::f32)
26647 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26648 if (VT == MVT::i16)
26649 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26650 if (VT == MVT::i8 || VT == MVT::i1)
26651 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26652 if (VT == MVT::i64)
26653 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26655 case 'r': // GENERAL_REGS
26656 case 'l': // INDEX_REGS
26657 if (VT == MVT::i8 || VT == MVT::i1)
26658 return std::make_pair(0U, &X86::GR8RegClass);
26659 if (VT == MVT::i16)
26660 return std::make_pair(0U, &X86::GR16RegClass);
26661 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26662 return std::make_pair(0U, &X86::GR32RegClass);
26663 return std::make_pair(0U, &X86::GR64RegClass);
26664 case 'R': // LEGACY_REGS
26665 if (VT == MVT::i8 || VT == MVT::i1)
26666 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26667 if (VT == MVT::i16)
26668 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26669 if (VT == MVT::i32 || !Subtarget->is64Bit())
26670 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26671 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26672 case 'f': // FP Stack registers.
26673 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26674 // value to the correct fpstack register class.
26675 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26676 return std::make_pair(0U, &X86::RFP32RegClass);
26677 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26678 return std::make_pair(0U, &X86::RFP64RegClass);
26679 return std::make_pair(0U, &X86::RFP80RegClass);
26680 case 'y': // MMX_REGS if MMX allowed.
26681 if (!Subtarget->hasMMX()) break;
26682 return std::make_pair(0U, &X86::VR64RegClass);
26683 case 'Y': // SSE_REGS if SSE2 allowed
26684 if (!Subtarget->hasSSE2()) break;
26686 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26687 if (!Subtarget->hasSSE1()) break;
26689 switch (VT.SimpleTy) {
26691 // Scalar SSE types.
26694 return std::make_pair(0U, &X86::FR32RegClass);
26697 return std::make_pair(0U, &X86::FR64RegClass);
26705 return std::make_pair(0U, &X86::VR128RegClass);
26713 return std::make_pair(0U, &X86::VR256RegClass);
26718 return std::make_pair(0U, &X86::VR512RegClass);
26724 // Use the default implementation in TargetLowering to convert the register
26725 // constraint into a member of a register class.
26726 std::pair<unsigned, const TargetRegisterClass*> Res;
26727 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26729 // Not found as a standard register?
26731 // Map st(0) -> st(7) -> ST0
26732 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26733 tolower(Constraint[1]) == 's' &&
26734 tolower(Constraint[2]) == 't' &&
26735 Constraint[3] == '(' &&
26736 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26737 Constraint[5] == ')' &&
26738 Constraint[6] == '}') {
26740 Res.first = X86::FP0+Constraint[4]-'0';
26741 Res.second = &X86::RFP80RegClass;
26745 // GCC allows "st(0)" to be called just plain "st".
26746 if (StringRef("{st}").equals_lower(Constraint)) {
26747 Res.first = X86::FP0;
26748 Res.second = &X86::RFP80RegClass;
26753 if (StringRef("{flags}").equals_lower(Constraint)) {
26754 Res.first = X86::EFLAGS;
26755 Res.second = &X86::CCRRegClass;
26759 // 'A' means EAX + EDX.
26760 if (Constraint == "A") {
26761 Res.first = X86::EAX;
26762 Res.second = &X86::GR32_ADRegClass;
26768 // Otherwise, check to see if this is a register class of the wrong value
26769 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26770 // turn into {ax},{dx}.
26771 // MVT::Other is used to specify clobber names.
26772 if (Res.second->hasType(VT) || VT == MVT::Other)
26773 return Res; // Correct type already, nothing to do.
26775 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26776 // return "eax". This should even work for things like getting 64bit integer
26777 // registers when given an f64 type.
26778 const TargetRegisterClass *Class = Res.second;
26779 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26780 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26781 unsigned Size = VT.getSizeInBits();
26782 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26783 : Size == 16 ? MVT::i16
26784 : Size == 32 ? MVT::i32
26785 : Size == 64 ? MVT::i64
26787 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26789 Res.first = DestReg;
26790 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26791 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26792 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26793 : &X86::GR64RegClass;
26794 assert(Res.second->contains(Res.first) && "Register in register class");
26796 // No register found/type mismatch.
26798 Res.second = nullptr;
26800 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26801 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26802 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26803 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26804 Class == &X86::VR512RegClass) {
26805 // Handle references to XMM physical registers that got mapped into the
26806 // wrong class. This can happen with constraints like {xmm0} where the
26807 // target independent register mapper will just pick the first match it can
26808 // find, ignoring the required type.
26810 if (VT == MVT::f32 || VT == MVT::i32)
26811 Res.second = &X86::FR32RegClass;
26812 else if (VT == MVT::f64 || VT == MVT::i64)
26813 Res.second = &X86::FR64RegClass;
26814 else if (X86::VR128RegClass.hasType(VT))
26815 Res.second = &X86::VR128RegClass;
26816 else if (X86::VR256RegClass.hasType(VT))
26817 Res.second = &X86::VR256RegClass;
26818 else if (X86::VR512RegClass.hasType(VT))
26819 Res.second = &X86::VR512RegClass;
26821 // Type mismatch and not a clobber: Return an error;
26823 Res.second = nullptr;
26830 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26831 const AddrMode &AM, Type *Ty,
26832 unsigned AS) const {
26833 // Scaling factors are not free at all.
26834 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26835 // will take 2 allocations in the out of order engine instead of 1
26836 // for plain addressing mode, i.e. inst (reg1).
26838 // vaddps (%rsi,%drx), %ymm0, %ymm1
26839 // Requires two allocations (one for the load, one for the computation)
26841 // vaddps (%rsi), %ymm0, %ymm1
26842 // Requires just 1 allocation, i.e., freeing allocations for other operations
26843 // and having less micro operations to execute.
26845 // For some X86 architectures, this is even worse because for instance for
26846 // stores, the complex addressing mode forces the instruction to use the
26847 // "load" ports instead of the dedicated "store" port.
26848 // E.g., on Haswell:
26849 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26850 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26851 if (isLegalAddressingMode(DL, AM, Ty, AS))
26852 // Scale represents reg2 * scale, thus account for 1
26853 // as soon as we use a second register.
26854 return AM.Scale != 0;
26858 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26859 // Integer division on x86 is expensive. However, when aggressively optimizing
26860 // for code size, we prefer to use a div instruction, as it is usually smaller
26861 // than the alternative sequence.
26862 // The exception to this is vector division. Since x86 doesn't have vector
26863 // integer division, leaving the division as-is is a loss even in terms of
26864 // size, because it will have to be scalarized, while the alternative code
26865 // sequence can be performed in vector form.
26866 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26867 Attribute::MinSize);
26868 return OptSize && !VT.isVector();