1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75 const X86Subtarget &STI)
76 : TargetLowering(TM), Subtarget(&STI) {
77 X86ScalarSSEf64 = Subtarget->hasSSE2();
78 X86ScalarSSEf32 = Subtarget->hasSSE1();
79 TD = TM.getDataLayout();
81 // Set up the TargetLowering object.
82 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
84 // X86 is weird. It always uses i8 for shift amounts and setcc results.
85 setBooleanContents(ZeroOrOneBooleanContent);
86 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
89 // For 64-bit, since we have so many registers, use the ILP scheduler.
90 // For 32-bit, use the register pressure specific scheduling.
91 // For Atom, always use ILP scheduling.
92 if (Subtarget->isAtom())
93 setSchedulingPreference(Sched::ILP);
94 else if (Subtarget->is64Bit())
95 setSchedulingPreference(Sched::ILP);
97 setSchedulingPreference(Sched::RegPressure);
98 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
101 // Bypass expensive divides on Atom when compiling with O2.
102 if (TM.getOptLevel() >= CodeGenOpt::Default) {
103 if (Subtarget->hasSlowDivide32())
104 addBypassSlowDiv(32, 8);
105 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106 addBypassSlowDiv(64, 16);
109 if (Subtarget->isTargetKnownWindowsMSVC()) {
110 // Setup Windows compiler runtime calls.
111 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113 setLibcallName(RTLIB::SREM_I64, "_allrem");
114 setLibcallName(RTLIB::UREM_I64, "_aullrem");
115 setLibcallName(RTLIB::MUL_I64, "_allmul");
116 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
122 // The _ftol2 runtime function has an unusual calling conv, which
123 // is modeled by a special pseudo-instruction.
124 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
130 if (Subtarget->isTargetDarwin()) {
131 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132 setUseUnderscoreSetJmp(false);
133 setUseUnderscoreLongJmp(false);
134 } else if (Subtarget->isTargetWindowsGNU()) {
135 // MS runtime is weird: it exports _setjmp, but longjmp!
136 setUseUnderscoreSetJmp(true);
137 setUseUnderscoreLongJmp(false);
139 setUseUnderscoreSetJmp(true);
140 setUseUnderscoreLongJmp(true);
143 // Set up the register classes.
144 addRegisterClass(MVT::i8, &X86::GR8RegClass);
145 addRegisterClass(MVT::i16, &X86::GR16RegClass);
146 addRegisterClass(MVT::i32, &X86::GR32RegClass);
147 if (Subtarget->is64Bit())
148 addRegisterClass(MVT::i64, &X86::GR64RegClass);
150 for (MVT VT : MVT::integer_valuetypes())
151 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
153 // We don't accept any truncstore of integer registers.
154 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
161 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
163 // SETOEQ and SETUNE require checking two conditions.
164 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
171 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
173 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
174 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
175 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
177 if (Subtarget->is64Bit()) {
178 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
179 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
180 } else if (!Subtarget->useSoftFloat()) {
181 // We have an algorithm for SSE2->double, and we turn this into a
182 // 64-bit FILD followed by conditional FADD for other targets.
183 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
184 // We have an algorithm for SSE2, and we turn this into a 64-bit
185 // FILD for other targets.
186 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
189 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
191 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
192 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
194 if (!Subtarget->useSoftFloat()) {
195 // SSE has no i16 to fp conversion, only i32
196 if (X86ScalarSSEf32) {
197 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
198 // f32 and f64 cases are Legal, f80 case is not
199 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
202 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
205 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
206 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
209 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
210 // are Legal, f80 is custom lowered.
211 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
214 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
216 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
217 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
219 if (X86ScalarSSEf32) {
220 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
221 // f32 and f64 cases are Legal, f80 case is not
222 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
225 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
228 // Handle FP_TO_UINT by promoting the destination to a larger signed
230 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
234 if (Subtarget->is64Bit()) {
235 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
236 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
237 } else if (!Subtarget->useSoftFloat()) {
238 // Since AVX is a superset of SSE3, only check for SSE here.
239 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240 // Expand FP_TO_UINT into a select.
241 // FIXME: We would like to use a Custom expander here eventually to do
242 // the optimal thing for SSE vs. the default expansion in the legalizer.
243 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
245 // With SSE3 we can use fisttpll to convert to a signed i64; without
246 // SSE, we're stuck with a fistpll.
247 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
250 if (isTargetFTOL()) {
251 // Use the _ftol2 runtime function, which has a pseudo-instruction
252 // to handle its weird calling convention.
253 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
256 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257 if (!X86ScalarSSEf64) {
258 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
259 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
260 if (Subtarget->is64Bit()) {
261 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
262 // Without SSE, i64->f64 goes through memory.
263 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
267 // Scalar integer divide and remainder are lowered to use operations that
268 // produce two results, to match the available instructions. This exposes
269 // the two-result form to trivial CSE, which is able to combine x/y and x%y
270 // into a single instruction.
272 // Scalar integer multiply-high is also lowered to use two-result
273 // operations, to match the available instructions. However, plain multiply
274 // (low) operations are left as Legal, as there are single-result
275 // instructions for this in x86. Using the two-result multiply instructions
276 // when both high and low results are needed must be arranged by dagcombine.
277 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
279 setOperationAction(ISD::MULHS, VT, Expand);
280 setOperationAction(ISD::MULHU, VT, Expand);
281 setOperationAction(ISD::SDIV, VT, Expand);
282 setOperationAction(ISD::UDIV, VT, Expand);
283 setOperationAction(ISD::SREM, VT, Expand);
284 setOperationAction(ISD::UREM, VT, Expand);
286 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287 setOperationAction(ISD::ADDC, VT, Custom);
288 setOperationAction(ISD::ADDE, VT, Custom);
289 setOperationAction(ISD::SUBC, VT, Custom);
290 setOperationAction(ISD::SUBE, VT, Custom);
293 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
294 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
295 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
296 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
297 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
298 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
299 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
300 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
301 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
302 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
303 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
305 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
306 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
307 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
309 if (Subtarget->is64Bit())
310 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
312 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
313 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
314 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
315 setOperationAction(ISD::FREM , MVT::f32 , Expand);
316 setOperationAction(ISD::FREM , MVT::f64 , Expand);
317 setOperationAction(ISD::FREM , MVT::f80 , Expand);
318 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
320 // Promote the i8 variants and force them on up to i32 which has a shorter
322 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
323 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
324 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
325 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
326 if (Subtarget->hasBMI()) {
327 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
328 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
329 if (Subtarget->is64Bit())
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
332 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
333 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
334 if (Subtarget->is64Bit())
335 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
338 if (Subtarget->hasLZCNT()) {
339 // When promoting the i8 variants, force them to i32 for a shorter
341 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
342 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
343 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
344 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
346 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
347 if (Subtarget->is64Bit())
348 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
350 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
351 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
352 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
353 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
355 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
356 if (Subtarget->is64Bit()) {
357 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
358 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
362 // Special handling for half-precision floating point conversions.
363 // If we don't have F16C support, then lower half float conversions
364 // into library calls.
365 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
370 // There's never any support for operations beyond MVT::f32.
371 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
376 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
383 if (Subtarget->hasPOPCNT()) {
384 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
386 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
387 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
388 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
389 if (Subtarget->is64Bit())
390 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
393 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
395 if (!Subtarget->hasMOVBE())
396 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
398 // These should be promoted to a larger select which is supported.
399 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
400 // X86 wants to expand cmov itself.
401 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
402 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
403 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
404 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
405 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
406 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
407 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
408 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
409 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
410 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
411 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
412 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
413 if (Subtarget->is64Bit()) {
414 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
417 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
418 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420 // support continuation, user-level threading, and etc.. As a result, no
421 // other SjLj exception interfaces are implemented and please don't build
422 // your own exception handling based on them.
423 // LLVM/Clang supports zero-cost DWARF exception handling.
424 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
428 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
429 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
430 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
431 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
435 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
436 if (Subtarget->is64Bit()) {
437 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
438 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
439 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
440 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
443 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
445 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
446 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
447 if (Subtarget->is64Bit()) {
448 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
449 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
450 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
453 if (Subtarget->hasSSE1())
454 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
456 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
458 // Expand certain atomics
459 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
461 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
466 if (Subtarget->hasCmpxchg16b()) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
470 // FIXME - use subtarget debug flags
471 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
476 if (Subtarget->is64Bit()) {
477 setExceptionPointerRegister(X86::RAX);
478 setExceptionSelectorRegister(X86::RDX);
480 setExceptionPointerRegister(X86::EAX);
481 setExceptionSelectorRegister(X86::EDX);
483 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
486 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
489 setOperationAction(ISD::TRAP, MVT::Other, Legal);
490 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
492 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493 setOperationAction(ISD::VASTART , MVT::Other, Custom);
494 setOperationAction(ISD::VAEND , MVT::Other, Expand);
495 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496 // TargetInfo::X86_64ABIBuiltinVaList
497 setOperationAction(ISD::VAARG , MVT::Other, Custom);
498 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
500 // TargetInfo::CharPtrBuiltinVaList
501 setOperationAction(ISD::VAARG , MVT::Other, Expand);
502 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
505 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
506 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
508 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(*TD), Custom);
510 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
514 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515 // f32 and f64 use SSE.
516 // Set up the FP register classes.
517 addRegisterClass(MVT::f32, &X86::FR32RegClass);
518 addRegisterClass(MVT::f64, &X86::FR64RegClass);
520 // Use ANDPD to simulate FABS.
521 setOperationAction(ISD::FABS , MVT::f64, Custom);
522 setOperationAction(ISD::FABS , MVT::f32, Custom);
524 // Use XORP to simulate FNEG.
525 setOperationAction(ISD::FNEG , MVT::f64, Custom);
526 setOperationAction(ISD::FNEG , MVT::f32, Custom);
528 // Use ANDPD and ORPD to simulate FCOPYSIGN.
529 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
532 // Lower this to FGETSIGNx86 plus an AND.
533 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
536 // We don't support sin/cos/fmod
537 setOperationAction(ISD::FSIN , MVT::f64, Expand);
538 setOperationAction(ISD::FCOS , MVT::f64, Expand);
539 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540 setOperationAction(ISD::FSIN , MVT::f32, Expand);
541 setOperationAction(ISD::FCOS , MVT::f32, Expand);
542 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
544 // Expand FP immediates into loads from the stack, except for the special
546 addLegalFPImmediate(APFloat(+0.0)); // xorpd
547 addLegalFPImmediate(APFloat(+0.0f)); // xorps
548 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549 // Use SSE for f32, x87 for f64.
550 // Set up the FP register classes.
551 addRegisterClass(MVT::f32, &X86::FR32RegClass);
552 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
554 // Use ANDPS to simulate FABS.
555 setOperationAction(ISD::FABS , MVT::f32, Custom);
557 // Use XORP to simulate FNEG.
558 setOperationAction(ISD::FNEG , MVT::f32, Custom);
560 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
562 // Use ANDPS and ORPS to simulate FCOPYSIGN.
563 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
566 // We don't support sin/cos/fmod
567 setOperationAction(ISD::FSIN , MVT::f32, Expand);
568 setOperationAction(ISD::FCOS , MVT::f32, Expand);
569 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
571 // Special cases we handle for FP constants.
572 addLegalFPImmediate(APFloat(+0.0f)); // xorps
573 addLegalFPImmediate(APFloat(+0.0)); // FLD0
574 addLegalFPImmediate(APFloat(+1.0)); // FLD1
575 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
578 if (!TM.Options.UnsafeFPMath) {
579 setOperationAction(ISD::FSIN , MVT::f64, Expand);
580 setOperationAction(ISD::FCOS , MVT::f64, Expand);
581 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
583 } else if (!Subtarget->useSoftFloat()) {
584 // f32 and f64 in x87.
585 // Set up the FP register classes.
586 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
589 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
590 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
591 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
594 if (!TM.Options.UnsafeFPMath) {
595 setOperationAction(ISD::FSIN , MVT::f64, Expand);
596 setOperationAction(ISD::FSIN , MVT::f32, Expand);
597 setOperationAction(ISD::FCOS , MVT::f64, Expand);
598 setOperationAction(ISD::FCOS , MVT::f32, Expand);
599 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
602 addLegalFPImmediate(APFloat(+0.0)); // FLD0
603 addLegalFPImmediate(APFloat(+1.0)); // FLD1
604 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612 // We don't support FMA.
613 setOperationAction(ISD::FMA, MVT::f64, Expand);
614 setOperationAction(ISD::FMA, MVT::f32, Expand);
616 // Long double always uses X87.
617 if (!Subtarget->useSoftFloat()) {
618 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
620 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
622 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623 addLegalFPImmediate(TmpFlt); // FLD0
625 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
628 APFloat TmpFlt2(+1.0);
629 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
631 addLegalFPImmediate(TmpFlt2); // FLD1
632 TmpFlt2.changeSign();
633 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
636 if (!TM.Options.UnsafeFPMath) {
637 setOperationAction(ISD::FSIN , MVT::f80, Expand);
638 setOperationAction(ISD::FCOS , MVT::f80, Expand);
639 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
644 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645 setOperationAction(ISD::FRINT, MVT::f80, Expand);
646 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647 setOperationAction(ISD::FMA, MVT::f80, Expand);
650 // Always use a library call for pow.
651 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
652 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
653 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
655 setOperationAction(ISD::FLOG, MVT::f80, Expand);
656 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658 setOperationAction(ISD::FEXP, MVT::f80, Expand);
659 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
663 // First set operation action for all vector types to either promote
664 // (for widening) or expand (for scalarization). Then we will selectively
665 // turn on ones that can be effectively codegen'd.
666 for (MVT VT : MVT::vector_valuetypes()) {
667 setOperationAction(ISD::ADD , VT, Expand);
668 setOperationAction(ISD::SUB , VT, Expand);
669 setOperationAction(ISD::FADD, VT, Expand);
670 setOperationAction(ISD::FNEG, VT, Expand);
671 setOperationAction(ISD::FSUB, VT, Expand);
672 setOperationAction(ISD::MUL , VT, Expand);
673 setOperationAction(ISD::FMUL, VT, Expand);
674 setOperationAction(ISD::SDIV, VT, Expand);
675 setOperationAction(ISD::UDIV, VT, Expand);
676 setOperationAction(ISD::FDIV, VT, Expand);
677 setOperationAction(ISD::SREM, VT, Expand);
678 setOperationAction(ISD::UREM, VT, Expand);
679 setOperationAction(ISD::LOAD, VT, Expand);
680 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685 setOperationAction(ISD::FABS, VT, Expand);
686 setOperationAction(ISD::FSIN, VT, Expand);
687 setOperationAction(ISD::FSINCOS, VT, Expand);
688 setOperationAction(ISD::FCOS, VT, Expand);
689 setOperationAction(ISD::FSINCOS, VT, Expand);
690 setOperationAction(ISD::FREM, VT, Expand);
691 setOperationAction(ISD::FMA, VT, Expand);
692 setOperationAction(ISD::FPOWI, VT, Expand);
693 setOperationAction(ISD::FSQRT, VT, Expand);
694 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695 setOperationAction(ISD::FFLOOR, VT, Expand);
696 setOperationAction(ISD::FCEIL, VT, Expand);
697 setOperationAction(ISD::FTRUNC, VT, Expand);
698 setOperationAction(ISD::FRINT, VT, Expand);
699 setOperationAction(ISD::FNEARBYINT, VT, Expand);
700 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701 setOperationAction(ISD::MULHS, VT, Expand);
702 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703 setOperationAction(ISD::MULHU, VT, Expand);
704 setOperationAction(ISD::SDIVREM, VT, Expand);
705 setOperationAction(ISD::UDIVREM, VT, Expand);
706 setOperationAction(ISD::FPOW, VT, Expand);
707 setOperationAction(ISD::CTPOP, VT, Expand);
708 setOperationAction(ISD::CTTZ, VT, Expand);
709 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710 setOperationAction(ISD::CTLZ, VT, Expand);
711 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712 setOperationAction(ISD::SHL, VT, Expand);
713 setOperationAction(ISD::SRA, VT, Expand);
714 setOperationAction(ISD::SRL, VT, Expand);
715 setOperationAction(ISD::ROTL, VT, Expand);
716 setOperationAction(ISD::ROTR, VT, Expand);
717 setOperationAction(ISD::BSWAP, VT, Expand);
718 setOperationAction(ISD::SETCC, VT, Expand);
719 setOperationAction(ISD::FLOG, VT, Expand);
720 setOperationAction(ISD::FLOG2, VT, Expand);
721 setOperationAction(ISD::FLOG10, VT, Expand);
722 setOperationAction(ISD::FEXP, VT, Expand);
723 setOperationAction(ISD::FEXP2, VT, Expand);
724 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729 setOperationAction(ISD::TRUNCATE, VT, Expand);
730 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733 setOperationAction(ISD::VSELECT, VT, Expand);
734 setOperationAction(ISD::SELECT_CC, VT, Expand);
735 for (MVT InnerVT : MVT::vector_valuetypes()) {
736 setTruncStoreAction(InnerVT, VT, Expand);
738 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
741 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742 // types, we have to deal with them whether we ask for Expansion or not.
743 // Setting Expand causes its own optimisation problems though, so leave
745 if (VT.getVectorElementType() == MVT::i1)
746 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749 // split/scalarized right now.
750 if (VT.getVectorElementType() == MVT::f16)
751 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
755 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756 // with -msoft-float, disable use of MMX as well.
757 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759 // No operations on x86mmx supported, everything uses intrinsics.
762 // MMX-sized vectors (other than x86mmx) are expected to be expanded
763 // into smaller operations.
764 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765 setOperationAction(ISD::MULHS, MMXTy, Expand);
766 setOperationAction(ISD::AND, MMXTy, Expand);
767 setOperationAction(ISD::OR, MMXTy, Expand);
768 setOperationAction(ISD::XOR, MMXTy, Expand);
769 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
770 setOperationAction(ISD::SELECT, MMXTy, Expand);
771 setOperationAction(ISD::BITCAST, MMXTy, Expand);
773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
775 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
778 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
779 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
780 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
781 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
782 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
783 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
784 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
785 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
786 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
787 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
788 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
791 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
794 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
797 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798 // registers cannot be used even for integer operations.
799 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
804 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
805 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
806 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
807 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
808 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
809 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
810 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
811 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
812 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
813 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
814 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
815 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
816 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
817 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
818 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
819 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
820 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
821 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
822 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
823 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
824 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
825 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
826 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
828 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
829 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
830 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
831 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
833 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
834 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
835 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
836 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
844 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
845 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
846 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851 MVT VT = (MVT::SimpleValueType)i;
852 // Do not attempt to custom lower non-power-of-2 vectors
853 if (!isPowerOf2_32(VT.getVectorNumElements()))
855 // Do not attempt to custom lower non-128-bit vectors
856 if (!VT.is128BitVector())
858 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
859 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
860 setOperationAction(ISD::VSELECT, VT, Custom);
861 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
864 // We support custom legalizing of sext and anyext loads for specific
865 // memory vector types which we can load as a scalar (or sequence of
866 // scalars) and extend in-register to a legal 128-bit vector type. For sext
867 // loads these must work with a single scalar load.
868 for (MVT VT : MVT::integer_vector_valuetypes()) {
869 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
880 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
881 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
882 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
883 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
884 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
885 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
889 if (Subtarget->is64Bit()) {
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
894 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896 MVT VT = (MVT::SimpleValueType)i;
898 // Do not attempt to promote non-128-bit vectors
899 if (!VT.is128BitVector())
902 setOperationAction(ISD::AND, VT, Promote);
903 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
904 setOperationAction(ISD::OR, VT, Promote);
905 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
906 setOperationAction(ISD::XOR, VT, Promote);
907 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
908 setOperationAction(ISD::LOAD, VT, Promote);
909 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
910 setOperationAction(ISD::SELECT, VT, Promote);
911 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
914 // Custom lower v2i64 and v2f64 selects.
915 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
916 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
917 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
918 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
920 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
921 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
923 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
925 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
926 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
927 // As there is no 64-bit GPR available, we need build a special custom
928 // sequence to convert from v2i32 to v2f32.
929 if (!Subtarget->is64Bit())
930 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
932 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
933 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
935 for (MVT VT : MVT::fp_vector_valuetypes())
936 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
938 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
939 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
940 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
943 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
946 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
947 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
948 setOperationAction(ISD::FRINT, RoundedTy, Legal);
949 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
952 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
953 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
954 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
955 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
956 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
957 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
958 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
959 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
961 // FIXME: Do we need to handle scalar-to-vector here?
962 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
964 // We directly match byte blends in the backend as they match the VSELECT
966 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
968 // SSE41 brings specific instructions for doing vector sign extend even in
969 // cases where we don't have SRA.
970 for (MVT VT : MVT::integer_vector_valuetypes()) {
971 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
976 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
978 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
979 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
980 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
984 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
985 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
986 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
987 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
991 // i8 and i16 vectors are custom because the source register and source
992 // source memory operand types are not the same width. f32 vectors are
993 // custom since the immediate controlling the insert encodes additional
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1005 // FIXME: these should be Legal, but that's only for the case where
1006 // the index is constant. For now custom expand to deal with that.
1007 if (Subtarget->is64Bit()) {
1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1009 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1013 if (Subtarget->hasSSE2()) {
1014 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1018 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1019 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1021 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1022 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1024 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1027 // In the customized shift lowering, the legal cases in AVX2 will be
1029 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1030 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1032 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1033 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1035 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1036 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1039 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1041 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1043 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1044 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1045 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1047 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1048 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1049 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1051 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1054 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1058 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1059 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1060 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1061 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1062 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1064 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1067 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1068 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1069 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1070 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1071 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1072 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1073 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1074 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1075 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1077 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078 // even though v8i16 is a legal type.
1079 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1080 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1081 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1083 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1084 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1085 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1087 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1088 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1090 for (MVT VT : MVT::fp_vector_valuetypes())
1091 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1093 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1094 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1096 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1097 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1099 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1100 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1102 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1103 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1104 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1105 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1107 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1108 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1109 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1111 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1112 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1113 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1114 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1115 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1116 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1117 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1118 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1119 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1120 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1121 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1122 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1124 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1125 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1126 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1127 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1129 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1132 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1133 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1134 setOperationAction(ISD::FMA, MVT::f32, Legal);
1135 setOperationAction(ISD::FMA, MVT::f64, Legal);
1138 if (Subtarget->hasInt256()) {
1139 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1140 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1141 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1142 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1144 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1145 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1146 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1147 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1149 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1150 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1151 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1152 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1154 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1155 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1156 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1157 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1159 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1160 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1161 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1162 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1163 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1164 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1165 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1166 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1167 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1168 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1169 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1170 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1172 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173 // when we have a 256bit-wide blend with immediate.
1174 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1176 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1179 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1180 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1181 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1182 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1184 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1186 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1187 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1188 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1189 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1191 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1192 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1193 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1194 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1196 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1198 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1199 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1201 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1202 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1203 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1204 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1207 // In the customized shift lowering, the legal cases in AVX2 will be
1209 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1210 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1212 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1213 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1215 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1216 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1218 // Custom lower several nodes for 256-bit types.
1219 for (MVT VT : MVT::vector_valuetypes()) {
1220 if (VT.getScalarSizeInBits() >= 32) {
1221 setOperationAction(ISD::MLOAD, VT, Legal);
1222 setOperationAction(ISD::MSTORE, VT, Legal);
1224 // Extract subvector is special because the value type
1225 // (result) is 128-bit but the source is 256-bit wide.
1226 if (VT.is128BitVector()) {
1227 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1229 // Do not attempt to custom lower other non-256-bit vectors
1230 if (!VT.is256BitVector())
1233 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1234 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1235 setOperationAction(ISD::VSELECT, VT, Custom);
1236 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1237 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1239 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1240 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1243 if (Subtarget->hasInt256())
1244 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1247 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249 MVT VT = (MVT::SimpleValueType)i;
1251 // Do not attempt to promote non-256-bit vectors
1252 if (!VT.is256BitVector())
1255 setOperationAction(ISD::AND, VT, Promote);
1256 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1257 setOperationAction(ISD::OR, VT, Promote);
1258 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1259 setOperationAction(ISD::XOR, VT, Promote);
1260 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1261 setOperationAction(ISD::LOAD, VT, Promote);
1262 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1263 setOperationAction(ISD::SELECT, VT, Promote);
1264 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1268 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1272 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1274 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1275 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1276 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1278 for (MVT VT : MVT::fp_vector_valuetypes())
1279 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1281 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1288 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1289 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1290 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1291 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1292 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1294 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1295 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1296 setOperationAction(ISD::XOR, MVT::i1, Legal);
1297 setOperationAction(ISD::OR, MVT::i1, Legal);
1298 setOperationAction(ISD::AND, MVT::i1, Legal);
1299 setOperationAction(ISD::SUB, MVT::i1, Custom);
1300 setOperationAction(ISD::ADD, MVT::i1, Custom);
1301 setOperationAction(ISD::MUL, MVT::i1, Custom);
1302 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1303 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1304 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1305 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1306 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1308 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1309 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1310 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1311 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1312 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1313 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1315 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1316 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1317 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1318 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1319 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1320 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1321 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1322 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1324 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1325 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1326 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1327 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1328 if (Subtarget->is64Bit()) {
1329 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1330 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1331 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1332 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1334 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1335 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1336 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1337 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1338 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1339 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1340 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1341 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1342 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1343 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1344 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1346 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1347 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1348 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1349 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1351 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1352 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1353 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1354 if (Subtarget->hasDQI()) {
1355 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1356 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1358 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1359 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1360 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1361 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1362 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1363 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1364 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1365 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1366 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1367 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1368 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1369 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1370 if (Subtarget->hasDQI()) {
1371 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1372 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1374 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1375 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1376 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1377 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1378 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1379 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1380 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1381 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1382 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1383 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1389 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1391 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1392 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1394 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1400 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1401 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1402 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1403 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1404 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1405 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1406 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1408 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1409 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1410 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1411 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1412 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1413 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1414 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1415 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1417 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1418 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1420 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1421 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1423 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1425 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1426 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1428 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1429 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1431 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1432 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1434 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1435 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1436 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1437 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1438 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1439 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1441 if (Subtarget->hasCDI()) {
1442 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1443 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1445 if (Subtarget->hasDQI()) {
1446 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1447 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1448 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1450 // Custom lower several nodes.
1451 for (MVT VT : MVT::vector_valuetypes()) {
1452 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1454 setOperationAction(ISD::AND, VT, Legal);
1455 setOperationAction(ISD::OR, VT, Legal);
1456 setOperationAction(ISD::XOR, VT, Legal);
1458 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1459 setOperationAction(ISD::MGATHER, VT, Custom);
1460 setOperationAction(ISD::MSCATTER, VT, Custom);
1462 // Extract subvector is special because the value type
1463 // (result) is 256/128-bit but the source is 512-bit wide.
1464 if (VT.is128BitVector() || VT.is256BitVector()) {
1465 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1467 if (VT.getVectorElementType() == MVT::i1)
1468 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1470 // Do not attempt to custom lower other non-512-bit vectors
1471 if (!VT.is512BitVector())
1474 if (EltSize >= 32) {
1475 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1476 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1477 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1478 setOperationAction(ISD::VSELECT, VT, Legal);
1479 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1480 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1481 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1482 setOperationAction(ISD::MLOAD, VT, Legal);
1483 setOperationAction(ISD::MSTORE, VT, Legal);
1486 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1487 MVT VT = (MVT::SimpleValueType)i;
1489 // Do not attempt to promote non-512-bit vectors.
1490 if (!VT.is512BitVector())
1493 setOperationAction(ISD::SELECT, VT, Promote);
1494 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1498 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1499 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1500 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1502 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1503 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1505 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1506 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1507 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1508 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1509 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1510 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1511 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1512 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1513 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1514 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1515 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1516 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1517 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1518 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1519 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1520 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1521 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1522 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1523 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1524 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1525 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1526 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1527 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1528 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1529 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1530 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1531 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1532 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1533 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1535 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1536 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1537 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1538 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1539 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1540 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1541 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1542 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1544 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1545 const MVT VT = (MVT::SimpleValueType)i;
1547 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1549 // Do not attempt to promote non-512-bit vectors.
1550 if (!VT.is512BitVector())
1554 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1555 setOperationAction(ISD::VSELECT, VT, Legal);
1560 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1561 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1562 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1564 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1565 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1566 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1567 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1568 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1569 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1570 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1571 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1572 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1573 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1575 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1576 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1577 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1578 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1579 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1580 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1581 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1582 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1584 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1585 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1586 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1587 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1588 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1589 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1590 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1591 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1594 // We want to custom lower some of our intrinsics.
1595 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1596 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1597 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1598 if (!Subtarget->is64Bit())
1599 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1601 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1602 // handle type legalization for these operations here.
1604 // FIXME: We really should do custom legalization for addition and
1605 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1606 // than generic legalization for 64-bit multiplication-with-overflow, though.
1607 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1608 // Add/Sub/Mul with overflow operations are custom lowered.
1610 setOperationAction(ISD::SADDO, VT, Custom);
1611 setOperationAction(ISD::UADDO, VT, Custom);
1612 setOperationAction(ISD::SSUBO, VT, Custom);
1613 setOperationAction(ISD::USUBO, VT, Custom);
1614 setOperationAction(ISD::SMULO, VT, Custom);
1615 setOperationAction(ISD::UMULO, VT, Custom);
1619 if (!Subtarget->is64Bit()) {
1620 // These libcalls are not available in 32-bit.
1621 setLibcallName(RTLIB::SHL_I128, nullptr);
1622 setLibcallName(RTLIB::SRL_I128, nullptr);
1623 setLibcallName(RTLIB::SRA_I128, nullptr);
1626 // Combine sin / cos into one node or libcall if possible.
1627 if (Subtarget->hasSinCos()) {
1628 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1629 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1630 if (Subtarget->isTargetDarwin()) {
1631 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1632 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1633 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1634 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1638 if (Subtarget->isTargetWin64()) {
1639 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1640 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1641 setOperationAction(ISD::SREM, MVT::i128, Custom);
1642 setOperationAction(ISD::UREM, MVT::i128, Custom);
1643 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1644 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1647 // We have target-specific dag combine patterns for the following nodes:
1648 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1649 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1650 setTargetDAGCombine(ISD::BITCAST);
1651 setTargetDAGCombine(ISD::VSELECT);
1652 setTargetDAGCombine(ISD::SELECT);
1653 setTargetDAGCombine(ISD::SHL);
1654 setTargetDAGCombine(ISD::SRA);
1655 setTargetDAGCombine(ISD::SRL);
1656 setTargetDAGCombine(ISD::OR);
1657 setTargetDAGCombine(ISD::AND);
1658 setTargetDAGCombine(ISD::ADD);
1659 setTargetDAGCombine(ISD::FADD);
1660 setTargetDAGCombine(ISD::FSUB);
1661 setTargetDAGCombine(ISD::FMA);
1662 setTargetDAGCombine(ISD::SUB);
1663 setTargetDAGCombine(ISD::LOAD);
1664 setTargetDAGCombine(ISD::MLOAD);
1665 setTargetDAGCombine(ISD::STORE);
1666 setTargetDAGCombine(ISD::MSTORE);
1667 setTargetDAGCombine(ISD::ZERO_EXTEND);
1668 setTargetDAGCombine(ISD::ANY_EXTEND);
1669 setTargetDAGCombine(ISD::SIGN_EXTEND);
1670 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1671 setTargetDAGCombine(ISD::SINT_TO_FP);
1672 setTargetDAGCombine(ISD::UINT_TO_FP);
1673 setTargetDAGCombine(ISD::SETCC);
1674 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1675 setTargetDAGCombine(ISD::BUILD_VECTOR);
1676 setTargetDAGCombine(ISD::MUL);
1677 setTargetDAGCombine(ISD::XOR);
1679 computeRegisterProperties(Subtarget->getRegisterInfo());
1681 // On Darwin, -Os means optimize for size without hurting performance,
1682 // do not reduce the limit.
1683 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1684 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1685 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1686 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1687 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1688 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1689 setPrefLoopAlignment(4); // 2^4 bytes.
1691 // Predictable cmov don't hurt on atom because it's in-order.
1692 PredictableSelectIsExpensive = !Subtarget->isAtom();
1693 EnableExtLdPromotion = true;
1694 setPrefFunctionAlignment(4); // 2^4 bytes.
1696 verifyIntrinsicTables();
1699 // This has so far only been implemented for 64-bit MachO.
1700 bool X86TargetLowering::useLoadStackGuardNode() const {
1701 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1704 TargetLoweringBase::LegalizeTypeAction
1705 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1706 if (ExperimentalVectorWideningLegalization &&
1707 VT.getVectorNumElements() != 1 &&
1708 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1709 return TypeWidenVector;
1711 return TargetLoweringBase::getPreferredVectorAction(VT);
1714 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1717 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1719 const unsigned NumElts = VT.getVectorNumElements();
1720 const EVT EltVT = VT.getVectorElementType();
1721 if (VT.is512BitVector()) {
1722 if (Subtarget->hasAVX512())
1723 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1724 EltVT == MVT::f32 || EltVT == MVT::f64)
1726 case 8: return MVT::v8i1;
1727 case 16: return MVT::v16i1;
1729 if (Subtarget->hasBWI())
1730 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1732 case 32: return MVT::v32i1;
1733 case 64: return MVT::v64i1;
1737 if (VT.is256BitVector() || VT.is128BitVector()) {
1738 if (Subtarget->hasVLX())
1739 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1740 EltVT == MVT::f32 || EltVT == MVT::f64)
1742 case 2: return MVT::v2i1;
1743 case 4: return MVT::v4i1;
1744 case 8: return MVT::v8i1;
1746 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1747 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1749 case 8: return MVT::v8i1;
1750 case 16: return MVT::v16i1;
1751 case 32: return MVT::v32i1;
1755 return VT.changeVectorElementTypeToInteger();
1758 /// Helper for getByValTypeAlignment to determine
1759 /// the desired ByVal argument alignment.
1760 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1763 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1764 if (VTy->getBitWidth() == 128)
1766 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1767 unsigned EltAlign = 0;
1768 getMaxByValAlign(ATy->getElementType(), EltAlign);
1769 if (EltAlign > MaxAlign)
1770 MaxAlign = EltAlign;
1771 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1772 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1773 unsigned EltAlign = 0;
1774 getMaxByValAlign(STy->getElementType(i), EltAlign);
1775 if (EltAlign > MaxAlign)
1776 MaxAlign = EltAlign;
1783 /// Return the desired alignment for ByVal aggregate
1784 /// function arguments in the caller parameter area. For X86, aggregates
1785 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1786 /// are at 4-byte boundaries.
1787 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1788 const DataLayout &DL) const {
1789 if (Subtarget->is64Bit()) {
1790 // Max of 8 and alignment of type.
1791 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1798 if (Subtarget->hasSSE1())
1799 getMaxByValAlign(Ty, Align);
1803 /// Returns the target specific optimal type for load
1804 /// and store operations as a result of memset, memcpy, and memmove
1805 /// lowering. If DstAlign is zero that means it's safe to destination
1806 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1807 /// means there isn't a need to check it against alignment requirement,
1808 /// probably because the source does not need to be loaded. If 'IsMemset' is
1809 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1810 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1811 /// source is constant so it does not need to be loaded.
1812 /// It returns EVT::Other if the type should be determined using generic
1813 /// target-independent logic.
1815 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1816 unsigned DstAlign, unsigned SrcAlign,
1817 bool IsMemset, bool ZeroMemset,
1819 MachineFunction &MF) const {
1820 const Function *F = MF.getFunction();
1821 if ((!IsMemset || ZeroMemset) &&
1822 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1824 (Subtarget->isUnalignedMemAccessFast() ||
1825 ((DstAlign == 0 || DstAlign >= 16) &&
1826 (SrcAlign == 0 || SrcAlign >= 16)))) {
1828 if (Subtarget->hasInt256())
1830 if (Subtarget->hasFp256())
1833 if (Subtarget->hasSSE2())
1835 if (Subtarget->hasSSE1())
1837 } else if (!MemcpyStrSrc && Size >= 8 &&
1838 !Subtarget->is64Bit() &&
1839 Subtarget->hasSSE2()) {
1840 // Do not use f64 to lower memcpy if source is string constant. It's
1841 // better to use i32 to avoid the loads.
1845 if (Subtarget->is64Bit() && Size >= 8)
1850 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1852 return X86ScalarSSEf32;
1853 else if (VT == MVT::f64)
1854 return X86ScalarSSEf64;
1859 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1864 *Fast = Subtarget->isUnalignedMemAccessFast();
1868 /// Return the entry encoding for a jump table in the
1869 /// current function. The returned value is a member of the
1870 /// MachineJumpTableInfo::JTEntryKind enum.
1871 unsigned X86TargetLowering::getJumpTableEncoding() const {
1872 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1874 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1875 Subtarget->isPICStyleGOT())
1876 return MachineJumpTableInfo::EK_Custom32;
1878 // Otherwise, use the normal jump table encoding heuristics.
1879 return TargetLowering::getJumpTableEncoding();
1882 bool X86TargetLowering::useSoftFloat() const {
1883 return Subtarget->useSoftFloat();
1887 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1888 const MachineBasicBlock *MBB,
1889 unsigned uid,MCContext &Ctx) const{
1890 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1891 Subtarget->isPICStyleGOT());
1892 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1894 return MCSymbolRefExpr::create(MBB->getSymbol(),
1895 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1898 /// Returns relocation base for the given PIC jumptable.
1899 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1900 SelectionDAG &DAG) const {
1901 if (!Subtarget->is64Bit())
1902 // This doesn't have SDLoc associated with it, but is not really the
1903 // same as a Register.
1904 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1905 getPointerTy(DAG.getDataLayout()));
1909 /// This returns the relocation base for the given PIC jumptable,
1910 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1911 const MCExpr *X86TargetLowering::
1912 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1913 MCContext &Ctx) const {
1914 // X86-64 uses RIP relative addressing based on the jump table label.
1915 if (Subtarget->isPICStyleRIPRel())
1916 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1918 // Otherwise, the reference is relative to the PIC base.
1919 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1922 std::pair<const TargetRegisterClass *, uint8_t>
1923 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1925 const TargetRegisterClass *RRC = nullptr;
1927 switch (VT.SimpleTy) {
1929 return TargetLowering::findRepresentativeClass(TRI, VT);
1930 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1931 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1934 RRC = &X86::VR64RegClass;
1936 case MVT::f32: case MVT::f64:
1937 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1938 case MVT::v4f32: case MVT::v2f64:
1939 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1941 RRC = &X86::VR128RegClass;
1944 return std::make_pair(RRC, Cost);
1947 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1948 unsigned &Offset) const {
1949 if (!Subtarget->isTargetLinux())
1952 if (Subtarget->is64Bit()) {
1953 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1955 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1967 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1968 unsigned DestAS) const {
1969 assert(SrcAS != DestAS && "Expected different address spaces!");
1971 return SrcAS < 256 && DestAS < 256;
1974 //===----------------------------------------------------------------------===//
1975 // Return Value Calling Convention Implementation
1976 //===----------------------------------------------------------------------===//
1978 #include "X86GenCallingConv.inc"
1981 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1982 MachineFunction &MF, bool isVarArg,
1983 const SmallVectorImpl<ISD::OutputArg> &Outs,
1984 LLVMContext &Context) const {
1985 SmallVector<CCValAssign, 16> RVLocs;
1986 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1987 return CCInfo.CheckReturn(Outs, RetCC_X86);
1990 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1991 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1996 X86TargetLowering::LowerReturn(SDValue Chain,
1997 CallingConv::ID CallConv, bool isVarArg,
1998 const SmallVectorImpl<ISD::OutputArg> &Outs,
1999 const SmallVectorImpl<SDValue> &OutVals,
2000 SDLoc dl, SelectionDAG &DAG) const {
2001 MachineFunction &MF = DAG.getMachineFunction();
2002 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2004 SmallVector<CCValAssign, 16> RVLocs;
2005 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2006 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2009 SmallVector<SDValue, 6> RetOps;
2010 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2011 // Operand #1 = Bytes To Pop
2012 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2015 // Copy the result values into the output registers.
2016 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2017 CCValAssign &VA = RVLocs[i];
2018 assert(VA.isRegLoc() && "Can only return in registers!");
2019 SDValue ValToCopy = OutVals[i];
2020 EVT ValVT = ValToCopy.getValueType();
2022 // Promote values to the appropriate types.
2023 if (VA.getLocInfo() == CCValAssign::SExt)
2024 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2025 else if (VA.getLocInfo() == CCValAssign::ZExt)
2026 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2027 else if (VA.getLocInfo() == CCValAssign::AExt) {
2028 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2029 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2031 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2033 else if (VA.getLocInfo() == CCValAssign::BCvt)
2034 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2036 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2037 "Unexpected FP-extend for return value.");
2039 // If this is x86-64, and we disabled SSE, we can't return FP values,
2040 // or SSE or MMX vectors.
2041 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2042 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2043 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2044 report_fatal_error("SSE register return with SSE disabled");
2046 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2047 // llvm-gcc has never done it right and no one has noticed, so this
2048 // should be OK for now.
2049 if (ValVT == MVT::f64 &&
2050 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2051 report_fatal_error("SSE2 register return with SSE2 disabled");
2053 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2054 // the RET instruction and handled by the FP Stackifier.
2055 if (VA.getLocReg() == X86::FP0 ||
2056 VA.getLocReg() == X86::FP1) {
2057 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2058 // change the value to the FP stack register class.
2059 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2060 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2061 RetOps.push_back(ValToCopy);
2062 // Don't emit a copytoreg.
2066 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2067 // which is returned in RAX / RDX.
2068 if (Subtarget->is64Bit()) {
2069 if (ValVT == MVT::x86mmx) {
2070 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2071 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2072 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2074 // If we don't have SSE2 available, convert to v4f32 so the generated
2075 // register is legal.
2076 if (!Subtarget->hasSSE2())
2077 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2082 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2083 Flag = Chain.getValue(1);
2084 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2087 // All x86 ABIs require that for returning structs by value we copy
2088 // the sret argument into %rax/%eax (depending on ABI) for the return.
2089 // We saved the argument into a virtual register in the entry block,
2090 // so now we copy the value out and into %rax/%eax.
2092 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2093 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2094 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2095 // either case FuncInfo->setSRetReturnReg() will have been called.
2096 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2097 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2098 getPointerTy(MF.getDataLayout()));
2101 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2102 X86::RAX : X86::EAX;
2103 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2104 Flag = Chain.getValue(1);
2106 // RAX/EAX now acts like a return value.
2108 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2111 RetOps[0] = Chain; // Update chain.
2113 // Add the flag if we have it.
2115 RetOps.push_back(Flag);
2117 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2120 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2121 if (N->getNumValues() != 1)
2123 if (!N->hasNUsesOfValue(1, 0))
2126 SDValue TCChain = Chain;
2127 SDNode *Copy = *N->use_begin();
2128 if (Copy->getOpcode() == ISD::CopyToReg) {
2129 // If the copy has a glue operand, we conservatively assume it isn't safe to
2130 // perform a tail call.
2131 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2133 TCChain = Copy->getOperand(0);
2134 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2137 bool HasRet = false;
2138 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2140 if (UI->getOpcode() != X86ISD::RET_FLAG)
2142 // If we are returning more than one value, we can definitely
2143 // not make a tail call see PR19530
2144 if (UI->getNumOperands() > 4)
2146 if (UI->getNumOperands() == 4 &&
2147 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2160 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2161 ISD::NodeType ExtendKind) const {
2163 // TODO: Is this also valid on 32-bit?
2164 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2165 ReturnMVT = MVT::i8;
2167 ReturnMVT = MVT::i32;
2169 EVT MinVT = getRegisterType(Context, ReturnMVT);
2170 return VT.bitsLT(MinVT) ? MinVT : VT;
2173 /// Lower the result values of a call into the
2174 /// appropriate copies out of appropriate physical registers.
2177 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2178 CallingConv::ID CallConv, bool isVarArg,
2179 const SmallVectorImpl<ISD::InputArg> &Ins,
2180 SDLoc dl, SelectionDAG &DAG,
2181 SmallVectorImpl<SDValue> &InVals) const {
2183 // Assign locations to each value returned by this call.
2184 SmallVector<CCValAssign, 16> RVLocs;
2185 bool Is64Bit = Subtarget->is64Bit();
2186 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2188 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2190 // Copy all of the result registers out of their specified physreg.
2191 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2192 CCValAssign &VA = RVLocs[i];
2193 EVT CopyVT = VA.getLocVT();
2195 // If this is x86-64, and we disabled SSE, we can't return FP values
2196 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2197 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2198 report_fatal_error("SSE register return with SSE disabled");
2201 // If we prefer to use the value in xmm registers, copy it out as f80 and
2202 // use a truncate to move it from fp stack reg to xmm reg.
2203 bool RoundAfterCopy = false;
2204 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2205 isScalarFPTypeInSSEReg(VA.getValVT())) {
2207 RoundAfterCopy = (CopyVT != VA.getLocVT());
2210 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2211 CopyVT, InFlag).getValue(1);
2212 SDValue Val = Chain.getValue(0);
2215 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2216 // This truncation won't change the value.
2217 DAG.getIntPtrConstant(1, dl));
2219 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2220 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2222 InFlag = Chain.getValue(2);
2223 InVals.push_back(Val);
2229 //===----------------------------------------------------------------------===//
2230 // C & StdCall & Fast Calling Convention implementation
2231 //===----------------------------------------------------------------------===//
2232 // StdCall calling convention seems to be standard for many Windows' API
2233 // routines and around. It differs from C calling convention just a little:
2234 // callee should clean up the stack, not caller. Symbols should be also
2235 // decorated in some fancy way :) It doesn't support any vector arguments.
2236 // For info on fast calling convention see Fast Calling Convention (tail call)
2237 // implementation LowerX86_32FastCCCallTo.
2239 /// CallIsStructReturn - Determines whether a call uses struct return
2241 enum StructReturnType {
2246 static StructReturnType
2247 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2249 return NotStructReturn;
2251 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2252 if (!Flags.isSRet())
2253 return NotStructReturn;
2254 if (Flags.isInReg())
2255 return RegStructReturn;
2256 return StackStructReturn;
2259 /// Determines whether a function uses struct return semantics.
2260 static StructReturnType
2261 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2263 return NotStructReturn;
2265 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2266 if (!Flags.isSRet())
2267 return NotStructReturn;
2268 if (Flags.isInReg())
2269 return RegStructReturn;
2270 return StackStructReturn;
2273 /// Make a copy of an aggregate at address specified by "Src" to address
2274 /// "Dst" with size and alignment information specified by the specific
2275 /// parameter attribute. The copy will be passed as a byval function parameter.
2277 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2278 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2280 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2282 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2283 /*isVolatile*/false, /*AlwaysInline=*/true,
2284 /*isTailCall*/false,
2285 MachinePointerInfo(), MachinePointerInfo());
2288 /// Return true if the calling convention is one that
2289 /// supports tail call optimization.
2290 static bool IsTailCallConvention(CallingConv::ID CC) {
2291 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2292 CC == CallingConv::HiPE);
2295 /// \brief Return true if the calling convention is a C calling convention.
2296 static bool IsCCallConvention(CallingConv::ID CC) {
2297 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2298 CC == CallingConv::X86_64_SysV);
2301 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2303 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2304 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2308 CallingConv::ID CalleeCC = CS.getCallingConv();
2309 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2315 /// Return true if the function is being made into
2316 /// a tailcall target by changing its ABI.
2317 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2318 bool GuaranteedTailCallOpt) {
2319 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2323 X86TargetLowering::LowerMemArgument(SDValue Chain,
2324 CallingConv::ID CallConv,
2325 const SmallVectorImpl<ISD::InputArg> &Ins,
2326 SDLoc dl, SelectionDAG &DAG,
2327 const CCValAssign &VA,
2328 MachineFrameInfo *MFI,
2330 // Create the nodes corresponding to a load from this parameter slot.
2331 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2332 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2333 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2334 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2337 // If value is passed by pointer we have address passed instead of the value
2339 bool ExtendedInMem = VA.isExtInLoc() &&
2340 VA.getValVT().getScalarType() == MVT::i1;
2342 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2343 ValVT = VA.getLocVT();
2345 ValVT = VA.getValVT();
2347 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2348 // changed with more analysis.
2349 // In case of tail call optimization mark all arguments mutable. Since they
2350 // could be overwritten by lowering of arguments in case of a tail call.
2351 if (Flags.isByVal()) {
2352 unsigned Bytes = Flags.getByValSize();
2353 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2354 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2355 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2357 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2358 VA.getLocMemOffset(), isImmutable);
2359 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2360 SDValue Val = DAG.getLoad(ValVT, dl, Chain, FIN,
2361 MachinePointerInfo::getFixedStack(FI),
2362 false, false, false, 0);
2363 return ExtendedInMem ?
2364 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2368 // FIXME: Get this from tablegen.
2369 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2370 const X86Subtarget *Subtarget) {
2371 assert(Subtarget->is64Bit());
2373 if (Subtarget->isCallingConvWin64(CallConv)) {
2374 static const MCPhysReg GPR64ArgRegsWin64[] = {
2375 X86::RCX, X86::RDX, X86::R8, X86::R9
2377 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2380 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2381 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2383 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2386 // FIXME: Get this from tablegen.
2387 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2388 CallingConv::ID CallConv,
2389 const X86Subtarget *Subtarget) {
2390 assert(Subtarget->is64Bit());
2391 if (Subtarget->isCallingConvWin64(CallConv)) {
2392 // The XMM registers which might contain var arg parameters are shadowed
2393 // in their paired GPR. So we only need to save the GPR to their home
2395 // TODO: __vectorcall will change this.
2399 const Function *Fn = MF.getFunction();
2400 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2401 bool isSoftFloat = Subtarget->useSoftFloat();
2402 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2403 "SSE register cannot be used when SSE is disabled!");
2404 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2405 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2409 static const MCPhysReg XMMArgRegs64Bit[] = {
2410 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2411 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2413 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2417 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2418 CallingConv::ID CallConv,
2420 const SmallVectorImpl<ISD::InputArg> &Ins,
2423 SmallVectorImpl<SDValue> &InVals)
2425 MachineFunction &MF = DAG.getMachineFunction();
2426 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2427 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2429 const Function* Fn = MF.getFunction();
2430 if (Fn->hasExternalLinkage() &&
2431 Subtarget->isTargetCygMing() &&
2432 Fn->getName() == "main")
2433 FuncInfo->setForceFramePointer(true);
2435 MachineFrameInfo *MFI = MF.getFrameInfo();
2436 bool Is64Bit = Subtarget->is64Bit();
2437 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2439 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2440 "Var args not supported with calling convention fastcc, ghc or hipe");
2442 // Assign locations to all of the incoming arguments.
2443 SmallVector<CCValAssign, 16> ArgLocs;
2444 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2446 // Allocate shadow area for Win64
2448 CCInfo.AllocateStack(32, 8);
2450 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2452 unsigned LastVal = ~0U;
2454 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2455 CCValAssign &VA = ArgLocs[i];
2456 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2458 assert(VA.getValNo() != LastVal &&
2459 "Don't support value assigned to multiple locs yet");
2461 LastVal = VA.getValNo();
2463 if (VA.isRegLoc()) {
2464 EVT RegVT = VA.getLocVT();
2465 const TargetRegisterClass *RC;
2466 if (RegVT == MVT::i32)
2467 RC = &X86::GR32RegClass;
2468 else if (Is64Bit && RegVT == MVT::i64)
2469 RC = &X86::GR64RegClass;
2470 else if (RegVT == MVT::f32)
2471 RC = &X86::FR32RegClass;
2472 else if (RegVT == MVT::f64)
2473 RC = &X86::FR64RegClass;
2474 else if (RegVT.is512BitVector())
2475 RC = &X86::VR512RegClass;
2476 else if (RegVT.is256BitVector())
2477 RC = &X86::VR256RegClass;
2478 else if (RegVT.is128BitVector())
2479 RC = &X86::VR128RegClass;
2480 else if (RegVT == MVT::x86mmx)
2481 RC = &X86::VR64RegClass;
2482 else if (RegVT == MVT::i1)
2483 RC = &X86::VK1RegClass;
2484 else if (RegVT == MVT::v8i1)
2485 RC = &X86::VK8RegClass;
2486 else if (RegVT == MVT::v16i1)
2487 RC = &X86::VK16RegClass;
2488 else if (RegVT == MVT::v32i1)
2489 RC = &X86::VK32RegClass;
2490 else if (RegVT == MVT::v64i1)
2491 RC = &X86::VK64RegClass;
2493 llvm_unreachable("Unknown argument type!");
2495 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2496 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2498 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2499 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2501 if (VA.getLocInfo() == CCValAssign::SExt)
2502 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2503 DAG.getValueType(VA.getValVT()));
2504 else if (VA.getLocInfo() == CCValAssign::ZExt)
2505 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2506 DAG.getValueType(VA.getValVT()));
2507 else if (VA.getLocInfo() == CCValAssign::BCvt)
2508 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2510 if (VA.isExtInLoc()) {
2511 // Handle MMX values passed in XMM regs.
2512 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2513 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2515 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2518 assert(VA.isMemLoc());
2519 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2522 // If value is passed via pointer - do a load.
2523 if (VA.getLocInfo() == CCValAssign::Indirect)
2524 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2525 MachinePointerInfo(), false, false, false, 0);
2527 InVals.push_back(ArgValue);
2530 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2531 // All x86 ABIs require that for returning structs by value we copy the
2532 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2533 // the argument into a virtual register so that we can access it from the
2535 if (Ins[i].Flags.isSRet()) {
2536 unsigned Reg = FuncInfo->getSRetReturnReg();
2538 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2539 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2540 FuncInfo->setSRetReturnReg(Reg);
2542 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2543 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2548 unsigned StackSize = CCInfo.getNextStackOffset();
2549 // Align stack specially for tail calls.
2550 if (FuncIsMadeTailCallSafe(CallConv,
2551 MF.getTarget().Options.GuaranteedTailCallOpt))
2552 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2554 // If the function takes variable number of arguments, make a frame index for
2555 // the start of the first vararg value... for expansion of llvm.va_start. We
2556 // can skip this if there are no va_start calls.
2557 if (MFI->hasVAStart() &&
2558 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2559 CallConv != CallingConv::X86_ThisCall))) {
2560 FuncInfo->setVarArgsFrameIndex(
2561 MFI->CreateFixedObject(1, StackSize, true));
2564 MachineModuleInfo &MMI = MF.getMMI();
2565 const Function *WinEHParent = nullptr;
2566 if (MMI.hasWinEHFuncInfo(Fn))
2567 WinEHParent = MMI.getWinEHParent(Fn);
2568 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2569 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2571 // Figure out if XMM registers are in use.
2572 assert(!(Subtarget->useSoftFloat() &&
2573 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2574 "SSE register cannot be used when SSE is disabled!");
2576 // 64-bit calling conventions support varargs and register parameters, so we
2577 // have to do extra work to spill them in the prologue.
2578 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2579 // Find the first unallocated argument registers.
2580 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2581 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2582 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2583 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2584 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2585 "SSE register cannot be used when SSE is disabled!");
2587 // Gather all the live in physical registers.
2588 SmallVector<SDValue, 6> LiveGPRs;
2589 SmallVector<SDValue, 8> LiveXMMRegs;
2591 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2592 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2594 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2596 if (!ArgXMMs.empty()) {
2597 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2598 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2599 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2600 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2601 LiveXMMRegs.push_back(
2602 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2607 // Get to the caller-allocated home save location. Add 8 to account
2608 // for the return address.
2609 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2610 FuncInfo->setRegSaveFrameIndex(
2611 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2612 // Fixup to set vararg frame on shadow area (4 x i64).
2614 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2616 // For X86-64, if there are vararg parameters that are passed via
2617 // registers, then we must store them to their spots on the stack so
2618 // they may be loaded by deferencing the result of va_next.
2619 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2620 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2621 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2622 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2625 // Store the integer parameter registers.
2626 SmallVector<SDValue, 8> MemOps;
2627 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2628 getPointerTy(DAG.getDataLayout()));
2629 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2630 for (SDValue Val : LiveGPRs) {
2631 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2632 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2634 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2635 MachinePointerInfo::getFixedStack(
2636 FuncInfo->getRegSaveFrameIndex(), Offset),
2638 MemOps.push_back(Store);
2642 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2643 // Now store the XMM (fp + vector) parameter registers.
2644 SmallVector<SDValue, 12> SaveXMMOps;
2645 SaveXMMOps.push_back(Chain);
2646 SaveXMMOps.push_back(ALVal);
2647 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2648 FuncInfo->getRegSaveFrameIndex(), dl));
2649 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2650 FuncInfo->getVarArgsFPOffset(), dl));
2651 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2653 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2654 MVT::Other, SaveXMMOps));
2657 if (!MemOps.empty())
2658 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2659 } else if (IsWin64 && IsWinEHOutlined) {
2660 // Get to the caller-allocated home save location. Add 8 to account
2661 // for the return address.
2662 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2663 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2664 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2666 MMI.getWinEHFuncInfo(Fn)
2667 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2668 FuncInfo->getRegSaveFrameIndex();
2670 // Store the second integer parameter (rdx) into rsp+16 relative to the
2671 // stack pointer at the entry of the function.
2672 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2673 getPointerTy(DAG.getDataLayout()));
2674 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2675 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2676 Chain = DAG.getStore(
2677 Val.getValue(1), dl, Val, RSFIN,
2678 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2679 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2682 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2683 // Find the largest legal vector type.
2684 MVT VecVT = MVT::Other;
2685 // FIXME: Only some x86_32 calling conventions support AVX512.
2686 if (Subtarget->hasAVX512() &&
2687 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2688 CallConv == CallingConv::Intel_OCL_BI)))
2689 VecVT = MVT::v16f32;
2690 else if (Subtarget->hasAVX())
2692 else if (Subtarget->hasSSE2())
2695 // We forward some GPRs and some vector types.
2696 SmallVector<MVT, 2> RegParmTypes;
2697 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2698 RegParmTypes.push_back(IntVT);
2699 if (VecVT != MVT::Other)
2700 RegParmTypes.push_back(VecVT);
2702 // Compute the set of forwarded registers. The rest are scratch.
2703 SmallVectorImpl<ForwardedRegister> &Forwards =
2704 FuncInfo->getForwardedMustTailRegParms();
2705 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2707 // Conservatively forward AL on x86_64, since it might be used for varargs.
2708 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2709 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2710 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2713 // Copy all forwards from physical to virtual registers.
2714 for (ForwardedRegister &F : Forwards) {
2715 // FIXME: Can we use a less constrained schedule?
2716 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2717 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2718 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2722 // Some CCs need callee pop.
2723 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2724 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2725 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2727 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2728 // If this is an sret function, the return should pop the hidden pointer.
2729 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2730 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2731 argsAreStructReturn(Ins) == StackStructReturn)
2732 FuncInfo->setBytesToPopOnReturn(4);
2736 // RegSaveFrameIndex is X86-64 only.
2737 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2738 if (CallConv == CallingConv::X86_FastCall ||
2739 CallConv == CallingConv::X86_ThisCall)
2740 // fastcc functions can't have varargs.
2741 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2744 FuncInfo->setArgumentStackSize(StackSize);
2746 if (IsWinEHParent) {
2748 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2749 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2750 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2751 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2752 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2753 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2754 /*isVolatile=*/true,
2755 /*isNonTemporal=*/false, /*Alignment=*/0);
2757 // Functions using Win32 EH are considered to have opaque SP adjustments
2758 // to force local variables to be addressed from the frame or base
2760 MFI->setHasOpaqueSPAdjustment(true);
2768 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2769 SDValue StackPtr, SDValue Arg,
2770 SDLoc dl, SelectionDAG &DAG,
2771 const CCValAssign &VA,
2772 ISD::ArgFlagsTy Flags) const {
2773 unsigned LocMemOffset = VA.getLocMemOffset();
2774 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2775 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2777 if (Flags.isByVal())
2778 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2780 return DAG.getStore(Chain, dl, Arg, PtrOff,
2781 MachinePointerInfo::getStack(LocMemOffset),
2785 /// Emit a load of return address if tail call
2786 /// optimization is performed and it is required.
2788 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2789 SDValue &OutRetAddr, SDValue Chain,
2790 bool IsTailCall, bool Is64Bit,
2791 int FPDiff, SDLoc dl) const {
2792 // Adjust the Return address stack slot.
2793 EVT VT = getPointerTy(DAG.getDataLayout());
2794 OutRetAddr = getReturnAddressFrameIndex(DAG);
2796 // Load the "old" Return address.
2797 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2798 false, false, false, 0);
2799 return SDValue(OutRetAddr.getNode(), 1);
2802 /// Emit a store of the return address if tail call
2803 /// optimization is performed and it is required (FPDiff!=0).
2804 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2805 SDValue Chain, SDValue RetAddrFrIdx,
2806 EVT PtrVT, unsigned SlotSize,
2807 int FPDiff, SDLoc dl) {
2808 // Store the return address to the appropriate stack slot.
2809 if (!FPDiff) return Chain;
2810 // Calculate the new stack slot for the return address.
2811 int NewReturnAddrFI =
2812 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2814 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2815 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2816 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2822 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2823 SmallVectorImpl<SDValue> &InVals) const {
2824 SelectionDAG &DAG = CLI.DAG;
2826 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2827 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2828 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2829 SDValue Chain = CLI.Chain;
2830 SDValue Callee = CLI.Callee;
2831 CallingConv::ID CallConv = CLI.CallConv;
2832 bool &isTailCall = CLI.IsTailCall;
2833 bool isVarArg = CLI.IsVarArg;
2835 MachineFunction &MF = DAG.getMachineFunction();
2836 bool Is64Bit = Subtarget->is64Bit();
2837 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2838 StructReturnType SR = callIsStructReturn(Outs);
2839 bool IsSibcall = false;
2840 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2841 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2843 if (Attr.getValueAsString() == "true")
2846 if (Subtarget->isPICStyleGOT() &&
2847 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2848 // If we are using a GOT, disable tail calls to external symbols with
2849 // default visibility. Tail calling such a symbol requires using a GOT
2850 // relocation, which forces early binding of the symbol. This breaks code
2851 // that require lazy function symbol resolution. Using musttail or
2852 // GuaranteedTailCallOpt will override this.
2853 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2854 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2855 G->getGlobal()->hasDefaultVisibility()))
2859 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2861 // Force this to be a tail call. The verifier rules are enough to ensure
2862 // that we can lower this successfully without moving the return address
2865 } else if (isTailCall) {
2866 // Check if it's really possible to do a tail call.
2867 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2868 isVarArg, SR != NotStructReturn,
2869 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2870 Outs, OutVals, Ins, DAG);
2872 // Sibcalls are automatically detected tailcalls which do not require
2874 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2881 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2882 "Var args not supported with calling convention fastcc, ghc or hipe");
2884 // Analyze operands of the call, assigning locations to each operand.
2885 SmallVector<CCValAssign, 16> ArgLocs;
2886 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2888 // Allocate shadow area for Win64
2890 CCInfo.AllocateStack(32, 8);
2892 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2894 // Get a count of how many bytes are to be pushed on the stack.
2895 unsigned NumBytes = CCInfo.getNextStackOffset();
2897 // This is a sibcall. The memory operands are available in caller's
2898 // own caller's stack.
2900 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2901 IsTailCallConvention(CallConv))
2902 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2905 if (isTailCall && !IsSibcall && !IsMustTail) {
2906 // Lower arguments at fp - stackoffset + fpdiff.
2907 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2909 FPDiff = NumBytesCallerPushed - NumBytes;
2911 // Set the delta of movement of the returnaddr stackslot.
2912 // But only set if delta is greater than previous delta.
2913 if (FPDiff < X86Info->getTCReturnAddrDelta())
2914 X86Info->setTCReturnAddrDelta(FPDiff);
2917 unsigned NumBytesToPush = NumBytes;
2918 unsigned NumBytesToPop = NumBytes;
2920 // If we have an inalloca argument, all stack space has already been allocated
2921 // for us and be right at the top of the stack. We don't support multiple
2922 // arguments passed in memory when using inalloca.
2923 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2925 if (!ArgLocs.back().isMemLoc())
2926 report_fatal_error("cannot use inalloca attribute on a register "
2928 if (ArgLocs.back().getLocMemOffset() != 0)
2929 report_fatal_error("any parameter with the inalloca attribute must be "
2930 "the only memory argument");
2934 Chain = DAG.getCALLSEQ_START(
2935 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2937 SDValue RetAddrFrIdx;
2938 // Load return address for tail calls.
2939 if (isTailCall && FPDiff)
2940 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2941 Is64Bit, FPDiff, dl);
2943 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2944 SmallVector<SDValue, 8> MemOpChains;
2947 // Walk the register/memloc assignments, inserting copies/loads. In the case
2948 // of tail call optimization arguments are handle later.
2949 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2950 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2951 // Skip inalloca arguments, they have already been written.
2952 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2953 if (Flags.isInAlloca())
2956 CCValAssign &VA = ArgLocs[i];
2957 EVT RegVT = VA.getLocVT();
2958 SDValue Arg = OutVals[i];
2959 bool isByVal = Flags.isByVal();
2961 // Promote the value if needed.
2962 switch (VA.getLocInfo()) {
2963 default: llvm_unreachable("Unknown loc info!");
2964 case CCValAssign::Full: break;
2965 case CCValAssign::SExt:
2966 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2968 case CCValAssign::ZExt:
2969 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2971 case CCValAssign::AExt:
2972 if (Arg.getValueType().isVector() &&
2973 Arg.getValueType().getScalarType() == MVT::i1)
2974 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2975 else if (RegVT.is128BitVector()) {
2976 // Special case: passing MMX values in XMM registers.
2977 Arg = DAG.getBitcast(MVT::i64, Arg);
2978 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2979 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2981 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2983 case CCValAssign::BCvt:
2984 Arg = DAG.getBitcast(RegVT, Arg);
2986 case CCValAssign::Indirect: {
2987 // Store the argument.
2988 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2989 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2990 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2991 MachinePointerInfo::getFixedStack(FI),
2998 if (VA.isRegLoc()) {
2999 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3000 if (isVarArg && IsWin64) {
3001 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3002 // shadow reg if callee is a varargs function.
3003 unsigned ShadowReg = 0;
3004 switch (VA.getLocReg()) {
3005 case X86::XMM0: ShadowReg = X86::RCX; break;
3006 case X86::XMM1: ShadowReg = X86::RDX; break;
3007 case X86::XMM2: ShadowReg = X86::R8; break;
3008 case X86::XMM3: ShadowReg = X86::R9; break;
3011 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3013 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3014 assert(VA.isMemLoc());
3015 if (!StackPtr.getNode())
3016 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3017 getPointerTy(DAG.getDataLayout()));
3018 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3019 dl, DAG, VA, Flags));
3023 if (!MemOpChains.empty())
3024 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3026 if (Subtarget->isPICStyleGOT()) {
3027 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3030 RegsToPass.push_back(std::make_pair(
3031 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3032 getPointerTy(DAG.getDataLayout()))));
3034 // If we are tail calling and generating PIC/GOT style code load the
3035 // address of the callee into ECX. The value in ecx is used as target of
3036 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3037 // for tail calls on PIC/GOT architectures. Normally we would just put the
3038 // address of GOT into ebx and then call target@PLT. But for tail calls
3039 // ebx would be restored (since ebx is callee saved) before jumping to the
3042 // Note: The actual moving to ECX is done further down.
3043 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3044 if (G && !G->getGlobal()->hasLocalLinkage() &&
3045 G->getGlobal()->hasDefaultVisibility())
3046 Callee = LowerGlobalAddress(Callee, DAG);
3047 else if (isa<ExternalSymbolSDNode>(Callee))
3048 Callee = LowerExternalSymbol(Callee, DAG);
3052 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3053 // From AMD64 ABI document:
3054 // For calls that may call functions that use varargs or stdargs
3055 // (prototype-less calls or calls to functions containing ellipsis (...) in
3056 // the declaration) %al is used as hidden argument to specify the number
3057 // of SSE registers used. The contents of %al do not need to match exactly
3058 // the number of registers, but must be an ubound on the number of SSE
3059 // registers used and is in the range 0 - 8 inclusive.
3061 // Count the number of XMM registers allocated.
3062 static const MCPhysReg XMMArgRegs[] = {
3063 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3064 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3066 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3067 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3068 && "SSE registers cannot be used when SSE is disabled");
3070 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3071 DAG.getConstant(NumXMMRegs, dl,
3075 if (isVarArg && IsMustTail) {
3076 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3077 for (const auto &F : Forwards) {
3078 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3079 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3083 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3084 // don't need this because the eligibility check rejects calls that require
3085 // shuffling arguments passed in memory.
3086 if (!IsSibcall && isTailCall) {
3087 // Force all the incoming stack arguments to be loaded from the stack
3088 // before any new outgoing arguments are stored to the stack, because the
3089 // outgoing stack slots may alias the incoming argument stack slots, and
3090 // the alias isn't otherwise explicit. This is slightly more conservative
3091 // than necessary, because it means that each store effectively depends
3092 // on every argument instead of just those arguments it would clobber.
3093 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3095 SmallVector<SDValue, 8> MemOpChains2;
3098 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3099 CCValAssign &VA = ArgLocs[i];
3102 assert(VA.isMemLoc());
3103 SDValue Arg = OutVals[i];
3104 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3105 // Skip inalloca arguments. They don't require any work.
3106 if (Flags.isInAlloca())
3108 // Create frame index.
3109 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3110 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3111 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3112 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3114 if (Flags.isByVal()) {
3115 // Copy relative to framepointer.
3116 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3117 if (!StackPtr.getNode())
3118 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3119 getPointerTy(DAG.getDataLayout()));
3120 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3123 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3127 // Store relative to framepointer.
3128 MemOpChains2.push_back(
3129 DAG.getStore(ArgChain, dl, Arg, FIN,
3130 MachinePointerInfo::getFixedStack(FI),
3135 if (!MemOpChains2.empty())
3136 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3138 // Store the return address to the appropriate stack slot.
3139 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3140 getPointerTy(DAG.getDataLayout()),
3141 RegInfo->getSlotSize(), FPDiff, dl);
3144 // Build a sequence of copy-to-reg nodes chained together with token chain
3145 // and flag operands which copy the outgoing args into registers.
3147 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3148 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3149 RegsToPass[i].second, InFlag);
3150 InFlag = Chain.getValue(1);
3153 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3154 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3155 // In the 64-bit large code model, we have to make all calls
3156 // through a register, since the call instruction's 32-bit
3157 // pc-relative offset may not be large enough to hold the whole
3159 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3160 // If the callee is a GlobalAddress node (quite common, every direct call
3161 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3163 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3165 // We should use extra load for direct calls to dllimported functions in
3167 const GlobalValue *GV = G->getGlobal();
3168 if (!GV->hasDLLImportStorageClass()) {
3169 unsigned char OpFlags = 0;
3170 bool ExtraLoad = false;
3171 unsigned WrapperKind = ISD::DELETED_NODE;
3173 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3174 // external symbols most go through the PLT in PIC mode. If the symbol
3175 // has hidden or protected visibility, or if it is static or local, then
3176 // we don't need to use the PLT - we can directly call it.
3177 if (Subtarget->isTargetELF() &&
3178 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3179 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3180 OpFlags = X86II::MO_PLT;
3181 } else if (Subtarget->isPICStyleStubAny() &&
3182 !GV->isStrongDefinitionForLinker() &&
3183 (!Subtarget->getTargetTriple().isMacOSX() ||
3184 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3185 // PC-relative references to external symbols should go through $stub,
3186 // unless we're building with the leopard linker or later, which
3187 // automatically synthesizes these stubs.
3188 OpFlags = X86II::MO_DARWIN_STUB;
3189 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3190 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3191 // If the function is marked as non-lazy, generate an indirect call
3192 // which loads from the GOT directly. This avoids runtime overhead
3193 // at the cost of eager binding (and one extra byte of encoding).
3194 OpFlags = X86II::MO_GOTPCREL;
3195 WrapperKind = X86ISD::WrapperRIP;
3199 Callee = DAG.getTargetGlobalAddress(
3200 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3202 // Add a wrapper if needed.
3203 if (WrapperKind != ISD::DELETED_NODE)
3204 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3205 getPointerTy(DAG.getDataLayout()), Callee);
3206 // Add extra indirection if needed.
3208 Callee = DAG.getLoad(
3209 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3210 MachinePointerInfo::getGOT(), false, false, false, 0);
3212 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3213 unsigned char OpFlags = 0;
3215 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3216 // external symbols should go through the PLT.
3217 if (Subtarget->isTargetELF() &&
3218 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3219 OpFlags = X86II::MO_PLT;
3220 } else if (Subtarget->isPICStyleStubAny() &&
3221 (!Subtarget->getTargetTriple().isMacOSX() ||
3222 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3223 // PC-relative references to external symbols should go through $stub,
3224 // unless we're building with the leopard linker or later, which
3225 // automatically synthesizes these stubs.
3226 OpFlags = X86II::MO_DARWIN_STUB;
3229 Callee = DAG.getTargetExternalSymbol(
3230 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3231 } else if (Subtarget->isTarget64BitILP32() &&
3232 Callee->getValueType(0) == MVT::i32) {
3233 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3234 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3237 // Returns a chain & a flag for retval copy to use.
3238 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3239 SmallVector<SDValue, 8> Ops;
3241 if (!IsSibcall && isTailCall) {
3242 Chain = DAG.getCALLSEQ_END(Chain,
3243 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3244 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3245 InFlag = Chain.getValue(1);
3248 Ops.push_back(Chain);
3249 Ops.push_back(Callee);
3252 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3254 // Add argument registers to the end of the list so that they are known live
3256 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3257 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3258 RegsToPass[i].second.getValueType()));
3260 // Add a register mask operand representing the call-preserved registers.
3261 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3262 assert(Mask && "Missing call preserved mask for calling convention");
3264 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3265 // the function clobbers all registers. If an exception is thrown, the runtime
3266 // will not restore CSRs.
3267 // FIXME: Model this more precisely so that we can register allocate across
3268 // the normal edge and spill and fill across the exceptional edge.
3269 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3270 const Function *CallerFn = MF.getFunction();
3271 EHPersonality Pers =
3272 CallerFn->hasPersonalityFn()
3273 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3274 : EHPersonality::Unknown;
3275 if (isMSVCEHPersonality(Pers))
3276 Mask = RegInfo->getNoPreservedMask();
3279 Ops.push_back(DAG.getRegisterMask(Mask));
3281 if (InFlag.getNode())
3282 Ops.push_back(InFlag);
3286 //// If this is the first return lowered for this function, add the regs
3287 //// to the liveout set for the function.
3288 // This isn't right, although it's probably harmless on x86; liveouts
3289 // should be computed from returns not tail calls. Consider a void
3290 // function making a tail call to a function returning int.
3291 MF.getFrameInfo()->setHasTailCall();
3292 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3295 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3296 InFlag = Chain.getValue(1);
3298 // Create the CALLSEQ_END node.
3299 unsigned NumBytesForCalleeToPop;
3300 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3301 DAG.getTarget().Options.GuaranteedTailCallOpt))
3302 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3303 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3304 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3305 SR == StackStructReturn)
3306 // If this is a call to a struct-return function, the callee
3307 // pops the hidden struct pointer, so we have to push it back.
3308 // This is common for Darwin/X86, Linux & Mingw32 targets.
3309 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3310 NumBytesForCalleeToPop = 4;
3312 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3314 // Returns a flag for retval copy to use.
3316 Chain = DAG.getCALLSEQ_END(Chain,
3317 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3318 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3321 InFlag = Chain.getValue(1);
3324 // Handle result values, copying them out of physregs into vregs that we
3326 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3327 Ins, dl, DAG, InVals);
3330 //===----------------------------------------------------------------------===//
3331 // Fast Calling Convention (tail call) implementation
3332 //===----------------------------------------------------------------------===//
3334 // Like std call, callee cleans arguments, convention except that ECX is
3335 // reserved for storing the tail called function address. Only 2 registers are
3336 // free for argument passing (inreg). Tail call optimization is performed
3338 // * tailcallopt is enabled
3339 // * caller/callee are fastcc
3340 // On X86_64 architecture with GOT-style position independent code only local
3341 // (within module) calls are supported at the moment.
3342 // To keep the stack aligned according to platform abi the function
3343 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3344 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3345 // If a tail called function callee has more arguments than the caller the
3346 // caller needs to make sure that there is room to move the RETADDR to. This is
3347 // achieved by reserving an area the size of the argument delta right after the
3348 // original RETADDR, but before the saved framepointer or the spilled registers
3349 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3361 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3362 /// for a 16 byte align requirement.
3364 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3365 SelectionDAG& DAG) const {
3366 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3367 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3368 unsigned StackAlignment = TFI.getStackAlignment();
3369 uint64_t AlignMask = StackAlignment - 1;
3370 int64_t Offset = StackSize;
3371 unsigned SlotSize = RegInfo->getSlotSize();
3372 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3373 // Number smaller than 12 so just add the difference.
3374 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3376 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3377 Offset = ((~AlignMask) & Offset) + StackAlignment +
3378 (StackAlignment-SlotSize);
3383 /// MatchingStackOffset - Return true if the given stack call argument is
3384 /// already available in the same position (relatively) of the caller's
3385 /// incoming argument stack.
3387 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3388 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3389 const X86InstrInfo *TII) {
3390 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3392 if (Arg.getOpcode() == ISD::CopyFromReg) {
3393 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3394 if (!TargetRegisterInfo::isVirtualRegister(VR))
3396 MachineInstr *Def = MRI->getVRegDef(VR);
3399 if (!Flags.isByVal()) {
3400 if (!TII->isLoadFromStackSlot(Def, FI))
3403 unsigned Opcode = Def->getOpcode();
3404 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3405 Opcode == X86::LEA64_32r) &&
3406 Def->getOperand(1).isFI()) {
3407 FI = Def->getOperand(1).getIndex();
3408 Bytes = Flags.getByValSize();
3412 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3413 if (Flags.isByVal())
3414 // ByVal argument is passed in as a pointer but it's now being
3415 // dereferenced. e.g.
3416 // define @foo(%struct.X* %A) {
3417 // tail call @bar(%struct.X* byval %A)
3420 SDValue Ptr = Ld->getBasePtr();
3421 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3424 FI = FINode->getIndex();
3425 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3426 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3427 FI = FINode->getIndex();
3428 Bytes = Flags.getByValSize();
3432 assert(FI != INT_MAX);
3433 if (!MFI->isFixedObjectIndex(FI))
3435 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3438 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3439 /// for tail call optimization. Targets which want to do tail call
3440 /// optimization should implement this function.
3442 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3443 CallingConv::ID CalleeCC,
3445 bool isCalleeStructRet,
3446 bool isCallerStructRet,
3448 const SmallVectorImpl<ISD::OutputArg> &Outs,
3449 const SmallVectorImpl<SDValue> &OutVals,
3450 const SmallVectorImpl<ISD::InputArg> &Ins,
3451 SelectionDAG &DAG) const {
3452 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3455 // If -tailcallopt is specified, make fastcc functions tail-callable.
3456 const MachineFunction &MF = DAG.getMachineFunction();
3457 const Function *CallerF = MF.getFunction();
3459 // If the function return type is x86_fp80 and the callee return type is not,
3460 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3461 // perform a tailcall optimization here.
3462 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3465 CallingConv::ID CallerCC = CallerF->getCallingConv();
3466 bool CCMatch = CallerCC == CalleeCC;
3467 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3468 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3470 // Win64 functions have extra shadow space for argument homing. Don't do the
3471 // sibcall if the caller and callee have mismatched expectations for this
3473 if (IsCalleeWin64 != IsCallerWin64)
3476 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3477 if (IsTailCallConvention(CalleeCC) && CCMatch)
3482 // Look for obvious safe cases to perform tail call optimization that do not
3483 // require ABI changes. This is what gcc calls sibcall.
3485 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3486 // emit a special epilogue.
3487 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3488 if (RegInfo->needsStackRealignment(MF))
3491 // Also avoid sibcall optimization if either caller or callee uses struct
3492 // return semantics.
3493 if (isCalleeStructRet || isCallerStructRet)
3496 // An stdcall/thiscall caller is expected to clean up its arguments; the
3497 // callee isn't going to do that.
3498 // FIXME: this is more restrictive than needed. We could produce a tailcall
3499 // when the stack adjustment matches. For example, with a thiscall that takes
3500 // only one argument.
3501 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3502 CallerCC == CallingConv::X86_ThisCall))
3505 // Do not sibcall optimize vararg calls unless all arguments are passed via
3507 if (isVarArg && !Outs.empty()) {
3509 // Optimizing for varargs on Win64 is unlikely to be safe without
3510 // additional testing.
3511 if (IsCalleeWin64 || IsCallerWin64)
3514 SmallVector<CCValAssign, 16> ArgLocs;
3515 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3518 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3519 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3520 if (!ArgLocs[i].isRegLoc())
3524 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3525 // stack. Therefore, if it's not used by the call it is not safe to optimize
3526 // this into a sibcall.
3527 bool Unused = false;
3528 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3535 SmallVector<CCValAssign, 16> RVLocs;
3536 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3538 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3539 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3540 CCValAssign &VA = RVLocs[i];
3541 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3546 // If the calling conventions do not match, then we'd better make sure the
3547 // results are returned in the same way as what the caller expects.
3549 SmallVector<CCValAssign, 16> RVLocs1;
3550 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3552 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3554 SmallVector<CCValAssign, 16> RVLocs2;
3555 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3557 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3559 if (RVLocs1.size() != RVLocs2.size())
3561 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3562 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3564 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3566 if (RVLocs1[i].isRegLoc()) {
3567 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3570 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3576 // If the callee takes no arguments then go on to check the results of the
3578 if (!Outs.empty()) {
3579 // Check if stack adjustment is needed. For now, do not do this if any
3580 // argument is passed on the stack.
3581 SmallVector<CCValAssign, 16> ArgLocs;
3582 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3585 // Allocate shadow area for Win64
3587 CCInfo.AllocateStack(32, 8);
3589 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3590 if (CCInfo.getNextStackOffset()) {
3591 MachineFunction &MF = DAG.getMachineFunction();
3592 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3595 // Check if the arguments are already laid out in the right way as
3596 // the caller's fixed stack objects.
3597 MachineFrameInfo *MFI = MF.getFrameInfo();
3598 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3599 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3600 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3601 CCValAssign &VA = ArgLocs[i];
3602 SDValue Arg = OutVals[i];
3603 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3604 if (VA.getLocInfo() == CCValAssign::Indirect)
3606 if (!VA.isRegLoc()) {
3607 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3614 // If the tailcall address may be in a register, then make sure it's
3615 // possible to register allocate for it. In 32-bit, the call address can
3616 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3617 // callee-saved registers are restored. These happen to be the same
3618 // registers used to pass 'inreg' arguments so watch out for those.
3619 if (!Subtarget->is64Bit() &&
3620 ((!isa<GlobalAddressSDNode>(Callee) &&
3621 !isa<ExternalSymbolSDNode>(Callee)) ||
3622 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3623 unsigned NumInRegs = 0;
3624 // In PIC we need an extra register to formulate the address computation
3626 unsigned MaxInRegs =
3627 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3629 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3630 CCValAssign &VA = ArgLocs[i];
3633 unsigned Reg = VA.getLocReg();
3636 case X86::EAX: case X86::EDX: case X86::ECX:
3637 if (++NumInRegs == MaxInRegs)
3649 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3650 const TargetLibraryInfo *libInfo) const {
3651 return X86::createFastISel(funcInfo, libInfo);
3654 //===----------------------------------------------------------------------===//
3655 // Other Lowering Hooks
3656 //===----------------------------------------------------------------------===//
3658 static bool MayFoldLoad(SDValue Op) {
3659 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3662 static bool MayFoldIntoStore(SDValue Op) {
3663 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3666 static bool isTargetShuffle(unsigned Opcode) {
3668 default: return false;
3669 case X86ISD::BLENDI:
3670 case X86ISD::PSHUFB:
3671 case X86ISD::PSHUFD:
3672 case X86ISD::PSHUFHW:
3673 case X86ISD::PSHUFLW:
3675 case X86ISD::PALIGNR:
3676 case X86ISD::MOVLHPS:
3677 case X86ISD::MOVLHPD:
3678 case X86ISD::MOVHLPS:
3679 case X86ISD::MOVLPS:
3680 case X86ISD::MOVLPD:
3681 case X86ISD::MOVSHDUP:
3682 case X86ISD::MOVSLDUP:
3683 case X86ISD::MOVDDUP:
3686 case X86ISD::UNPCKL:
3687 case X86ISD::UNPCKH:
3688 case X86ISD::VPERMILPI:
3689 case X86ISD::VPERM2X128:
3690 case X86ISD::VPERMI:
3695 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3696 SDValue V1, unsigned TargetMask,
3697 SelectionDAG &DAG) {
3699 default: llvm_unreachable("Unknown x86 shuffle node");
3700 case X86ISD::PSHUFD:
3701 case X86ISD::PSHUFHW:
3702 case X86ISD::PSHUFLW:
3703 case X86ISD::VPERMILPI:
3704 case X86ISD::VPERMI:
3705 return DAG.getNode(Opc, dl, VT, V1,
3706 DAG.getConstant(TargetMask, dl, MVT::i8));
3710 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3711 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3713 default: llvm_unreachable("Unknown x86 shuffle node");
3714 case X86ISD::MOVLHPS:
3715 case X86ISD::MOVLHPD:
3716 case X86ISD::MOVHLPS:
3717 case X86ISD::MOVLPS:
3718 case X86ISD::MOVLPD:
3721 case X86ISD::UNPCKL:
3722 case X86ISD::UNPCKH:
3723 return DAG.getNode(Opc, dl, VT, V1, V2);
3727 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3728 MachineFunction &MF = DAG.getMachineFunction();
3729 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3730 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3731 int ReturnAddrIndex = FuncInfo->getRAIndex();
3733 if (ReturnAddrIndex == 0) {
3734 // Set up a frame object for the return address.
3735 unsigned SlotSize = RegInfo->getSlotSize();
3736 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3739 FuncInfo->setRAIndex(ReturnAddrIndex);
3742 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3745 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3746 bool hasSymbolicDisplacement) {
3747 // Offset should fit into 32 bit immediate field.
3748 if (!isInt<32>(Offset))
3751 // If we don't have a symbolic displacement - we don't have any extra
3753 if (!hasSymbolicDisplacement)
3756 // FIXME: Some tweaks might be needed for medium code model.
3757 if (M != CodeModel::Small && M != CodeModel::Kernel)
3760 // For small code model we assume that latest object is 16MB before end of 31
3761 // bits boundary. We may also accept pretty large negative constants knowing
3762 // that all objects are in the positive half of address space.
3763 if (M == CodeModel::Small && Offset < 16*1024*1024)
3766 // For kernel code model we know that all object resist in the negative half
3767 // of 32bits address space. We may not accept negative offsets, since they may
3768 // be just off and we may accept pretty large positive ones.
3769 if (M == CodeModel::Kernel && Offset >= 0)
3775 /// isCalleePop - Determines whether the callee is required to pop its
3776 /// own arguments. Callee pop is necessary to support tail calls.
3777 bool X86::isCalleePop(CallingConv::ID CallingConv,
3778 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3779 switch (CallingConv) {
3782 case CallingConv::X86_StdCall:
3783 case CallingConv::X86_FastCall:
3784 case CallingConv::X86_ThisCall:
3786 case CallingConv::Fast:
3787 case CallingConv::GHC:
3788 case CallingConv::HiPE:
3795 /// \brief Return true if the condition is an unsigned comparison operation.
3796 static bool isX86CCUnsigned(unsigned X86CC) {
3798 default: llvm_unreachable("Invalid integer condition!");
3799 case X86::COND_E: return true;
3800 case X86::COND_G: return false;
3801 case X86::COND_GE: return false;
3802 case X86::COND_L: return false;
3803 case X86::COND_LE: return false;
3804 case X86::COND_NE: return true;
3805 case X86::COND_B: return true;
3806 case X86::COND_A: return true;
3807 case X86::COND_BE: return true;
3808 case X86::COND_AE: return true;
3810 llvm_unreachable("covered switch fell through?!");
3813 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3814 /// specific condition code, returning the condition code and the LHS/RHS of the
3815 /// comparison to make.
3816 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3817 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3819 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3820 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3821 // X > -1 -> X == 0, jump !sign.
3822 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3823 return X86::COND_NS;
3825 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3826 // X < 0 -> X == 0, jump on sign.
3829 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3831 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3832 return X86::COND_LE;
3836 switch (SetCCOpcode) {
3837 default: llvm_unreachable("Invalid integer condition!");
3838 case ISD::SETEQ: return X86::COND_E;
3839 case ISD::SETGT: return X86::COND_G;
3840 case ISD::SETGE: return X86::COND_GE;
3841 case ISD::SETLT: return X86::COND_L;
3842 case ISD::SETLE: return X86::COND_LE;
3843 case ISD::SETNE: return X86::COND_NE;
3844 case ISD::SETULT: return X86::COND_B;
3845 case ISD::SETUGT: return X86::COND_A;
3846 case ISD::SETULE: return X86::COND_BE;
3847 case ISD::SETUGE: return X86::COND_AE;
3851 // First determine if it is required or is profitable to flip the operands.
3853 // If LHS is a foldable load, but RHS is not, flip the condition.
3854 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3855 !ISD::isNON_EXTLoad(RHS.getNode())) {
3856 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3857 std::swap(LHS, RHS);
3860 switch (SetCCOpcode) {
3866 std::swap(LHS, RHS);
3870 // On a floating point condition, the flags are set as follows:
3872 // 0 | 0 | 0 | X > Y
3873 // 0 | 0 | 1 | X < Y
3874 // 1 | 0 | 0 | X == Y
3875 // 1 | 1 | 1 | unordered
3876 switch (SetCCOpcode) {
3877 default: llvm_unreachable("Condcode should be pre-legalized away");
3879 case ISD::SETEQ: return X86::COND_E;
3880 case ISD::SETOLT: // flipped
3882 case ISD::SETGT: return X86::COND_A;
3883 case ISD::SETOLE: // flipped
3885 case ISD::SETGE: return X86::COND_AE;
3886 case ISD::SETUGT: // flipped
3888 case ISD::SETLT: return X86::COND_B;
3889 case ISD::SETUGE: // flipped
3891 case ISD::SETLE: return X86::COND_BE;
3893 case ISD::SETNE: return X86::COND_NE;
3894 case ISD::SETUO: return X86::COND_P;
3895 case ISD::SETO: return X86::COND_NP;
3897 case ISD::SETUNE: return X86::COND_INVALID;
3901 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3902 /// code. Current x86 isa includes the following FP cmov instructions:
3903 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3904 static bool hasFPCMov(unsigned X86CC) {
3920 /// isFPImmLegal - Returns true if the target can instruction select the
3921 /// specified FP immediate natively. If false, the legalizer will
3922 /// materialize the FP immediate as a load from a constant pool.
3923 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3924 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3925 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3931 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3932 ISD::LoadExtType ExtTy,
3934 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3935 // relocation target a movq or addq instruction: don't let the load shrink.
3936 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3937 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3938 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3939 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3943 /// \brief Returns true if it is beneficial to convert a load of a constant
3944 /// to just the constant itself.
3945 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3947 assert(Ty->isIntegerTy());
3949 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3950 if (BitSize == 0 || BitSize > 64)
3955 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3956 unsigned Index) const {
3957 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3960 return (Index == 0 || Index == ResVT.getVectorNumElements());
3963 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3964 // Speculate cttz only if we can directly use TZCNT.
3965 return Subtarget->hasBMI();
3968 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3969 // Speculate ctlz only if we can directly use LZCNT.
3970 return Subtarget->hasLZCNT();
3973 /// isUndefInRange - Return true if every element in Mask, beginning
3974 /// from position Pos and ending in Pos+Size is undef.
3975 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3976 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
3982 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3983 /// the specified range (L, H].
3984 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3985 return (Val < 0) || (Val >= Low && Val < Hi);
3988 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3989 /// specified value.
3990 static bool isUndefOrEqual(int Val, int CmpVal) {
3991 return (Val < 0 || Val == CmpVal);
3994 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3995 /// from position Pos and ending in Pos+Size, falls within the specified
3996 /// sequential range (Low, Low+Size]. or is undef.
3997 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3998 unsigned Pos, unsigned Size, int Low) {
3999 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4000 if (!isUndefOrEqual(Mask[i], Low))
4005 /// isVEXTRACTIndex - Return true if the specified
4006 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4007 /// suitable for instruction that extract 128 or 256 bit vectors
4008 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4009 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4010 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4013 // The index should be aligned on a vecWidth-bit boundary.
4015 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4017 MVT VT = N->getSimpleValueType(0);
4018 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4019 bool Result = (Index * ElSize) % vecWidth == 0;
4024 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4025 /// operand specifies a subvector insert that is suitable for input to
4026 /// insertion of 128 or 256-bit subvectors
4027 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4028 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4029 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4031 // The index should be aligned on a vecWidth-bit boundary.
4033 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4035 MVT VT = N->getSimpleValueType(0);
4036 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4037 bool Result = (Index * ElSize) % vecWidth == 0;
4042 bool X86::isVINSERT128Index(SDNode *N) {
4043 return isVINSERTIndex(N, 128);
4046 bool X86::isVINSERT256Index(SDNode *N) {
4047 return isVINSERTIndex(N, 256);
4050 bool X86::isVEXTRACT128Index(SDNode *N) {
4051 return isVEXTRACTIndex(N, 128);
4054 bool X86::isVEXTRACT256Index(SDNode *N) {
4055 return isVEXTRACTIndex(N, 256);
4058 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4059 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4060 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4061 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4064 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4066 MVT VecVT = N->getOperand(0).getSimpleValueType();
4067 MVT ElVT = VecVT.getVectorElementType();
4069 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4070 return Index / NumElemsPerChunk;
4073 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4074 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4075 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4076 llvm_unreachable("Illegal insert subvector for VINSERT");
4079 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4081 MVT VecVT = N->getSimpleValueType(0);
4082 MVT ElVT = VecVT.getVectorElementType();
4084 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4085 return Index / NumElemsPerChunk;
4088 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4089 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4090 /// and VINSERTI128 instructions.
4091 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4092 return getExtractVEXTRACTImmediate(N, 128);
4095 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4096 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4097 /// and VINSERTI64x4 instructions.
4098 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4099 return getExtractVEXTRACTImmediate(N, 256);
4102 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4103 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4104 /// and VINSERTI128 instructions.
4105 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4106 return getInsertVINSERTImmediate(N, 128);
4109 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4110 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4111 /// and VINSERTI64x4 instructions.
4112 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4113 return getInsertVINSERTImmediate(N, 256);
4116 /// isZero - Returns true if Elt is a constant integer zero
4117 static bool isZero(SDValue V) {
4118 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4119 return C && C->isNullValue();
4122 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4124 bool X86::isZeroNode(SDValue Elt) {
4127 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4128 return CFP->getValueAPF().isPosZero();
4132 /// getZeroVector - Returns a vector of specified type with all zero elements.
4134 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4135 SelectionDAG &DAG, SDLoc dl) {
4136 assert(VT.isVector() && "Expected a vector type");
4138 // Always build SSE zero vectors as <4 x i32> bitcasted
4139 // to their dest type. This ensures they get CSE'd.
4141 if (VT.is128BitVector()) { // SSE
4142 if (Subtarget->hasSSE2()) { // SSE2
4143 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4144 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4146 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4147 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4149 } else if (VT.is256BitVector()) { // AVX
4150 if (Subtarget->hasInt256()) { // AVX2
4151 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4152 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4153 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4155 // 256-bit logic and arithmetic instructions in AVX are all
4156 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4157 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4158 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4159 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4161 } else if (VT.is512BitVector()) { // AVX-512
4162 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4163 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4164 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4165 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4166 } else if (VT.getScalarType() == MVT::i1) {
4168 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4169 && "Unexpected vector type");
4170 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4171 && "Unexpected vector type");
4172 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4173 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4174 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4176 llvm_unreachable("Unexpected vector type");
4178 return DAG.getBitcast(VT, Vec);
4181 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4182 SelectionDAG &DAG, SDLoc dl,
4183 unsigned vectorWidth) {
4184 assert((vectorWidth == 128 || vectorWidth == 256) &&
4185 "Unsupported vector width");
4186 EVT VT = Vec.getValueType();
4187 EVT ElVT = VT.getVectorElementType();
4188 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4189 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4190 VT.getVectorNumElements()/Factor);
4192 // Extract from UNDEF is UNDEF.
4193 if (Vec.getOpcode() == ISD::UNDEF)
4194 return DAG.getUNDEF(ResultVT);
4196 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4197 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4199 // This is the index of the first element of the vectorWidth-bit chunk
4201 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4204 // If the input is a buildvector just emit a smaller one.
4205 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4206 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4207 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4210 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4211 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4214 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4215 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4216 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4217 /// instructions or a simple subregister reference. Idx is an index in the
4218 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4219 /// lowering EXTRACT_VECTOR_ELT operations easier.
4220 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4221 SelectionDAG &DAG, SDLoc dl) {
4222 assert((Vec.getValueType().is256BitVector() ||
4223 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4224 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4227 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4228 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4229 SelectionDAG &DAG, SDLoc dl) {
4230 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4231 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4234 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4235 unsigned IdxVal, SelectionDAG &DAG,
4236 SDLoc dl, unsigned vectorWidth) {
4237 assert((vectorWidth == 128 || vectorWidth == 256) &&
4238 "Unsupported vector width");
4239 // Inserting UNDEF is Result
4240 if (Vec.getOpcode() == ISD::UNDEF)
4242 EVT VT = Vec.getValueType();
4243 EVT ElVT = VT.getVectorElementType();
4244 EVT ResultVT = Result.getValueType();
4246 // Insert the relevant vectorWidth bits.
4247 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4249 // This is the index of the first element of the vectorWidth-bit chunk
4251 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4254 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4255 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4258 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4259 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4260 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4261 /// simple superregister reference. Idx is an index in the 128 bits
4262 /// we want. It need not be aligned to a 128-bit boundary. That makes
4263 /// lowering INSERT_VECTOR_ELT operations easier.
4264 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4265 SelectionDAG &DAG, SDLoc dl) {
4266 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4268 // For insertion into the zero index (low half) of a 256-bit vector, it is
4269 // more efficient to generate a blend with immediate instead of an insert*128.
4270 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4271 // extend the subvector to the size of the result vector. Make sure that
4272 // we are not recursing on that node by checking for undef here.
4273 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4274 Result.getOpcode() != ISD::UNDEF) {
4275 EVT ResultVT = Result.getValueType();
4276 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4277 SDValue Undef = DAG.getUNDEF(ResultVT);
4278 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4281 // The blend instruction, and therefore its mask, depend on the data type.
4282 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4283 if (ScalarType.isFloatingPoint()) {
4284 // Choose either vblendps (float) or vblendpd (double).
4285 unsigned ScalarSize = ScalarType.getSizeInBits();
4286 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4287 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4288 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4289 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4292 const X86Subtarget &Subtarget =
4293 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4295 // AVX2 is needed for 256-bit integer blend support.
4296 // Integers must be cast to 32-bit because there is only vpblendd;
4297 // vpblendw can't be used for this because it has a handicapped mask.
4299 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4300 // is still more efficient than using the wrong domain vinsertf128 that
4301 // will be created by InsertSubVector().
4302 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4304 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4305 Vec256 = DAG.getBitcast(CastVT, Vec256);
4306 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4307 return DAG.getBitcast(ResultVT, Vec256);
4310 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4313 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4314 SelectionDAG &DAG, SDLoc dl) {
4315 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4316 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4319 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4320 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4321 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4322 /// large BUILD_VECTORS.
4323 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4324 unsigned NumElems, SelectionDAG &DAG,
4326 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4327 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4330 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4331 unsigned NumElems, SelectionDAG &DAG,
4333 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4334 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4337 /// getOnesVector - Returns a vector of specified type with all bits set.
4338 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4339 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4340 /// Then bitcast to their original type, ensuring they get CSE'd.
4341 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4343 assert(VT.isVector() && "Expected a vector type");
4345 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4347 if (VT.is256BitVector()) {
4348 if (HasInt256) { // AVX2
4349 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4350 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4352 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4353 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4355 } else if (VT.is128BitVector()) {
4356 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4358 llvm_unreachable("Unexpected vector type");
4360 return DAG.getBitcast(VT, Vec);
4363 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4364 /// operation of specified width.
4365 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4367 unsigned NumElems = VT.getVectorNumElements();
4368 SmallVector<int, 8> Mask;
4369 Mask.push_back(NumElems);
4370 for (unsigned i = 1; i != NumElems; ++i)
4372 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4375 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4376 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4378 unsigned NumElems = VT.getVectorNumElements();
4379 SmallVector<int, 8> Mask;
4380 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4382 Mask.push_back(i + NumElems);
4384 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4387 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4388 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4390 unsigned NumElems = VT.getVectorNumElements();
4391 SmallVector<int, 8> Mask;
4392 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4393 Mask.push_back(i + Half);
4394 Mask.push_back(i + NumElems + Half);
4396 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4399 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4400 /// vector of zero or undef vector. This produces a shuffle where the low
4401 /// element of V2 is swizzled into the zero/undef vector, landing at element
4402 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4403 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4405 const X86Subtarget *Subtarget,
4406 SelectionDAG &DAG) {
4407 MVT VT = V2.getSimpleValueType();
4409 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4410 unsigned NumElems = VT.getVectorNumElements();
4411 SmallVector<int, 16> MaskVec;
4412 for (unsigned i = 0; i != NumElems; ++i)
4413 // If this is the insertion idx, put the low elt of V2 here.
4414 MaskVec.push_back(i == Idx ? NumElems : i);
4415 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4418 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4419 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4420 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4421 /// shuffles which use a single input multiple times, and in those cases it will
4422 /// adjust the mask to only have indices within that single input.
4423 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4424 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4425 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4426 unsigned NumElems = VT.getVectorNumElements();
4430 bool IsFakeUnary = false;
4431 switch(N->getOpcode()) {
4432 case X86ISD::BLENDI:
4433 ImmN = N->getOperand(N->getNumOperands()-1);
4434 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4437 ImmN = N->getOperand(N->getNumOperands()-1);
4438 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4439 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4441 case X86ISD::UNPCKH:
4442 DecodeUNPCKHMask(VT, Mask);
4443 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4445 case X86ISD::UNPCKL:
4446 DecodeUNPCKLMask(VT, Mask);
4447 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4449 case X86ISD::MOVHLPS:
4450 DecodeMOVHLPSMask(NumElems, Mask);
4451 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4453 case X86ISD::MOVLHPS:
4454 DecodeMOVLHPSMask(NumElems, Mask);
4455 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4457 case X86ISD::PALIGNR:
4458 ImmN = N->getOperand(N->getNumOperands()-1);
4459 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4461 case X86ISD::PSHUFD:
4462 case X86ISD::VPERMILPI:
4463 ImmN = N->getOperand(N->getNumOperands()-1);
4464 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4467 case X86ISD::PSHUFHW:
4468 ImmN = N->getOperand(N->getNumOperands()-1);
4469 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4472 case X86ISD::PSHUFLW:
4473 ImmN = N->getOperand(N->getNumOperands()-1);
4474 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4477 case X86ISD::PSHUFB: {
4479 SDValue MaskNode = N->getOperand(1);
4480 while (MaskNode->getOpcode() == ISD::BITCAST)
4481 MaskNode = MaskNode->getOperand(0);
4483 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4484 // If we have a build-vector, then things are easy.
4485 EVT VT = MaskNode.getValueType();
4486 assert(VT.isVector() &&
4487 "Can't produce a non-vector with a build_vector!");
4488 if (!VT.isInteger())
4491 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4493 SmallVector<uint64_t, 32> RawMask;
4494 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4495 SDValue Op = MaskNode->getOperand(i);
4496 if (Op->getOpcode() == ISD::UNDEF) {
4497 RawMask.push_back((uint64_t)SM_SentinelUndef);
4500 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4503 APInt MaskElement = CN->getAPIntValue();
4505 // We now have to decode the element which could be any integer size and
4506 // extract each byte of it.
4507 for (int j = 0; j < NumBytesPerElement; ++j) {
4508 // Note that this is x86 and so always little endian: the low byte is
4509 // the first byte of the mask.
4510 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4511 MaskElement = MaskElement.lshr(8);
4514 DecodePSHUFBMask(RawMask, Mask);
4518 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4522 SDValue Ptr = MaskLoad->getBasePtr();
4523 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4524 Ptr->getOpcode() == X86ISD::WrapperRIP)
4525 Ptr = Ptr->getOperand(0);
4527 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4528 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4531 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4532 DecodePSHUFBMask(C, Mask);
4540 case X86ISD::VPERMI:
4541 ImmN = N->getOperand(N->getNumOperands()-1);
4542 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4547 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4549 case X86ISD::VPERM2X128:
4550 ImmN = N->getOperand(N->getNumOperands()-1);
4551 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4552 if (Mask.empty()) return false;
4553 // Mask only contains negative index if an element is zero.
4554 if (std::any_of(Mask.begin(), Mask.end(),
4555 [](int M){ return M == SM_SentinelZero; }))
4558 case X86ISD::MOVSLDUP:
4559 DecodeMOVSLDUPMask(VT, Mask);
4562 case X86ISD::MOVSHDUP:
4563 DecodeMOVSHDUPMask(VT, Mask);
4566 case X86ISD::MOVDDUP:
4567 DecodeMOVDDUPMask(VT, Mask);
4570 case X86ISD::MOVLHPD:
4571 case X86ISD::MOVLPD:
4572 case X86ISD::MOVLPS:
4573 // Not yet implemented
4575 default: llvm_unreachable("unknown target shuffle node");
4578 // If we have a fake unary shuffle, the shuffle mask is spread across two
4579 // inputs that are actually the same node. Re-map the mask to always point
4580 // into the first input.
4583 if (M >= (int)Mask.size())
4589 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4590 /// element of the result of the vector shuffle.
4591 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4594 return SDValue(); // Limit search depth.
4596 SDValue V = SDValue(N, 0);
4597 EVT VT = V.getValueType();
4598 unsigned Opcode = V.getOpcode();
4600 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4601 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4602 int Elt = SV->getMaskElt(Index);
4605 return DAG.getUNDEF(VT.getVectorElementType());
4607 unsigned NumElems = VT.getVectorNumElements();
4608 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4609 : SV->getOperand(1);
4610 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4613 // Recurse into target specific vector shuffles to find scalars.
4614 if (isTargetShuffle(Opcode)) {
4615 MVT ShufVT = V.getSimpleValueType();
4616 unsigned NumElems = ShufVT.getVectorNumElements();
4617 SmallVector<int, 16> ShuffleMask;
4620 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4623 int Elt = ShuffleMask[Index];
4625 return DAG.getUNDEF(ShufVT.getVectorElementType());
4627 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4629 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4633 // Actual nodes that may contain scalar elements
4634 if (Opcode == ISD::BITCAST) {
4635 V = V.getOperand(0);
4636 EVT SrcVT = V.getValueType();
4637 unsigned NumElems = VT.getVectorNumElements();
4639 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4643 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4644 return (Index == 0) ? V.getOperand(0)
4645 : DAG.getUNDEF(VT.getVectorElementType());
4647 if (V.getOpcode() == ISD::BUILD_VECTOR)
4648 return V.getOperand(Index);
4653 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4655 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4656 unsigned NumNonZero, unsigned NumZero,
4658 const X86Subtarget* Subtarget,
4659 const TargetLowering &TLI) {
4667 // SSE4.1 - use PINSRB to insert each byte directly.
4668 if (Subtarget->hasSSE41()) {
4669 for (unsigned i = 0; i < 16; ++i) {
4670 bool isNonZero = (NonZeros & (1 << i)) != 0;
4674 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4676 V = DAG.getUNDEF(MVT::v16i8);
4679 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4680 MVT::v16i8, V, Op.getOperand(i),
4681 DAG.getIntPtrConstant(i, dl));
4688 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4689 for (unsigned i = 0; i < 16; ++i) {
4690 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4691 if (ThisIsNonZero && First) {
4693 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4695 V = DAG.getUNDEF(MVT::v8i16);
4700 SDValue ThisElt, LastElt;
4701 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4702 if (LastIsNonZero) {
4703 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4704 MVT::i16, Op.getOperand(i-1));
4706 if (ThisIsNonZero) {
4707 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4708 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4709 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4711 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4715 if (ThisElt.getNode())
4716 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4717 DAG.getIntPtrConstant(i/2, dl));
4721 return DAG.getBitcast(MVT::v16i8, V);
4724 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4726 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4727 unsigned NumNonZero, unsigned NumZero,
4729 const X86Subtarget* Subtarget,
4730 const TargetLowering &TLI) {
4737 for (unsigned i = 0; i < 8; ++i) {
4738 bool isNonZero = (NonZeros & (1 << i)) != 0;
4742 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4744 V = DAG.getUNDEF(MVT::v8i16);
4747 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4748 MVT::v8i16, V, Op.getOperand(i),
4749 DAG.getIntPtrConstant(i, dl));
4756 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4757 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4758 const X86Subtarget *Subtarget,
4759 const TargetLowering &TLI) {
4760 // Find all zeroable elements.
4761 std::bitset<4> Zeroable;
4762 for (int i=0; i < 4; ++i) {
4763 SDValue Elt = Op->getOperand(i);
4764 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4766 assert(Zeroable.size() - Zeroable.count() > 1 &&
4767 "We expect at least two non-zero elements!");
4769 // We only know how to deal with build_vector nodes where elements are either
4770 // zeroable or extract_vector_elt with constant index.
4771 SDValue FirstNonZero;
4772 unsigned FirstNonZeroIdx;
4773 for (unsigned i=0; i < 4; ++i) {
4776 SDValue Elt = Op->getOperand(i);
4777 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4778 !isa<ConstantSDNode>(Elt.getOperand(1)))
4780 // Make sure that this node is extracting from a 128-bit vector.
4781 MVT VT = Elt.getOperand(0).getSimpleValueType();
4782 if (!VT.is128BitVector())
4784 if (!FirstNonZero.getNode()) {
4786 FirstNonZeroIdx = i;
4790 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4791 SDValue V1 = FirstNonZero.getOperand(0);
4792 MVT VT = V1.getSimpleValueType();
4794 // See if this build_vector can be lowered as a blend with zero.
4796 unsigned EltMaskIdx, EltIdx;
4798 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4799 if (Zeroable[EltIdx]) {
4800 // The zero vector will be on the right hand side.
4801 Mask[EltIdx] = EltIdx+4;
4805 Elt = Op->getOperand(EltIdx);
4806 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4807 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4808 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4810 Mask[EltIdx] = EltIdx;
4814 // Let the shuffle legalizer deal with blend operations.
4815 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4816 if (V1.getSimpleValueType() != VT)
4817 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4818 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4821 // See if we can lower this build_vector to a INSERTPS.
4822 if (!Subtarget->hasSSE41())
4825 SDValue V2 = Elt.getOperand(0);
4826 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4829 bool CanFold = true;
4830 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4834 SDValue Current = Op->getOperand(i);
4835 SDValue SrcVector = Current->getOperand(0);
4838 CanFold = SrcVector == V1 &&
4839 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4845 assert(V1.getNode() && "Expected at least two non-zero elements!");
4846 if (V1.getSimpleValueType() != MVT::v4f32)
4847 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4848 if (V2.getSimpleValueType() != MVT::v4f32)
4849 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4851 // Ok, we can emit an INSERTPS instruction.
4852 unsigned ZMask = Zeroable.to_ulong();
4854 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4855 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4857 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4858 DAG.getIntPtrConstant(InsertPSMask, DL));
4859 return DAG.getBitcast(VT, Result);
4862 /// Return a vector logical shift node.
4863 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4864 unsigned NumBits, SelectionDAG &DAG,
4865 const TargetLowering &TLI, SDLoc dl) {
4866 assert(VT.is128BitVector() && "Unknown type for VShift");
4867 MVT ShVT = MVT::v2i64;
4868 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4869 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4870 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4871 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4872 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4873 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4877 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4879 // Check if the scalar load can be widened into a vector load. And if
4880 // the address is "base + cst" see if the cst can be "absorbed" into
4881 // the shuffle mask.
4882 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4883 SDValue Ptr = LD->getBasePtr();
4884 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4886 EVT PVT = LD->getValueType(0);
4887 if (PVT != MVT::i32 && PVT != MVT::f32)
4892 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4893 FI = FINode->getIndex();
4895 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4896 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4897 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4898 Offset = Ptr.getConstantOperandVal(1);
4899 Ptr = Ptr.getOperand(0);
4904 // FIXME: 256-bit vector instructions don't require a strict alignment,
4905 // improve this code to support it better.
4906 unsigned RequiredAlign = VT.getSizeInBits()/8;
4907 SDValue Chain = LD->getChain();
4908 // Make sure the stack object alignment is at least 16 or 32.
4909 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4910 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4911 if (MFI->isFixedObjectIndex(FI)) {
4912 // Can't change the alignment. FIXME: It's possible to compute
4913 // the exact stack offset and reference FI + adjust offset instead.
4914 // If someone *really* cares about this. That's the way to implement it.
4917 MFI->setObjectAlignment(FI, RequiredAlign);
4921 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4922 // Ptr + (Offset & ~15).
4925 if ((Offset % RequiredAlign) & 3)
4927 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4930 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4931 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4934 int EltNo = (Offset - StartOffset) >> 2;
4935 unsigned NumElems = VT.getVectorNumElements();
4937 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4938 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4939 LD->getPointerInfo().getWithOffset(StartOffset),
4940 false, false, false, 0);
4942 SmallVector<int, 8> Mask(NumElems, EltNo);
4944 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4950 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4951 /// elements can be replaced by a single large load which has the same value as
4952 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4954 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4956 /// FIXME: we'd also like to handle the case where the last elements are zero
4957 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4958 /// There's even a handy isZeroNode for that purpose.
4959 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4960 SDLoc &DL, SelectionDAG &DAG,
4961 bool isAfterLegalize) {
4962 unsigned NumElems = Elts.size();
4964 LoadSDNode *LDBase = nullptr;
4965 unsigned LastLoadedElt = -1U;
4967 // For each element in the initializer, see if we've found a load or an undef.
4968 // If we don't find an initial load element, or later load elements are
4969 // non-consecutive, bail out.
4970 for (unsigned i = 0; i < NumElems; ++i) {
4971 SDValue Elt = Elts[i];
4972 // Look through a bitcast.
4973 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4974 Elt = Elt.getOperand(0);
4975 if (!Elt.getNode() ||
4976 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4979 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4981 LDBase = cast<LoadSDNode>(Elt.getNode());
4985 if (Elt.getOpcode() == ISD::UNDEF)
4988 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4989 EVT LdVT = Elt.getValueType();
4990 // Each loaded element must be the correct fractional portion of the
4991 // requested vector load.
4992 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4994 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4999 // If we have found an entire vector of loads and undefs, then return a large
5000 // load of the entire vector width starting at the base pointer. If we found
5001 // consecutive loads for the low half, generate a vzext_load node.
5002 if (LastLoadedElt == NumElems - 1) {
5003 assert(LDBase && "Did not find base load for merging consecutive loads");
5004 EVT EltVT = LDBase->getValueType(0);
5005 // Ensure that the input vector size for the merged loads matches the
5006 // cumulative size of the input elements.
5007 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5010 if (isAfterLegalize &&
5011 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5014 SDValue NewLd = SDValue();
5016 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5017 LDBase->getPointerInfo(), LDBase->isVolatile(),
5018 LDBase->isNonTemporal(), LDBase->isInvariant(),
5019 LDBase->getAlignment());
5021 if (LDBase->hasAnyUseOfValue(1)) {
5022 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5024 SDValue(NewLd.getNode(), 1));
5025 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5026 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5027 SDValue(NewLd.getNode(), 1));
5033 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5034 //of a v4i32 / v4f32. It's probably worth generalizing.
5035 EVT EltVT = VT.getVectorElementType();
5036 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5037 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5038 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5039 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5041 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5042 LDBase->getPointerInfo(),
5043 LDBase->getAlignment(),
5044 false/*isVolatile*/, true/*ReadMem*/,
5047 // Make sure the newly-created LOAD is in the same position as LDBase in
5048 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5049 // update uses of LDBase's output chain to use the TokenFactor.
5050 if (LDBase->hasAnyUseOfValue(1)) {
5051 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5052 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5053 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5054 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5055 SDValue(ResNode.getNode(), 1));
5058 return DAG.getBitcast(VT, ResNode);
5063 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5064 /// to generate a splat value for the following cases:
5065 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5066 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5067 /// a scalar load, or a constant.
5068 /// The VBROADCAST node is returned when a pattern is found,
5069 /// or SDValue() otherwise.
5070 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5071 SelectionDAG &DAG) {
5072 // VBROADCAST requires AVX.
5073 // TODO: Splats could be generated for non-AVX CPUs using SSE
5074 // instructions, but there's less potential gain for only 128-bit vectors.
5075 if (!Subtarget->hasAVX())
5078 MVT VT = Op.getSimpleValueType();
5081 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5082 "Unsupported vector type for broadcast.");
5087 switch (Op.getOpcode()) {
5089 // Unknown pattern found.
5092 case ISD::BUILD_VECTOR: {
5093 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5094 BitVector UndefElements;
5095 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5097 // We need a splat of a single value to use broadcast, and it doesn't
5098 // make any sense if the value is only in one element of the vector.
5099 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5103 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5104 Ld.getOpcode() == ISD::ConstantFP);
5106 // Make sure that all of the users of a non-constant load are from the
5107 // BUILD_VECTOR node.
5108 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5113 case ISD::VECTOR_SHUFFLE: {
5114 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5116 // Shuffles must have a splat mask where the first element is
5118 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5121 SDValue Sc = Op.getOperand(0);
5122 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5123 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5125 if (!Subtarget->hasInt256())
5128 // Use the register form of the broadcast instruction available on AVX2.
5129 if (VT.getSizeInBits() >= 256)
5130 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5131 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5134 Ld = Sc.getOperand(0);
5135 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5136 Ld.getOpcode() == ISD::ConstantFP);
5138 // The scalar_to_vector node and the suspected
5139 // load node must have exactly one user.
5140 // Constants may have multiple users.
5142 // AVX-512 has register version of the broadcast
5143 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5144 Ld.getValueType().getSizeInBits() >= 32;
5145 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5152 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5153 bool IsGE256 = (VT.getSizeInBits() >= 256);
5155 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5156 // instruction to save 8 or more bytes of constant pool data.
5157 // TODO: If multiple splats are generated to load the same constant,
5158 // it may be detrimental to overall size. There needs to be a way to detect
5159 // that condition to know if this is truly a size win.
5160 const Function *F = DAG.getMachineFunction().getFunction();
5161 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5163 // Handle broadcasting a single constant scalar from the constant pool
5165 // On Sandybridge (no AVX2), it is still better to load a constant vector
5166 // from the constant pool and not to broadcast it from a scalar.
5167 // But override that restriction when optimizing for size.
5168 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5169 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5170 EVT CVT = Ld.getValueType();
5171 assert(!CVT.isVector() && "Must not broadcast a vector type");
5173 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5174 // For size optimization, also splat v2f64 and v2i64, and for size opt
5175 // with AVX2, also splat i8 and i16.
5176 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5177 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5178 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5179 const Constant *C = nullptr;
5180 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5181 C = CI->getConstantIntValue();
5182 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5183 C = CF->getConstantFPValue();
5185 assert(C && "Invalid constant type");
5187 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5189 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5190 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5191 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5192 MachinePointerInfo::getConstantPool(),
5193 false, false, false, Alignment);
5195 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5199 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5201 // Handle AVX2 in-register broadcasts.
5202 if (!IsLoad && Subtarget->hasInt256() &&
5203 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5204 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5206 // The scalar source must be a normal load.
5210 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5211 (Subtarget->hasVLX() && ScalarSize == 64))
5212 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5214 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5215 // double since there is no vbroadcastsd xmm
5216 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5217 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5218 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5221 // Unsupported broadcast.
5225 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5226 /// underlying vector and index.
5228 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5230 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5232 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5233 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5236 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5238 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5240 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5241 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5244 // In this case the vector is the extract_subvector expression and the index
5245 // is 2, as specified by the shuffle.
5246 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5247 SDValue ShuffleVec = SVOp->getOperand(0);
5248 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5249 assert(ShuffleVecVT.getVectorElementType() ==
5250 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5252 int ShuffleIdx = SVOp->getMaskElt(Idx);
5253 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5254 ExtractedFromVec = ShuffleVec;
5260 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5261 MVT VT = Op.getSimpleValueType();
5263 // Skip if insert_vec_elt is not supported.
5264 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5265 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5269 unsigned NumElems = Op.getNumOperands();
5273 SmallVector<unsigned, 4> InsertIndices;
5274 SmallVector<int, 8> Mask(NumElems, -1);
5276 for (unsigned i = 0; i != NumElems; ++i) {
5277 unsigned Opc = Op.getOperand(i).getOpcode();
5279 if (Opc == ISD::UNDEF)
5282 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5283 // Quit if more than 1 elements need inserting.
5284 if (InsertIndices.size() > 1)
5287 InsertIndices.push_back(i);
5291 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5292 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5293 // Quit if non-constant index.
5294 if (!isa<ConstantSDNode>(ExtIdx))
5296 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5298 // Quit if extracted from vector of different type.
5299 if (ExtractedFromVec.getValueType() != VT)
5302 if (!VecIn1.getNode())
5303 VecIn1 = ExtractedFromVec;
5304 else if (VecIn1 != ExtractedFromVec) {
5305 if (!VecIn2.getNode())
5306 VecIn2 = ExtractedFromVec;
5307 else if (VecIn2 != ExtractedFromVec)
5308 // Quit if more than 2 vectors to shuffle
5312 if (ExtractedFromVec == VecIn1)
5314 else if (ExtractedFromVec == VecIn2)
5315 Mask[i] = Idx + NumElems;
5318 if (!VecIn1.getNode())
5321 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5322 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5323 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5324 unsigned Idx = InsertIndices[i];
5325 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5326 DAG.getIntPtrConstant(Idx, DL));
5332 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5333 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5334 Op.getScalarValueSizeInBits() == 1 &&
5335 "Can not convert non-constant vector");
5336 uint64_t Immediate = 0;
5337 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5338 SDValue In = Op.getOperand(idx);
5339 if (In.getOpcode() != ISD::UNDEF)
5340 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5344 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5345 return DAG.getConstant(Immediate, dl, VT);
5347 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5349 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5351 MVT VT = Op.getSimpleValueType();
5352 assert((VT.getVectorElementType() == MVT::i1) &&
5353 "Unexpected type in LowerBUILD_VECTORvXi1!");
5356 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5357 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5358 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5359 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5362 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5363 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5364 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5365 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5368 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5369 SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5370 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5371 return DAG.getBitcast(VT, Imm);
5372 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5373 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5374 DAG.getIntPtrConstant(0, dl));
5377 // Vector has one or more non-const elements
5378 uint64_t Immediate = 0;
5379 SmallVector<unsigned, 16> NonConstIdx;
5380 bool IsSplat = true;
5381 bool HasConstElts = false;
5383 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5384 SDValue In = Op.getOperand(idx);
5385 if (In.getOpcode() == ISD::UNDEF)
5387 if (!isa<ConstantSDNode>(In))
5388 NonConstIdx.push_back(idx);
5390 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5391 HasConstElts = true;
5395 else if (In != Op.getOperand(SplatIdx))
5399 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5401 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5402 DAG.getConstant(1, dl, VT),
5403 DAG.getConstant(0, dl, VT));
5405 // insert elements one by one
5409 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5410 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5412 else if (HasConstElts)
5413 Imm = DAG.getConstant(0, dl, VT);
5415 Imm = DAG.getUNDEF(VT);
5416 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5417 DstVec = DAG.getBitcast(VT, Imm);
5419 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5420 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5421 DAG.getIntPtrConstant(0, dl));
5424 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5425 unsigned InsertIdx = NonConstIdx[i];
5426 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5427 Op.getOperand(InsertIdx),
5428 DAG.getIntPtrConstant(InsertIdx, dl));
5433 /// \brief Return true if \p N implements a horizontal binop and return the
5434 /// operands for the horizontal binop into V0 and V1.
5436 /// This is a helper function of LowerToHorizontalOp().
5437 /// This function checks that the build_vector \p N in input implements a
5438 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5439 /// operation to match.
5440 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5441 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5442 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5445 /// This function only analyzes elements of \p N whose indices are
5446 /// in range [BaseIdx, LastIdx).
5447 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5449 unsigned BaseIdx, unsigned LastIdx,
5450 SDValue &V0, SDValue &V1) {
5451 EVT VT = N->getValueType(0);
5453 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5454 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5455 "Invalid Vector in input!");
5457 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5458 bool CanFold = true;
5459 unsigned ExpectedVExtractIdx = BaseIdx;
5460 unsigned NumElts = LastIdx - BaseIdx;
5461 V0 = DAG.getUNDEF(VT);
5462 V1 = DAG.getUNDEF(VT);
5464 // Check if N implements a horizontal binop.
5465 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5466 SDValue Op = N->getOperand(i + BaseIdx);
5469 if (Op->getOpcode() == ISD::UNDEF) {
5470 // Update the expected vector extract index.
5471 if (i * 2 == NumElts)
5472 ExpectedVExtractIdx = BaseIdx;
5473 ExpectedVExtractIdx += 2;
5477 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5482 SDValue Op0 = Op.getOperand(0);
5483 SDValue Op1 = Op.getOperand(1);
5485 // Try to match the following pattern:
5486 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5487 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5488 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5489 Op0.getOperand(0) == Op1.getOperand(0) &&
5490 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5491 isa<ConstantSDNode>(Op1.getOperand(1)));
5495 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5496 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5498 if (i * 2 < NumElts) {
5499 if (V0.getOpcode() == ISD::UNDEF) {
5500 V0 = Op0.getOperand(0);
5501 if (V0.getValueType() != VT)
5505 if (V1.getOpcode() == ISD::UNDEF) {
5506 V1 = Op0.getOperand(0);
5507 if (V1.getValueType() != VT)
5510 if (i * 2 == NumElts)
5511 ExpectedVExtractIdx = BaseIdx;
5514 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5515 if (I0 == ExpectedVExtractIdx)
5516 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5517 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5518 // Try to match the following dag sequence:
5519 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5520 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5524 ExpectedVExtractIdx += 2;
5530 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5531 /// a concat_vector.
5533 /// This is a helper function of LowerToHorizontalOp().
5534 /// This function expects two 256-bit vectors called V0 and V1.
5535 /// At first, each vector is split into two separate 128-bit vectors.
5536 /// Then, the resulting 128-bit vectors are used to implement two
5537 /// horizontal binary operations.
5539 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5541 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5542 /// the two new horizontal binop.
5543 /// When Mode is set, the first horizontal binop dag node would take as input
5544 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5545 /// horizontal binop dag node would take as input the lower 128-bit of V1
5546 /// and the upper 128-bit of V1.
5548 /// HADD V0_LO, V0_HI
5549 /// HADD V1_LO, V1_HI
5551 /// Otherwise, the first horizontal binop dag node takes as input the lower
5552 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5553 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5555 /// HADD V0_LO, V1_LO
5556 /// HADD V0_HI, V1_HI
5558 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5559 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5560 /// the upper 128-bits of the result.
5561 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5562 SDLoc DL, SelectionDAG &DAG,
5563 unsigned X86Opcode, bool Mode,
5564 bool isUndefLO, bool isUndefHI) {
5565 EVT VT = V0.getValueType();
5566 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5567 "Invalid nodes in input!");
5569 unsigned NumElts = VT.getVectorNumElements();
5570 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5571 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5572 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5573 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5574 EVT NewVT = V0_LO.getValueType();
5576 SDValue LO = DAG.getUNDEF(NewVT);
5577 SDValue HI = DAG.getUNDEF(NewVT);
5580 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5581 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5582 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5583 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5584 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5586 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5587 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5588 V1_LO->getOpcode() != ISD::UNDEF))
5589 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5591 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5592 V1_HI->getOpcode() != ISD::UNDEF))
5593 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5596 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5599 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5601 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5602 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5603 EVT VT = BV->getValueType(0);
5604 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5605 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5609 unsigned NumElts = VT.getVectorNumElements();
5610 SDValue InVec0 = DAG.getUNDEF(VT);
5611 SDValue InVec1 = DAG.getUNDEF(VT);
5613 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5614 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5616 // Odd-numbered elements in the input build vector are obtained from
5617 // adding two integer/float elements.
5618 // Even-numbered elements in the input build vector are obtained from
5619 // subtracting two integer/float elements.
5620 unsigned ExpectedOpcode = ISD::FSUB;
5621 unsigned NextExpectedOpcode = ISD::FADD;
5622 bool AddFound = false;
5623 bool SubFound = false;
5625 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5626 SDValue Op = BV->getOperand(i);
5628 // Skip 'undef' values.
5629 unsigned Opcode = Op.getOpcode();
5630 if (Opcode == ISD::UNDEF) {
5631 std::swap(ExpectedOpcode, NextExpectedOpcode);
5635 // Early exit if we found an unexpected opcode.
5636 if (Opcode != ExpectedOpcode)
5639 SDValue Op0 = Op.getOperand(0);
5640 SDValue Op1 = Op.getOperand(1);
5642 // Try to match the following pattern:
5643 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5644 // Early exit if we cannot match that sequence.
5645 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5646 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5647 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5648 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5649 Op0.getOperand(1) != Op1.getOperand(1))
5652 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5656 // We found a valid add/sub node. Update the information accordingly.
5662 // Update InVec0 and InVec1.
5663 if (InVec0.getOpcode() == ISD::UNDEF) {
5664 InVec0 = Op0.getOperand(0);
5665 if (InVec0.getValueType() != VT)
5668 if (InVec1.getOpcode() == ISD::UNDEF) {
5669 InVec1 = Op1.getOperand(0);
5670 if (InVec1.getValueType() != VT)
5674 // Make sure that operands in input to each add/sub node always
5675 // come from a same pair of vectors.
5676 if (InVec0 != Op0.getOperand(0)) {
5677 if (ExpectedOpcode == ISD::FSUB)
5680 // FADD is commutable. Try to commute the operands
5681 // and then test again.
5682 std::swap(Op0, Op1);
5683 if (InVec0 != Op0.getOperand(0))
5687 if (InVec1 != Op1.getOperand(0))
5690 // Update the pair of expected opcodes.
5691 std::swap(ExpectedOpcode, NextExpectedOpcode);
5694 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5695 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5696 InVec1.getOpcode() != ISD::UNDEF)
5697 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5702 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5703 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5704 const X86Subtarget *Subtarget,
5705 SelectionDAG &DAG) {
5706 EVT VT = BV->getValueType(0);
5707 unsigned NumElts = VT.getVectorNumElements();
5708 unsigned NumUndefsLO = 0;
5709 unsigned NumUndefsHI = 0;
5710 unsigned Half = NumElts/2;
5712 // Count the number of UNDEF operands in the build_vector in input.
5713 for (unsigned i = 0, e = Half; i != e; ++i)
5714 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5717 for (unsigned i = Half, e = NumElts; i != e; ++i)
5718 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5721 // Early exit if this is either a build_vector of all UNDEFs or all the
5722 // operands but one are UNDEF.
5723 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5727 SDValue InVec0, InVec1;
5728 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5729 // Try to match an SSE3 float HADD/HSUB.
5730 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5731 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5733 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5734 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5735 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5736 // Try to match an SSSE3 integer HADD/HSUB.
5737 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5738 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5740 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5741 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5744 if (!Subtarget->hasAVX())
5747 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5748 // Try to match an AVX horizontal add/sub of packed single/double
5749 // precision floating point values from 256-bit vectors.
5750 SDValue InVec2, InVec3;
5751 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5752 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5753 ((InVec0.getOpcode() == ISD::UNDEF ||
5754 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5755 ((InVec1.getOpcode() == ISD::UNDEF ||
5756 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5757 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5759 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5760 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5761 ((InVec0.getOpcode() == ISD::UNDEF ||
5762 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5763 ((InVec1.getOpcode() == ISD::UNDEF ||
5764 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5765 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5766 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5767 // Try to match an AVX2 horizontal add/sub of signed integers.
5768 SDValue InVec2, InVec3;
5770 bool CanFold = true;
5772 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5773 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5774 ((InVec0.getOpcode() == ISD::UNDEF ||
5775 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5776 ((InVec1.getOpcode() == ISD::UNDEF ||
5777 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5778 X86Opcode = X86ISD::HADD;
5779 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5780 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5781 ((InVec0.getOpcode() == ISD::UNDEF ||
5782 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5783 ((InVec1.getOpcode() == ISD::UNDEF ||
5784 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5785 X86Opcode = X86ISD::HSUB;
5790 // Fold this build_vector into a single horizontal add/sub.
5791 // Do this only if the target has AVX2.
5792 if (Subtarget->hasAVX2())
5793 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5795 // Do not try to expand this build_vector into a pair of horizontal
5796 // add/sub if we can emit a pair of scalar add/sub.
5797 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5800 // Convert this build_vector into a pair of horizontal binop followed by
5802 bool isUndefLO = NumUndefsLO == Half;
5803 bool isUndefHI = NumUndefsHI == Half;
5804 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5805 isUndefLO, isUndefHI);
5809 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5810 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5812 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5813 X86Opcode = X86ISD::HADD;
5814 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5815 X86Opcode = X86ISD::HSUB;
5816 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5817 X86Opcode = X86ISD::FHADD;
5818 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5819 X86Opcode = X86ISD::FHSUB;
5823 // Don't try to expand this build_vector into a pair of horizontal add/sub
5824 // if we can simply emit a pair of scalar add/sub.
5825 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5828 // Convert this build_vector into two horizontal add/sub followed by
5830 bool isUndefLO = NumUndefsLO == Half;
5831 bool isUndefHI = NumUndefsHI == Half;
5832 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5833 isUndefLO, isUndefHI);
5840 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5843 MVT VT = Op.getSimpleValueType();
5844 MVT ExtVT = VT.getVectorElementType();
5845 unsigned NumElems = Op.getNumOperands();
5847 // Generate vectors for predicate vectors.
5848 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5849 return LowerBUILD_VECTORvXi1(Op, DAG);
5851 // Vectors containing all zeros can be matched by pxor and xorps later
5852 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5853 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5854 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5855 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5858 return getZeroVector(VT, Subtarget, DAG, dl);
5861 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5862 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5863 // vpcmpeqd on 256-bit vectors.
5864 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5865 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5868 if (!VT.is512BitVector())
5869 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5872 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5873 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5875 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5876 return HorizontalOp;
5877 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5880 unsigned EVTBits = ExtVT.getSizeInBits();
5882 unsigned NumZero = 0;
5883 unsigned NumNonZero = 0;
5884 unsigned NonZeros = 0;
5885 bool IsAllConstants = true;
5886 SmallSet<SDValue, 8> Values;
5887 for (unsigned i = 0; i < NumElems; ++i) {
5888 SDValue Elt = Op.getOperand(i);
5889 if (Elt.getOpcode() == ISD::UNDEF)
5892 if (Elt.getOpcode() != ISD::Constant &&
5893 Elt.getOpcode() != ISD::ConstantFP)
5894 IsAllConstants = false;
5895 if (X86::isZeroNode(Elt))
5898 NonZeros |= (1 << i);
5903 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5904 if (NumNonZero == 0)
5905 return DAG.getUNDEF(VT);
5907 // Special case for single non-zero, non-undef, element.
5908 if (NumNonZero == 1) {
5909 unsigned Idx = countTrailingZeros(NonZeros);
5910 SDValue Item = Op.getOperand(Idx);
5912 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5913 // the value are obviously zero, truncate the value to i32 and do the
5914 // insertion that way. Only do this if the value is non-constant or if the
5915 // value is a constant being inserted into element 0. It is cheaper to do
5916 // a constant pool load than it is to do a movd + shuffle.
5917 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5918 (!IsAllConstants || Idx == 0)) {
5919 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5921 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5922 EVT VecVT = MVT::v4i32;
5924 // Truncate the value (which may itself be a constant) to i32, and
5925 // convert it to a vector with movd (S2V+shuffle to zero extend).
5926 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5927 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5928 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5929 Item, Idx * 2, true, Subtarget, DAG));
5933 // If we have a constant or non-constant insertion into the low element of
5934 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5935 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5936 // depending on what the source datatype is.
5939 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5941 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5942 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5943 if (VT.is512BitVector()) {
5944 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5945 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5946 Item, DAG.getIntPtrConstant(0, dl));
5948 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5949 "Expected an SSE value type!");
5950 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5951 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5952 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5955 // We can't directly insert an i8 or i16 into a vector, so zero extend
5957 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5958 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5959 if (VT.is256BitVector()) {
5960 if (Subtarget->hasAVX()) {
5961 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5962 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5964 // Without AVX, we need to extend to a 128-bit vector and then
5965 // insert into the 256-bit vector.
5966 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5967 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5968 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5971 assert(VT.is128BitVector() && "Expected an SSE value type!");
5972 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5973 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5975 return DAG.getBitcast(VT, Item);
5979 // Is it a vector logical left shift?
5980 if (NumElems == 2 && Idx == 1 &&
5981 X86::isZeroNode(Op.getOperand(0)) &&
5982 !X86::isZeroNode(Op.getOperand(1))) {
5983 unsigned NumBits = VT.getSizeInBits();
5984 return getVShift(true, VT,
5985 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5986 VT, Op.getOperand(1)),
5987 NumBits/2, DAG, *this, dl);
5990 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5993 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5994 // is a non-constant being inserted into an element other than the low one,
5995 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5996 // movd/movss) to move this into the low element, then shuffle it into
5998 if (EVTBits == 32) {
5999 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6000 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6004 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6005 if (Values.size() == 1) {
6006 if (EVTBits == 32) {
6007 // Instead of a shuffle like this:
6008 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6009 // Check if it's possible to issue this instead.
6010 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6011 unsigned Idx = countTrailingZeros(NonZeros);
6012 SDValue Item = Op.getOperand(Idx);
6013 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6014 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6019 // A vector full of immediates; various special cases are already
6020 // handled, so this is best done with a single constant-pool load.
6024 // For AVX-length vectors, see if we can use a vector load to get all of the
6025 // elements, otherwise build the individual 128-bit pieces and use
6026 // shuffles to put them in place.
6027 if (VT.is256BitVector() || VT.is512BitVector()) {
6028 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6030 // Check for a build vector of consecutive loads.
6031 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6034 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6036 // Build both the lower and upper subvector.
6037 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6038 makeArrayRef(&V[0], NumElems/2));
6039 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6040 makeArrayRef(&V[NumElems / 2], NumElems/2));
6042 // Recreate the wider vector with the lower and upper part.
6043 if (VT.is256BitVector())
6044 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6045 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6048 // Let legalizer expand 2-wide build_vectors.
6049 if (EVTBits == 64) {
6050 if (NumNonZero == 1) {
6051 // One half is zero or undef.
6052 unsigned Idx = countTrailingZeros(NonZeros);
6053 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6054 Op.getOperand(Idx));
6055 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6060 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6061 if (EVTBits == 8 && NumElems == 16)
6062 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6066 if (EVTBits == 16 && NumElems == 8)
6067 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6071 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6072 if (EVTBits == 32 && NumElems == 4)
6073 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6076 // If element VT is == 32 bits, turn it into a number of shuffles.
6077 SmallVector<SDValue, 8> V(NumElems);
6078 if (NumElems == 4 && NumZero > 0) {
6079 for (unsigned i = 0; i < 4; ++i) {
6080 bool isZero = !(NonZeros & (1 << i));
6082 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6084 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6087 for (unsigned i = 0; i < 2; ++i) {
6088 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6091 V[i] = V[i*2]; // Must be a zero vector.
6094 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6097 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6100 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6105 bool Reverse1 = (NonZeros & 0x3) == 2;
6106 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6110 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6111 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6113 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6116 if (Values.size() > 1 && VT.is128BitVector()) {
6117 // Check for a build vector of consecutive loads.
6118 for (unsigned i = 0; i < NumElems; ++i)
6119 V[i] = Op.getOperand(i);
6121 // Check for elements which are consecutive loads.
6122 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6125 // Check for a build vector from mostly shuffle plus few inserting.
6126 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6129 // For SSE 4.1, use insertps to put the high elements into the low element.
6130 if (Subtarget->hasSSE41()) {
6132 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6133 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6135 Result = DAG.getUNDEF(VT);
6137 for (unsigned i = 1; i < NumElems; ++i) {
6138 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6139 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6140 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6145 // Otherwise, expand into a number of unpckl*, start by extending each of
6146 // our (non-undef) elements to the full vector width with the element in the
6147 // bottom slot of the vector (which generates no code for SSE).
6148 for (unsigned i = 0; i < NumElems; ++i) {
6149 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6150 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6152 V[i] = DAG.getUNDEF(VT);
6155 // Next, we iteratively mix elements, e.g. for v4f32:
6156 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6157 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6158 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6159 unsigned EltStride = NumElems >> 1;
6160 while (EltStride != 0) {
6161 for (unsigned i = 0; i < EltStride; ++i) {
6162 // If V[i+EltStride] is undef and this is the first round of mixing,
6163 // then it is safe to just drop this shuffle: V[i] is already in the
6164 // right place, the one element (since it's the first round) being
6165 // inserted as undef can be dropped. This isn't safe for successive
6166 // rounds because they will permute elements within both vectors.
6167 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6168 EltStride == NumElems/2)
6171 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6180 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6181 // to create 256-bit vectors from two other 128-bit ones.
6182 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6184 MVT ResVT = Op.getSimpleValueType();
6186 assert((ResVT.is256BitVector() ||
6187 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6189 SDValue V1 = Op.getOperand(0);
6190 SDValue V2 = Op.getOperand(1);
6191 unsigned NumElems = ResVT.getVectorNumElements();
6192 if (ResVT.is256BitVector())
6193 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6195 if (Op.getNumOperands() == 4) {
6196 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6197 ResVT.getVectorNumElements()/2);
6198 SDValue V3 = Op.getOperand(2);
6199 SDValue V4 = Op.getOperand(3);
6200 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6201 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6203 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6206 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6207 const X86Subtarget *Subtarget,
6208 SelectionDAG & DAG) {
6210 MVT ResVT = Op.getSimpleValueType();
6211 unsigned NumOfOperands = Op.getNumOperands();
6213 assert(isPowerOf2_32(NumOfOperands) &&
6214 "Unexpected number of operands in CONCAT_VECTORS");
6216 if (NumOfOperands > 2) {
6217 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6218 ResVT.getVectorNumElements()/2);
6219 SmallVector<SDValue, 2> Ops;
6220 for (unsigned i = 0; i < NumOfOperands/2; i++)
6221 Ops.push_back(Op.getOperand(i));
6222 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6224 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6225 Ops.push_back(Op.getOperand(i));
6226 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6227 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6230 SDValue V1 = Op.getOperand(0);
6231 SDValue V2 = Op.getOperand(1);
6232 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6233 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6235 if (IsZeroV1 && IsZeroV2)
6236 return getZeroVector(ResVT, Subtarget, DAG, dl);
6238 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6239 SDValue Undef = DAG.getUNDEF(ResVT);
6240 unsigned NumElems = ResVT.getVectorNumElements();
6241 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6243 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6244 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6248 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6249 // Zero the upper bits of V1
6250 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6251 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6254 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6257 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6258 const X86Subtarget *Subtarget,
6259 SelectionDAG &DAG) {
6260 MVT VT = Op.getSimpleValueType();
6261 if (VT.getVectorElementType() == MVT::i1)
6262 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6264 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6265 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6266 Op.getNumOperands() == 4)));
6268 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6269 // from two other 128-bit ones.
6271 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6272 return LowerAVXCONCAT_VECTORS(Op, DAG);
6276 //===----------------------------------------------------------------------===//
6277 // Vector shuffle lowering
6279 // This is an experimental code path for lowering vector shuffles on x86. It is
6280 // designed to handle arbitrary vector shuffles and blends, gracefully
6281 // degrading performance as necessary. It works hard to recognize idiomatic
6282 // shuffles and lower them to optimal instruction patterns without leaving
6283 // a framework that allows reasonably efficient handling of all vector shuffle
6285 //===----------------------------------------------------------------------===//
6287 /// \brief Tiny helper function to identify a no-op mask.
6289 /// This is a somewhat boring predicate function. It checks whether the mask
6290 /// array input, which is assumed to be a single-input shuffle mask of the kind
6291 /// used by the X86 shuffle instructions (not a fully general
6292 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6293 /// in-place shuffle are 'no-op's.
6294 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6295 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6296 if (Mask[i] != -1 && Mask[i] != i)
6301 /// \brief Helper function to classify a mask as a single-input mask.
6303 /// This isn't a generic single-input test because in the vector shuffle
6304 /// lowering we canonicalize single inputs to be the first input operand. This
6305 /// means we can more quickly test for a single input by only checking whether
6306 /// an input from the second operand exists. We also assume that the size of
6307 /// mask corresponds to the size of the input vectors which isn't true in the
6308 /// fully general case.
6309 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6311 if (M >= (int)Mask.size())
6316 /// \brief Test whether there are elements crossing 128-bit lanes in this
6319 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6320 /// and we routinely test for these.
6321 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6322 int LaneSize = 128 / VT.getScalarSizeInBits();
6323 int Size = Mask.size();
6324 for (int i = 0; i < Size; ++i)
6325 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6330 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6332 /// This checks a shuffle mask to see if it is performing the same
6333 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6334 /// that it is also not lane-crossing. It may however involve a blend from the
6335 /// same lane of a second vector.
6337 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6338 /// non-trivial to compute in the face of undef lanes. The representation is
6339 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6340 /// entries from both V1 and V2 inputs to the wider mask.
6342 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6343 SmallVectorImpl<int> &RepeatedMask) {
6344 int LaneSize = 128 / VT.getScalarSizeInBits();
6345 RepeatedMask.resize(LaneSize, -1);
6346 int Size = Mask.size();
6347 for (int i = 0; i < Size; ++i) {
6350 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6351 // This entry crosses lanes, so there is no way to model this shuffle.
6354 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6355 if (RepeatedMask[i % LaneSize] == -1)
6356 // This is the first non-undef entry in this slot of a 128-bit lane.
6357 RepeatedMask[i % LaneSize] =
6358 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6359 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6360 // Found a mismatch with the repeated mask.
6366 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6369 /// This is a fast way to test a shuffle mask against a fixed pattern:
6371 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6373 /// It returns true if the mask is exactly as wide as the argument list, and
6374 /// each element of the mask is either -1 (signifying undef) or the value given
6375 /// in the argument.
6376 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6377 ArrayRef<int> ExpectedMask) {
6378 if (Mask.size() != ExpectedMask.size())
6381 int Size = Mask.size();
6383 // If the values are build vectors, we can look through them to find
6384 // equivalent inputs that make the shuffles equivalent.
6385 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6386 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6388 for (int i = 0; i < Size; ++i)
6389 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6390 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6391 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6392 if (!MaskBV || !ExpectedBV ||
6393 MaskBV->getOperand(Mask[i] % Size) !=
6394 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6401 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6403 /// This helper function produces an 8-bit shuffle immediate corresponding to
6404 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6405 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6408 /// NB: We rely heavily on "undef" masks preserving the input lane.
6409 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6410 SelectionDAG &DAG) {
6411 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6412 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6413 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6414 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6415 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6418 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6419 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6420 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6421 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6422 return DAG.getConstant(Imm, DL, MVT::i8);
6425 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6427 /// This is used as a fallback approach when first class blend instructions are
6428 /// unavailable. Currently it is only suitable for integer vectors, but could
6429 /// be generalized for floating point vectors if desirable.
6430 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6431 SDValue V2, ArrayRef<int> Mask,
6432 SelectionDAG &DAG) {
6433 assert(VT.isInteger() && "Only supports integer vector types!");
6434 MVT EltVT = VT.getScalarType();
6435 int NumEltBits = EltVT.getSizeInBits();
6436 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6437 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6439 SmallVector<SDValue, 16> MaskOps;
6440 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6441 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6442 return SDValue(); // Shuffled input!
6443 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6446 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6447 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6448 // We have to cast V2 around.
6449 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6450 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6451 DAG.getBitcast(MaskVT, V1Mask),
6452 DAG.getBitcast(MaskVT, V2)));
6453 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6456 /// \brief Try to emit a blend instruction for a shuffle.
6458 /// This doesn't do any checks for the availability of instructions for blending
6459 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6460 /// be matched in the backend with the type given. What it does check for is
6461 /// that the shuffle mask is in fact a blend.
6462 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6463 SDValue V2, ArrayRef<int> Mask,
6464 const X86Subtarget *Subtarget,
6465 SelectionDAG &DAG) {
6466 unsigned BlendMask = 0;
6467 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6468 if (Mask[i] >= Size) {
6469 if (Mask[i] != i + Size)
6470 return SDValue(); // Shuffled V2 input!
6471 BlendMask |= 1u << i;
6474 if (Mask[i] >= 0 && Mask[i] != i)
6475 return SDValue(); // Shuffled V1 input!
6477 switch (VT.SimpleTy) {
6482 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6483 DAG.getConstant(BlendMask, DL, MVT::i8));
6487 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6491 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6492 // that instruction.
6493 if (Subtarget->hasAVX2()) {
6494 // Scale the blend by the number of 32-bit dwords per element.
6495 int Scale = VT.getScalarSizeInBits() / 32;
6497 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6498 if (Mask[i] >= Size)
6499 for (int j = 0; j < Scale; ++j)
6500 BlendMask |= 1u << (i * Scale + j);
6502 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6503 V1 = DAG.getBitcast(BlendVT, V1);
6504 V2 = DAG.getBitcast(BlendVT, V2);
6505 return DAG.getBitcast(
6506 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6507 DAG.getConstant(BlendMask, DL, MVT::i8)));
6511 // For integer shuffles we need to expand the mask and cast the inputs to
6512 // v8i16s prior to blending.
6513 int Scale = 8 / VT.getVectorNumElements();
6515 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6516 if (Mask[i] >= Size)
6517 for (int j = 0; j < Scale; ++j)
6518 BlendMask |= 1u << (i * Scale + j);
6520 V1 = DAG.getBitcast(MVT::v8i16, V1);
6521 V2 = DAG.getBitcast(MVT::v8i16, V2);
6522 return DAG.getBitcast(VT,
6523 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6524 DAG.getConstant(BlendMask, DL, MVT::i8)));
6528 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6529 SmallVector<int, 8> RepeatedMask;
6530 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6531 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6532 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6534 for (int i = 0; i < 8; ++i)
6535 if (RepeatedMask[i] >= 16)
6536 BlendMask |= 1u << i;
6537 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6538 DAG.getConstant(BlendMask, DL, MVT::i8));
6544 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6545 "256-bit byte-blends require AVX2 support!");
6547 // Scale the blend by the number of bytes per element.
6548 int Scale = VT.getScalarSizeInBits() / 8;
6550 // This form of blend is always done on bytes. Compute the byte vector
6552 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6554 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6555 // mix of LLVM's code generator and the x86 backend. We tell the code
6556 // generator that boolean values in the elements of an x86 vector register
6557 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6558 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6559 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6560 // of the element (the remaining are ignored) and 0 in that high bit would
6561 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6562 // the LLVM model for boolean values in vector elements gets the relevant
6563 // bit set, it is set backwards and over constrained relative to x86's
6565 SmallVector<SDValue, 32> VSELECTMask;
6566 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6567 for (int j = 0; j < Scale; ++j)
6568 VSELECTMask.push_back(
6569 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6570 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6573 V1 = DAG.getBitcast(BlendVT, V1);
6574 V2 = DAG.getBitcast(BlendVT, V2);
6575 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6576 DAG.getNode(ISD::BUILD_VECTOR, DL,
6577 BlendVT, VSELECTMask),
6582 llvm_unreachable("Not a supported integer vector type!");
6586 /// \brief Try to lower as a blend of elements from two inputs followed by
6587 /// a single-input permutation.
6589 /// This matches the pattern where we can blend elements from two inputs and
6590 /// then reduce the shuffle to a single-input permutation.
6591 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6594 SelectionDAG &DAG) {
6595 // We build up the blend mask while checking whether a blend is a viable way
6596 // to reduce the shuffle.
6597 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6598 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6600 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6604 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6606 if (BlendMask[Mask[i] % Size] == -1)
6607 BlendMask[Mask[i] % Size] = Mask[i];
6608 else if (BlendMask[Mask[i] % Size] != Mask[i])
6609 return SDValue(); // Can't blend in the needed input!
6611 PermuteMask[i] = Mask[i] % Size;
6614 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6615 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6618 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6619 /// blends and permutes.
6621 /// This matches the extremely common pattern for handling combined
6622 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6623 /// operations. It will try to pick the best arrangement of shuffles and
6625 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6629 SelectionDAG &DAG) {
6630 // Shuffle the input elements into the desired positions in V1 and V2 and
6631 // blend them together.
6632 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6633 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6634 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6635 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6636 if (Mask[i] >= 0 && Mask[i] < Size) {
6637 V1Mask[i] = Mask[i];
6639 } else if (Mask[i] >= Size) {
6640 V2Mask[i] = Mask[i] - Size;
6641 BlendMask[i] = i + Size;
6644 // Try to lower with the simpler initial blend strategy unless one of the
6645 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6646 // shuffle may be able to fold with a load or other benefit. However, when
6647 // we'll have to do 2x as many shuffles in order to achieve this, blending
6648 // first is a better strategy.
6649 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6650 if (SDValue BlendPerm =
6651 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6654 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6655 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6656 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6659 /// \brief Try to lower a vector shuffle as a byte rotation.
6661 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6662 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6663 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6664 /// try to generically lower a vector shuffle through such an pattern. It
6665 /// does not check for the profitability of lowering either as PALIGNR or
6666 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6667 /// This matches shuffle vectors that look like:
6669 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6671 /// Essentially it concatenates V1 and V2, shifts right by some number of
6672 /// elements, and takes the low elements as the result. Note that while this is
6673 /// specified as a *right shift* because x86 is little-endian, it is a *left
6674 /// rotate* of the vector lanes.
6675 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6678 const X86Subtarget *Subtarget,
6679 SelectionDAG &DAG) {
6680 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6682 int NumElts = Mask.size();
6683 int NumLanes = VT.getSizeInBits() / 128;
6684 int NumLaneElts = NumElts / NumLanes;
6686 // We need to detect various ways of spelling a rotation:
6687 // [11, 12, 13, 14, 15, 0, 1, 2]
6688 // [-1, 12, 13, 14, -1, -1, 1, -1]
6689 // [-1, -1, -1, -1, -1, -1, 1, 2]
6690 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6691 // [-1, 4, 5, 6, -1, -1, 9, -1]
6692 // [-1, 4, 5, 6, -1, -1, -1, -1]
6695 for (int l = 0; l < NumElts; l += NumLaneElts) {
6696 for (int i = 0; i < NumLaneElts; ++i) {
6697 if (Mask[l + i] == -1)
6699 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6701 // Get the mod-Size index and lane correct it.
6702 int LaneIdx = (Mask[l + i] % NumElts) - l;
6703 // Make sure it was in this lane.
6704 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6707 // Determine where a rotated vector would have started.
6708 int StartIdx = i - LaneIdx;
6710 // The identity rotation isn't interesting, stop.
6713 // If we found the tail of a vector the rotation must be the missing
6714 // front. If we found the head of a vector, it must be how much of the
6716 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6719 Rotation = CandidateRotation;
6720 else if (Rotation != CandidateRotation)
6721 // The rotations don't match, so we can't match this mask.
6724 // Compute which value this mask is pointing at.
6725 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6727 // Compute which of the two target values this index should be assigned
6728 // to. This reflects whether the high elements are remaining or the low
6729 // elements are remaining.
6730 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6732 // Either set up this value if we've not encountered it before, or check
6733 // that it remains consistent.
6736 else if (TargetV != MaskV)
6737 // This may be a rotation, but it pulls from the inputs in some
6738 // unsupported interleaving.
6743 // Check that we successfully analyzed the mask, and normalize the results.
6744 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6745 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6751 // The actual rotate instruction rotates bytes, so we need to scale the
6752 // rotation based on how many bytes are in the vector lane.
6753 int Scale = 16 / NumLaneElts;
6755 // SSSE3 targets can use the palignr instruction.
6756 if (Subtarget->hasSSSE3()) {
6757 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6758 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6759 Lo = DAG.getBitcast(AlignVT, Lo);
6760 Hi = DAG.getBitcast(AlignVT, Hi);
6762 return DAG.getBitcast(
6763 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6764 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6767 assert(VT.getSizeInBits() == 128 &&
6768 "Rotate-based lowering only supports 128-bit lowering!");
6769 assert(Mask.size() <= 16 &&
6770 "Can shuffle at most 16 bytes in a 128-bit vector!");
6772 // Default SSE2 implementation
6773 int LoByteShift = 16 - Rotation * Scale;
6774 int HiByteShift = Rotation * Scale;
6776 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6777 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6778 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6780 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6781 DAG.getConstant(LoByteShift, DL, MVT::i8));
6782 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6783 DAG.getConstant(HiByteShift, DL, MVT::i8));
6784 return DAG.getBitcast(VT,
6785 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6788 /// \brief Compute whether each element of a shuffle is zeroable.
6790 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6791 /// Either it is an undef element in the shuffle mask, the element of the input
6792 /// referenced is undef, or the element of the input referenced is known to be
6793 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6794 /// as many lanes with this technique as possible to simplify the remaining
6796 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6797 SDValue V1, SDValue V2) {
6798 SmallBitVector Zeroable(Mask.size(), false);
6800 while (V1.getOpcode() == ISD::BITCAST)
6801 V1 = V1->getOperand(0);
6802 while (V2.getOpcode() == ISD::BITCAST)
6803 V2 = V2->getOperand(0);
6805 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6806 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6808 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6810 // Handle the easy cases.
6811 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6816 // If this is an index into a build_vector node (which has the same number
6817 // of elements), dig out the input value and use it.
6818 SDValue V = M < Size ? V1 : V2;
6819 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6822 SDValue Input = V.getOperand(M % Size);
6823 // The UNDEF opcode check really should be dead code here, but not quite
6824 // worth asserting on (it isn't invalid, just unexpected).
6825 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6832 /// \brief Try to emit a bitmask instruction for a shuffle.
6834 /// This handles cases where we can model a blend exactly as a bitmask due to
6835 /// one of the inputs being zeroable.
6836 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6837 SDValue V2, ArrayRef<int> Mask,
6838 SelectionDAG &DAG) {
6839 MVT EltVT = VT.getScalarType();
6840 int NumEltBits = EltVT.getSizeInBits();
6841 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6842 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6843 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6845 if (EltVT.isFloatingPoint()) {
6846 Zero = DAG.getBitcast(EltVT, Zero);
6847 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6849 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6850 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6852 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6855 if (Mask[i] % Size != i)
6856 return SDValue(); // Not a blend.
6858 V = Mask[i] < Size ? V1 : V2;
6859 else if (V != (Mask[i] < Size ? V1 : V2))
6860 return SDValue(); // Can only let one input through the mask.
6862 VMaskOps[i] = AllOnes;
6865 return SDValue(); // No non-zeroable elements!
6867 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6868 V = DAG.getNode(VT.isFloatingPoint()
6869 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6874 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6876 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6877 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6878 /// matches elements from one of the input vectors shuffled to the left or
6879 /// right with zeroable elements 'shifted in'. It handles both the strictly
6880 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6883 /// PSHL : (little-endian) left bit shift.
6884 /// [ zz, 0, zz, 2 ]
6885 /// [ -1, 4, zz, -1 ]
6886 /// PSRL : (little-endian) right bit shift.
6888 /// [ -1, -1, 7, zz]
6889 /// PSLLDQ : (little-endian) left byte shift
6890 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6891 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6892 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6893 /// PSRLDQ : (little-endian) right byte shift
6894 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6895 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6896 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6897 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6898 SDValue V2, ArrayRef<int> Mask,
6899 SelectionDAG &DAG) {
6900 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6902 int Size = Mask.size();
6903 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6905 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6906 for (int i = 0; i < Size; i += Scale)
6907 for (int j = 0; j < Shift; ++j)
6908 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6914 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6915 for (int i = 0; i != Size; i += Scale) {
6916 unsigned Pos = Left ? i + Shift : i;
6917 unsigned Low = Left ? i : i + Shift;
6918 unsigned Len = Scale - Shift;
6919 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6920 Low + (V == V1 ? 0 : Size)))
6924 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6925 bool ByteShift = ShiftEltBits > 64;
6926 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6927 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6928 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6930 // Normalize the scale for byte shifts to still produce an i64 element
6932 Scale = ByteShift ? Scale / 2 : Scale;
6934 // We need to round trip through the appropriate type for the shift.
6935 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6936 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6937 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6938 "Illegal integer vector type");
6939 V = DAG.getBitcast(ShiftVT, V);
6941 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6942 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6943 return DAG.getBitcast(VT, V);
6946 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6947 // keep doubling the size of the integer elements up to that. We can
6948 // then shift the elements of the integer vector by whole multiples of
6949 // their width within the elements of the larger integer vector. Test each
6950 // multiple to see if we can find a match with the moved element indices
6951 // and that the shifted in elements are all zeroable.
6952 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6953 for (int Shift = 1; Shift != Scale; ++Shift)
6954 for (bool Left : {true, false})
6955 if (CheckZeros(Shift, Scale, Left))
6956 for (SDValue V : {V1, V2})
6957 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6964 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6965 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6966 SDValue V2, ArrayRef<int> Mask,
6967 SelectionDAG &DAG) {
6968 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6969 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6971 int Size = Mask.size();
6972 int HalfSize = Size / 2;
6973 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6975 // Upper half must be undefined.
6976 if (!isUndefInRange(Mask, HalfSize, HalfSize))
6979 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
6980 // Remainder of lower half result is zero and upper half is all undef.
6981 auto LowerAsEXTRQ = [&]() {
6982 // Determine the extraction length from the part of the
6983 // lower half that isn't zeroable.
6985 for (; Len >= 0; --Len)
6986 if (!Zeroable[Len - 1])
6988 assert(Len > 0 && "Zeroable shuffle mask");
6990 // Attempt to match first Len sequential elements from the lower half.
6993 for (int i = 0; i != Len; ++i) {
6997 SDValue &V = (M < Size ? V1 : V2);
7000 // All mask elements must be in the lower half.
7004 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7015 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7016 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7017 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7018 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7019 DAG.getConstant(BitLen, DL, MVT::i8),
7020 DAG.getConstant(BitIdx, DL, MVT::i8));
7023 if (SDValue ExtrQ = LowerAsEXTRQ())
7026 // INSERTQ: Extract lowest Len elements from lower half of second source and
7027 // insert over first source, starting at Idx.
7028 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7029 auto LowerAsInsertQ = [&]() {
7030 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7033 // Attempt to match first source from mask before insertion point.
7034 if (isUndefInRange(Mask, 0, Idx)) {
7036 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7038 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7044 // Extend the extraction length looking to match both the insertion of
7045 // the second source and the remaining elements of the first.
7046 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7051 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7053 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7059 // Match the remaining elements of the lower half.
7060 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7062 } else if ((!Base || (Base == V1)) &&
7063 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7065 } else if ((!Base || (Base == V2)) &&
7066 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7073 // We may not have a base (first source) - this can safely be undefined.
7075 Base = DAG.getUNDEF(VT);
7077 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7078 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7079 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7080 DAG.getConstant(BitLen, DL, MVT::i8),
7081 DAG.getConstant(BitIdx, DL, MVT::i8));
7088 if (SDValue InsertQ = LowerAsInsertQ())
7094 /// \brief Lower a vector shuffle as a zero or any extension.
7096 /// Given a specific number of elements, element bit width, and extension
7097 /// stride, produce either a zero or any extension based on the available
7098 /// features of the subtarget.
7099 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7100 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7101 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7102 assert(Scale > 1 && "Need a scale to extend.");
7103 int NumElements = VT.getVectorNumElements();
7104 int EltBits = VT.getScalarSizeInBits();
7105 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7106 "Only 8, 16, and 32 bit elements can be extended.");
7107 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7109 // Found a valid zext mask! Try various lowering strategies based on the
7110 // input type and available ISA extensions.
7111 if (Subtarget->hasSSE41()) {
7112 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7113 NumElements / Scale);
7114 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7117 // For any extends we can cheat for larger element sizes and use shuffle
7118 // instructions that can fold with a load and/or copy.
7119 if (AnyExt && EltBits == 32) {
7120 int PSHUFDMask[4] = {0, -1, 1, -1};
7121 return DAG.getBitcast(
7122 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7123 DAG.getBitcast(MVT::v4i32, InputV),
7124 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7126 if (AnyExt && EltBits == 16 && Scale > 2) {
7127 int PSHUFDMask[4] = {0, -1, 0, -1};
7128 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7129 DAG.getBitcast(MVT::v4i32, InputV),
7130 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7131 int PSHUFHWMask[4] = {1, -1, -1, -1};
7132 return DAG.getBitcast(
7133 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7134 DAG.getBitcast(MVT::v8i16, InputV),
7135 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7138 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7140 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7141 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7142 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7144 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7145 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7146 DAG.getConstant(EltBits, DL, MVT::i8),
7147 DAG.getConstant(0, DL, MVT::i8)));
7148 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7149 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7152 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7153 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7154 DAG.getConstant(EltBits, DL, MVT::i8),
7155 DAG.getConstant(EltBits, DL, MVT::i8)));
7156 return DAG.getNode(ISD::BITCAST, DL, VT,
7157 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7160 // If this would require more than 2 unpack instructions to expand, use
7161 // pshufb when available. We can only use more than 2 unpack instructions
7162 // when zero extending i8 elements which also makes it easier to use pshufb.
7163 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7164 assert(NumElements == 16 && "Unexpected byte vector width!");
7165 SDValue PSHUFBMask[16];
7166 for (int i = 0; i < 16; ++i)
7168 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7169 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7170 return DAG.getBitcast(VT,
7171 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7172 DAG.getNode(ISD::BUILD_VECTOR, DL,
7173 MVT::v16i8, PSHUFBMask)));
7176 // Otherwise emit a sequence of unpacks.
7178 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7179 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7180 : getZeroVector(InputVT, Subtarget, DAG, DL);
7181 InputV = DAG.getBitcast(InputVT, InputV);
7182 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7186 } while (Scale > 1);
7187 return DAG.getBitcast(VT, InputV);
7190 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7192 /// This routine will try to do everything in its power to cleverly lower
7193 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7194 /// check for the profitability of this lowering, it tries to aggressively
7195 /// match this pattern. It will use all of the micro-architectural details it
7196 /// can to emit an efficient lowering. It handles both blends with all-zero
7197 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7198 /// masking out later).
7200 /// The reason we have dedicated lowering for zext-style shuffles is that they
7201 /// are both incredibly common and often quite performance sensitive.
7202 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7203 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7204 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7205 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7207 int Bits = VT.getSizeInBits();
7208 int NumElements = VT.getVectorNumElements();
7209 assert(VT.getScalarSizeInBits() <= 32 &&
7210 "Exceeds 32-bit integer zero extension limit");
7211 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7213 // Define a helper function to check a particular ext-scale and lower to it if
7215 auto Lower = [&](int Scale) -> SDValue {
7218 for (int i = 0; i < NumElements; ++i) {
7220 continue; // Valid anywhere but doesn't tell us anything.
7221 if (i % Scale != 0) {
7222 // Each of the extended elements need to be zeroable.
7226 // We no longer are in the anyext case.
7231 // Each of the base elements needs to be consecutive indices into the
7232 // same input vector.
7233 SDValue V = Mask[i] < NumElements ? V1 : V2;
7236 else if (InputV != V)
7237 return SDValue(); // Flip-flopping inputs.
7239 if (Mask[i] % NumElements != i / Scale)
7240 return SDValue(); // Non-consecutive strided elements.
7243 // If we fail to find an input, we have a zero-shuffle which should always
7244 // have already been handled.
7245 // FIXME: Maybe handle this here in case during blending we end up with one?
7249 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7250 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7253 // The widest scale possible for extending is to a 64-bit integer.
7254 assert(Bits % 64 == 0 &&
7255 "The number of bits in a vector must be divisible by 64 on x86!");
7256 int NumExtElements = Bits / 64;
7258 // Each iteration, try extending the elements half as much, but into twice as
7260 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7261 assert(NumElements % NumExtElements == 0 &&
7262 "The input vector size must be divisible by the extended size.");
7263 if (SDValue V = Lower(NumElements / NumExtElements))
7267 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7271 // Returns one of the source operands if the shuffle can be reduced to a
7272 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7273 auto CanZExtLowHalf = [&]() {
7274 for (int i = NumElements / 2; i != NumElements; ++i)
7277 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7279 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7284 if (SDValue V = CanZExtLowHalf()) {
7285 V = DAG.getBitcast(MVT::v2i64, V);
7286 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7287 return DAG.getBitcast(VT, V);
7290 // No viable ext lowering found.
7294 /// \brief Try to get a scalar value for a specific element of a vector.
7296 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7297 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7298 SelectionDAG &DAG) {
7299 MVT VT = V.getSimpleValueType();
7300 MVT EltVT = VT.getVectorElementType();
7301 while (V.getOpcode() == ISD::BITCAST)
7302 V = V.getOperand(0);
7303 // If the bitcasts shift the element size, we can't extract an equivalent
7305 MVT NewVT = V.getSimpleValueType();
7306 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7309 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7310 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7311 // Ensure the scalar operand is the same size as the destination.
7312 // FIXME: Add support for scalar truncation where possible.
7313 SDValue S = V.getOperand(Idx);
7314 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7315 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7321 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7323 /// This is particularly important because the set of instructions varies
7324 /// significantly based on whether the operand is a load or not.
7325 static bool isShuffleFoldableLoad(SDValue V) {
7326 while (V.getOpcode() == ISD::BITCAST)
7327 V = V.getOperand(0);
7329 return ISD::isNON_EXTLoad(V.getNode());
7332 /// \brief Try to lower insertion of a single element into a zero vector.
7334 /// This is a common pattern that we have especially efficient patterns to lower
7335 /// across all subtarget feature sets.
7336 static SDValue lowerVectorShuffleAsElementInsertion(
7337 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7338 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7339 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7341 MVT EltVT = VT.getVectorElementType();
7343 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7344 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7346 bool IsV1Zeroable = true;
7347 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7348 if (i != V2Index && !Zeroable[i]) {
7349 IsV1Zeroable = false;
7353 // Check for a single input from a SCALAR_TO_VECTOR node.
7354 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7355 // all the smarts here sunk into that routine. However, the current
7356 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7357 // vector shuffle lowering is dead.
7358 if (SDValue V2S = getScalarValueForVectorElement(
7359 V2, Mask[V2Index] - Mask.size(), DAG)) {
7360 // We need to zext the scalar if it is smaller than an i32.
7361 V2S = DAG.getBitcast(EltVT, V2S);
7362 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7363 // Using zext to expand a narrow element won't work for non-zero
7368 // Zero-extend directly to i32.
7370 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7372 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7373 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7374 EltVT == MVT::i16) {
7375 // Either not inserting from the low element of the input or the input
7376 // element size is too small to use VZEXT_MOVL to clear the high bits.
7380 if (!IsV1Zeroable) {
7381 // If V1 can't be treated as a zero vector we have fewer options to lower
7382 // this. We can't support integer vectors or non-zero targets cheaply, and
7383 // the V1 elements can't be permuted in any way.
7384 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7385 if (!VT.isFloatingPoint() || V2Index != 0)
7387 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7388 V1Mask[V2Index] = -1;
7389 if (!isNoopShuffleMask(V1Mask))
7391 // This is essentially a special case blend operation, but if we have
7392 // general purpose blend operations, they are always faster. Bail and let
7393 // the rest of the lowering handle these as blends.
7394 if (Subtarget->hasSSE41())
7397 // Otherwise, use MOVSD or MOVSS.
7398 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7399 "Only two types of floating point element types to handle!");
7400 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7404 // This lowering only works for the low element with floating point vectors.
7405 if (VT.isFloatingPoint() && V2Index != 0)
7408 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7410 V2 = DAG.getBitcast(VT, V2);
7413 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7414 // the desired position. Otherwise it is more efficient to do a vector
7415 // shift left. We know that we can do a vector shift left because all
7416 // the inputs are zero.
7417 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7418 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7419 V2Shuffle[V2Index] = 0;
7420 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7422 V2 = DAG.getBitcast(MVT::v2i64, V2);
7424 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7425 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7426 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7427 DAG.getDataLayout(), VT)));
7428 V2 = DAG.getBitcast(VT, V2);
7434 /// \brief Try to lower broadcast of a single element.
7436 /// For convenience, this code also bundles all of the subtarget feature set
7437 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7438 /// a convenient way to factor it out.
7439 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7441 const X86Subtarget *Subtarget,
7442 SelectionDAG &DAG) {
7443 if (!Subtarget->hasAVX())
7445 if (VT.isInteger() && !Subtarget->hasAVX2())
7448 // Check that the mask is a broadcast.
7449 int BroadcastIdx = -1;
7451 if (M >= 0 && BroadcastIdx == -1)
7453 else if (M >= 0 && M != BroadcastIdx)
7456 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7457 "a sorted mask where the broadcast "
7460 // Go up the chain of (vector) values to find a scalar load that we can
7461 // combine with the broadcast.
7463 switch (V.getOpcode()) {
7464 case ISD::CONCAT_VECTORS: {
7465 int OperandSize = Mask.size() / V.getNumOperands();
7466 V = V.getOperand(BroadcastIdx / OperandSize);
7467 BroadcastIdx %= OperandSize;
7471 case ISD::INSERT_SUBVECTOR: {
7472 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7473 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7477 int BeginIdx = (int)ConstantIdx->getZExtValue();
7479 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7480 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7481 BroadcastIdx -= BeginIdx;
7492 // Check if this is a broadcast of a scalar. We special case lowering
7493 // for scalars so that we can more effectively fold with loads.
7494 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7495 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7496 V = V.getOperand(BroadcastIdx);
7498 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7499 // Only AVX2 has register broadcasts.
7500 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7502 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7503 // We can't broadcast from a vector register without AVX2, and we can only
7504 // broadcast from the zero-element of a vector register.
7508 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7511 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7512 // INSERTPS when the V1 elements are already in the correct locations
7513 // because otherwise we can just always use two SHUFPS instructions which
7514 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7515 // perform INSERTPS if a single V1 element is out of place and all V2
7516 // elements are zeroable.
7517 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7519 SelectionDAG &DAG) {
7520 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7521 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7522 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7523 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7525 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7528 int V1DstIndex = -1;
7529 int V2DstIndex = -1;
7530 bool V1UsedInPlace = false;
7532 for (int i = 0; i < 4; ++i) {
7533 // Synthesize a zero mask from the zeroable elements (includes undefs).
7539 // Flag if we use any V1 inputs in place.
7541 V1UsedInPlace = true;
7545 // We can only insert a single non-zeroable element.
7546 if (V1DstIndex != -1 || V2DstIndex != -1)
7550 // V1 input out of place for insertion.
7553 // V2 input for insertion.
7558 // Don't bother if we have no (non-zeroable) element for insertion.
7559 if (V1DstIndex == -1 && V2DstIndex == -1)
7562 // Determine element insertion src/dst indices. The src index is from the
7563 // start of the inserted vector, not the start of the concatenated vector.
7564 unsigned V2SrcIndex = 0;
7565 if (V1DstIndex != -1) {
7566 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7567 // and don't use the original V2 at all.
7568 V2SrcIndex = Mask[V1DstIndex];
7569 V2DstIndex = V1DstIndex;
7572 V2SrcIndex = Mask[V2DstIndex] - 4;
7575 // If no V1 inputs are used in place, then the result is created only from
7576 // the zero mask and the V2 insertion - so remove V1 dependency.
7578 V1 = DAG.getUNDEF(MVT::v4f32);
7580 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7581 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7583 // Insert the V2 element into the desired position.
7585 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7586 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7589 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7590 /// UNPCK instruction.
7592 /// This specifically targets cases where we end up with alternating between
7593 /// the two inputs, and so can permute them into something that feeds a single
7594 /// UNPCK instruction. Note that this routine only targets integer vectors
7595 /// because for floating point vectors we have a generalized SHUFPS lowering
7596 /// strategy that handles everything that doesn't *exactly* match an unpack,
7597 /// making this clever lowering unnecessary.
7598 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7599 SDValue V2, ArrayRef<int> Mask,
7600 SelectionDAG &DAG) {
7601 assert(!VT.isFloatingPoint() &&
7602 "This routine only supports integer vectors.");
7603 assert(!isSingleInputShuffleMask(Mask) &&
7604 "This routine should only be used when blending two inputs.");
7605 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7607 int Size = Mask.size();
7609 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7610 return M >= 0 && M % Size < Size / 2;
7612 int NumHiInputs = std::count_if(
7613 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7615 bool UnpackLo = NumLoInputs >= NumHiInputs;
7617 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7618 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7619 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7621 for (int i = 0; i < Size; ++i) {
7625 // Each element of the unpack contains Scale elements from this mask.
7626 int UnpackIdx = i / Scale;
7628 // We only handle the case where V1 feeds the first slots of the unpack.
7629 // We rely on canonicalization to ensure this is the case.
7630 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7633 // Setup the mask for this input. The indexing is tricky as we have to
7634 // handle the unpack stride.
7635 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7636 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7640 // If we will have to shuffle both inputs to use the unpack, check whether
7641 // we can just unpack first and shuffle the result. If so, skip this unpack.
7642 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7643 !isNoopShuffleMask(V2Mask))
7646 // Shuffle the inputs into place.
7647 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7648 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7650 // Cast the inputs to the type we will use to unpack them.
7651 V1 = DAG.getBitcast(UnpackVT, V1);
7652 V2 = DAG.getBitcast(UnpackVT, V2);
7654 // Unpack the inputs and cast the result back to the desired type.
7655 return DAG.getBitcast(
7656 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7660 // We try each unpack from the largest to the smallest to try and find one
7661 // that fits this mask.
7662 int OrigNumElements = VT.getVectorNumElements();
7663 int OrigScalarSize = VT.getScalarSizeInBits();
7664 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7665 int Scale = ScalarSize / OrigScalarSize;
7666 int NumElements = OrigNumElements / Scale;
7667 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7668 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7672 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7674 if (NumLoInputs == 0 || NumHiInputs == 0) {
7675 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7676 "We have to have *some* inputs!");
7677 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7679 // FIXME: We could consider the total complexity of the permute of each
7680 // possible unpacking. Or at the least we should consider how many
7681 // half-crossings are created.
7682 // FIXME: We could consider commuting the unpacks.
7684 SmallVector<int, 32> PermMask;
7685 PermMask.assign(Size, -1);
7686 for (int i = 0; i < Size; ++i) {
7690 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7693 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7695 return DAG.getVectorShuffle(
7696 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7698 DAG.getUNDEF(VT), PermMask);
7704 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7706 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7707 /// support for floating point shuffles but not integer shuffles. These
7708 /// instructions will incur a domain crossing penalty on some chips though so
7709 /// it is better to avoid lowering through this for integer vectors where
7711 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7712 const X86Subtarget *Subtarget,
7713 SelectionDAG &DAG) {
7715 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7716 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7717 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7718 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7719 ArrayRef<int> Mask = SVOp->getMask();
7720 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7722 if (isSingleInputShuffleMask(Mask)) {
7723 // Use low duplicate instructions for masks that match their pattern.
7724 if (Subtarget->hasSSE3())
7725 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7726 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7728 // Straight shuffle of a single input vector. Simulate this by using the
7729 // single input as both of the "inputs" to this instruction..
7730 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7732 if (Subtarget->hasAVX()) {
7733 // If we have AVX, we can use VPERMILPS which will allow folding a load
7734 // into the shuffle.
7735 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7736 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7739 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7740 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7742 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7743 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7745 // If we have a single input, insert that into V1 if we can do so cheaply.
7746 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7747 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7748 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7750 // Try inverting the insertion since for v2 masks it is easy to do and we
7751 // can't reliably sort the mask one way or the other.
7752 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7753 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7754 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7755 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7759 // Try to use one of the special instruction patterns to handle two common
7760 // blend patterns if a zero-blend above didn't work.
7761 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7762 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7763 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7764 // We can either use a special instruction to load over the low double or
7765 // to move just the low double.
7767 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7769 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7771 if (Subtarget->hasSSE41())
7772 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7776 // Use dedicated unpack instructions for masks that match their pattern.
7777 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7778 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7779 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7780 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7782 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7783 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7784 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7787 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7789 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7790 /// the integer unit to minimize domain crossing penalties. However, for blends
7791 /// it falls back to the floating point shuffle operation with appropriate bit
7793 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7794 const X86Subtarget *Subtarget,
7795 SelectionDAG &DAG) {
7797 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7798 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7799 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7800 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7801 ArrayRef<int> Mask = SVOp->getMask();
7802 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7804 if (isSingleInputShuffleMask(Mask)) {
7805 // Check for being able to broadcast a single element.
7806 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7807 Mask, Subtarget, DAG))
7810 // Straight shuffle of a single input vector. For everything from SSE2
7811 // onward this has a single fast instruction with no scary immediates.
7812 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7813 V1 = DAG.getBitcast(MVT::v4i32, V1);
7814 int WidenedMask[4] = {
7815 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7816 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7817 return DAG.getBitcast(
7819 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7820 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7822 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7823 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7824 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7825 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7827 // If we have a blend of two PACKUS operations an the blend aligns with the
7828 // low and half halves, we can just merge the PACKUS operations. This is
7829 // particularly important as it lets us merge shuffles that this routine itself
7831 auto GetPackNode = [](SDValue V) {
7832 while (V.getOpcode() == ISD::BITCAST)
7833 V = V.getOperand(0);
7835 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7837 if (SDValue V1Pack = GetPackNode(V1))
7838 if (SDValue V2Pack = GetPackNode(V2))
7839 return DAG.getBitcast(MVT::v2i64,
7840 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7841 Mask[0] == 0 ? V1Pack.getOperand(0)
7842 : V1Pack.getOperand(1),
7843 Mask[1] == 2 ? V2Pack.getOperand(0)
7844 : V2Pack.getOperand(1)));
7846 // Try to use shift instructions.
7848 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7851 // When loading a scalar and then shuffling it into a vector we can often do
7852 // the insertion cheaply.
7853 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7854 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7856 // Try inverting the insertion since for v2 masks it is easy to do and we
7857 // can't reliably sort the mask one way or the other.
7858 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7859 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7860 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7863 // We have different paths for blend lowering, but they all must use the
7864 // *exact* same predicate.
7865 bool IsBlendSupported = Subtarget->hasSSE41();
7866 if (IsBlendSupported)
7867 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7871 // Use dedicated unpack instructions for masks that match their pattern.
7872 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7873 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7874 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7875 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7877 // Try to use byte rotation instructions.
7878 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7879 if (Subtarget->hasSSSE3())
7880 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7881 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7884 // If we have direct support for blends, we should lower by decomposing into
7885 // a permute. That will be faster than the domain cross.
7886 if (IsBlendSupported)
7887 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7890 // We implement this with SHUFPD which is pretty lame because it will likely
7891 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7892 // However, all the alternatives are still more cycles and newer chips don't
7893 // have this problem. It would be really nice if x86 had better shuffles here.
7894 V1 = DAG.getBitcast(MVT::v2f64, V1);
7895 V2 = DAG.getBitcast(MVT::v2f64, V2);
7896 return DAG.getBitcast(MVT::v2i64,
7897 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7900 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7902 /// This is used to disable more specialized lowerings when the shufps lowering
7903 /// will happen to be efficient.
7904 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7905 // This routine only handles 128-bit shufps.
7906 assert(Mask.size() == 4 && "Unsupported mask size!");
7908 // To lower with a single SHUFPS we need to have the low half and high half
7909 // each requiring a single input.
7910 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7912 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7918 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7920 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7921 /// It makes no assumptions about whether this is the *best* lowering, it simply
7923 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7924 ArrayRef<int> Mask, SDValue V1,
7925 SDValue V2, SelectionDAG &DAG) {
7926 SDValue LowV = V1, HighV = V2;
7927 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7930 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7932 if (NumV2Elements == 1) {
7934 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7937 // Compute the index adjacent to V2Index and in the same half by toggling
7939 int V2AdjIndex = V2Index ^ 1;
7941 if (Mask[V2AdjIndex] == -1) {
7942 // Handles all the cases where we have a single V2 element and an undef.
7943 // This will only ever happen in the high lanes because we commute the
7944 // vector otherwise.
7946 std::swap(LowV, HighV);
7947 NewMask[V2Index] -= 4;
7949 // Handle the case where the V2 element ends up adjacent to a V1 element.
7950 // To make this work, blend them together as the first step.
7951 int V1Index = V2AdjIndex;
7952 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7953 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7954 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7956 // Now proceed to reconstruct the final blend as we have the necessary
7957 // high or low half formed.
7964 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7965 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7967 } else if (NumV2Elements == 2) {
7968 if (Mask[0] < 4 && Mask[1] < 4) {
7969 // Handle the easy case where we have V1 in the low lanes and V2 in the
7973 } else if (Mask[2] < 4 && Mask[3] < 4) {
7974 // We also handle the reversed case because this utility may get called
7975 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7976 // arrange things in the right direction.
7982 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7983 // trying to place elements directly, just blend them and set up the final
7984 // shuffle to place them.
7986 // The first two blend mask elements are for V1, the second two are for
7988 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7989 Mask[2] < 4 ? Mask[2] : Mask[3],
7990 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7991 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7992 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7993 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7995 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7998 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7999 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8000 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8001 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8004 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8005 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8008 /// \brief Lower 4-lane 32-bit floating point shuffles.
8010 /// Uses instructions exclusively from the floating point unit to minimize
8011 /// domain crossing penalties, as these are sufficient to implement all v4f32
8013 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8014 const X86Subtarget *Subtarget,
8015 SelectionDAG &DAG) {
8017 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8018 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8019 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8020 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8021 ArrayRef<int> Mask = SVOp->getMask();
8022 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8025 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8027 if (NumV2Elements == 0) {
8028 // Check for being able to broadcast a single element.
8029 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8030 Mask, Subtarget, DAG))
8033 // Use even/odd duplicate instructions for masks that match their pattern.
8034 if (Subtarget->hasSSE3()) {
8035 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8036 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8037 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8038 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8041 if (Subtarget->hasAVX()) {
8042 // If we have AVX, we can use VPERMILPS which will allow folding a load
8043 // into the shuffle.
8044 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8045 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8048 // Otherwise, use a straight shuffle of a single input vector. We pass the
8049 // input vector to both operands to simulate this with a SHUFPS.
8050 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8051 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8054 // There are special ways we can lower some single-element blends. However, we
8055 // have custom ways we can lower more complex single-element blends below that
8056 // we defer to if both this and BLENDPS fail to match, so restrict this to
8057 // when the V2 input is targeting element 0 of the mask -- that is the fast
8059 if (NumV2Elements == 1 && Mask[0] >= 4)
8060 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8061 Mask, Subtarget, DAG))
8064 if (Subtarget->hasSSE41()) {
8065 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8069 // Use INSERTPS if we can complete the shuffle efficiently.
8070 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8073 if (!isSingleSHUFPSMask(Mask))
8074 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8075 DL, MVT::v4f32, V1, V2, Mask, DAG))
8079 // Use dedicated unpack instructions for masks that match their pattern.
8080 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8081 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8082 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8083 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8084 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8085 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8086 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8087 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8089 // Otherwise fall back to a SHUFPS lowering strategy.
8090 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8093 /// \brief Lower 4-lane i32 vector shuffles.
8095 /// We try to handle these with integer-domain shuffles where we can, but for
8096 /// blends we use the floating point domain blend instructions.
8097 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8098 const X86Subtarget *Subtarget,
8099 SelectionDAG &DAG) {
8101 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8102 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8103 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8104 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8105 ArrayRef<int> Mask = SVOp->getMask();
8106 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8108 // Whenever we can lower this as a zext, that instruction is strictly faster
8109 // than any alternative. It also allows us to fold memory operands into the
8110 // shuffle in many cases.
8111 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8112 Mask, Subtarget, DAG))
8116 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8118 if (NumV2Elements == 0) {
8119 // Check for being able to broadcast a single element.
8120 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8121 Mask, Subtarget, DAG))
8124 // Straight shuffle of a single input vector. For everything from SSE2
8125 // onward this has a single fast instruction with no scary immediates.
8126 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8127 // but we aren't actually going to use the UNPCK instruction because doing
8128 // so prevents folding a load into this instruction or making a copy.
8129 const int UnpackLoMask[] = {0, 0, 1, 1};
8130 const int UnpackHiMask[] = {2, 2, 3, 3};
8131 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8132 Mask = UnpackLoMask;
8133 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8134 Mask = UnpackHiMask;
8136 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8137 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8140 // Try to use shift instructions.
8142 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8145 // There are special ways we can lower some single-element blends.
8146 if (NumV2Elements == 1)
8147 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8148 Mask, Subtarget, DAG))
8151 // We have different paths for blend lowering, but they all must use the
8152 // *exact* same predicate.
8153 bool IsBlendSupported = Subtarget->hasSSE41();
8154 if (IsBlendSupported)
8155 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8159 if (SDValue Masked =
8160 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8163 // Use dedicated unpack instructions for masks that match their pattern.
8164 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8165 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8166 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8167 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8168 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8169 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8170 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8171 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8173 // Try to use byte rotation instructions.
8174 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8175 if (Subtarget->hasSSSE3())
8176 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8177 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8180 // If we have direct support for blends, we should lower by decomposing into
8181 // a permute. That will be faster than the domain cross.
8182 if (IsBlendSupported)
8183 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8186 // Try to lower by permuting the inputs into an unpack instruction.
8187 if (SDValue Unpack =
8188 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8191 // We implement this with SHUFPS because it can blend from two vectors.
8192 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8193 // up the inputs, bypassing domain shift penalties that we would encur if we
8194 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8196 return DAG.getBitcast(
8198 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8199 DAG.getBitcast(MVT::v4f32, V2), Mask));
8202 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8203 /// shuffle lowering, and the most complex part.
8205 /// The lowering strategy is to try to form pairs of input lanes which are
8206 /// targeted at the same half of the final vector, and then use a dword shuffle
8207 /// to place them onto the right half, and finally unpack the paired lanes into
8208 /// their final position.
8210 /// The exact breakdown of how to form these dword pairs and align them on the
8211 /// correct sides is really tricky. See the comments within the function for
8212 /// more of the details.
8214 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8215 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8216 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8217 /// vector, form the analogous 128-bit 8-element Mask.
8218 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8219 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8220 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8221 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8222 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8224 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8225 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8226 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8228 SmallVector<int, 4> LoInputs;
8229 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8230 [](int M) { return M >= 0; });
8231 std::sort(LoInputs.begin(), LoInputs.end());
8232 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8233 SmallVector<int, 4> HiInputs;
8234 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8235 [](int M) { return M >= 0; });
8236 std::sort(HiInputs.begin(), HiInputs.end());
8237 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8239 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8240 int NumHToL = LoInputs.size() - NumLToL;
8242 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8243 int NumHToH = HiInputs.size() - NumLToH;
8244 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8245 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8246 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8247 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8249 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8250 // such inputs we can swap two of the dwords across the half mark and end up
8251 // with <=2 inputs to each half in each half. Once there, we can fall through
8252 // to the generic code below. For example:
8254 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8255 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8257 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8258 // and an existing 2-into-2 on the other half. In this case we may have to
8259 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8260 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8261 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8262 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8263 // half than the one we target for fixing) will be fixed when we re-enter this
8264 // path. We will also combine away any sequence of PSHUFD instructions that
8265 // result into a single instruction. Here is an example of the tricky case:
8267 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8268 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8270 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8272 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8273 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8275 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8276 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8278 // The result is fine to be handled by the generic logic.
8279 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8280 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8281 int AOffset, int BOffset) {
8282 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8283 "Must call this with A having 3 or 1 inputs from the A half.");
8284 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8285 "Must call this with B having 1 or 3 inputs from the B half.");
8286 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8287 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8289 // Compute the index of dword with only one word among the three inputs in
8290 // a half by taking the sum of the half with three inputs and subtracting
8291 // the sum of the actual three inputs. The difference is the remaining
8294 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8295 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8296 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8297 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8298 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8299 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8300 int TripleNonInputIdx =
8301 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8302 TripleDWord = TripleNonInputIdx / 2;
8304 // We use xor with one to compute the adjacent DWord to whichever one the
8306 OneInputDWord = (OneInput / 2) ^ 1;
8308 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8309 // and BToA inputs. If there is also such a problem with the BToB and AToB
8310 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8311 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8312 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8313 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8314 // Compute how many inputs will be flipped by swapping these DWords. We
8316 // to balance this to ensure we don't form a 3-1 shuffle in the other
8318 int NumFlippedAToBInputs =
8319 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8320 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8321 int NumFlippedBToBInputs =
8322 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8323 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8324 if ((NumFlippedAToBInputs == 1 &&
8325 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8326 (NumFlippedBToBInputs == 1 &&
8327 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8328 // We choose whether to fix the A half or B half based on whether that
8329 // half has zero flipped inputs. At zero, we may not be able to fix it
8330 // with that half. We also bias towards fixing the B half because that
8331 // will more commonly be the high half, and we have to bias one way.
8332 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8333 ArrayRef<int> Inputs) {
8334 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8335 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8336 PinnedIdx ^ 1) != Inputs.end();
8337 // Determine whether the free index is in the flipped dword or the
8338 // unflipped dword based on where the pinned index is. We use this bit
8339 // in an xor to conditionally select the adjacent dword.
8340 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8341 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8342 FixFreeIdx) != Inputs.end();
8343 if (IsFixIdxInput == IsFixFreeIdxInput)
8345 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8346 FixFreeIdx) != Inputs.end();
8347 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8348 "We need to be changing the number of flipped inputs!");
8349 int PSHUFHalfMask[] = {0, 1, 2, 3};
8350 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8351 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8353 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8356 if (M != -1 && M == FixIdx)
8358 else if (M != -1 && M == FixFreeIdx)
8361 if (NumFlippedBToBInputs != 0) {
8363 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8364 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8366 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8368 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8369 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8374 int PSHUFDMask[] = {0, 1, 2, 3};
8375 PSHUFDMask[ADWord] = BDWord;
8376 PSHUFDMask[BDWord] = ADWord;
8379 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8380 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8382 // Adjust the mask to match the new locations of A and B.
8384 if (M != -1 && M/2 == ADWord)
8385 M = 2 * BDWord + M % 2;
8386 else if (M != -1 && M/2 == BDWord)
8387 M = 2 * ADWord + M % 2;
8389 // Recurse back into this routine to re-compute state now that this isn't
8390 // a 3 and 1 problem.
8391 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8394 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8395 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8396 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8397 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8399 // At this point there are at most two inputs to the low and high halves from
8400 // each half. That means the inputs can always be grouped into dwords and
8401 // those dwords can then be moved to the correct half with a dword shuffle.
8402 // We use at most one low and one high word shuffle to collect these paired
8403 // inputs into dwords, and finally a dword shuffle to place them.
8404 int PSHUFLMask[4] = {-1, -1, -1, -1};
8405 int PSHUFHMask[4] = {-1, -1, -1, -1};
8406 int PSHUFDMask[4] = {-1, -1, -1, -1};
8408 // First fix the masks for all the inputs that are staying in their
8409 // original halves. This will then dictate the targets of the cross-half
8411 auto fixInPlaceInputs =
8412 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8413 MutableArrayRef<int> SourceHalfMask,
8414 MutableArrayRef<int> HalfMask, int HalfOffset) {
8415 if (InPlaceInputs.empty())
8417 if (InPlaceInputs.size() == 1) {
8418 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8419 InPlaceInputs[0] - HalfOffset;
8420 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8423 if (IncomingInputs.empty()) {
8424 // Just fix all of the in place inputs.
8425 for (int Input : InPlaceInputs) {
8426 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8427 PSHUFDMask[Input / 2] = Input / 2;
8432 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8433 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8434 InPlaceInputs[0] - HalfOffset;
8435 // Put the second input next to the first so that they are packed into
8436 // a dword. We find the adjacent index by toggling the low bit.
8437 int AdjIndex = InPlaceInputs[0] ^ 1;
8438 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8439 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8440 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8442 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8443 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8445 // Now gather the cross-half inputs and place them into a free dword of
8446 // their target half.
8447 // FIXME: This operation could almost certainly be simplified dramatically to
8448 // look more like the 3-1 fixing operation.
8449 auto moveInputsToRightHalf = [&PSHUFDMask](
8450 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8451 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8452 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8454 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8455 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8457 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8459 int LowWord = Word & ~1;
8460 int HighWord = Word | 1;
8461 return isWordClobbered(SourceHalfMask, LowWord) ||
8462 isWordClobbered(SourceHalfMask, HighWord);
8465 if (IncomingInputs.empty())
8468 if (ExistingInputs.empty()) {
8469 // Map any dwords with inputs from them into the right half.
8470 for (int Input : IncomingInputs) {
8471 // If the source half mask maps over the inputs, turn those into
8472 // swaps and use the swapped lane.
8473 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8474 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8475 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8476 Input - SourceOffset;
8477 // We have to swap the uses in our half mask in one sweep.
8478 for (int &M : HalfMask)
8479 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8481 else if (M == Input)
8482 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8484 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8485 Input - SourceOffset &&
8486 "Previous placement doesn't match!");
8488 // Note that this correctly re-maps both when we do a swap and when
8489 // we observe the other side of the swap above. We rely on that to
8490 // avoid swapping the members of the input list directly.
8491 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8494 // Map the input's dword into the correct half.
8495 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8496 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8498 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8500 "Previous placement doesn't match!");
8503 // And just directly shift any other-half mask elements to be same-half
8504 // as we will have mirrored the dword containing the element into the
8505 // same position within that half.
8506 for (int &M : HalfMask)
8507 if (M >= SourceOffset && M < SourceOffset + 4) {
8508 M = M - SourceOffset + DestOffset;
8509 assert(M >= 0 && "This should never wrap below zero!");
8514 // Ensure we have the input in a viable dword of its current half. This
8515 // is particularly tricky because the original position may be clobbered
8516 // by inputs being moved and *staying* in that half.
8517 if (IncomingInputs.size() == 1) {
8518 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8519 int InputFixed = std::find(std::begin(SourceHalfMask),
8520 std::end(SourceHalfMask), -1) -
8521 std::begin(SourceHalfMask) + SourceOffset;
8522 SourceHalfMask[InputFixed - SourceOffset] =
8523 IncomingInputs[0] - SourceOffset;
8524 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8526 IncomingInputs[0] = InputFixed;
8528 } else if (IncomingInputs.size() == 2) {
8529 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8530 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8531 // We have two non-adjacent or clobbered inputs we need to extract from
8532 // the source half. To do this, we need to map them into some adjacent
8533 // dword slot in the source mask.
8534 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8535 IncomingInputs[1] - SourceOffset};
8537 // If there is a free slot in the source half mask adjacent to one of
8538 // the inputs, place the other input in it. We use (Index XOR 1) to
8539 // compute an adjacent index.
8540 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8541 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8542 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8543 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8544 InputsFixed[1] = InputsFixed[0] ^ 1;
8545 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8546 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8547 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8548 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8549 InputsFixed[0] = InputsFixed[1] ^ 1;
8550 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8551 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8552 // The two inputs are in the same DWord but it is clobbered and the
8553 // adjacent DWord isn't used at all. Move both inputs to the free
8555 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8556 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8557 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8558 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8560 // The only way we hit this point is if there is no clobbering
8561 // (because there are no off-half inputs to this half) and there is no
8562 // free slot adjacent to one of the inputs. In this case, we have to
8563 // swap an input with a non-input.
8564 for (int i = 0; i < 4; ++i)
8565 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8566 "We can't handle any clobbers here!");
8567 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8568 "Cannot have adjacent inputs here!");
8570 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8571 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8573 // We also have to update the final source mask in this case because
8574 // it may need to undo the above swap.
8575 for (int &M : FinalSourceHalfMask)
8576 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8577 M = InputsFixed[1] + SourceOffset;
8578 else if (M == InputsFixed[1] + SourceOffset)
8579 M = (InputsFixed[0] ^ 1) + SourceOffset;
8581 InputsFixed[1] = InputsFixed[0] ^ 1;
8584 // Point everything at the fixed inputs.
8585 for (int &M : HalfMask)
8586 if (M == IncomingInputs[0])
8587 M = InputsFixed[0] + SourceOffset;
8588 else if (M == IncomingInputs[1])
8589 M = InputsFixed[1] + SourceOffset;
8591 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8592 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8595 llvm_unreachable("Unhandled input size!");
8598 // Now hoist the DWord down to the right half.
8599 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8600 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8601 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8602 for (int &M : HalfMask)
8603 for (int Input : IncomingInputs)
8605 M = FreeDWord * 2 + Input % 2;
8607 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8608 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8609 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8610 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8612 // Now enact all the shuffles we've computed to move the inputs into their
8614 if (!isNoopShuffleMask(PSHUFLMask))
8615 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8616 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8617 if (!isNoopShuffleMask(PSHUFHMask))
8618 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8619 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8620 if (!isNoopShuffleMask(PSHUFDMask))
8623 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8624 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8626 // At this point, each half should contain all its inputs, and we can then
8627 // just shuffle them into their final position.
8628 assert(std::count_if(LoMask.begin(), LoMask.end(),
8629 [](int M) { return M >= 4; }) == 0 &&
8630 "Failed to lift all the high half inputs to the low mask!");
8631 assert(std::count_if(HiMask.begin(), HiMask.end(),
8632 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8633 "Failed to lift all the low half inputs to the high mask!");
8635 // Do a half shuffle for the low mask.
8636 if (!isNoopShuffleMask(LoMask))
8637 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8638 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8640 // Do a half shuffle with the high mask after shifting its values down.
8641 for (int &M : HiMask)
8644 if (!isNoopShuffleMask(HiMask))
8645 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8646 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8651 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8652 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8653 SDValue V2, ArrayRef<int> Mask,
8654 SelectionDAG &DAG, bool &V1InUse,
8656 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8662 int Size = Mask.size();
8663 int Scale = 16 / Size;
8664 for (int i = 0; i < 16; ++i) {
8665 if (Mask[i / Scale] == -1) {
8666 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8668 const int ZeroMask = 0x80;
8669 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8671 int V2Idx = Mask[i / Scale] < Size
8673 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8674 if (Zeroable[i / Scale])
8675 V1Idx = V2Idx = ZeroMask;
8676 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8677 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8678 V1InUse |= (ZeroMask != V1Idx);
8679 V2InUse |= (ZeroMask != V2Idx);
8684 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8685 DAG.getBitcast(MVT::v16i8, V1),
8686 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8688 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8689 DAG.getBitcast(MVT::v16i8, V2),
8690 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8692 // If we need shuffled inputs from both, blend the two.
8694 if (V1InUse && V2InUse)
8695 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8697 V = V1InUse ? V1 : V2;
8699 // Cast the result back to the correct type.
8700 return DAG.getBitcast(VT, V);
8703 /// \brief Generic lowering of 8-lane i16 shuffles.
8705 /// This handles both single-input shuffles and combined shuffle/blends with
8706 /// two inputs. The single input shuffles are immediately delegated to
8707 /// a dedicated lowering routine.
8709 /// The blends are lowered in one of three fundamental ways. If there are few
8710 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8711 /// of the input is significantly cheaper when lowered as an interleaving of
8712 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8713 /// halves of the inputs separately (making them have relatively few inputs)
8714 /// and then concatenate them.
8715 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8716 const X86Subtarget *Subtarget,
8717 SelectionDAG &DAG) {
8719 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8720 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8721 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8722 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8723 ArrayRef<int> OrigMask = SVOp->getMask();
8724 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8725 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8726 MutableArrayRef<int> Mask(MaskStorage);
8728 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8730 // Whenever we can lower this as a zext, that instruction is strictly faster
8731 // than any alternative.
8732 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8733 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8736 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8738 auto isV2 = [](int M) { return M >= 8; };
8740 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8742 if (NumV2Inputs == 0) {
8743 // Check for being able to broadcast a single element.
8744 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8745 Mask, Subtarget, DAG))
8748 // Try to use shift instructions.
8750 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8753 // Use dedicated unpack instructions for masks that match their pattern.
8754 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8755 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8756 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8757 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8759 // Try to use byte rotation instructions.
8760 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8761 Mask, Subtarget, DAG))
8764 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8768 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8769 "All single-input shuffles should be canonicalized to be V1-input "
8772 // Try to use shift instructions.
8774 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8777 // See if we can use SSE4A Extraction / Insertion.
8778 if (Subtarget->hasSSE4A())
8779 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8782 // There are special ways we can lower some single-element blends.
8783 if (NumV2Inputs == 1)
8784 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8785 Mask, Subtarget, DAG))
8788 // We have different paths for blend lowering, but they all must use the
8789 // *exact* same predicate.
8790 bool IsBlendSupported = Subtarget->hasSSE41();
8791 if (IsBlendSupported)
8792 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8796 if (SDValue Masked =
8797 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8800 // Use dedicated unpack instructions for masks that match their pattern.
8801 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8802 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8803 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8804 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8806 // Try to use byte rotation instructions.
8807 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8808 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8811 if (SDValue BitBlend =
8812 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8815 if (SDValue Unpack =
8816 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8819 // If we can't directly blend but can use PSHUFB, that will be better as it
8820 // can both shuffle and set up the inefficient blend.
8821 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8822 bool V1InUse, V2InUse;
8823 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8827 // We can always bit-blend if we have to so the fallback strategy is to
8828 // decompose into single-input permutes and blends.
8829 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8833 /// \brief Check whether a compaction lowering can be done by dropping even
8834 /// elements and compute how many times even elements must be dropped.
8836 /// This handles shuffles which take every Nth element where N is a power of
8837 /// two. Example shuffle masks:
8839 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8840 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8841 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8842 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8843 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8844 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8846 /// Any of these lanes can of course be undef.
8848 /// This routine only supports N <= 3.
8849 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8852 /// \returns N above, or the number of times even elements must be dropped if
8853 /// there is such a number. Otherwise returns zero.
8854 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8855 // Figure out whether we're looping over two inputs or just one.
8856 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8858 // The modulus for the shuffle vector entries is based on whether this is
8859 // a single input or not.
8860 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8861 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8862 "We should only be called with masks with a power-of-2 size!");
8864 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8866 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8867 // and 2^3 simultaneously. This is because we may have ambiguity with
8868 // partially undef inputs.
8869 bool ViableForN[3] = {true, true, true};
8871 for (int i = 0, e = Mask.size(); i < e; ++i) {
8872 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8877 bool IsAnyViable = false;
8878 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8879 if (ViableForN[j]) {
8882 // The shuffle mask must be equal to (i * 2^N) % M.
8883 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8886 ViableForN[j] = false;
8888 // Early exit if we exhaust the possible powers of two.
8893 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8897 // Return 0 as there is no viable power of two.
8901 /// \brief Generic lowering of v16i8 shuffles.
8903 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8904 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8905 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8906 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8908 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8909 const X86Subtarget *Subtarget,
8910 SelectionDAG &DAG) {
8912 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8913 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8914 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8915 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8916 ArrayRef<int> Mask = SVOp->getMask();
8917 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8919 // Try to use shift instructions.
8921 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8924 // Try to use byte rotation instructions.
8925 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8926 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8929 // Try to use a zext lowering.
8930 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8931 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8934 // See if we can use SSE4A Extraction / Insertion.
8935 if (Subtarget->hasSSE4A())
8936 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8940 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8942 // For single-input shuffles, there are some nicer lowering tricks we can use.
8943 if (NumV2Elements == 0) {
8944 // Check for being able to broadcast a single element.
8945 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8946 Mask, Subtarget, DAG))
8949 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8950 // Notably, this handles splat and partial-splat shuffles more efficiently.
8951 // However, it only makes sense if the pre-duplication shuffle simplifies
8952 // things significantly. Currently, this means we need to be able to
8953 // express the pre-duplication shuffle as an i16 shuffle.
8955 // FIXME: We should check for other patterns which can be widened into an
8956 // i16 shuffle as well.
8957 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8958 for (int i = 0; i < 16; i += 2)
8959 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8964 auto tryToWidenViaDuplication = [&]() -> SDValue {
8965 if (!canWidenViaDuplication(Mask))
8967 SmallVector<int, 4> LoInputs;
8968 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8969 [](int M) { return M >= 0 && M < 8; });
8970 std::sort(LoInputs.begin(), LoInputs.end());
8971 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8973 SmallVector<int, 4> HiInputs;
8974 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8975 [](int M) { return M >= 8; });
8976 std::sort(HiInputs.begin(), HiInputs.end());
8977 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8980 bool TargetLo = LoInputs.size() >= HiInputs.size();
8981 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8982 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8984 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8985 SmallDenseMap<int, int, 8> LaneMap;
8986 for (int I : InPlaceInputs) {
8987 PreDupI16Shuffle[I/2] = I/2;
8990 int j = TargetLo ? 0 : 4, je = j + 4;
8991 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8992 // Check if j is already a shuffle of this input. This happens when
8993 // there are two adjacent bytes after we move the low one.
8994 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8995 // If we haven't yet mapped the input, search for a slot into which
8997 while (j < je && PreDupI16Shuffle[j] != -1)
9001 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9004 // Map this input with the i16 shuffle.
9005 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9008 // Update the lane map based on the mapping we ended up with.
9009 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9011 V1 = DAG.getBitcast(
9013 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9014 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9016 // Unpack the bytes to form the i16s that will be shuffled into place.
9017 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9018 MVT::v16i8, V1, V1);
9020 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9021 for (int i = 0; i < 16; ++i)
9022 if (Mask[i] != -1) {
9023 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9024 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9025 if (PostDupI16Shuffle[i / 2] == -1)
9026 PostDupI16Shuffle[i / 2] = MappedMask;
9028 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9029 "Conflicting entrties in the original shuffle!");
9031 return DAG.getBitcast(
9033 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9034 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9036 if (SDValue V = tryToWidenViaDuplication())
9040 // Use dedicated unpack instructions for masks that match their pattern.
9041 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9042 0, 16, 1, 17, 2, 18, 3, 19,
9044 4, 20, 5, 21, 6, 22, 7, 23}))
9045 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9046 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9047 8, 24, 9, 25, 10, 26, 11, 27,
9049 12, 28, 13, 29, 14, 30, 15, 31}))
9050 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9052 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9053 // with PSHUFB. It is important to do this before we attempt to generate any
9054 // blends but after all of the single-input lowerings. If the single input
9055 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9056 // want to preserve that and we can DAG combine any longer sequences into
9057 // a PSHUFB in the end. But once we start blending from multiple inputs,
9058 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9059 // and there are *very* few patterns that would actually be faster than the
9060 // PSHUFB approach because of its ability to zero lanes.
9062 // FIXME: The only exceptions to the above are blends which are exact
9063 // interleavings with direct instructions supporting them. We currently don't
9064 // handle those well here.
9065 if (Subtarget->hasSSSE3()) {
9066 bool V1InUse = false;
9067 bool V2InUse = false;
9069 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9070 DAG, V1InUse, V2InUse);
9072 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9073 // do so. This avoids using them to handle blends-with-zero which is
9074 // important as a single pshufb is significantly faster for that.
9075 if (V1InUse && V2InUse) {
9076 if (Subtarget->hasSSE41())
9077 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9078 Mask, Subtarget, DAG))
9081 // We can use an unpack to do the blending rather than an or in some
9082 // cases. Even though the or may be (very minorly) more efficient, we
9083 // preference this lowering because there are common cases where part of
9084 // the complexity of the shuffles goes away when we do the final blend as
9086 // FIXME: It might be worth trying to detect if the unpack-feeding
9087 // shuffles will both be pshufb, in which case we shouldn't bother with
9089 if (SDValue Unpack =
9090 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9097 // There are special ways we can lower some single-element blends.
9098 if (NumV2Elements == 1)
9099 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9100 Mask, Subtarget, DAG))
9103 if (SDValue BitBlend =
9104 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9107 // Check whether a compaction lowering can be done. This handles shuffles
9108 // which take every Nth element for some even N. See the helper function for
9111 // We special case these as they can be particularly efficiently handled with
9112 // the PACKUSB instruction on x86 and they show up in common patterns of
9113 // rearranging bytes to truncate wide elements.
9114 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9115 // NumEvenDrops is the power of two stride of the elements. Another way of
9116 // thinking about it is that we need to drop the even elements this many
9117 // times to get the original input.
9118 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9120 // First we need to zero all the dropped bytes.
9121 assert(NumEvenDrops <= 3 &&
9122 "No support for dropping even elements more than 3 times.");
9123 // We use the mask type to pick which bytes are preserved based on how many
9124 // elements are dropped.
9125 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9126 SDValue ByteClearMask = DAG.getBitcast(
9127 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9128 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9130 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9132 // Now pack things back together.
9133 V1 = DAG.getBitcast(MVT::v8i16, V1);
9134 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9135 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9136 for (int i = 1; i < NumEvenDrops; ++i) {
9137 Result = DAG.getBitcast(MVT::v8i16, Result);
9138 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9144 // Handle multi-input cases by blending single-input shuffles.
9145 if (NumV2Elements > 0)
9146 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9149 // The fallback path for single-input shuffles widens this into two v8i16
9150 // vectors with unpacks, shuffles those, and then pulls them back together
9154 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9155 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9156 for (int i = 0; i < 16; ++i)
9158 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9160 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9162 SDValue VLoHalf, VHiHalf;
9163 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9164 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9166 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9167 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9168 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9169 [](int M) { return M >= 0 && M % 2 == 1; })) {
9170 // Use a mask to drop the high bytes.
9171 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9172 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9173 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9175 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9176 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9178 // Squash the masks to point directly into VLoHalf.
9179 for (int &M : LoBlendMask)
9182 for (int &M : HiBlendMask)
9186 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9187 // VHiHalf so that we can blend them as i16s.
9188 VLoHalf = DAG.getBitcast(
9189 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9190 VHiHalf = DAG.getBitcast(
9191 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9194 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9195 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9197 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9200 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9202 /// This routine breaks down the specific type of 128-bit shuffle and
9203 /// dispatches to the lowering routines accordingly.
9204 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9205 MVT VT, const X86Subtarget *Subtarget,
9206 SelectionDAG &DAG) {
9207 switch (VT.SimpleTy) {
9209 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9211 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9213 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9215 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9217 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9219 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9222 llvm_unreachable("Unimplemented!");
9226 /// \brief Helper function to test whether a shuffle mask could be
9227 /// simplified by widening the elements being shuffled.
9229 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9230 /// leaves it in an unspecified state.
9232 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9233 /// shuffle masks. The latter have the special property of a '-2' representing
9234 /// a zero-ed lane of a vector.
9235 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9236 SmallVectorImpl<int> &WidenedMask) {
9237 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9238 // If both elements are undef, its trivial.
9239 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9240 WidenedMask.push_back(SM_SentinelUndef);
9244 // Check for an undef mask and a mask value properly aligned to fit with
9245 // a pair of values. If we find such a case, use the non-undef mask's value.
9246 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9247 WidenedMask.push_back(Mask[i + 1] / 2);
9250 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9251 WidenedMask.push_back(Mask[i] / 2);
9255 // When zeroing, we need to spread the zeroing across both lanes to widen.
9256 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9257 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9258 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9259 WidenedMask.push_back(SM_SentinelZero);
9265 // Finally check if the two mask values are adjacent and aligned with
9267 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9268 WidenedMask.push_back(Mask[i] / 2);
9272 // Otherwise we can't safely widen the elements used in this shuffle.
9275 assert(WidenedMask.size() == Mask.size() / 2 &&
9276 "Incorrect size of mask after widening the elements!");
9281 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9283 /// This routine just extracts two subvectors, shuffles them independently, and
9284 /// then concatenates them back together. This should work effectively with all
9285 /// AVX vector shuffle types.
9286 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9287 SDValue V2, ArrayRef<int> Mask,
9288 SelectionDAG &DAG) {
9289 assert(VT.getSizeInBits() >= 256 &&
9290 "Only for 256-bit or wider vector shuffles!");
9291 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9292 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9294 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9295 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9297 int NumElements = VT.getVectorNumElements();
9298 int SplitNumElements = NumElements / 2;
9299 MVT ScalarVT = VT.getScalarType();
9300 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9302 // Rather than splitting build-vectors, just build two narrower build
9303 // vectors. This helps shuffling with splats and zeros.
9304 auto SplitVector = [&](SDValue V) {
9305 while (V.getOpcode() == ISD::BITCAST)
9306 V = V->getOperand(0);
9308 MVT OrigVT = V.getSimpleValueType();
9309 int OrigNumElements = OrigVT.getVectorNumElements();
9310 int OrigSplitNumElements = OrigNumElements / 2;
9311 MVT OrigScalarVT = OrigVT.getScalarType();
9312 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9316 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9318 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9319 DAG.getIntPtrConstant(0, DL));
9320 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9321 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9324 SmallVector<SDValue, 16> LoOps, HiOps;
9325 for (int i = 0; i < OrigSplitNumElements; ++i) {
9326 LoOps.push_back(BV->getOperand(i));
9327 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9329 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9330 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9332 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9333 DAG.getBitcast(SplitVT, HiV));
9336 SDValue LoV1, HiV1, LoV2, HiV2;
9337 std::tie(LoV1, HiV1) = SplitVector(V1);
9338 std::tie(LoV2, HiV2) = SplitVector(V2);
9340 // Now create two 4-way blends of these half-width vectors.
9341 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9342 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9343 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9344 for (int i = 0; i < SplitNumElements; ++i) {
9345 int M = HalfMask[i];
9346 if (M >= NumElements) {
9347 if (M >= NumElements + SplitNumElements)
9351 V2BlendMask.push_back(M - NumElements);
9352 V1BlendMask.push_back(-1);
9353 BlendMask.push_back(SplitNumElements + i);
9354 } else if (M >= 0) {
9355 if (M >= SplitNumElements)
9359 V2BlendMask.push_back(-1);
9360 V1BlendMask.push_back(M);
9361 BlendMask.push_back(i);
9363 V2BlendMask.push_back(-1);
9364 V1BlendMask.push_back(-1);
9365 BlendMask.push_back(-1);
9369 // Because the lowering happens after all combining takes place, we need to
9370 // manually combine these blend masks as much as possible so that we create
9371 // a minimal number of high-level vector shuffle nodes.
9373 // First try just blending the halves of V1 or V2.
9374 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9375 return DAG.getUNDEF(SplitVT);
9376 if (!UseLoV2 && !UseHiV2)
9377 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9378 if (!UseLoV1 && !UseHiV1)
9379 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9381 SDValue V1Blend, V2Blend;
9382 if (UseLoV1 && UseHiV1) {
9384 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9386 // We only use half of V1 so map the usage down into the final blend mask.
9387 V1Blend = UseLoV1 ? LoV1 : HiV1;
9388 for (int i = 0; i < SplitNumElements; ++i)
9389 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9390 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9392 if (UseLoV2 && UseHiV2) {
9394 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9396 // We only use half of V2 so map the usage down into the final blend mask.
9397 V2Blend = UseLoV2 ? LoV2 : HiV2;
9398 for (int i = 0; i < SplitNumElements; ++i)
9399 if (BlendMask[i] >= SplitNumElements)
9400 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9402 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9404 SDValue Lo = HalfBlend(LoMask);
9405 SDValue Hi = HalfBlend(HiMask);
9406 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9409 /// \brief Either split a vector in halves or decompose the shuffles and the
9412 /// This is provided as a good fallback for many lowerings of non-single-input
9413 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9414 /// between splitting the shuffle into 128-bit components and stitching those
9415 /// back together vs. extracting the single-input shuffles and blending those
9417 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9418 SDValue V2, ArrayRef<int> Mask,
9419 SelectionDAG &DAG) {
9420 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9421 "lower single-input shuffles as it "
9422 "could then recurse on itself.");
9423 int Size = Mask.size();
9425 // If this can be modeled as a broadcast of two elements followed by a blend,
9426 // prefer that lowering. This is especially important because broadcasts can
9427 // often fold with memory operands.
9428 auto DoBothBroadcast = [&] {
9429 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9432 if (V2BroadcastIdx == -1)
9433 V2BroadcastIdx = M - Size;
9434 else if (M - Size != V2BroadcastIdx)
9436 } else if (M >= 0) {
9437 if (V1BroadcastIdx == -1)
9439 else if (M != V1BroadcastIdx)
9444 if (DoBothBroadcast())
9445 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9448 // If the inputs all stem from a single 128-bit lane of each input, then we
9449 // split them rather than blending because the split will decompose to
9450 // unusually few instructions.
9451 int LaneCount = VT.getSizeInBits() / 128;
9452 int LaneSize = Size / LaneCount;
9453 SmallBitVector LaneInputs[2];
9454 LaneInputs[0].resize(LaneCount, false);
9455 LaneInputs[1].resize(LaneCount, false);
9456 for (int i = 0; i < Size; ++i)
9458 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9459 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9460 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9462 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9463 // that the decomposed single-input shuffles don't end up here.
9464 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9467 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9468 /// a permutation and blend of those lanes.
9470 /// This essentially blends the out-of-lane inputs to each lane into the lane
9471 /// from a permuted copy of the vector. This lowering strategy results in four
9472 /// instructions in the worst case for a single-input cross lane shuffle which
9473 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9474 /// of. Special cases for each particular shuffle pattern should be handled
9475 /// prior to trying this lowering.
9476 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9477 SDValue V1, SDValue V2,
9479 SelectionDAG &DAG) {
9480 // FIXME: This should probably be generalized for 512-bit vectors as well.
9481 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9482 int LaneSize = Mask.size() / 2;
9484 // If there are only inputs from one 128-bit lane, splitting will in fact be
9485 // less expensive. The flags track whether the given lane contains an element
9486 // that crosses to another lane.
9487 bool LaneCrossing[2] = {false, false};
9488 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9489 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9490 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9491 if (!LaneCrossing[0] || !LaneCrossing[1])
9492 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9494 if (isSingleInputShuffleMask(Mask)) {
9495 SmallVector<int, 32> FlippedBlendMask;
9496 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9497 FlippedBlendMask.push_back(
9498 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9500 : Mask[i] % LaneSize +
9501 (i / LaneSize) * LaneSize + Size));
9503 // Flip the vector, and blend the results which should now be in-lane. The
9504 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9505 // 5 for the high source. The value 3 selects the high half of source 2 and
9506 // the value 2 selects the low half of source 2. We only use source 2 to
9507 // allow folding it into a memory operand.
9508 unsigned PERMMask = 3 | 2 << 4;
9509 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9510 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9511 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9514 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9515 // will be handled by the above logic and a blend of the results, much like
9516 // other patterns in AVX.
9517 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9520 /// \brief Handle lowering 2-lane 128-bit shuffles.
9521 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9522 SDValue V2, ArrayRef<int> Mask,
9523 const X86Subtarget *Subtarget,
9524 SelectionDAG &DAG) {
9525 // TODO: If minimizing size and one of the inputs is a zero vector and the
9526 // the zero vector has only one use, we could use a VPERM2X128 to save the
9527 // instruction bytes needed to explicitly generate the zero vector.
9529 // Blends are faster and handle all the non-lane-crossing cases.
9530 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9534 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9535 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9537 // If either input operand is a zero vector, use VPERM2X128 because its mask
9538 // allows us to replace the zero input with an implicit zero.
9539 if (!IsV1Zero && !IsV2Zero) {
9540 // Check for patterns which can be matched with a single insert of a 128-bit
9542 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9543 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9544 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9545 VT.getVectorNumElements() / 2);
9546 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9547 DAG.getIntPtrConstant(0, DL));
9548 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9549 OnlyUsesV1 ? V1 : V2,
9550 DAG.getIntPtrConstant(0, DL));
9551 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9555 // Otherwise form a 128-bit permutation. After accounting for undefs,
9556 // convert the 64-bit shuffle mask selection values into 128-bit
9557 // selection bits by dividing the indexes by 2 and shifting into positions
9558 // defined by a vperm2*128 instruction's immediate control byte.
9560 // The immediate permute control byte looks like this:
9561 // [1:0] - select 128 bits from sources for low half of destination
9563 // [3] - zero low half of destination
9564 // [5:4] - select 128 bits from sources for high half of destination
9566 // [7] - zero high half of destination
9568 int MaskLO = Mask[0];
9569 if (MaskLO == SM_SentinelUndef)
9570 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9572 int MaskHI = Mask[2];
9573 if (MaskHI == SM_SentinelUndef)
9574 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9576 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9578 // If either input is a zero vector, replace it with an undef input.
9579 // Shuffle mask values < 4 are selecting elements of V1.
9580 // Shuffle mask values >= 4 are selecting elements of V2.
9581 // Adjust each half of the permute mask by clearing the half that was
9582 // selecting the zero vector and setting the zero mask bit.
9584 V1 = DAG.getUNDEF(VT);
9586 PermMask = (PermMask & 0xf0) | 0x08;
9588 PermMask = (PermMask & 0x0f) | 0x80;
9591 V2 = DAG.getUNDEF(VT);
9593 PermMask = (PermMask & 0xf0) | 0x08;
9595 PermMask = (PermMask & 0x0f) | 0x80;
9598 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9599 DAG.getConstant(PermMask, DL, MVT::i8));
9602 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9603 /// shuffling each lane.
9605 /// This will only succeed when the result of fixing the 128-bit lanes results
9606 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9607 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9608 /// the lane crosses early and then use simpler shuffles within each lane.
9610 /// FIXME: It might be worthwhile at some point to support this without
9611 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9612 /// in x86 only floating point has interesting non-repeating shuffles, and even
9613 /// those are still *marginally* more expensive.
9614 static SDValue lowerVectorShuffleByMerging128BitLanes(
9615 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9616 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9617 assert(!isSingleInputShuffleMask(Mask) &&
9618 "This is only useful with multiple inputs.");
9620 int Size = Mask.size();
9621 int LaneSize = 128 / VT.getScalarSizeInBits();
9622 int NumLanes = Size / LaneSize;
9623 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9625 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9626 // check whether the in-128-bit lane shuffles share a repeating pattern.
9627 SmallVector<int, 4> Lanes;
9628 Lanes.resize(NumLanes, -1);
9629 SmallVector<int, 4> InLaneMask;
9630 InLaneMask.resize(LaneSize, -1);
9631 for (int i = 0; i < Size; ++i) {
9635 int j = i / LaneSize;
9638 // First entry we've seen for this lane.
9639 Lanes[j] = Mask[i] / LaneSize;
9640 } else if (Lanes[j] != Mask[i] / LaneSize) {
9641 // This doesn't match the lane selected previously!
9645 // Check that within each lane we have a consistent shuffle mask.
9646 int k = i % LaneSize;
9647 if (InLaneMask[k] < 0) {
9648 InLaneMask[k] = Mask[i] % LaneSize;
9649 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9650 // This doesn't fit a repeating in-lane mask.
9655 // First shuffle the lanes into place.
9656 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9657 VT.getSizeInBits() / 64);
9658 SmallVector<int, 8> LaneMask;
9659 LaneMask.resize(NumLanes * 2, -1);
9660 for (int i = 0; i < NumLanes; ++i)
9661 if (Lanes[i] >= 0) {
9662 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9663 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9666 V1 = DAG.getBitcast(LaneVT, V1);
9667 V2 = DAG.getBitcast(LaneVT, V2);
9668 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9670 // Cast it back to the type we actually want.
9671 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9673 // Now do a simple shuffle that isn't lane crossing.
9674 SmallVector<int, 8> NewMask;
9675 NewMask.resize(Size, -1);
9676 for (int i = 0; i < Size; ++i)
9678 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9679 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9680 "Must not introduce lane crosses at this point!");
9682 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9685 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9688 /// This returns true if the elements from a particular input are already in the
9689 /// slot required by the given mask and require no permutation.
9690 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9691 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9692 int Size = Mask.size();
9693 for (int i = 0; i < Size; ++i)
9694 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9700 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9701 ArrayRef<int> Mask, SDValue V1,
9702 SDValue V2, SelectionDAG &DAG) {
9704 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9705 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9706 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9707 int NumElts = VT.getVectorNumElements();
9708 bool ShufpdMask = true;
9709 bool CommutableMask = true;
9710 unsigned Immediate = 0;
9711 for (int i = 0; i < NumElts; ++i) {
9714 int Val = (i & 6) + NumElts * (i & 1);
9715 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9716 if (Mask[i] < Val || Mask[i] > Val + 1)
9718 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9719 CommutableMask = false;
9720 Immediate |= (Mask[i] % 2) << i;
9723 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9724 DAG.getConstant(Immediate, DL, MVT::i8));
9726 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9727 DAG.getConstant(Immediate, DL, MVT::i8));
9731 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9733 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9734 /// isn't available.
9735 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9736 const X86Subtarget *Subtarget,
9737 SelectionDAG &DAG) {
9739 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9740 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9741 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9742 ArrayRef<int> Mask = SVOp->getMask();
9743 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9745 SmallVector<int, 4> WidenedMask;
9746 if (canWidenShuffleElements(Mask, WidenedMask))
9747 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9750 if (isSingleInputShuffleMask(Mask)) {
9751 // Check for being able to broadcast a single element.
9752 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9753 Mask, Subtarget, DAG))
9756 // Use low duplicate instructions for masks that match their pattern.
9757 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9758 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9760 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9761 // Non-half-crossing single input shuffles can be lowerid with an
9762 // interleaved permutation.
9763 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9764 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9765 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9766 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9769 // With AVX2 we have direct support for this permutation.
9770 if (Subtarget->hasAVX2())
9771 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9772 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9774 // Otherwise, fall back.
9775 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9779 // X86 has dedicated unpack instructions that can handle specific blend
9780 // operations: UNPCKH and UNPCKL.
9781 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9782 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9783 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9784 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9785 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9786 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9787 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9788 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9790 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9794 // Check if the blend happens to exactly fit that of SHUFPD.
9796 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9799 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9800 // shuffle. However, if we have AVX2 and either inputs are already in place,
9801 // we will be able to shuffle even across lanes the other input in a single
9802 // instruction so skip this pattern.
9803 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9804 isShuffleMaskInputInPlace(1, Mask))))
9805 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9806 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9809 // If we have AVX2 then we always want to lower with a blend because an v4 we
9810 // can fully permute the elements.
9811 if (Subtarget->hasAVX2())
9812 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9815 // Otherwise fall back on generic lowering.
9816 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9819 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9821 /// This routine is only called when we have AVX2 and thus a reasonable
9822 /// instruction set for v4i64 shuffling..
9823 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9824 const X86Subtarget *Subtarget,
9825 SelectionDAG &DAG) {
9827 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9828 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9829 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9830 ArrayRef<int> Mask = SVOp->getMask();
9831 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9832 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9834 SmallVector<int, 4> WidenedMask;
9835 if (canWidenShuffleElements(Mask, WidenedMask))
9836 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9839 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9843 // Check for being able to broadcast a single element.
9844 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9845 Mask, Subtarget, DAG))
9848 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9849 // use lower latency instructions that will operate on both 128-bit lanes.
9850 SmallVector<int, 2> RepeatedMask;
9851 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9852 if (isSingleInputShuffleMask(Mask)) {
9853 int PSHUFDMask[] = {-1, -1, -1, -1};
9854 for (int i = 0; i < 2; ++i)
9855 if (RepeatedMask[i] >= 0) {
9856 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9857 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9859 return DAG.getBitcast(
9861 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9862 DAG.getBitcast(MVT::v8i32, V1),
9863 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9867 // AVX2 provides a direct instruction for permuting a single input across
9869 if (isSingleInputShuffleMask(Mask))
9870 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9871 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9873 // Try to use shift instructions.
9875 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9878 // Use dedicated unpack instructions for masks that match their pattern.
9879 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9880 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9881 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9882 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9883 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9884 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9885 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9886 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9888 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9889 // shuffle. However, if we have AVX2 and either inputs are already in place,
9890 // we will be able to shuffle even across lanes the other input in a single
9891 // instruction so skip this pattern.
9892 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9893 isShuffleMaskInputInPlace(1, Mask))))
9894 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9895 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9898 // Otherwise fall back on generic blend lowering.
9899 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9903 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9905 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9906 /// isn't available.
9907 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9908 const X86Subtarget *Subtarget,
9909 SelectionDAG &DAG) {
9911 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9912 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9913 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9914 ArrayRef<int> Mask = SVOp->getMask();
9915 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9917 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9921 // Check for being able to broadcast a single element.
9922 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9923 Mask, Subtarget, DAG))
9926 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9927 // options to efficiently lower the shuffle.
9928 SmallVector<int, 4> RepeatedMask;
9929 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9930 assert(RepeatedMask.size() == 4 &&
9931 "Repeated masks must be half the mask width!");
9933 // Use even/odd duplicate instructions for masks that match their pattern.
9934 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9935 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9936 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9937 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9939 if (isSingleInputShuffleMask(Mask))
9940 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9941 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9943 // Use dedicated unpack instructions for masks that match their pattern.
9944 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9945 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9946 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9947 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9948 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9949 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9950 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9951 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9953 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9954 // have already handled any direct blends. We also need to squash the
9955 // repeated mask into a simulated v4f32 mask.
9956 for (int i = 0; i < 4; ++i)
9957 if (RepeatedMask[i] >= 8)
9958 RepeatedMask[i] -= 4;
9959 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9962 // If we have a single input shuffle with different shuffle patterns in the
9963 // two 128-bit lanes use the variable mask to VPERMILPS.
9964 if (isSingleInputShuffleMask(Mask)) {
9965 SDValue VPermMask[8];
9966 for (int i = 0; i < 8; ++i)
9967 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9968 : DAG.getConstant(Mask[i], DL, MVT::i32);
9969 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9971 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9972 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9974 if (Subtarget->hasAVX2())
9976 X86ISD::VPERMV, DL, MVT::v8f32,
9977 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9978 MVT::v8i32, VPermMask)),
9981 // Otherwise, fall back.
9982 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9986 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9988 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9989 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9992 // If we have AVX2 then we always want to lower with a blend because at v8 we
9993 // can fully permute the elements.
9994 if (Subtarget->hasAVX2())
9995 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9998 // Otherwise fall back on generic lowering.
9999 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10002 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10004 /// This routine is only called when we have AVX2 and thus a reasonable
10005 /// instruction set for v8i32 shuffling..
10006 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10007 const X86Subtarget *Subtarget,
10008 SelectionDAG &DAG) {
10010 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10011 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10012 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10013 ArrayRef<int> Mask = SVOp->getMask();
10014 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10015 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10017 // Whenever we can lower this as a zext, that instruction is strictly faster
10018 // than any alternative. It also allows us to fold memory operands into the
10019 // shuffle in many cases.
10020 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10021 Mask, Subtarget, DAG))
10024 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10028 // Check for being able to broadcast a single element.
10029 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10030 Mask, Subtarget, DAG))
10033 // If the shuffle mask is repeated in each 128-bit lane we can use more
10034 // efficient instructions that mirror the shuffles across the two 128-bit
10036 SmallVector<int, 4> RepeatedMask;
10037 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10038 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10039 if (isSingleInputShuffleMask(Mask))
10040 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10041 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10043 // Use dedicated unpack instructions for masks that match their pattern.
10044 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10045 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10046 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10047 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10048 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10049 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10050 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10051 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10054 // Try to use shift instructions.
10055 if (SDValue Shift =
10056 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10059 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10060 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10063 // If the shuffle patterns aren't repeated but it is a single input, directly
10064 // generate a cross-lane VPERMD instruction.
10065 if (isSingleInputShuffleMask(Mask)) {
10066 SDValue VPermMask[8];
10067 for (int i = 0; i < 8; ++i)
10068 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10069 : DAG.getConstant(Mask[i], DL, MVT::i32);
10070 return DAG.getNode(
10071 X86ISD::VPERMV, DL, MVT::v8i32,
10072 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10075 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10077 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10078 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10081 // Otherwise fall back on generic blend lowering.
10082 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10086 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10088 /// This routine is only called when we have AVX2 and thus a reasonable
10089 /// instruction set for v16i16 shuffling..
10090 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10091 const X86Subtarget *Subtarget,
10092 SelectionDAG &DAG) {
10094 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10095 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10096 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10097 ArrayRef<int> Mask = SVOp->getMask();
10098 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10099 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10101 // Whenever we can lower this as a zext, that instruction is strictly faster
10102 // than any alternative. It also allows us to fold memory operands into the
10103 // shuffle in many cases.
10104 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10105 Mask, Subtarget, DAG))
10108 // Check for being able to broadcast a single element.
10109 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10110 Mask, Subtarget, DAG))
10113 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10117 // Use dedicated unpack instructions for masks that match their pattern.
10118 if (isShuffleEquivalent(V1, V2, Mask,
10119 {// First 128-bit lane:
10120 0, 16, 1, 17, 2, 18, 3, 19,
10121 // Second 128-bit lane:
10122 8, 24, 9, 25, 10, 26, 11, 27}))
10123 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10124 if (isShuffleEquivalent(V1, V2, Mask,
10125 {// First 128-bit lane:
10126 4, 20, 5, 21, 6, 22, 7, 23,
10127 // Second 128-bit lane:
10128 12, 28, 13, 29, 14, 30, 15, 31}))
10129 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10131 // Try to use shift instructions.
10132 if (SDValue Shift =
10133 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10136 // Try to use byte rotation instructions.
10137 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10138 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10141 if (isSingleInputShuffleMask(Mask)) {
10142 // There are no generalized cross-lane shuffle operations available on i16
10144 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10145 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10148 SmallVector<int, 8> RepeatedMask;
10149 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10150 // As this is a single-input shuffle, the repeated mask should be
10151 // a strictly valid v8i16 mask that we can pass through to the v8i16
10152 // lowering to handle even the v16 case.
10153 return lowerV8I16GeneralSingleInputVectorShuffle(
10154 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10157 SDValue PSHUFBMask[32];
10158 for (int i = 0; i < 16; ++i) {
10159 if (Mask[i] == -1) {
10160 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10164 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10165 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10166 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10167 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10169 return DAG.getBitcast(MVT::v16i16,
10170 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10171 DAG.getBitcast(MVT::v32i8, V1),
10172 DAG.getNode(ISD::BUILD_VECTOR, DL,
10173 MVT::v32i8, PSHUFBMask)));
10176 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10178 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10179 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10182 // Otherwise fall back on generic lowering.
10183 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10186 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10188 /// This routine is only called when we have AVX2 and thus a reasonable
10189 /// instruction set for v32i8 shuffling..
10190 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10191 const X86Subtarget *Subtarget,
10192 SelectionDAG &DAG) {
10194 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10195 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10196 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10197 ArrayRef<int> Mask = SVOp->getMask();
10198 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10199 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10201 // Whenever we can lower this as a zext, that instruction is strictly faster
10202 // than any alternative. It also allows us to fold memory operands into the
10203 // shuffle in many cases.
10204 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10205 Mask, Subtarget, DAG))
10208 // Check for being able to broadcast a single element.
10209 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10210 Mask, Subtarget, DAG))
10213 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10217 // Use dedicated unpack instructions for masks that match their pattern.
10218 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10220 if (isShuffleEquivalent(
10222 {// First 128-bit lane:
10223 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10224 // Second 128-bit lane:
10225 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10226 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10227 if (isShuffleEquivalent(
10229 {// First 128-bit lane:
10230 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10231 // Second 128-bit lane:
10232 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10233 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10235 // Try to use shift instructions.
10236 if (SDValue Shift =
10237 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10240 // Try to use byte rotation instructions.
10241 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10242 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10245 if (isSingleInputShuffleMask(Mask)) {
10246 // There are no generalized cross-lane shuffle operations available on i8
10248 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10249 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10252 SDValue PSHUFBMask[32];
10253 for (int i = 0; i < 32; ++i)
10256 ? DAG.getUNDEF(MVT::i8)
10257 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10260 return DAG.getNode(
10261 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10262 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10265 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10267 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10268 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10271 // Otherwise fall back on generic lowering.
10272 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10275 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10277 /// This routine either breaks down the specific type of a 256-bit x86 vector
10278 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10279 /// together based on the available instructions.
10280 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10281 MVT VT, const X86Subtarget *Subtarget,
10282 SelectionDAG &DAG) {
10284 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10285 ArrayRef<int> Mask = SVOp->getMask();
10287 // If we have a single input to the zero element, insert that into V1 if we
10288 // can do so cheaply.
10289 int NumElts = VT.getVectorNumElements();
10290 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10291 return M >= NumElts;
10294 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10295 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10296 DL, VT, V1, V2, Mask, Subtarget, DAG))
10299 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10300 // check for those subtargets here and avoid much of the subtarget querying in
10301 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10302 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10303 // floating point types there eventually, just immediately cast everything to
10304 // a float and operate entirely in that domain.
10305 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10306 int ElementBits = VT.getScalarSizeInBits();
10307 if (ElementBits < 32)
10308 // No floating point type available, decompose into 128-bit vectors.
10309 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10311 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10312 VT.getVectorNumElements());
10313 V1 = DAG.getBitcast(FpVT, V1);
10314 V2 = DAG.getBitcast(FpVT, V2);
10315 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10318 switch (VT.SimpleTy) {
10320 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10322 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10324 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10326 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10328 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10330 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10333 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10337 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10338 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10339 const X86Subtarget *Subtarget,
10340 SelectionDAG &DAG) {
10342 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10343 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10344 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10345 ArrayRef<int> Mask = SVOp->getMask();
10346 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10348 // X86 has dedicated unpack instructions that can handle specific blend
10349 // operations: UNPCKH and UNPCKL.
10350 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10351 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10352 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10353 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10355 // FIXME: Implement direct support for this type!
10356 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10359 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10360 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10361 const X86Subtarget *Subtarget,
10362 SelectionDAG &DAG) {
10364 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10365 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10366 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10367 ArrayRef<int> Mask = SVOp->getMask();
10368 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10370 // Use dedicated unpack instructions for masks that match their pattern.
10371 if (isShuffleEquivalent(V1, V2, Mask,
10372 {// First 128-bit lane.
10373 0, 16, 1, 17, 4, 20, 5, 21,
10374 // Second 128-bit lane.
10375 8, 24, 9, 25, 12, 28, 13, 29}))
10376 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10377 if (isShuffleEquivalent(V1, V2, Mask,
10378 {// First 128-bit lane.
10379 2, 18, 3, 19, 6, 22, 7, 23,
10380 // Second 128-bit lane.
10381 10, 26, 11, 27, 14, 30, 15, 31}))
10382 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10384 // FIXME: Implement direct support for this type!
10385 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10388 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10389 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10390 const X86Subtarget *Subtarget,
10391 SelectionDAG &DAG) {
10393 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10394 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10395 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10396 ArrayRef<int> Mask = SVOp->getMask();
10397 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10399 // X86 has dedicated unpack instructions that can handle specific blend
10400 // operations: UNPCKH and UNPCKL.
10401 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10402 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10403 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10404 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10406 // FIXME: Implement direct support for this type!
10407 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10410 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10411 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10412 const X86Subtarget *Subtarget,
10413 SelectionDAG &DAG) {
10415 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10416 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10417 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10418 ArrayRef<int> Mask = SVOp->getMask();
10419 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10421 // Use dedicated unpack instructions for masks that match their pattern.
10422 if (isShuffleEquivalent(V1, V2, Mask,
10423 {// First 128-bit lane.
10424 0, 16, 1, 17, 4, 20, 5, 21,
10425 // Second 128-bit lane.
10426 8, 24, 9, 25, 12, 28, 13, 29}))
10427 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10428 if (isShuffleEquivalent(V1, V2, Mask,
10429 {// First 128-bit lane.
10430 2, 18, 3, 19, 6, 22, 7, 23,
10431 // Second 128-bit lane.
10432 10, 26, 11, 27, 14, 30, 15, 31}))
10433 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10435 // FIXME: Implement direct support for this type!
10436 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10439 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10440 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10441 const X86Subtarget *Subtarget,
10442 SelectionDAG &DAG) {
10444 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10445 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10446 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10447 ArrayRef<int> Mask = SVOp->getMask();
10448 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10449 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10451 // FIXME: Implement direct support for this type!
10452 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10455 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10456 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10457 const X86Subtarget *Subtarget,
10458 SelectionDAG &DAG) {
10460 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10461 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10462 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10463 ArrayRef<int> Mask = SVOp->getMask();
10464 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10465 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10467 // FIXME: Implement direct support for this type!
10468 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10471 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10473 /// This routine either breaks down the specific type of a 512-bit x86 vector
10474 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10475 /// together based on the available instructions.
10476 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10477 MVT VT, const X86Subtarget *Subtarget,
10478 SelectionDAG &DAG) {
10480 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10481 ArrayRef<int> Mask = SVOp->getMask();
10482 assert(Subtarget->hasAVX512() &&
10483 "Cannot lower 512-bit vectors w/ basic ISA!");
10485 // Check for being able to broadcast a single element.
10486 if (SDValue Broadcast =
10487 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10490 // Dispatch to each element type for lowering. If we don't have supprot for
10491 // specific element type shuffles at 512 bits, immediately split them and
10492 // lower them. Each lowering routine of a given type is allowed to assume that
10493 // the requisite ISA extensions for that element type are available.
10494 switch (VT.SimpleTy) {
10496 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10498 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10500 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10502 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10504 if (Subtarget->hasBWI())
10505 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10508 if (Subtarget->hasBWI())
10509 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10513 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10516 // Otherwise fall back on splitting.
10517 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10520 /// \brief Top-level lowering for x86 vector shuffles.
10522 /// This handles decomposition, canonicalization, and lowering of all x86
10523 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10524 /// above in helper routines. The canonicalization attempts to widen shuffles
10525 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10526 /// s.t. only one of the two inputs needs to be tested, etc.
10527 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10528 SelectionDAG &DAG) {
10529 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10530 ArrayRef<int> Mask = SVOp->getMask();
10531 SDValue V1 = Op.getOperand(0);
10532 SDValue V2 = Op.getOperand(1);
10533 MVT VT = Op.getSimpleValueType();
10534 int NumElements = VT.getVectorNumElements();
10537 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10539 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10540 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10541 if (V1IsUndef && V2IsUndef)
10542 return DAG.getUNDEF(VT);
10544 // When we create a shuffle node we put the UNDEF node to second operand,
10545 // but in some cases the first operand may be transformed to UNDEF.
10546 // In this case we should just commute the node.
10548 return DAG.getCommutedVectorShuffle(*SVOp);
10550 // Check for non-undef masks pointing at an undef vector and make the masks
10551 // undef as well. This makes it easier to match the shuffle based solely on
10555 if (M >= NumElements) {
10556 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10557 for (int &M : NewMask)
10558 if (M >= NumElements)
10560 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10563 // We actually see shuffles that are entirely re-arrangements of a set of
10564 // zero inputs. This mostly happens while decomposing complex shuffles into
10565 // simple ones. Directly lower these as a buildvector of zeros.
10566 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10567 if (Zeroable.all())
10568 return getZeroVector(VT, Subtarget, DAG, dl);
10570 // Try to collapse shuffles into using a vector type with fewer elements but
10571 // wider element types. We cap this to not form integers or floating point
10572 // elements wider than 64 bits, but it might be interesting to form i128
10573 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10574 SmallVector<int, 16> WidenedMask;
10575 if (VT.getScalarSizeInBits() < 64 &&
10576 canWidenShuffleElements(Mask, WidenedMask)) {
10577 MVT NewEltVT = VT.isFloatingPoint()
10578 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10579 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10580 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10581 // Make sure that the new vector type is legal. For example, v2f64 isn't
10583 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10584 V1 = DAG.getBitcast(NewVT, V1);
10585 V2 = DAG.getBitcast(NewVT, V2);
10586 return DAG.getBitcast(
10587 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10591 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10592 for (int M : SVOp->getMask())
10594 ++NumUndefElements;
10595 else if (M < NumElements)
10600 // Commute the shuffle as needed such that more elements come from V1 than
10601 // V2. This allows us to match the shuffle pattern strictly on how many
10602 // elements come from V1 without handling the symmetric cases.
10603 if (NumV2Elements > NumV1Elements)
10604 return DAG.getCommutedVectorShuffle(*SVOp);
10606 // When the number of V1 and V2 elements are the same, try to minimize the
10607 // number of uses of V2 in the low half of the vector. When that is tied,
10608 // ensure that the sum of indices for V1 is equal to or lower than the sum
10609 // indices for V2. When those are equal, try to ensure that the number of odd
10610 // indices for V1 is lower than the number of odd indices for V2.
10611 if (NumV1Elements == NumV2Elements) {
10612 int LowV1Elements = 0, LowV2Elements = 0;
10613 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10614 if (M >= NumElements)
10618 if (LowV2Elements > LowV1Elements) {
10619 return DAG.getCommutedVectorShuffle(*SVOp);
10620 } else if (LowV2Elements == LowV1Elements) {
10621 int SumV1Indices = 0, SumV2Indices = 0;
10622 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10623 if (SVOp->getMask()[i] >= NumElements)
10625 else if (SVOp->getMask()[i] >= 0)
10627 if (SumV2Indices < SumV1Indices) {
10628 return DAG.getCommutedVectorShuffle(*SVOp);
10629 } else if (SumV2Indices == SumV1Indices) {
10630 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10631 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10632 if (SVOp->getMask()[i] >= NumElements)
10633 NumV2OddIndices += i % 2;
10634 else if (SVOp->getMask()[i] >= 0)
10635 NumV1OddIndices += i % 2;
10636 if (NumV2OddIndices < NumV1OddIndices)
10637 return DAG.getCommutedVectorShuffle(*SVOp);
10642 // For each vector width, delegate to a specialized lowering routine.
10643 if (VT.getSizeInBits() == 128)
10644 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10646 if (VT.getSizeInBits() == 256)
10647 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10649 // Force AVX-512 vectors to be scalarized for now.
10650 // FIXME: Implement AVX-512 support!
10651 if (VT.getSizeInBits() == 512)
10652 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10654 llvm_unreachable("Unimplemented!");
10657 // This function assumes its argument is a BUILD_VECTOR of constants or
10658 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10660 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10661 unsigned &MaskValue) {
10663 unsigned NumElems = BuildVector->getNumOperands();
10664 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10665 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10666 unsigned NumElemsInLane = NumElems / NumLanes;
10668 // Blend for v16i16 should be symetric for the both lanes.
10669 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10670 SDValue EltCond = BuildVector->getOperand(i);
10671 SDValue SndLaneEltCond =
10672 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10674 int Lane1Cond = -1, Lane2Cond = -1;
10675 if (isa<ConstantSDNode>(EltCond))
10676 Lane1Cond = !isZero(EltCond);
10677 if (isa<ConstantSDNode>(SndLaneEltCond))
10678 Lane2Cond = !isZero(SndLaneEltCond);
10680 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10681 // Lane1Cond != 0, means we want the first argument.
10682 // Lane1Cond == 0, means we want the second argument.
10683 // The encoding of this argument is 0 for the first argument, 1
10684 // for the second. Therefore, invert the condition.
10685 MaskValue |= !Lane1Cond << i;
10686 else if (Lane1Cond < 0)
10687 MaskValue |= !Lane2Cond << i;
10694 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10695 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10696 const X86Subtarget *Subtarget,
10697 SelectionDAG &DAG) {
10698 SDValue Cond = Op.getOperand(0);
10699 SDValue LHS = Op.getOperand(1);
10700 SDValue RHS = Op.getOperand(2);
10702 MVT VT = Op.getSimpleValueType();
10704 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10706 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10708 // Only non-legal VSELECTs reach this lowering, convert those into generic
10709 // shuffles and re-use the shuffle lowering path for blends.
10710 SmallVector<int, 32> Mask;
10711 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10712 SDValue CondElt = CondBV->getOperand(i);
10714 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10716 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10719 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10720 // A vselect where all conditions and data are constants can be optimized into
10721 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10722 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10723 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10724 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10727 // Try to lower this to a blend-style vector shuffle. This can handle all
10728 // constant condition cases.
10729 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10732 // Variable blends are only legal from SSE4.1 onward.
10733 if (!Subtarget->hasSSE41())
10736 // Only some types will be legal on some subtargets. If we can emit a legal
10737 // VSELECT-matching blend, return Op, and but if we need to expand, return
10739 switch (Op.getSimpleValueType().SimpleTy) {
10741 // Most of the vector types have blends past SSE4.1.
10745 // The byte blends for AVX vectors were introduced only in AVX2.
10746 if (Subtarget->hasAVX2())
10753 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10754 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10757 // FIXME: We should custom lower this by fixing the condition and using i8
10763 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10764 MVT VT = Op.getSimpleValueType();
10767 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10770 if (VT.getSizeInBits() == 8) {
10771 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10772 Op.getOperand(0), Op.getOperand(1));
10773 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10774 DAG.getValueType(VT));
10775 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10778 if (VT.getSizeInBits() == 16) {
10779 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10780 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10782 return DAG.getNode(
10783 ISD::TRUNCATE, dl, MVT::i16,
10784 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10785 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10786 Op.getOperand(1)));
10787 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10788 Op.getOperand(0), Op.getOperand(1));
10789 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10790 DAG.getValueType(VT));
10791 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10794 if (VT == MVT::f32) {
10795 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10796 // the result back to FR32 register. It's only worth matching if the
10797 // result has a single use which is a store or a bitcast to i32. And in
10798 // the case of a store, it's not worth it if the index is a constant 0,
10799 // because a MOVSSmr can be used instead, which is smaller and faster.
10800 if (!Op.hasOneUse())
10802 SDNode *User = *Op.getNode()->use_begin();
10803 if ((User->getOpcode() != ISD::STORE ||
10804 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10805 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10806 (User->getOpcode() != ISD::BITCAST ||
10807 User->getValueType(0) != MVT::i32))
10809 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10810 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10812 return DAG.getBitcast(MVT::f32, Extract);
10815 if (VT == MVT::i32 || VT == MVT::i64) {
10816 // ExtractPS/pextrq works with constant index.
10817 if (isa<ConstantSDNode>(Op.getOperand(1)))
10823 /// Extract one bit from mask vector, like v16i1 or v8i1.
10824 /// AVX-512 feature.
10826 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10827 SDValue Vec = Op.getOperand(0);
10829 MVT VecVT = Vec.getSimpleValueType();
10830 SDValue Idx = Op.getOperand(1);
10831 MVT EltVT = Op.getSimpleValueType();
10833 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10834 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10835 "Unexpected vector type in ExtractBitFromMaskVector");
10837 // variable index can't be handled in mask registers,
10838 // extend vector to VR512
10839 if (!isa<ConstantSDNode>(Idx)) {
10840 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10841 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10842 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10843 ExtVT.getVectorElementType(), Ext, Idx);
10844 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10847 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10848 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10849 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10850 rc = getRegClassFor(MVT::v16i1);
10851 unsigned MaxSift = rc->getSize()*8 - 1;
10852 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10853 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10854 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10855 DAG.getConstant(MaxSift, dl, MVT::i8));
10856 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10857 DAG.getIntPtrConstant(0, dl));
10861 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10862 SelectionDAG &DAG) const {
10864 SDValue Vec = Op.getOperand(0);
10865 MVT VecVT = Vec.getSimpleValueType();
10866 SDValue Idx = Op.getOperand(1);
10868 if (Op.getSimpleValueType() == MVT::i1)
10869 return ExtractBitFromMaskVector(Op, DAG);
10871 if (!isa<ConstantSDNode>(Idx)) {
10872 if (VecVT.is512BitVector() ||
10873 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10874 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10877 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10878 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10879 MaskEltVT.getSizeInBits());
10881 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10882 auto PtrVT = getPointerTy(DAG.getDataLayout());
10883 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10884 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10885 DAG.getConstant(0, dl, PtrVT));
10886 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10887 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10888 DAG.getConstant(0, dl, PtrVT));
10893 // If this is a 256-bit vector result, first extract the 128-bit vector and
10894 // then extract the element from the 128-bit vector.
10895 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10897 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10898 // Get the 128-bit vector.
10899 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10900 MVT EltVT = VecVT.getVectorElementType();
10902 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10904 //if (IdxVal >= NumElems/2)
10905 // IdxVal -= NumElems/2;
10906 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10907 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10908 DAG.getConstant(IdxVal, dl, MVT::i32));
10911 assert(VecVT.is128BitVector() && "Unexpected vector length");
10913 if (Subtarget->hasSSE41())
10914 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10917 MVT VT = Op.getSimpleValueType();
10918 // TODO: handle v16i8.
10919 if (VT.getSizeInBits() == 16) {
10920 SDValue Vec = Op.getOperand(0);
10921 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10923 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10924 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10925 DAG.getBitcast(MVT::v4i32, Vec),
10926 Op.getOperand(1)));
10927 // Transform it so it match pextrw which produces a 32-bit result.
10928 MVT EltVT = MVT::i32;
10929 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10930 Op.getOperand(0), Op.getOperand(1));
10931 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10932 DAG.getValueType(VT));
10933 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10936 if (VT.getSizeInBits() == 32) {
10937 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10941 // SHUFPS the element to the lowest double word, then movss.
10942 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10943 MVT VVT = Op.getOperand(0).getSimpleValueType();
10944 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10945 DAG.getUNDEF(VVT), Mask);
10946 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10947 DAG.getIntPtrConstant(0, dl));
10950 if (VT.getSizeInBits() == 64) {
10951 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10952 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10953 // to match extract_elt for f64.
10954 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10958 // UNPCKHPD the element to the lowest double word, then movsd.
10959 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10960 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10961 int Mask[2] = { 1, -1 };
10962 MVT VVT = Op.getOperand(0).getSimpleValueType();
10963 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10964 DAG.getUNDEF(VVT), Mask);
10965 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10966 DAG.getIntPtrConstant(0, dl));
10972 /// Insert one bit to mask vector, like v16i1 or v8i1.
10973 /// AVX-512 feature.
10975 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10977 SDValue Vec = Op.getOperand(0);
10978 SDValue Elt = Op.getOperand(1);
10979 SDValue Idx = Op.getOperand(2);
10980 MVT VecVT = Vec.getSimpleValueType();
10982 if (!isa<ConstantSDNode>(Idx)) {
10983 // Non constant index. Extend source and destination,
10984 // insert element and then truncate the result.
10985 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10986 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10987 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10988 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10989 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10990 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10993 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10994 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10996 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10997 DAG.getConstant(IdxVal, dl, MVT::i8));
10998 if (Vec.getOpcode() == ISD::UNDEF)
11000 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11003 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11004 SelectionDAG &DAG) const {
11005 MVT VT = Op.getSimpleValueType();
11006 MVT EltVT = VT.getVectorElementType();
11008 if (EltVT == MVT::i1)
11009 return InsertBitToMaskVector(Op, DAG);
11012 SDValue N0 = Op.getOperand(0);
11013 SDValue N1 = Op.getOperand(1);
11014 SDValue N2 = Op.getOperand(2);
11015 if (!isa<ConstantSDNode>(N2))
11017 auto *N2C = cast<ConstantSDNode>(N2);
11018 unsigned IdxVal = N2C->getZExtValue();
11020 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11021 // into that, and then insert the subvector back into the result.
11022 if (VT.is256BitVector() || VT.is512BitVector()) {
11023 // With a 256-bit vector, we can insert into the zero element efficiently
11024 // using a blend if we have AVX or AVX2 and the right data type.
11025 if (VT.is256BitVector() && IdxVal == 0) {
11026 // TODO: It is worthwhile to cast integer to floating point and back
11027 // and incur a domain crossing penalty if that's what we'll end up
11028 // doing anyway after extracting to a 128-bit vector.
11029 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11030 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11031 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11032 N2 = DAG.getIntPtrConstant(1, dl);
11033 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11037 // Get the desired 128-bit vector chunk.
11038 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11040 // Insert the element into the desired chunk.
11041 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11042 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11044 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11045 DAG.getConstant(IdxIn128, dl, MVT::i32));
11047 // Insert the changed part back into the bigger vector
11048 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11050 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11052 if (Subtarget->hasSSE41()) {
11053 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11055 if (VT == MVT::v8i16) {
11056 Opc = X86ISD::PINSRW;
11058 assert(VT == MVT::v16i8);
11059 Opc = X86ISD::PINSRB;
11062 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11064 if (N1.getValueType() != MVT::i32)
11065 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11066 if (N2.getValueType() != MVT::i32)
11067 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11068 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11071 if (EltVT == MVT::f32) {
11072 // Bits [7:6] of the constant are the source select. This will always be
11073 // zero here. The DAG Combiner may combine an extract_elt index into
11074 // these bits. For example (insert (extract, 3), 2) could be matched by
11075 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11076 // Bits [5:4] of the constant are the destination select. This is the
11077 // value of the incoming immediate.
11078 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11079 // combine either bitwise AND or insert of float 0.0 to set these bits.
11081 const Function *F = DAG.getMachineFunction().getFunction();
11082 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11083 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11084 // If this is an insertion of 32-bits into the low 32-bits of
11085 // a vector, we prefer to generate a blend with immediate rather
11086 // than an insertps. Blends are simpler operations in hardware and so
11087 // will always have equal or better performance than insertps.
11088 // But if optimizing for size and there's a load folding opportunity,
11089 // generate insertps because blendps does not have a 32-bit memory
11091 N2 = DAG.getIntPtrConstant(1, dl);
11092 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11093 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11095 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11096 // Create this as a scalar to vector..
11097 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11098 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11101 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11102 // PINSR* works with constant index.
11107 if (EltVT == MVT::i8)
11110 if (EltVT.getSizeInBits() == 16) {
11111 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11112 // as its second argument.
11113 if (N1.getValueType() != MVT::i32)
11114 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11115 if (N2.getValueType() != MVT::i32)
11116 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11117 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11122 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11124 MVT OpVT = Op.getSimpleValueType();
11126 // If this is a 256-bit vector result, first insert into a 128-bit
11127 // vector and then insert into the 256-bit vector.
11128 if (!OpVT.is128BitVector()) {
11129 // Insert into a 128-bit vector.
11130 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11131 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11132 OpVT.getVectorNumElements() / SizeFactor);
11134 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11136 // Insert the 128-bit vector.
11137 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11140 if (OpVT == MVT::v1i64 &&
11141 Op.getOperand(0).getValueType() == MVT::i64)
11142 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11144 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11145 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11146 return DAG.getBitcast(
11147 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11150 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11151 // a simple subregister reference or explicit instructions to grab
11152 // upper bits of a vector.
11153 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11154 SelectionDAG &DAG) {
11156 SDValue In = Op.getOperand(0);
11157 SDValue Idx = Op.getOperand(1);
11158 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11159 MVT ResVT = Op.getSimpleValueType();
11160 MVT InVT = In.getSimpleValueType();
11162 if (Subtarget->hasFp256()) {
11163 if (ResVT.is128BitVector() &&
11164 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11165 isa<ConstantSDNode>(Idx)) {
11166 return Extract128BitVector(In, IdxVal, DAG, dl);
11168 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11169 isa<ConstantSDNode>(Idx)) {
11170 return Extract256BitVector(In, IdxVal, DAG, dl);
11176 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11177 // simple superregister reference or explicit instructions to insert
11178 // the upper bits of a vector.
11179 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11180 SelectionDAG &DAG) {
11181 if (!Subtarget->hasAVX())
11185 SDValue Vec = Op.getOperand(0);
11186 SDValue SubVec = Op.getOperand(1);
11187 SDValue Idx = Op.getOperand(2);
11189 if (!isa<ConstantSDNode>(Idx))
11192 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11193 MVT OpVT = Op.getSimpleValueType();
11194 MVT SubVecVT = SubVec.getSimpleValueType();
11196 // Fold two 16-byte subvector loads into one 32-byte load:
11197 // (insert_subvector (insert_subvector undef, (load addr), 0),
11198 // (load addr + 16), Elts/2)
11200 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11201 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11202 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11203 !Subtarget->isUnalignedMem32Slow()) {
11204 SDValue SubVec2 = Vec.getOperand(1);
11205 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11206 if (Idx2->getZExtValue() == 0) {
11207 SDValue Ops[] = { SubVec2, SubVec };
11208 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11214 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11215 SubVecVT.is128BitVector())
11216 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11218 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11219 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11221 if (OpVT.getVectorElementType() == MVT::i1) {
11222 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11224 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11225 SDValue Undef = DAG.getUNDEF(OpVT);
11226 unsigned NumElems = OpVT.getVectorNumElements();
11227 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11229 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11230 // Zero upper bits of the Vec
11231 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11232 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11234 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11236 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11237 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11240 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11242 // Zero upper bits of the Vec2
11243 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11244 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11245 // Zero lower bits of the Vec
11246 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11247 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11248 // Merge them together
11249 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11255 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11256 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11257 // one of the above mentioned nodes. It has to be wrapped because otherwise
11258 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11259 // be used to form addressing mode. These wrapped nodes will be selected
11262 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11263 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11265 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11266 // global base reg.
11267 unsigned char OpFlag = 0;
11268 unsigned WrapperKind = X86ISD::Wrapper;
11269 CodeModel::Model M = DAG.getTarget().getCodeModel();
11271 if (Subtarget->isPICStyleRIPRel() &&
11272 (M == CodeModel::Small || M == CodeModel::Kernel))
11273 WrapperKind = X86ISD::WrapperRIP;
11274 else if (Subtarget->isPICStyleGOT())
11275 OpFlag = X86II::MO_GOTOFF;
11276 else if (Subtarget->isPICStyleStubPIC())
11277 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11279 auto PtrVT = getPointerTy(DAG.getDataLayout());
11280 SDValue Result = DAG.getTargetConstantPool(
11281 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11283 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11284 // With PIC, the address is actually $g + Offset.
11287 DAG.getNode(ISD::ADD, DL, PtrVT,
11288 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11294 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11295 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11297 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11298 // global base reg.
11299 unsigned char OpFlag = 0;
11300 unsigned WrapperKind = X86ISD::Wrapper;
11301 CodeModel::Model M = DAG.getTarget().getCodeModel();
11303 if (Subtarget->isPICStyleRIPRel() &&
11304 (M == CodeModel::Small || M == CodeModel::Kernel))
11305 WrapperKind = X86ISD::WrapperRIP;
11306 else if (Subtarget->isPICStyleGOT())
11307 OpFlag = X86II::MO_GOTOFF;
11308 else if (Subtarget->isPICStyleStubPIC())
11309 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11311 auto PtrVT = getPointerTy(DAG.getDataLayout());
11312 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11314 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11316 // With PIC, the address is actually $g + Offset.
11319 DAG.getNode(ISD::ADD, DL, PtrVT,
11320 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11326 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11327 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11329 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11330 // global base reg.
11331 unsigned char OpFlag = 0;
11332 unsigned WrapperKind = X86ISD::Wrapper;
11333 CodeModel::Model M = DAG.getTarget().getCodeModel();
11335 if (Subtarget->isPICStyleRIPRel() &&
11336 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11337 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11338 OpFlag = X86II::MO_GOTPCREL;
11339 WrapperKind = X86ISD::WrapperRIP;
11340 } else if (Subtarget->isPICStyleGOT()) {
11341 OpFlag = X86II::MO_GOT;
11342 } else if (Subtarget->isPICStyleStubPIC()) {
11343 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11344 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11345 OpFlag = X86II::MO_DARWIN_NONLAZY;
11348 auto PtrVT = getPointerTy(DAG.getDataLayout());
11349 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11352 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11354 // With PIC, the address is actually $g + Offset.
11355 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11356 !Subtarget->is64Bit()) {
11358 DAG.getNode(ISD::ADD, DL, PtrVT,
11359 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11362 // For symbols that require a load from a stub to get the address, emit the
11364 if (isGlobalStubReference(OpFlag))
11365 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11366 MachinePointerInfo::getGOT(), false, false, false, 0);
11372 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11373 // Create the TargetBlockAddressAddress node.
11374 unsigned char OpFlags =
11375 Subtarget->ClassifyBlockAddressReference();
11376 CodeModel::Model M = DAG.getTarget().getCodeModel();
11377 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11378 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11380 auto PtrVT = getPointerTy(DAG.getDataLayout());
11381 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11383 if (Subtarget->isPICStyleRIPRel() &&
11384 (M == CodeModel::Small || M == CodeModel::Kernel))
11385 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11387 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11389 // With PIC, the address is actually $g + Offset.
11390 if (isGlobalRelativeToPICBase(OpFlags)) {
11391 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11392 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11399 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11400 int64_t Offset, SelectionDAG &DAG) const {
11401 // Create the TargetGlobalAddress node, folding in the constant
11402 // offset if it is legal.
11403 unsigned char OpFlags =
11404 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11405 CodeModel::Model M = DAG.getTarget().getCodeModel();
11406 auto PtrVT = getPointerTy(DAG.getDataLayout());
11408 if (OpFlags == X86II::MO_NO_FLAG &&
11409 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11410 // A direct static reference to a global.
11411 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11414 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11417 if (Subtarget->isPICStyleRIPRel() &&
11418 (M == CodeModel::Small || M == CodeModel::Kernel))
11419 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11421 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11423 // With PIC, the address is actually $g + Offset.
11424 if (isGlobalRelativeToPICBase(OpFlags)) {
11425 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11426 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11429 // For globals that require a load from a stub to get the address, emit the
11431 if (isGlobalStubReference(OpFlags))
11432 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11433 MachinePointerInfo::getGOT(), false, false, false, 0);
11435 // If there was a non-zero offset that we didn't fold, create an explicit
11436 // addition for it.
11438 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11439 DAG.getConstant(Offset, dl, PtrVT));
11445 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11446 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11447 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11448 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11452 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11453 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11454 unsigned char OperandFlags, bool LocalDynamic = false) {
11455 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11456 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11458 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11459 GA->getValueType(0),
11463 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11467 SDValue Ops[] = { Chain, TGA, *InFlag };
11468 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11470 SDValue Ops[] = { Chain, TGA };
11471 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11474 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11475 MFI->setAdjustsStack(true);
11476 MFI->setHasCalls(true);
11478 SDValue Flag = Chain.getValue(1);
11479 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11482 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11484 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11487 SDLoc dl(GA); // ? function entry point might be better
11488 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11489 DAG.getNode(X86ISD::GlobalBaseReg,
11490 SDLoc(), PtrVT), InFlag);
11491 InFlag = Chain.getValue(1);
11493 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11496 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11498 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11500 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11501 X86::RAX, X86II::MO_TLSGD);
11504 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11510 // Get the start address of the TLS block for this module.
11511 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11512 .getInfo<X86MachineFunctionInfo>();
11513 MFI->incNumLocalDynamicTLSAccesses();
11517 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11518 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11521 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11522 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11523 InFlag = Chain.getValue(1);
11524 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11525 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11528 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11532 unsigned char OperandFlags = X86II::MO_DTPOFF;
11533 unsigned WrapperKind = X86ISD::Wrapper;
11534 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11535 GA->getValueType(0),
11536 GA->getOffset(), OperandFlags);
11537 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11539 // Add x@dtpoff with the base.
11540 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11543 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11544 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11545 const EVT PtrVT, TLSModel::Model model,
11546 bool is64Bit, bool isPIC) {
11549 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11550 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11551 is64Bit ? 257 : 256));
11553 SDValue ThreadPointer =
11554 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11555 MachinePointerInfo(Ptr), false, false, false, 0);
11557 unsigned char OperandFlags = 0;
11558 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11560 unsigned WrapperKind = X86ISD::Wrapper;
11561 if (model == TLSModel::LocalExec) {
11562 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11563 } else if (model == TLSModel::InitialExec) {
11565 OperandFlags = X86II::MO_GOTTPOFF;
11566 WrapperKind = X86ISD::WrapperRIP;
11568 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11571 llvm_unreachable("Unexpected model");
11574 // emit "addl x@ntpoff,%eax" (local exec)
11575 // or "addl x@indntpoff,%eax" (initial exec)
11576 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11578 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11579 GA->getOffset(), OperandFlags);
11580 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11582 if (model == TLSModel::InitialExec) {
11583 if (isPIC && !is64Bit) {
11584 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11585 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11589 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11590 MachinePointerInfo::getGOT(), false, false, false, 0);
11593 // The address of the thread local variable is the add of the thread
11594 // pointer with the offset of the variable.
11595 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11599 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11601 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11602 const GlobalValue *GV = GA->getGlobal();
11603 auto PtrVT = getPointerTy(DAG.getDataLayout());
11605 if (Subtarget->isTargetELF()) {
11606 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11608 case TLSModel::GeneralDynamic:
11609 if (Subtarget->is64Bit())
11610 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11611 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11612 case TLSModel::LocalDynamic:
11613 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11614 Subtarget->is64Bit());
11615 case TLSModel::InitialExec:
11616 case TLSModel::LocalExec:
11617 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11618 DAG.getTarget().getRelocationModel() ==
11621 llvm_unreachable("Unknown TLS model.");
11624 if (Subtarget->isTargetDarwin()) {
11625 // Darwin only has one model of TLS. Lower to that.
11626 unsigned char OpFlag = 0;
11627 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11628 X86ISD::WrapperRIP : X86ISD::Wrapper;
11630 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11631 // global base reg.
11632 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11633 !Subtarget->is64Bit();
11635 OpFlag = X86II::MO_TLVP_PIC_BASE;
11637 OpFlag = X86II::MO_TLVP;
11639 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11640 GA->getValueType(0),
11641 GA->getOffset(), OpFlag);
11642 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11644 // With PIC32, the address is actually $g + Offset.
11646 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11647 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11650 // Lowering the machine isd will make sure everything is in the right
11652 SDValue Chain = DAG.getEntryNode();
11653 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11654 SDValue Args[] = { Chain, Offset };
11655 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11657 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11658 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11659 MFI->setAdjustsStack(true);
11661 // And our return value (tls address) is in the standard call return value
11663 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11664 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11667 if (Subtarget->isTargetKnownWindowsMSVC() ||
11668 Subtarget->isTargetWindowsGNU()) {
11669 // Just use the implicit TLS architecture
11670 // Need to generate someting similar to:
11671 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11673 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11674 // mov rcx, qword [rdx+rcx*8]
11675 // mov eax, .tls$:tlsvar
11676 // [rax+rcx] contains the address
11677 // Windows 64bit: gs:0x58
11678 // Windows 32bit: fs:__tls_array
11681 SDValue Chain = DAG.getEntryNode();
11683 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11684 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11685 // use its literal value of 0x2C.
11686 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11687 ? Type::getInt8PtrTy(*DAG.getContext(),
11689 : Type::getInt32PtrTy(*DAG.getContext(),
11692 SDValue TlsArray = Subtarget->is64Bit()
11693 ? DAG.getIntPtrConstant(0x58, dl)
11694 : (Subtarget->isTargetWindowsGNU()
11695 ? DAG.getIntPtrConstant(0x2C, dl)
11696 : DAG.getExternalSymbol("_tls_array", PtrVT));
11698 SDValue ThreadPointer =
11699 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11703 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11704 res = ThreadPointer;
11706 // Load the _tls_index variable
11707 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11708 if (Subtarget->is64Bit())
11709 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11710 MachinePointerInfo(), MVT::i32, false, false,
11713 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11716 auto &DL = DAG.getDataLayout();
11718 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11719 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11721 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11724 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11727 // Get the offset of start of .tls section
11728 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11729 GA->getValueType(0),
11730 GA->getOffset(), X86II::MO_SECREL);
11731 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11733 // The address of the thread local variable is the add of the thread
11734 // pointer with the offset of the variable.
11735 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11738 llvm_unreachable("TLS not implemented for this target.");
11741 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11742 /// and take a 2 x i32 value to shift plus a shift amount.
11743 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11744 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11745 MVT VT = Op.getSimpleValueType();
11746 unsigned VTBits = VT.getSizeInBits();
11748 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11749 SDValue ShOpLo = Op.getOperand(0);
11750 SDValue ShOpHi = Op.getOperand(1);
11751 SDValue ShAmt = Op.getOperand(2);
11752 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11753 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11755 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11756 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11757 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11758 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11759 : DAG.getConstant(0, dl, VT);
11761 SDValue Tmp2, Tmp3;
11762 if (Op.getOpcode() == ISD::SHL_PARTS) {
11763 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11764 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11766 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11767 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11770 // If the shift amount is larger or equal than the width of a part we can't
11771 // rely on the results of shld/shrd. Insert a test and select the appropriate
11772 // values for large shift amounts.
11773 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11774 DAG.getConstant(VTBits, dl, MVT::i8));
11775 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11776 AndNode, DAG.getConstant(0, dl, MVT::i8));
11779 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11780 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11781 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11783 if (Op.getOpcode() == ISD::SHL_PARTS) {
11784 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11785 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11787 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11788 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11791 SDValue Ops[2] = { Lo, Hi };
11792 return DAG.getMergeValues(Ops, dl);
11795 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11796 SelectionDAG &DAG) const {
11797 SDValue Src = Op.getOperand(0);
11798 MVT SrcVT = Src.getSimpleValueType();
11799 MVT VT = Op.getSimpleValueType();
11802 if (SrcVT.isVector()) {
11803 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11804 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11805 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11806 DAG.getUNDEF(SrcVT)));
11808 if (SrcVT.getVectorElementType() == MVT::i1) {
11809 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11810 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11811 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11816 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11817 "Unknown SINT_TO_FP to lower!");
11819 // These are really Legal; return the operand so the caller accepts it as
11821 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11823 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11824 Subtarget->is64Bit()) {
11828 unsigned Size = SrcVT.getSizeInBits()/8;
11829 MachineFunction &MF = DAG.getMachineFunction();
11830 auto PtrVT = getPointerTy(MF.getDataLayout());
11831 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11832 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11833 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11835 MachinePointerInfo::getFixedStack(SSFI),
11837 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11840 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11842 SelectionDAG &DAG) const {
11846 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11848 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11850 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11852 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11854 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11855 MachineMemOperand *MMO;
11857 int SSFI = FI->getIndex();
11859 DAG.getMachineFunction()
11860 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11861 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11863 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11864 StackSlot = StackSlot.getOperand(1);
11866 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11867 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11869 Tys, Ops, SrcVT, MMO);
11872 Chain = Result.getValue(1);
11873 SDValue InFlag = Result.getValue(2);
11875 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11876 // shouldn't be necessary except that RFP cannot be live across
11877 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11878 MachineFunction &MF = DAG.getMachineFunction();
11879 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11880 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11881 auto PtrVT = getPointerTy(MF.getDataLayout());
11882 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11883 Tys = DAG.getVTList(MVT::Other);
11885 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11887 MachineMemOperand *MMO =
11888 DAG.getMachineFunction()
11889 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11890 MachineMemOperand::MOStore, SSFISize, SSFISize);
11892 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11893 Ops, Op.getValueType(), MMO);
11894 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11895 MachinePointerInfo::getFixedStack(SSFI),
11896 false, false, false, 0);
11902 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11903 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11904 SelectionDAG &DAG) const {
11905 // This algorithm is not obvious. Here it is what we're trying to output:
11908 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11909 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11911 haddpd %xmm0, %xmm0
11913 pshufd $0x4e, %xmm0, %xmm1
11919 LLVMContext *Context = DAG.getContext();
11921 // Build some magic constants.
11922 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11923 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11924 auto PtrVT = getPointerTy(DAG.getDataLayout());
11925 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11927 SmallVector<Constant*,2> CV1;
11929 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11930 APInt(64, 0x4330000000000000ULL))));
11932 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11933 APInt(64, 0x4530000000000000ULL))));
11934 Constant *C1 = ConstantVector::get(CV1);
11935 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11937 // Load the 64-bit value into an XMM register.
11938 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11940 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11941 MachinePointerInfo::getConstantPool(),
11942 false, false, false, 16);
11944 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11946 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11947 MachinePointerInfo::getConstantPool(),
11948 false, false, false, 16);
11949 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11950 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11953 if (Subtarget->hasSSE3()) {
11954 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11955 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11957 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11958 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11960 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11961 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11964 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11965 DAG.getIntPtrConstant(0, dl));
11968 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11969 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11970 SelectionDAG &DAG) const {
11972 // FP constant to bias correct the final result.
11973 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11976 // Load the 32-bit value into an XMM register.
11977 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11980 // Zero out the upper parts of the register.
11981 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11983 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11984 DAG.getBitcast(MVT::v2f64, Load),
11985 DAG.getIntPtrConstant(0, dl));
11987 // Or the load with the bias.
11988 SDValue Or = DAG.getNode(
11989 ISD::OR, dl, MVT::v2i64,
11990 DAG.getBitcast(MVT::v2i64,
11991 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11992 DAG.getBitcast(MVT::v2i64,
11993 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11995 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11996 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11998 // Subtract the bias.
11999 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12001 // Handle final rounding.
12002 EVT DestVT = Op.getValueType();
12004 if (DestVT.bitsLT(MVT::f64))
12005 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12006 DAG.getIntPtrConstant(0, dl));
12007 if (DestVT.bitsGT(MVT::f64))
12008 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12010 // Handle final rounding.
12014 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12015 const X86Subtarget &Subtarget) {
12016 // The algorithm is the following:
12017 // #ifdef __SSE4_1__
12018 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12019 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12020 // (uint4) 0x53000000, 0xaa);
12022 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12023 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12025 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12026 // return (float4) lo + fhi;
12029 SDValue V = Op->getOperand(0);
12030 EVT VecIntVT = V.getValueType();
12031 bool Is128 = VecIntVT == MVT::v4i32;
12032 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12033 // If we convert to something else than the supported type, e.g., to v4f64,
12035 if (VecFloatVT != Op->getValueType(0))
12038 unsigned NumElts = VecIntVT.getVectorNumElements();
12039 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12040 "Unsupported custom type");
12041 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12043 // In the #idef/#else code, we have in common:
12044 // - The vector of constants:
12050 // Create the splat vector for 0x4b000000.
12051 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12052 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12053 CstLow, CstLow, CstLow, CstLow};
12054 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12055 makeArrayRef(&CstLowArray[0], NumElts));
12056 // Create the splat vector for 0x53000000.
12057 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12058 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12059 CstHigh, CstHigh, CstHigh, CstHigh};
12060 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12061 makeArrayRef(&CstHighArray[0], NumElts));
12063 // Create the right shift.
12064 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12065 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12066 CstShift, CstShift, CstShift, CstShift};
12067 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12068 makeArrayRef(&CstShiftArray[0], NumElts));
12069 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12072 if (Subtarget.hasSSE41()) {
12073 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12074 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12075 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12076 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12077 // Low will be bitcasted right away, so do not bother bitcasting back to its
12079 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12080 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12081 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12082 // (uint4) 0x53000000, 0xaa);
12083 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12084 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12085 // High will be bitcasted right away, so do not bother bitcasting back to
12086 // its original type.
12087 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12088 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12090 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12091 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12092 CstMask, CstMask, CstMask);
12093 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12094 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12095 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12097 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12098 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12101 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12102 SDValue CstFAdd = DAG.getConstantFP(
12103 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12104 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12105 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12106 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12107 makeArrayRef(&CstFAddArray[0], NumElts));
12109 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12110 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12112 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12113 // return (float4) lo + fhi;
12114 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12115 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12118 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12119 SelectionDAG &DAG) const {
12120 SDValue N0 = Op.getOperand(0);
12121 MVT SVT = N0.getSimpleValueType();
12124 switch (SVT.SimpleTy) {
12126 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12131 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12132 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12133 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12137 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12140 if (Subtarget->hasAVX512())
12141 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12142 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12144 llvm_unreachable(nullptr);
12147 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12148 SelectionDAG &DAG) const {
12149 SDValue N0 = Op.getOperand(0);
12151 auto PtrVT = getPointerTy(DAG.getDataLayout());
12153 if (Op.getValueType().isVector())
12154 return lowerUINT_TO_FP_vec(Op, DAG);
12156 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12157 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12158 // the optimization here.
12159 if (DAG.SignBitIsZero(N0))
12160 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12162 MVT SrcVT = N0.getSimpleValueType();
12163 MVT DstVT = Op.getSimpleValueType();
12164 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12165 return LowerUINT_TO_FP_i64(Op, DAG);
12166 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12167 return LowerUINT_TO_FP_i32(Op, DAG);
12168 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12171 // Make a 64-bit buffer, and use it to build an FILD.
12172 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12173 if (SrcVT == MVT::i32) {
12174 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12175 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12176 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12177 StackSlot, MachinePointerInfo(),
12179 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12180 OffsetSlot, MachinePointerInfo(),
12182 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12186 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12187 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12188 StackSlot, MachinePointerInfo(),
12190 // For i64 source, we need to add the appropriate power of 2 if the input
12191 // was negative. This is the same as the optimization in
12192 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12193 // we must be careful to do the computation in x87 extended precision, not
12194 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12195 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12196 MachineMemOperand *MMO =
12197 DAG.getMachineFunction()
12198 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12199 MachineMemOperand::MOLoad, 8, 8);
12201 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12202 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12203 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12206 APInt FF(32, 0x5F800000ULL);
12208 // Check whether the sign bit is set.
12209 SDValue SignSet = DAG.getSetCC(
12210 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12211 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12213 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12214 SDValue FudgePtr = DAG.getConstantPool(
12215 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12217 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12218 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12219 SDValue Four = DAG.getIntPtrConstant(4, dl);
12220 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12222 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12224 // Load the value out, extending it from f32 to f80.
12225 // FIXME: Avoid the extend by constructing the right constant pool?
12226 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12227 FudgePtr, MachinePointerInfo::getConstantPool(),
12228 MVT::f32, false, false, false, 4);
12229 // Extend everything to 80 bits to force it to be done on x87.
12230 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12231 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12232 DAG.getIntPtrConstant(0, dl));
12235 std::pair<SDValue,SDValue>
12236 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12237 bool IsSigned, bool IsReplace) const {
12240 EVT DstTy = Op.getValueType();
12241 auto PtrVT = getPointerTy(DAG.getDataLayout());
12243 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12244 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12248 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12249 DstTy.getSimpleVT() >= MVT::i16 &&
12250 "Unknown FP_TO_INT to lower!");
12252 // These are really Legal.
12253 if (DstTy == MVT::i32 &&
12254 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12255 return std::make_pair(SDValue(), SDValue());
12256 if (Subtarget->is64Bit() &&
12257 DstTy == MVT::i64 &&
12258 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12259 return std::make_pair(SDValue(), SDValue());
12261 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12262 // stack slot, or into the FTOL runtime function.
12263 MachineFunction &MF = DAG.getMachineFunction();
12264 unsigned MemSize = DstTy.getSizeInBits()/8;
12265 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12266 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12269 if (!IsSigned && isIntegerTypeFTOL(DstTy))
12270 Opc = X86ISD::WIN_FTOL;
12272 switch (DstTy.getSimpleVT().SimpleTy) {
12273 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12274 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12275 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12276 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12279 SDValue Chain = DAG.getEntryNode();
12280 SDValue Value = Op.getOperand(0);
12281 EVT TheVT = Op.getOperand(0).getValueType();
12282 // FIXME This causes a redundant load/store if the SSE-class value is already
12283 // in memory, such as if it is on the callstack.
12284 if (isScalarFPTypeInSSEReg(TheVT)) {
12285 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12286 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12287 MachinePointerInfo::getFixedStack(SSFI),
12289 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12291 Chain, StackSlot, DAG.getValueType(TheVT)
12294 MachineMemOperand *MMO =
12295 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12296 MachineMemOperand::MOLoad, MemSize, MemSize);
12297 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12298 Chain = Value.getValue(1);
12299 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12300 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12303 MachineMemOperand *MMO =
12304 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12305 MachineMemOperand::MOStore, MemSize, MemSize);
12307 if (Opc != X86ISD::WIN_FTOL) {
12308 // Build the FP_TO_INT*_IN_MEM
12309 SDValue Ops[] = { Chain, Value, StackSlot };
12310 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12312 return std::make_pair(FIST, StackSlot);
12314 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12315 DAG.getVTList(MVT::Other, MVT::Glue),
12317 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12318 MVT::i32, ftol.getValue(1));
12319 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12320 MVT::i32, eax.getValue(2));
12321 SDValue Ops[] = { eax, edx };
12322 SDValue pair = IsReplace
12323 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12324 : DAG.getMergeValues(Ops, DL);
12325 return std::make_pair(pair, SDValue());
12329 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12330 const X86Subtarget *Subtarget) {
12331 MVT VT = Op->getSimpleValueType(0);
12332 SDValue In = Op->getOperand(0);
12333 MVT InVT = In.getSimpleValueType();
12336 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12337 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12339 // Optimize vectors in AVX mode:
12342 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12343 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12344 // Concat upper and lower parts.
12347 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12348 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12349 // Concat upper and lower parts.
12352 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12353 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12354 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12357 if (Subtarget->hasInt256())
12358 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12360 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12361 SDValue Undef = DAG.getUNDEF(InVT);
12362 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12363 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12364 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12366 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12367 VT.getVectorNumElements()/2);
12369 OpLo = DAG.getBitcast(HVT, OpLo);
12370 OpHi = DAG.getBitcast(HVT, OpHi);
12372 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12375 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12376 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12377 MVT VT = Op->getSimpleValueType(0);
12378 SDValue In = Op->getOperand(0);
12379 MVT InVT = In.getSimpleValueType();
12381 unsigned int NumElts = VT.getVectorNumElements();
12382 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12385 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12386 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12388 assert(InVT.getVectorElementType() == MVT::i1);
12389 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12391 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12393 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12395 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12396 if (VT.is512BitVector())
12398 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12401 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12402 SelectionDAG &DAG) {
12403 if (Subtarget->hasFp256())
12404 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12410 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12411 SelectionDAG &DAG) {
12413 MVT VT = Op.getSimpleValueType();
12414 SDValue In = Op.getOperand(0);
12415 MVT SVT = In.getSimpleValueType();
12417 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12418 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12420 if (Subtarget->hasFp256())
12421 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12424 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12425 VT.getVectorNumElements() != SVT.getVectorNumElements());
12429 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12431 MVT VT = Op.getSimpleValueType();
12432 SDValue In = Op.getOperand(0);
12433 MVT InVT = In.getSimpleValueType();
12435 if (VT == MVT::i1) {
12436 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12437 "Invalid scalar TRUNCATE operation");
12438 if (InVT.getSizeInBits() >= 32)
12440 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12441 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12443 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12444 "Invalid TRUNCATE operation");
12446 // move vector to mask - truncate solution for SKX
12447 if (VT.getVectorElementType() == MVT::i1) {
12448 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12449 Subtarget->hasBWI())
12450 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12451 if ((InVT.is256BitVector() || InVT.is128BitVector())
12452 && InVT.getScalarSizeInBits() <= 16 &&
12453 Subtarget->hasBWI() && Subtarget->hasVLX())
12454 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12455 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12456 Subtarget->hasDQI())
12457 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12458 if ((InVT.is256BitVector() || InVT.is128BitVector())
12459 && InVT.getScalarSizeInBits() >= 32 &&
12460 Subtarget->hasDQI() && Subtarget->hasVLX())
12461 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12463 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12464 if (VT.getVectorElementType().getSizeInBits() >=8)
12465 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12467 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12468 unsigned NumElts = InVT.getVectorNumElements();
12469 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12470 if (InVT.getSizeInBits() < 512) {
12471 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12472 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12477 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12478 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12479 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12482 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12483 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12484 if (Subtarget->hasInt256()) {
12485 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12486 In = DAG.getBitcast(MVT::v8i32, In);
12487 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12489 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12490 DAG.getIntPtrConstant(0, DL));
12493 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12494 DAG.getIntPtrConstant(0, DL));
12495 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12496 DAG.getIntPtrConstant(2, DL));
12497 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12498 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12499 static const int ShufMask[] = {0, 2, 4, 6};
12500 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12503 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12504 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12505 if (Subtarget->hasInt256()) {
12506 In = DAG.getBitcast(MVT::v32i8, In);
12508 SmallVector<SDValue,32> pshufbMask;
12509 for (unsigned i = 0; i < 2; ++i) {
12510 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12511 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12512 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12513 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12514 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12515 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12516 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12517 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12518 for (unsigned j = 0; j < 8; ++j)
12519 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12521 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12522 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12523 In = DAG.getBitcast(MVT::v4i64, In);
12525 static const int ShufMask[] = {0, 2, -1, -1};
12526 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12528 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12529 DAG.getIntPtrConstant(0, DL));
12530 return DAG.getBitcast(VT, In);
12533 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12534 DAG.getIntPtrConstant(0, DL));
12536 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12537 DAG.getIntPtrConstant(4, DL));
12539 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12540 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12542 // The PSHUFB mask:
12543 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12544 -1, -1, -1, -1, -1, -1, -1, -1};
12546 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12547 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12548 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12550 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12551 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12553 // The MOVLHPS Mask:
12554 static const int ShufMask2[] = {0, 1, 4, 5};
12555 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12556 return DAG.getBitcast(MVT::v8i16, res);
12559 // Handle truncation of V256 to V128 using shuffles.
12560 if (!VT.is128BitVector() || !InVT.is256BitVector())
12563 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12565 unsigned NumElems = VT.getVectorNumElements();
12566 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12568 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12569 // Prepare truncation shuffle mask
12570 for (unsigned i = 0; i != NumElems; ++i)
12571 MaskVec[i] = i * 2;
12572 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12573 DAG.getUNDEF(NVT), &MaskVec[0]);
12574 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12575 DAG.getIntPtrConstant(0, DL));
12578 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12579 SelectionDAG &DAG) const {
12580 assert(!Op.getSimpleValueType().isVector());
12582 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12583 /*IsSigned=*/ true, /*IsReplace=*/ false);
12584 SDValue FIST = Vals.first, StackSlot = Vals.second;
12585 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12586 if (!FIST.getNode()) return Op;
12588 if (StackSlot.getNode())
12589 // Load the result.
12590 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12591 FIST, StackSlot, MachinePointerInfo(),
12592 false, false, false, 0);
12594 // The node is the result.
12598 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12599 SelectionDAG &DAG) const {
12600 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12601 /*IsSigned=*/ false, /*IsReplace=*/ false);
12602 SDValue FIST = Vals.first, StackSlot = Vals.second;
12603 assert(FIST.getNode() && "Unexpected failure");
12605 if (StackSlot.getNode())
12606 // Load the result.
12607 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12608 FIST, StackSlot, MachinePointerInfo(),
12609 false, false, false, 0);
12611 // The node is the result.
12615 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12617 MVT VT = Op.getSimpleValueType();
12618 SDValue In = Op.getOperand(0);
12619 MVT SVT = In.getSimpleValueType();
12621 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12623 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12624 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12625 In, DAG.getUNDEF(SVT)));
12628 /// The only differences between FABS and FNEG are the mask and the logic op.
12629 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12630 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12631 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12632 "Wrong opcode for lowering FABS or FNEG.");
12634 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12636 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12637 // into an FNABS. We'll lower the FABS after that if it is still in use.
12639 for (SDNode *User : Op->uses())
12640 if (User->getOpcode() == ISD::FNEG)
12643 SDValue Op0 = Op.getOperand(0);
12644 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12647 MVT VT = Op.getSimpleValueType();
12648 // Assume scalar op for initialization; update for vector if needed.
12649 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12650 // generate a 16-byte vector constant and logic op even for the scalar case.
12651 // Using a 16-byte mask allows folding the load of the mask with
12652 // the logic op, so it can save (~4 bytes) on code size.
12654 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12655 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12656 // decide if we should generate a 16-byte constant mask when we only need 4 or
12657 // 8 bytes for the scalar case.
12658 if (VT.isVector()) {
12659 EltVT = VT.getVectorElementType();
12660 NumElts = VT.getVectorNumElements();
12663 unsigned EltBits = EltVT.getSizeInBits();
12664 LLVMContext *Context = DAG.getContext();
12665 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12667 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12668 Constant *C = ConstantInt::get(*Context, MaskElt);
12669 C = ConstantVector::getSplat(NumElts, C);
12670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12671 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12672 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12673 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12674 MachinePointerInfo::getConstantPool(),
12675 false, false, false, Alignment);
12677 if (VT.isVector()) {
12678 // For a vector, cast operands to a vector type, perform the logic op,
12679 // and cast the result back to the original value type.
12680 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12681 SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12682 SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12683 : DAG.getBitcast(VecVT, Op0);
12684 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12685 return DAG.getBitcast(VT,
12686 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12689 // If not vector, then scalar.
12690 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12691 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12692 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12695 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12697 LLVMContext *Context = DAG.getContext();
12698 SDValue Op0 = Op.getOperand(0);
12699 SDValue Op1 = Op.getOperand(1);
12701 MVT VT = Op.getSimpleValueType();
12702 MVT SrcVT = Op1.getSimpleValueType();
12704 // If second operand is smaller, extend it first.
12705 if (SrcVT.bitsLT(VT)) {
12706 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12709 // And if it is bigger, shrink it first.
12710 if (SrcVT.bitsGT(VT)) {
12711 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12715 // At this point the operands and the result should have the same
12716 // type, and that won't be f80 since that is not custom lowered.
12718 const fltSemantics &Sem =
12719 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12720 const unsigned SizeInBits = VT.getSizeInBits();
12722 SmallVector<Constant *, 4> CV(
12723 VT == MVT::f64 ? 2 : 4,
12724 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12726 // First, clear all bits but the sign bit from the second operand (sign).
12727 CV[0] = ConstantFP::get(*Context,
12728 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12729 Constant *C = ConstantVector::get(CV);
12730 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12731 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12732 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12733 MachinePointerInfo::getConstantPool(),
12734 false, false, false, 16);
12735 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12737 // Next, clear the sign bit from the first operand (magnitude).
12738 // If it's a constant, we can clear it here.
12739 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12740 APFloat APF = Op0CN->getValueAPF();
12741 // If the magnitude is a positive zero, the sign bit alone is enough.
12742 if (APF.isPosZero())
12745 CV[0] = ConstantFP::get(*Context, APF);
12747 CV[0] = ConstantFP::get(
12749 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12751 C = ConstantVector::get(CV);
12752 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12753 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12754 MachinePointerInfo::getConstantPool(),
12755 false, false, false, 16);
12756 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12757 if (!isa<ConstantFPSDNode>(Op0))
12758 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12760 // OR the magnitude value with the sign bit.
12761 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12764 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12765 SDValue N0 = Op.getOperand(0);
12767 MVT VT = Op.getSimpleValueType();
12769 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12770 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12771 DAG.getConstant(1, dl, VT));
12772 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12775 // Check whether an OR'd tree is PTEST-able.
12776 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12777 SelectionDAG &DAG) {
12778 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12780 if (!Subtarget->hasSSE41())
12783 if (!Op->hasOneUse())
12786 SDNode *N = Op.getNode();
12789 SmallVector<SDValue, 8> Opnds;
12790 DenseMap<SDValue, unsigned> VecInMap;
12791 SmallVector<SDValue, 8> VecIns;
12792 EVT VT = MVT::Other;
12794 // Recognize a special case where a vector is casted into wide integer to
12796 Opnds.push_back(N->getOperand(0));
12797 Opnds.push_back(N->getOperand(1));
12799 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12800 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12801 // BFS traverse all OR'd operands.
12802 if (I->getOpcode() == ISD::OR) {
12803 Opnds.push_back(I->getOperand(0));
12804 Opnds.push_back(I->getOperand(1));
12805 // Re-evaluate the number of nodes to be traversed.
12806 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12810 // Quit if a non-EXTRACT_VECTOR_ELT
12811 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12814 // Quit if without a constant index.
12815 SDValue Idx = I->getOperand(1);
12816 if (!isa<ConstantSDNode>(Idx))
12819 SDValue ExtractedFromVec = I->getOperand(0);
12820 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12821 if (M == VecInMap.end()) {
12822 VT = ExtractedFromVec.getValueType();
12823 // Quit if not 128/256-bit vector.
12824 if (!VT.is128BitVector() && !VT.is256BitVector())
12826 // Quit if not the same type.
12827 if (VecInMap.begin() != VecInMap.end() &&
12828 VT != VecInMap.begin()->first.getValueType())
12830 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12831 VecIns.push_back(ExtractedFromVec);
12833 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12836 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12837 "Not extracted from 128-/256-bit vector.");
12839 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12841 for (DenseMap<SDValue, unsigned>::const_iterator
12842 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12843 // Quit if not all elements are used.
12844 if (I->second != FullMask)
12848 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12850 // Cast all vectors into TestVT for PTEST.
12851 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12852 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12854 // If more than one full vectors are evaluated, OR them first before PTEST.
12855 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12856 // Each iteration will OR 2 nodes and append the result until there is only
12857 // 1 node left, i.e. the final OR'd value of all vectors.
12858 SDValue LHS = VecIns[Slot];
12859 SDValue RHS = VecIns[Slot + 1];
12860 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12863 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12864 VecIns.back(), VecIns.back());
12867 /// \brief return true if \c Op has a use that doesn't just read flags.
12868 static bool hasNonFlagsUse(SDValue Op) {
12869 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12871 SDNode *User = *UI;
12872 unsigned UOpNo = UI.getOperandNo();
12873 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12874 // Look pass truncate.
12875 UOpNo = User->use_begin().getOperandNo();
12876 User = *User->use_begin();
12879 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12880 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12886 /// Emit nodes that will be selected as "test Op0,Op0", or something
12888 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12889 SelectionDAG &DAG) const {
12890 if (Op.getValueType() == MVT::i1) {
12891 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12892 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12893 DAG.getConstant(0, dl, MVT::i8));
12895 // CF and OF aren't always set the way we want. Determine which
12896 // of these we need.
12897 bool NeedCF = false;
12898 bool NeedOF = false;
12901 case X86::COND_A: case X86::COND_AE:
12902 case X86::COND_B: case X86::COND_BE:
12905 case X86::COND_G: case X86::COND_GE:
12906 case X86::COND_L: case X86::COND_LE:
12907 case X86::COND_O: case X86::COND_NO: {
12908 // Check if we really need to set the
12909 // Overflow flag. If NoSignedWrap is present
12910 // that is not actually needed.
12911 switch (Op->getOpcode()) {
12916 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12917 if (BinNode->Flags.hasNoSignedWrap())
12927 // See if we can use the EFLAGS value from the operand instead of
12928 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12929 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12930 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12931 // Emit a CMP with 0, which is the TEST pattern.
12932 //if (Op.getValueType() == MVT::i1)
12933 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12934 // DAG.getConstant(0, MVT::i1));
12935 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12936 DAG.getConstant(0, dl, Op.getValueType()));
12938 unsigned Opcode = 0;
12939 unsigned NumOperands = 0;
12941 // Truncate operations may prevent the merge of the SETCC instruction
12942 // and the arithmetic instruction before it. Attempt to truncate the operands
12943 // of the arithmetic instruction and use a reduced bit-width instruction.
12944 bool NeedTruncation = false;
12945 SDValue ArithOp = Op;
12946 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12947 SDValue Arith = Op->getOperand(0);
12948 // Both the trunc and the arithmetic op need to have one user each.
12949 if (Arith->hasOneUse())
12950 switch (Arith.getOpcode()) {
12957 NeedTruncation = true;
12963 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12964 // which may be the result of a CAST. We use the variable 'Op', which is the
12965 // non-casted variable when we check for possible users.
12966 switch (ArithOp.getOpcode()) {
12968 // Due to an isel shortcoming, be conservative if this add is likely to be
12969 // selected as part of a load-modify-store instruction. When the root node
12970 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12971 // uses of other nodes in the match, such as the ADD in this case. This
12972 // leads to the ADD being left around and reselected, with the result being
12973 // two adds in the output. Alas, even if none our users are stores, that
12974 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12975 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12976 // climbing the DAG back to the root, and it doesn't seem to be worth the
12978 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12979 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12980 if (UI->getOpcode() != ISD::CopyToReg &&
12981 UI->getOpcode() != ISD::SETCC &&
12982 UI->getOpcode() != ISD::STORE)
12985 if (ConstantSDNode *C =
12986 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12987 // An add of one will be selected as an INC.
12988 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12989 Opcode = X86ISD::INC;
12994 // An add of negative one (subtract of one) will be selected as a DEC.
12995 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12996 Opcode = X86ISD::DEC;
13002 // Otherwise use a regular EFLAGS-setting add.
13003 Opcode = X86ISD::ADD;
13008 // If we have a constant logical shift that's only used in a comparison
13009 // against zero turn it into an equivalent AND. This allows turning it into
13010 // a TEST instruction later.
13011 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13012 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13013 EVT VT = Op.getValueType();
13014 unsigned BitWidth = VT.getSizeInBits();
13015 unsigned ShAmt = Op->getConstantOperandVal(1);
13016 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13018 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13019 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13020 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13021 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13023 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13024 DAG.getConstant(Mask, dl, VT));
13025 DAG.ReplaceAllUsesWith(Op, New);
13031 // If the primary and result isn't used, don't bother using X86ISD::AND,
13032 // because a TEST instruction will be better.
13033 if (!hasNonFlagsUse(Op))
13039 // Due to the ISEL shortcoming noted above, be conservative if this op is
13040 // likely to be selected as part of a load-modify-store instruction.
13041 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13042 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13043 if (UI->getOpcode() == ISD::STORE)
13046 // Otherwise use a regular EFLAGS-setting instruction.
13047 switch (ArithOp.getOpcode()) {
13048 default: llvm_unreachable("unexpected operator!");
13049 case ISD::SUB: Opcode = X86ISD::SUB; break;
13050 case ISD::XOR: Opcode = X86ISD::XOR; break;
13051 case ISD::AND: Opcode = X86ISD::AND; break;
13053 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13054 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13055 if (EFLAGS.getNode())
13058 Opcode = X86ISD::OR;
13072 return SDValue(Op.getNode(), 1);
13078 // If we found that truncation is beneficial, perform the truncation and
13080 if (NeedTruncation) {
13081 EVT VT = Op.getValueType();
13082 SDValue WideVal = Op->getOperand(0);
13083 EVT WideVT = WideVal.getValueType();
13084 unsigned ConvertedOp = 0;
13085 // Use a target machine opcode to prevent further DAGCombine
13086 // optimizations that may separate the arithmetic operations
13087 // from the setcc node.
13088 switch (WideVal.getOpcode()) {
13090 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13091 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13092 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13093 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13094 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13098 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13099 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13100 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13101 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13102 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13108 // Emit a CMP with 0, which is the TEST pattern.
13109 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13110 DAG.getConstant(0, dl, Op.getValueType()));
13112 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13113 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13115 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13116 DAG.ReplaceAllUsesWith(Op, New);
13117 return SDValue(New.getNode(), 1);
13120 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13122 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13123 SDLoc dl, SelectionDAG &DAG) const {
13124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13125 if (C->getAPIntValue() == 0)
13126 return EmitTest(Op0, X86CC, dl, DAG);
13128 if (Op0.getValueType() == MVT::i1)
13129 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13132 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13133 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13134 // Do the comparison at i32 if it's smaller, besides the Atom case.
13135 // This avoids subregister aliasing issues. Keep the smaller reference
13136 // if we're optimizing for size, however, as that'll allow better folding
13137 // of memory operations.
13138 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13139 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13140 Attribute::MinSize) &&
13141 !Subtarget->isAtom()) {
13142 unsigned ExtendOp =
13143 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13144 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13145 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13147 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13148 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13149 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13151 return SDValue(Sub.getNode(), 1);
13153 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13156 /// Convert a comparison if required by the subtarget.
13157 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13158 SelectionDAG &DAG) const {
13159 // If the subtarget does not support the FUCOMI instruction, floating-point
13160 // comparisons have to be converted.
13161 if (Subtarget->hasCMov() ||
13162 Cmp.getOpcode() != X86ISD::CMP ||
13163 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13164 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13167 // The instruction selector will select an FUCOM instruction instead of
13168 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13169 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13170 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13172 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13173 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13174 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13175 DAG.getConstant(8, dl, MVT::i8));
13176 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13177 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13180 /// The minimum architected relative accuracy is 2^-12. We need one
13181 /// Newton-Raphson step to have a good float result (24 bits of precision).
13182 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13183 DAGCombinerInfo &DCI,
13184 unsigned &RefinementSteps,
13185 bool &UseOneConstNR) const {
13186 EVT VT = Op.getValueType();
13187 const char *RecipOp;
13189 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13190 // TODO: Add support for AVX512 (v16f32).
13191 // It is likely not profitable to do this for f64 because a double-precision
13192 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13193 // instructions: convert to single, rsqrtss, convert back to double, refine
13194 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13195 // along with FMA, this could be a throughput win.
13196 if (VT == MVT::f32 && Subtarget->hasSSE1())
13198 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13199 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13200 RecipOp = "vec-sqrtf";
13204 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13205 if (!Recips.isEnabled(RecipOp))
13208 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13209 UseOneConstNR = false;
13210 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13213 /// The minimum architected relative accuracy is 2^-12. We need one
13214 /// Newton-Raphson step to have a good float result (24 bits of precision).
13215 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13216 DAGCombinerInfo &DCI,
13217 unsigned &RefinementSteps) const {
13218 EVT VT = Op.getValueType();
13219 const char *RecipOp;
13221 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13222 // TODO: Add support for AVX512 (v16f32).
13223 // It is likely not profitable to do this for f64 because a double-precision
13224 // reciprocal estimate with refinement on x86 prior to FMA requires
13225 // 15 instructions: convert to single, rcpss, convert back to double, refine
13226 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13227 // along with FMA, this could be a throughput win.
13228 if (VT == MVT::f32 && Subtarget->hasSSE1())
13230 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13231 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13232 RecipOp = "vec-divf";
13236 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13237 if (!Recips.isEnabled(RecipOp))
13240 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13241 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13244 /// If we have at least two divisions that use the same divisor, convert to
13245 /// multplication by a reciprocal. This may need to be adjusted for a given
13246 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13247 /// This is because we still need one division to calculate the reciprocal and
13248 /// then we need two multiplies by that reciprocal as replacements for the
13249 /// original divisions.
13250 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13251 return NumUsers > 1;
13254 static bool isAllOnes(SDValue V) {
13255 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13256 return C && C->isAllOnesValue();
13259 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13260 /// if it's possible.
13261 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13262 SDLoc dl, SelectionDAG &DAG) const {
13263 SDValue Op0 = And.getOperand(0);
13264 SDValue Op1 = And.getOperand(1);
13265 if (Op0.getOpcode() == ISD::TRUNCATE)
13266 Op0 = Op0.getOperand(0);
13267 if (Op1.getOpcode() == ISD::TRUNCATE)
13268 Op1 = Op1.getOperand(0);
13271 if (Op1.getOpcode() == ISD::SHL)
13272 std::swap(Op0, Op1);
13273 if (Op0.getOpcode() == ISD::SHL) {
13274 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13275 if (And00C->getZExtValue() == 1) {
13276 // If we looked past a truncate, check that it's only truncating away
13278 unsigned BitWidth = Op0.getValueSizeInBits();
13279 unsigned AndBitWidth = And.getValueSizeInBits();
13280 if (BitWidth > AndBitWidth) {
13282 DAG.computeKnownBits(Op0, Zeros, Ones);
13283 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13287 RHS = Op0.getOperand(1);
13289 } else if (Op1.getOpcode() == ISD::Constant) {
13290 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13291 uint64_t AndRHSVal = AndRHS->getZExtValue();
13292 SDValue AndLHS = Op0;
13294 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13295 LHS = AndLHS.getOperand(0);
13296 RHS = AndLHS.getOperand(1);
13299 // Use BT if the immediate can't be encoded in a TEST instruction.
13300 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13302 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13306 if (LHS.getNode()) {
13307 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13308 // instruction. Since the shift amount is in-range-or-undefined, we know
13309 // that doing a bittest on the i32 value is ok. We extend to i32 because
13310 // the encoding for the i16 version is larger than the i32 version.
13311 // Also promote i16 to i32 for performance / code size reason.
13312 if (LHS.getValueType() == MVT::i8 ||
13313 LHS.getValueType() == MVT::i16)
13314 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13316 // If the operand types disagree, extend the shift amount to match. Since
13317 // BT ignores high bits (like shifts) we can use anyextend.
13318 if (LHS.getValueType() != RHS.getValueType())
13319 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13321 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13322 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13323 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13324 DAG.getConstant(Cond, dl, MVT::i8), BT);
13330 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13332 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13337 // SSE Condition code mapping:
13346 switch (SetCCOpcode) {
13347 default: llvm_unreachable("Unexpected SETCC condition");
13349 case ISD::SETEQ: SSECC = 0; break;
13351 case ISD::SETGT: Swap = true; // Fallthrough
13353 case ISD::SETOLT: SSECC = 1; break;
13355 case ISD::SETGE: Swap = true; // Fallthrough
13357 case ISD::SETOLE: SSECC = 2; break;
13358 case ISD::SETUO: SSECC = 3; break;
13360 case ISD::SETNE: SSECC = 4; break;
13361 case ISD::SETULE: Swap = true; // Fallthrough
13362 case ISD::SETUGE: SSECC = 5; break;
13363 case ISD::SETULT: Swap = true; // Fallthrough
13364 case ISD::SETUGT: SSECC = 6; break;
13365 case ISD::SETO: SSECC = 7; break;
13367 case ISD::SETONE: SSECC = 8; break;
13370 std::swap(Op0, Op1);
13375 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13376 // ones, and then concatenate the result back.
13377 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13378 MVT VT = Op.getSimpleValueType();
13380 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13381 "Unsupported value type for operation");
13383 unsigned NumElems = VT.getVectorNumElements();
13385 SDValue CC = Op.getOperand(2);
13387 // Extract the LHS vectors
13388 SDValue LHS = Op.getOperand(0);
13389 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13390 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13392 // Extract the RHS vectors
13393 SDValue RHS = Op.getOperand(1);
13394 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13395 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13397 // Issue the operation on the smaller types and concatenate the result back
13398 MVT EltVT = VT.getVectorElementType();
13399 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13400 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13401 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13402 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13405 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13406 SDValue Op0 = Op.getOperand(0);
13407 SDValue Op1 = Op.getOperand(1);
13408 SDValue CC = Op.getOperand(2);
13409 MVT VT = Op.getSimpleValueType();
13412 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13413 "Unexpected type for boolean compare operation");
13414 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13415 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13416 DAG.getConstant(-1, dl, VT));
13417 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13418 DAG.getConstant(-1, dl, VT));
13419 switch (SetCCOpcode) {
13420 default: llvm_unreachable("Unexpected SETCC condition");
13422 // (x == y) -> ~(x ^ y)
13423 return DAG.getNode(ISD::XOR, dl, VT,
13424 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13425 DAG.getConstant(-1, dl, VT));
13427 // (x != y) -> (x ^ y)
13428 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13431 // (x > y) -> (x & ~y)
13432 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13435 // (x < y) -> (~x & y)
13436 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13439 // (x <= y) -> (~x | y)
13440 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13443 // (x >=y) -> (x | ~y)
13444 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13448 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13449 const X86Subtarget *Subtarget) {
13450 SDValue Op0 = Op.getOperand(0);
13451 SDValue Op1 = Op.getOperand(1);
13452 SDValue CC = Op.getOperand(2);
13453 MVT VT = Op.getSimpleValueType();
13456 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13457 Op.getValueType().getScalarType() == MVT::i1 &&
13458 "Cannot set masked compare for this operation");
13460 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13462 bool Unsigned = false;
13465 switch (SetCCOpcode) {
13466 default: llvm_unreachable("Unexpected SETCC condition");
13467 case ISD::SETNE: SSECC = 4; break;
13468 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13469 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13470 case ISD::SETLT: Swap = true; //fall-through
13471 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13472 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13473 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13474 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13475 case ISD::SETULE: Unsigned = true; //fall-through
13476 case ISD::SETLE: SSECC = 2; break;
13480 std::swap(Op0, Op1);
13482 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13483 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13484 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13485 DAG.getConstant(SSECC, dl, MVT::i8));
13488 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13489 /// operand \p Op1. If non-trivial (for example because it's not constant)
13490 /// return an empty value.
13491 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13493 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13497 MVT VT = Op1.getSimpleValueType();
13498 MVT EVT = VT.getVectorElementType();
13499 unsigned n = VT.getVectorNumElements();
13500 SmallVector<SDValue, 8> ULTOp1;
13502 for (unsigned i = 0; i < n; ++i) {
13503 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13504 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13507 // Avoid underflow.
13508 APInt Val = Elt->getAPIntValue();
13512 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13515 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13518 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13519 SelectionDAG &DAG) {
13520 SDValue Op0 = Op.getOperand(0);
13521 SDValue Op1 = Op.getOperand(1);
13522 SDValue CC = Op.getOperand(2);
13523 MVT VT = Op.getSimpleValueType();
13524 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13525 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13530 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13531 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13534 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13535 unsigned Opc = X86ISD::CMPP;
13536 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13537 assert(VT.getVectorNumElements() <= 16);
13538 Opc = X86ISD::CMPM;
13540 // In the two special cases we can't handle, emit two comparisons.
13543 unsigned CombineOpc;
13544 if (SetCCOpcode == ISD::SETUEQ) {
13545 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13547 assert(SetCCOpcode == ISD::SETONE);
13548 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13551 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13552 DAG.getConstant(CC0, dl, MVT::i8));
13553 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13554 DAG.getConstant(CC1, dl, MVT::i8));
13555 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13557 // Handle all other FP comparisons here.
13558 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13559 DAG.getConstant(SSECC, dl, MVT::i8));
13562 // Break 256-bit integer vector compare into smaller ones.
13563 if (VT.is256BitVector() && !Subtarget->hasInt256())
13564 return Lower256IntVSETCC(Op, DAG);
13566 EVT OpVT = Op1.getValueType();
13567 if (OpVT.getVectorElementType() == MVT::i1)
13568 return LowerBoolVSETCC_AVX512(Op, DAG);
13570 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13571 if (Subtarget->hasAVX512()) {
13572 if (Op1.getValueType().is512BitVector() ||
13573 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13574 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13575 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13577 // In AVX-512 architecture setcc returns mask with i1 elements,
13578 // But there is no compare instruction for i8 and i16 elements in KNL.
13579 // We are not talking about 512-bit operands in this case, these
13580 // types are illegal.
13582 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13583 OpVT.getVectorElementType().getSizeInBits() >= 8))
13584 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13585 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13588 // We are handling one of the integer comparisons here. Since SSE only has
13589 // GT and EQ comparisons for integer, swapping operands and multiple
13590 // operations may be required for some comparisons.
13592 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13593 bool Subus = false;
13595 switch (SetCCOpcode) {
13596 default: llvm_unreachable("Unexpected SETCC condition");
13597 case ISD::SETNE: Invert = true;
13598 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13599 case ISD::SETLT: Swap = true;
13600 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13601 case ISD::SETGE: Swap = true;
13602 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13603 Invert = true; break;
13604 case ISD::SETULT: Swap = true;
13605 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13606 FlipSigns = true; break;
13607 case ISD::SETUGE: Swap = true;
13608 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13609 FlipSigns = true; Invert = true; break;
13612 // Special case: Use min/max operations for SETULE/SETUGE
13613 MVT VET = VT.getVectorElementType();
13615 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13616 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13619 switch (SetCCOpcode) {
13621 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13622 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13625 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13628 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13629 if (!MinMax && hasSubus) {
13630 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13632 // t = psubus Op0, Op1
13633 // pcmpeq t, <0..0>
13634 switch (SetCCOpcode) {
13636 case ISD::SETULT: {
13637 // If the comparison is against a constant we can turn this into a
13638 // setule. With psubus, setule does not require a swap. This is
13639 // beneficial because the constant in the register is no longer
13640 // destructed as the destination so it can be hoisted out of a loop.
13641 // Only do this pre-AVX since vpcmp* is no longer destructive.
13642 if (Subtarget->hasAVX())
13644 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13645 if (ULEOp1.getNode()) {
13647 Subus = true; Invert = false; Swap = false;
13651 // Psubus is better than flip-sign because it requires no inversion.
13652 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13653 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13657 Opc = X86ISD::SUBUS;
13663 std::swap(Op0, Op1);
13665 // Check that the operation in question is available (most are plain SSE2,
13666 // but PCMPGTQ and PCMPEQQ have different requirements).
13667 if (VT == MVT::v2i64) {
13668 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13669 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13671 // First cast everything to the right type.
13672 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13673 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13675 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13676 // bits of the inputs before performing those operations. The lower
13677 // compare is always unsigned.
13680 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13682 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13683 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13684 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13685 Sign, Zero, Sign, Zero);
13687 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13688 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13690 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13691 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13692 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13694 // Create masks for only the low parts/high parts of the 64 bit integers.
13695 static const int MaskHi[] = { 1, 1, 3, 3 };
13696 static const int MaskLo[] = { 0, 0, 2, 2 };
13697 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13698 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13699 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13701 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13702 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13705 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13707 return DAG.getBitcast(VT, Result);
13710 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13711 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13712 // pcmpeqd + pshufd + pand.
13713 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13715 // First cast everything to the right type.
13716 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13717 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13720 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13722 // Make sure the lower and upper halves are both all-ones.
13723 static const int Mask[] = { 1, 0, 3, 2 };
13724 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13725 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13728 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13730 return DAG.getBitcast(VT, Result);
13734 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13735 // bits of the inputs before performing those operations.
13737 EVT EltVT = VT.getVectorElementType();
13738 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13740 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13741 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13744 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13746 // If the logical-not of the result is required, perform that now.
13748 Result = DAG.getNOT(dl, Result, VT);
13751 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13754 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13755 getZeroVector(VT, Subtarget, DAG, dl));
13760 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13762 MVT VT = Op.getSimpleValueType();
13764 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13766 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13767 && "SetCC type must be 8-bit or 1-bit integer");
13768 SDValue Op0 = Op.getOperand(0);
13769 SDValue Op1 = Op.getOperand(1);
13771 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13773 // Optimize to BT if possible.
13774 // Lower (X & (1 << N)) == 0 to BT(X, N).
13775 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13776 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13777 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13778 Op1.getOpcode() == ISD::Constant &&
13779 cast<ConstantSDNode>(Op1)->isNullValue() &&
13780 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13781 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13782 if (NewSetCC.getNode()) {
13784 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13789 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13791 if (Op1.getOpcode() == ISD::Constant &&
13792 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13793 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13794 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13796 // If the input is a setcc, then reuse the input setcc or use a new one with
13797 // the inverted condition.
13798 if (Op0.getOpcode() == X86ISD::SETCC) {
13799 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13800 bool Invert = (CC == ISD::SETNE) ^
13801 cast<ConstantSDNode>(Op1)->isNullValue();
13805 CCode = X86::GetOppositeBranchCondition(CCode);
13806 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13807 DAG.getConstant(CCode, dl, MVT::i8),
13808 Op0.getOperand(1));
13810 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13814 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13815 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13816 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13818 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13819 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13822 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13823 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13824 if (X86CC == X86::COND_INVALID)
13827 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13828 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13829 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13830 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13832 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13836 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13837 static bool isX86LogicalCmp(SDValue Op) {
13838 unsigned Opc = Op.getNode()->getOpcode();
13839 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13840 Opc == X86ISD::SAHF)
13842 if (Op.getResNo() == 1 &&
13843 (Opc == X86ISD::ADD ||
13844 Opc == X86ISD::SUB ||
13845 Opc == X86ISD::ADC ||
13846 Opc == X86ISD::SBB ||
13847 Opc == X86ISD::SMUL ||
13848 Opc == X86ISD::UMUL ||
13849 Opc == X86ISD::INC ||
13850 Opc == X86ISD::DEC ||
13851 Opc == X86ISD::OR ||
13852 Opc == X86ISD::XOR ||
13853 Opc == X86ISD::AND))
13856 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13862 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13863 if (V.getOpcode() != ISD::TRUNCATE)
13866 SDValue VOp0 = V.getOperand(0);
13867 unsigned InBits = VOp0.getValueSizeInBits();
13868 unsigned Bits = V.getValueSizeInBits();
13869 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13872 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13873 bool addTest = true;
13874 SDValue Cond = Op.getOperand(0);
13875 SDValue Op1 = Op.getOperand(1);
13876 SDValue Op2 = Op.getOperand(2);
13878 EVT VT = Op1.getValueType();
13881 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13882 // are available or VBLENDV if AVX is available.
13883 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13884 if (Cond.getOpcode() == ISD::SETCC &&
13885 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13886 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13887 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13888 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13889 int SSECC = translateX86FSETCC(
13890 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13893 if (Subtarget->hasAVX512()) {
13894 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13895 DAG.getConstant(SSECC, DL, MVT::i8));
13896 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13899 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13900 DAG.getConstant(SSECC, DL, MVT::i8));
13902 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13903 // of 3 logic instructions for size savings and potentially speed.
13904 // Unfortunately, there is no scalar form of VBLENDV.
13906 // If either operand is a constant, don't try this. We can expect to
13907 // optimize away at least one of the logic instructions later in that
13908 // case, so that sequence would be faster than a variable blend.
13910 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13911 // uses XMM0 as the selection register. That may need just as many
13912 // instructions as the AND/ANDN/OR sequence due to register moves, so
13915 if (Subtarget->hasAVX() &&
13916 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13918 // Convert to vectors, do a VSELECT, and convert back to scalar.
13919 // All of the conversions should be optimized away.
13921 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13922 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13923 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13924 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13926 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13927 VCmp = DAG.getBitcast(VCmpVT, VCmp);
13929 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13931 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13932 VSel, DAG.getIntPtrConstant(0, DL));
13934 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13935 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13936 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13940 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13942 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13943 Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13944 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13945 Op1Scalar = Op1.getOperand(0);
13947 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13948 Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13949 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13950 Op2Scalar = Op2.getOperand(0);
13951 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13952 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13953 Op1Scalar.getValueType(),
13954 Cond, Op1Scalar, Op2Scalar);
13955 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13956 return DAG.getBitcast(VT, newSelect);
13957 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13958 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13959 DAG.getIntPtrConstant(0, DL));
13963 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13964 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13965 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13966 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13967 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13968 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13969 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13971 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13974 if (Cond.getOpcode() == ISD::SETCC) {
13975 SDValue NewCond = LowerSETCC(Cond, DAG);
13976 if (NewCond.getNode())
13980 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13981 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13982 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13983 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13984 if (Cond.getOpcode() == X86ISD::SETCC &&
13985 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13986 isZero(Cond.getOperand(1).getOperand(1))) {
13987 SDValue Cmp = Cond.getOperand(1);
13989 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13991 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13992 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13993 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13995 SDValue CmpOp0 = Cmp.getOperand(0);
13996 // Apply further optimizations for special cases
13997 // (select (x != 0), -1, 0) -> neg & sbb
13998 // (select (x == 0), 0, -1) -> neg & sbb
13999 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14000 if (YC->isNullValue() &&
14001 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14002 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14003 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14004 DAG.getConstant(0, DL,
14005 CmpOp0.getValueType()),
14007 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14008 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14009 SDValue(Neg.getNode(), 1));
14013 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14014 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14015 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14017 SDValue Res = // Res = 0 or -1.
14018 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14019 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14021 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14022 Res = DAG.getNOT(DL, Res, Res.getValueType());
14024 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14025 if (!N2C || !N2C->isNullValue())
14026 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14031 // Look past (and (setcc_carry (cmp ...)), 1).
14032 if (Cond.getOpcode() == ISD::AND &&
14033 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14034 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14035 if (C && C->getAPIntValue() == 1)
14036 Cond = Cond.getOperand(0);
14039 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14040 // setting operand in place of the X86ISD::SETCC.
14041 unsigned CondOpcode = Cond.getOpcode();
14042 if (CondOpcode == X86ISD::SETCC ||
14043 CondOpcode == X86ISD::SETCC_CARRY) {
14044 CC = Cond.getOperand(0);
14046 SDValue Cmp = Cond.getOperand(1);
14047 unsigned Opc = Cmp.getOpcode();
14048 MVT VT = Op.getSimpleValueType();
14050 bool IllegalFPCMov = false;
14051 if (VT.isFloatingPoint() && !VT.isVector() &&
14052 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14053 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14055 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14056 Opc == X86ISD::BT) { // FIXME
14060 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14061 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14062 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14063 Cond.getOperand(0).getValueType() != MVT::i8)) {
14064 SDValue LHS = Cond.getOperand(0);
14065 SDValue RHS = Cond.getOperand(1);
14066 unsigned X86Opcode;
14069 switch (CondOpcode) {
14070 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14071 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14072 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14073 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14074 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14075 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14076 default: llvm_unreachable("unexpected overflowing operator");
14078 if (CondOpcode == ISD::UMULO)
14079 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14082 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14084 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14086 if (CondOpcode == ISD::UMULO)
14087 Cond = X86Op.getValue(2);
14089 Cond = X86Op.getValue(1);
14091 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14096 // Look pass the truncate if the high bits are known zero.
14097 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14098 Cond = Cond.getOperand(0);
14100 // We know the result of AND is compared against zero. Try to match
14102 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14103 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14104 if (NewSetCC.getNode()) {
14105 CC = NewSetCC.getOperand(0);
14106 Cond = NewSetCC.getOperand(1);
14113 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14114 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14117 // a < b ? -1 : 0 -> RES = ~setcc_carry
14118 // a < b ? 0 : -1 -> RES = setcc_carry
14119 // a >= b ? -1 : 0 -> RES = setcc_carry
14120 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14121 if (Cond.getOpcode() == X86ISD::SUB) {
14122 Cond = ConvertCmpIfNecessary(Cond, DAG);
14123 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14125 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14126 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14127 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14128 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14130 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14131 return DAG.getNOT(DL, Res, Res.getValueType());
14136 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14137 // widen the cmov and push the truncate through. This avoids introducing a new
14138 // branch during isel and doesn't add any extensions.
14139 if (Op.getValueType() == MVT::i8 &&
14140 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14141 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14142 if (T1.getValueType() == T2.getValueType() &&
14143 // Blacklist CopyFromReg to avoid partial register stalls.
14144 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14145 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14146 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14147 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14151 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14152 // condition is true.
14153 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14154 SDValue Ops[] = { Op2, Op1, CC, Cond };
14155 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14158 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14159 const X86Subtarget *Subtarget,
14160 SelectionDAG &DAG) {
14161 MVT VT = Op->getSimpleValueType(0);
14162 SDValue In = Op->getOperand(0);
14163 MVT InVT = In.getSimpleValueType();
14164 MVT VTElt = VT.getVectorElementType();
14165 MVT InVTElt = InVT.getVectorElementType();
14169 if ((InVTElt == MVT::i1) &&
14170 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14171 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14173 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14174 VTElt.getSizeInBits() <= 16)) ||
14176 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14177 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14179 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14180 VTElt.getSizeInBits() >= 32))))
14181 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14183 unsigned int NumElts = VT.getVectorNumElements();
14185 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14188 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14189 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14190 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14191 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14194 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14195 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14197 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14200 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14202 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14203 if (VT.is512BitVector())
14205 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14208 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14209 const X86Subtarget *Subtarget,
14210 SelectionDAG &DAG) {
14211 SDValue In = Op->getOperand(0);
14212 MVT VT = Op->getSimpleValueType(0);
14213 MVT InVT = In.getSimpleValueType();
14214 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14216 MVT InSVT = InVT.getScalarType();
14217 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14219 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14221 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14226 // SSE41 targets can use the pmovsx* instructions directly.
14227 if (Subtarget->hasSSE41())
14228 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14230 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14234 // As SRAI is only available on i16/i32 types, we expand only up to i32
14235 // and handle i64 separately.
14236 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14237 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14238 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14239 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14240 Curr = DAG.getBitcast(CurrVT, Curr);
14243 SDValue SignExt = Curr;
14244 if (CurrVT != InVT) {
14245 unsigned SignExtShift =
14246 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14247 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14248 DAG.getConstant(SignExtShift, dl, MVT::i8));
14254 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14255 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14256 DAG.getConstant(31, dl, MVT::i8));
14257 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14258 return DAG.getBitcast(VT, Ext);
14264 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14265 SelectionDAG &DAG) {
14266 MVT VT = Op->getSimpleValueType(0);
14267 SDValue In = Op->getOperand(0);
14268 MVT InVT = In.getSimpleValueType();
14271 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14272 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14274 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14275 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14276 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14279 if (Subtarget->hasInt256())
14280 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14282 // Optimize vectors in AVX mode
14283 // Sign extend v8i16 to v8i32 and
14286 // Divide input vector into two parts
14287 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14288 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14289 // concat the vectors to original VT
14291 unsigned NumElems = InVT.getVectorNumElements();
14292 SDValue Undef = DAG.getUNDEF(InVT);
14294 SmallVector<int,8> ShufMask1(NumElems, -1);
14295 for (unsigned i = 0; i != NumElems/2; ++i)
14298 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14300 SmallVector<int,8> ShufMask2(NumElems, -1);
14301 for (unsigned i = 0; i != NumElems/2; ++i)
14302 ShufMask2[i] = i + NumElems/2;
14304 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14306 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14307 VT.getVectorNumElements()/2);
14309 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14310 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14312 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14315 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14316 // may emit an illegal shuffle but the expansion is still better than scalar
14317 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14318 // we'll emit a shuffle and a arithmetic shift.
14319 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14320 // TODO: It is possible to support ZExt by zeroing the undef values during
14321 // the shuffle phase or after the shuffle.
14322 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14323 SelectionDAG &DAG) {
14324 MVT RegVT = Op.getSimpleValueType();
14325 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14326 assert(RegVT.isInteger() &&
14327 "We only custom lower integer vector sext loads.");
14329 // Nothing useful we can do without SSE2 shuffles.
14330 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14332 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14334 EVT MemVT = Ld->getMemoryVT();
14335 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14336 unsigned RegSz = RegVT.getSizeInBits();
14338 ISD::LoadExtType Ext = Ld->getExtensionType();
14340 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14341 && "Only anyext and sext are currently implemented.");
14342 assert(MemVT != RegVT && "Cannot extend to the same type");
14343 assert(MemVT.isVector() && "Must load a vector from memory");
14345 unsigned NumElems = RegVT.getVectorNumElements();
14346 unsigned MemSz = MemVT.getSizeInBits();
14347 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14349 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14350 // The only way in which we have a legal 256-bit vector result but not the
14351 // integer 256-bit operations needed to directly lower a sextload is if we
14352 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14353 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14354 // correctly legalized. We do this late to allow the canonical form of
14355 // sextload to persist throughout the rest of the DAG combiner -- it wants
14356 // to fold together any extensions it can, and so will fuse a sign_extend
14357 // of an sextload into a sextload targeting a wider value.
14359 if (MemSz == 128) {
14360 // Just switch this to a normal load.
14361 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14362 "it must be a legal 128-bit vector "
14364 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14365 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14366 Ld->isInvariant(), Ld->getAlignment());
14368 assert(MemSz < 128 &&
14369 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14370 // Do an sext load to a 128-bit vector type. We want to use the same
14371 // number of elements, but elements half as wide. This will end up being
14372 // recursively lowered by this routine, but will succeed as we definitely
14373 // have all the necessary features if we're using AVX1.
14375 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14376 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14378 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14379 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14380 Ld->isNonTemporal(), Ld->isInvariant(),
14381 Ld->getAlignment());
14384 // Replace chain users with the new chain.
14385 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14386 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14388 // Finally, do a normal sign-extend to the desired register.
14389 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14392 // All sizes must be a power of two.
14393 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14394 "Non-power-of-two elements are not custom lowered!");
14396 // Attempt to load the original value using scalar loads.
14397 // Find the largest scalar type that divides the total loaded size.
14398 MVT SclrLoadTy = MVT::i8;
14399 for (MVT Tp : MVT::integer_valuetypes()) {
14400 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14405 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14406 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14408 SclrLoadTy = MVT::f64;
14410 // Calculate the number of scalar loads that we need to perform
14411 // in order to load our vector from memory.
14412 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14414 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14415 "Can only lower sext loads with a single scalar load!");
14417 unsigned loadRegZize = RegSz;
14418 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14421 // Represent our vector as a sequence of elements which are the
14422 // largest scalar that we can load.
14423 EVT LoadUnitVecVT = EVT::getVectorVT(
14424 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14426 // Represent the data using the same element type that is stored in
14427 // memory. In practice, we ''widen'' MemVT.
14429 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14430 loadRegZize / MemVT.getScalarType().getSizeInBits());
14432 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14433 "Invalid vector type");
14435 // We can't shuffle using an illegal type.
14436 assert(TLI.isTypeLegal(WideVecVT) &&
14437 "We only lower types that form legal widened vector types");
14439 SmallVector<SDValue, 8> Chains;
14440 SDValue Ptr = Ld->getBasePtr();
14441 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14442 TLI.getPointerTy(DAG.getDataLayout()));
14443 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14445 for (unsigned i = 0; i < NumLoads; ++i) {
14446 // Perform a single load.
14447 SDValue ScalarLoad =
14448 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14449 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14450 Ld->getAlignment());
14451 Chains.push_back(ScalarLoad.getValue(1));
14452 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14453 // another round of DAGCombining.
14455 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14457 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14458 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14460 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14463 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14465 // Bitcast the loaded value to a vector of the original element type, in
14466 // the size of the target vector type.
14467 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14468 unsigned SizeRatio = RegSz / MemSz;
14470 if (Ext == ISD::SEXTLOAD) {
14471 // If we have SSE4.1, we can directly emit a VSEXT node.
14472 if (Subtarget->hasSSE41()) {
14473 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14474 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14478 // Otherwise we'll shuffle the small elements in the high bits of the
14479 // larger type and perform an arithmetic shift. If the shift is not legal
14480 // it's better to scalarize.
14481 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14482 "We can't implement a sext load without an arithmetic right shift!");
14484 // Redistribute the loaded elements into the different locations.
14485 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14486 for (unsigned i = 0; i != NumElems; ++i)
14487 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14489 SDValue Shuff = DAG.getVectorShuffle(
14490 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14492 Shuff = DAG.getBitcast(RegVT, Shuff);
14494 // Build the arithmetic shift.
14495 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14496 MemVT.getVectorElementType().getSizeInBits();
14498 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14499 DAG.getConstant(Amt, dl, RegVT));
14501 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14505 // Redistribute the loaded elements into the different locations.
14506 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14507 for (unsigned i = 0; i != NumElems; ++i)
14508 ShuffleVec[i * SizeRatio] = i;
14510 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14511 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14513 // Bitcast to the requested type.
14514 Shuff = DAG.getBitcast(RegVT, Shuff);
14515 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14519 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14520 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14521 // from the AND / OR.
14522 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14523 Opc = Op.getOpcode();
14524 if (Opc != ISD::OR && Opc != ISD::AND)
14526 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14527 Op.getOperand(0).hasOneUse() &&
14528 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14529 Op.getOperand(1).hasOneUse());
14532 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14533 // 1 and that the SETCC node has a single use.
14534 static bool isXor1OfSetCC(SDValue Op) {
14535 if (Op.getOpcode() != ISD::XOR)
14537 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14538 if (N1C && N1C->getAPIntValue() == 1) {
14539 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14540 Op.getOperand(0).hasOneUse();
14545 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14546 bool addTest = true;
14547 SDValue Chain = Op.getOperand(0);
14548 SDValue Cond = Op.getOperand(1);
14549 SDValue Dest = Op.getOperand(2);
14552 bool Inverted = false;
14554 if (Cond.getOpcode() == ISD::SETCC) {
14555 // Check for setcc([su]{add,sub,mul}o == 0).
14556 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14557 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14558 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14559 Cond.getOperand(0).getResNo() == 1 &&
14560 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14561 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14562 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14563 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14564 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14565 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14567 Cond = Cond.getOperand(0);
14569 SDValue NewCond = LowerSETCC(Cond, DAG);
14570 if (NewCond.getNode())
14575 // FIXME: LowerXALUO doesn't handle these!!
14576 else if (Cond.getOpcode() == X86ISD::ADD ||
14577 Cond.getOpcode() == X86ISD::SUB ||
14578 Cond.getOpcode() == X86ISD::SMUL ||
14579 Cond.getOpcode() == X86ISD::UMUL)
14580 Cond = LowerXALUO(Cond, DAG);
14583 // Look pass (and (setcc_carry (cmp ...)), 1).
14584 if (Cond.getOpcode() == ISD::AND &&
14585 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14586 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14587 if (C && C->getAPIntValue() == 1)
14588 Cond = Cond.getOperand(0);
14591 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14592 // setting operand in place of the X86ISD::SETCC.
14593 unsigned CondOpcode = Cond.getOpcode();
14594 if (CondOpcode == X86ISD::SETCC ||
14595 CondOpcode == X86ISD::SETCC_CARRY) {
14596 CC = Cond.getOperand(0);
14598 SDValue Cmp = Cond.getOperand(1);
14599 unsigned Opc = Cmp.getOpcode();
14600 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14601 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14605 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14609 // These can only come from an arithmetic instruction with overflow,
14610 // e.g. SADDO, UADDO.
14611 Cond = Cond.getNode()->getOperand(1);
14617 CondOpcode = Cond.getOpcode();
14618 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14619 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14620 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14621 Cond.getOperand(0).getValueType() != MVT::i8)) {
14622 SDValue LHS = Cond.getOperand(0);
14623 SDValue RHS = Cond.getOperand(1);
14624 unsigned X86Opcode;
14627 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14628 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14630 switch (CondOpcode) {
14631 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14633 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14635 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14638 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14639 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14641 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14643 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14646 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14647 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14648 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14649 default: llvm_unreachable("unexpected overflowing operator");
14652 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14653 if (CondOpcode == ISD::UMULO)
14654 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14657 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14659 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14661 if (CondOpcode == ISD::UMULO)
14662 Cond = X86Op.getValue(2);
14664 Cond = X86Op.getValue(1);
14666 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14670 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14671 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14672 if (CondOpc == ISD::OR) {
14673 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14674 // two branches instead of an explicit OR instruction with a
14676 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14677 isX86LogicalCmp(Cmp)) {
14678 CC = Cond.getOperand(0).getOperand(0);
14679 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14680 Chain, Dest, CC, Cmp);
14681 CC = Cond.getOperand(1).getOperand(0);
14685 } else { // ISD::AND
14686 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14687 // two branches instead of an explicit AND instruction with a
14688 // separate test. However, we only do this if this block doesn't
14689 // have a fall-through edge, because this requires an explicit
14690 // jmp when the condition is false.
14691 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14692 isX86LogicalCmp(Cmp) &&
14693 Op.getNode()->hasOneUse()) {
14694 X86::CondCode CCode =
14695 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14696 CCode = X86::GetOppositeBranchCondition(CCode);
14697 CC = DAG.getConstant(CCode, dl, MVT::i8);
14698 SDNode *User = *Op.getNode()->use_begin();
14699 // Look for an unconditional branch following this conditional branch.
14700 // We need this because we need to reverse the successors in order
14701 // to implement FCMP_OEQ.
14702 if (User->getOpcode() == ISD::BR) {
14703 SDValue FalseBB = User->getOperand(1);
14705 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14706 assert(NewBR == User);
14710 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14711 Chain, Dest, CC, Cmp);
14712 X86::CondCode CCode =
14713 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14714 CCode = X86::GetOppositeBranchCondition(CCode);
14715 CC = DAG.getConstant(CCode, dl, MVT::i8);
14721 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14722 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14723 // It should be transformed during dag combiner except when the condition
14724 // is set by a arithmetics with overflow node.
14725 X86::CondCode CCode =
14726 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14727 CCode = X86::GetOppositeBranchCondition(CCode);
14728 CC = DAG.getConstant(CCode, dl, MVT::i8);
14729 Cond = Cond.getOperand(0).getOperand(1);
14731 } else if (Cond.getOpcode() == ISD::SETCC &&
14732 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14733 // For FCMP_OEQ, we can emit
14734 // two branches instead of an explicit AND instruction with a
14735 // separate test. However, we only do this if this block doesn't
14736 // have a fall-through edge, because this requires an explicit
14737 // jmp when the condition is false.
14738 if (Op.getNode()->hasOneUse()) {
14739 SDNode *User = *Op.getNode()->use_begin();
14740 // Look for an unconditional branch following this conditional branch.
14741 // We need this because we need to reverse the successors in order
14742 // to implement FCMP_OEQ.
14743 if (User->getOpcode() == ISD::BR) {
14744 SDValue FalseBB = User->getOperand(1);
14746 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14747 assert(NewBR == User);
14751 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14752 Cond.getOperand(0), Cond.getOperand(1));
14753 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14754 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14755 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14756 Chain, Dest, CC, Cmp);
14757 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14762 } else if (Cond.getOpcode() == ISD::SETCC &&
14763 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14764 // For FCMP_UNE, we can emit
14765 // two branches instead of an explicit AND instruction with a
14766 // separate test. However, we only do this if this block doesn't
14767 // have a fall-through edge, because this requires an explicit
14768 // jmp when the condition is false.
14769 if (Op.getNode()->hasOneUse()) {
14770 SDNode *User = *Op.getNode()->use_begin();
14771 // Look for an unconditional branch following this conditional branch.
14772 // We need this because we need to reverse the successors in order
14773 // to implement FCMP_UNE.
14774 if (User->getOpcode() == ISD::BR) {
14775 SDValue FalseBB = User->getOperand(1);
14777 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14778 assert(NewBR == User);
14781 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14782 Cond.getOperand(0), Cond.getOperand(1));
14783 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14784 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14785 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14786 Chain, Dest, CC, Cmp);
14787 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14797 // Look pass the truncate if the high bits are known zero.
14798 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14799 Cond = Cond.getOperand(0);
14801 // We know the result of AND is compared against zero. Try to match
14803 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14804 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14805 if (NewSetCC.getNode()) {
14806 CC = NewSetCC.getOperand(0);
14807 Cond = NewSetCC.getOperand(1);
14814 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14815 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14816 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14818 Cond = ConvertCmpIfNecessary(Cond, DAG);
14819 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14820 Chain, Dest, CC, Cond);
14823 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14824 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14825 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14826 // that the guard pages used by the OS virtual memory manager are allocated in
14827 // correct sequence.
14829 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14830 SelectionDAG &DAG) const {
14831 MachineFunction &MF = DAG.getMachineFunction();
14832 bool SplitStack = MF.shouldSplitStack();
14833 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14838 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14839 SDNode* Node = Op.getNode();
14841 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14842 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14843 " not tell us which reg is the stack pointer!");
14844 EVT VT = Node->getValueType(0);
14845 SDValue Tmp1 = SDValue(Node, 0);
14846 SDValue Tmp2 = SDValue(Node, 1);
14847 SDValue Tmp3 = Node->getOperand(2);
14848 SDValue Chain = Tmp1.getOperand(0);
14850 // Chain the dynamic stack allocation so that it doesn't modify the stack
14851 // pointer when other instructions are using the stack.
14852 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14855 SDValue Size = Tmp2.getOperand(1);
14856 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14857 Chain = SP.getValue(1);
14858 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14859 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14860 unsigned StackAlign = TFI.getStackAlignment();
14861 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14862 if (Align > StackAlign)
14863 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14864 DAG.getConstant(-(uint64_t)Align, dl, VT));
14865 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14867 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14868 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14871 SDValue Ops[2] = { Tmp1, Tmp2 };
14872 return DAG.getMergeValues(Ops, dl);
14876 SDValue Chain = Op.getOperand(0);
14877 SDValue Size = Op.getOperand(1);
14878 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14879 EVT VT = Op.getNode()->getValueType(0);
14881 bool Is64Bit = Subtarget->is64Bit();
14882 MVT SPTy = getPointerTy(DAG.getDataLayout());
14885 MachineRegisterInfo &MRI = MF.getRegInfo();
14888 // The 64 bit implementation of segmented stacks needs to clobber both r10
14889 // r11. This makes it impossible to use it along with nested parameters.
14890 const Function *F = MF.getFunction();
14892 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14894 if (I->hasNestAttr())
14895 report_fatal_error("Cannot use segmented stacks with functions that "
14896 "have nested arguments.");
14899 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14900 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14901 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14902 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14903 DAG.getRegister(Vreg, SPTy));
14904 SDValue Ops1[2] = { Value, Chain };
14905 return DAG.getMergeValues(Ops1, dl);
14908 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14910 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14911 Flag = Chain.getValue(1);
14912 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14914 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14916 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14917 unsigned SPReg = RegInfo->getStackRegister();
14918 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14919 Chain = SP.getValue(1);
14922 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14923 DAG.getConstant(-(uint64_t)Align, dl, VT));
14924 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14927 SDValue Ops1[2] = { SP, Chain };
14928 return DAG.getMergeValues(Ops1, dl);
14932 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14933 MachineFunction &MF = DAG.getMachineFunction();
14934 auto PtrVT = getPointerTy(MF.getDataLayout());
14935 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14937 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14940 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14941 // vastart just stores the address of the VarArgsFrameIndex slot into the
14942 // memory location argument.
14943 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14944 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14945 MachinePointerInfo(SV), false, false, 0);
14949 // gp_offset (0 - 6 * 8)
14950 // fp_offset (48 - 48 + 8 * 16)
14951 // overflow_arg_area (point to parameters coming in memory).
14953 SmallVector<SDValue, 8> MemOps;
14954 SDValue FIN = Op.getOperand(1);
14956 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14957 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14959 FIN, MachinePointerInfo(SV), false, false, 0);
14960 MemOps.push_back(Store);
14963 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14964 Store = DAG.getStore(Op.getOperand(0), DL,
14965 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14967 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14968 MemOps.push_back(Store);
14970 // Store ptr to overflow_arg_area
14971 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14972 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14973 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14974 MachinePointerInfo(SV, 8),
14976 MemOps.push_back(Store);
14978 // Store ptr to reg_save_area.
14979 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
14980 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
14981 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14982 MachinePointerInfo(SV, 16), false, false, 0);
14983 MemOps.push_back(Store);
14984 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14987 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14988 assert(Subtarget->is64Bit() &&
14989 "LowerVAARG only handles 64-bit va_arg!");
14990 assert((Subtarget->isTargetLinux() ||
14991 Subtarget->isTargetDarwin()) &&
14992 "Unhandled target in LowerVAARG");
14993 assert(Op.getNode()->getNumOperands() == 4);
14994 SDValue Chain = Op.getOperand(0);
14995 SDValue SrcPtr = Op.getOperand(1);
14996 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14997 unsigned Align = Op.getConstantOperandVal(3);
15000 EVT ArgVT = Op.getNode()->getValueType(0);
15001 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15002 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15005 // Decide which area this value should be read from.
15006 // TODO: Implement the AMD64 ABI in its entirety. This simple
15007 // selection mechanism works only for the basic types.
15008 if (ArgVT == MVT::f80) {
15009 llvm_unreachable("va_arg for f80 not yet implemented");
15010 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15011 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15012 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15013 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15015 llvm_unreachable("Unhandled argument type in LowerVAARG");
15018 if (ArgMode == 2) {
15019 // Sanity Check: Make sure using fp_offset makes sense.
15020 assert(!Subtarget->useSoftFloat() &&
15021 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15022 Attribute::NoImplicitFloat)) &&
15023 Subtarget->hasSSE1());
15026 // Insert VAARG_64 node into the DAG
15027 // VAARG_64 returns two values: Variable Argument Address, Chain
15028 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15029 DAG.getConstant(ArgMode, dl, MVT::i8),
15030 DAG.getConstant(Align, dl, MVT::i32)};
15031 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15032 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15033 VTs, InstOps, MVT::i64,
15034 MachinePointerInfo(SV),
15036 /*Volatile=*/false,
15038 /*WriteMem=*/true);
15039 Chain = VAARG.getValue(1);
15041 // Load the next argument and return it
15042 return DAG.getLoad(ArgVT, dl,
15045 MachinePointerInfo(),
15046 false, false, false, 0);
15049 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15050 SelectionDAG &DAG) {
15051 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15052 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15053 SDValue Chain = Op.getOperand(0);
15054 SDValue DstPtr = Op.getOperand(1);
15055 SDValue SrcPtr = Op.getOperand(2);
15056 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15057 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15060 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15061 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15063 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15066 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15067 // amount is a constant. Takes immediate version of shift as input.
15068 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15069 SDValue SrcOp, uint64_t ShiftAmt,
15070 SelectionDAG &DAG) {
15071 MVT ElementType = VT.getVectorElementType();
15073 // Fold this packed shift into its first operand if ShiftAmt is 0.
15077 // Check for ShiftAmt >= element width
15078 if (ShiftAmt >= ElementType.getSizeInBits()) {
15079 if (Opc == X86ISD::VSRAI)
15080 ShiftAmt = ElementType.getSizeInBits() - 1;
15082 return DAG.getConstant(0, dl, VT);
15085 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15086 && "Unknown target vector shift-by-constant node");
15088 // Fold this packed vector shift into a build vector if SrcOp is a
15089 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15090 if (VT == SrcOp.getSimpleValueType() &&
15091 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15092 SmallVector<SDValue, 8> Elts;
15093 unsigned NumElts = SrcOp->getNumOperands();
15094 ConstantSDNode *ND;
15097 default: llvm_unreachable(nullptr);
15098 case X86ISD::VSHLI:
15099 for (unsigned i=0; i!=NumElts; ++i) {
15100 SDValue CurrentOp = SrcOp->getOperand(i);
15101 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15102 Elts.push_back(CurrentOp);
15105 ND = cast<ConstantSDNode>(CurrentOp);
15106 const APInt &C = ND->getAPIntValue();
15107 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15110 case X86ISD::VSRLI:
15111 for (unsigned i=0; i!=NumElts; ++i) {
15112 SDValue CurrentOp = SrcOp->getOperand(i);
15113 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15114 Elts.push_back(CurrentOp);
15117 ND = cast<ConstantSDNode>(CurrentOp);
15118 const APInt &C = ND->getAPIntValue();
15119 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15122 case X86ISD::VSRAI:
15123 for (unsigned i=0; i!=NumElts; ++i) {
15124 SDValue CurrentOp = SrcOp->getOperand(i);
15125 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15126 Elts.push_back(CurrentOp);
15129 ND = cast<ConstantSDNode>(CurrentOp);
15130 const APInt &C = ND->getAPIntValue();
15131 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15136 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15139 return DAG.getNode(Opc, dl, VT, SrcOp,
15140 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15143 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15144 // may or may not be a constant. Takes immediate version of shift as input.
15145 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15146 SDValue SrcOp, SDValue ShAmt,
15147 SelectionDAG &DAG) {
15148 MVT SVT = ShAmt.getSimpleValueType();
15149 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15151 // Catch shift-by-constant.
15152 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15153 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15154 CShAmt->getZExtValue(), DAG);
15156 // Change opcode to non-immediate version
15158 default: llvm_unreachable("Unknown target vector shift node");
15159 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15160 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15161 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15164 const X86Subtarget &Subtarget =
15165 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15166 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15167 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15168 // Let the shuffle legalizer expand this shift amount node.
15169 SDValue Op0 = ShAmt.getOperand(0);
15170 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15171 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15173 // Need to build a vector containing shift amount.
15174 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15175 SmallVector<SDValue, 4> ShOps;
15176 ShOps.push_back(ShAmt);
15177 if (SVT == MVT::i32) {
15178 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15179 ShOps.push_back(DAG.getUNDEF(SVT));
15181 ShOps.push_back(DAG.getUNDEF(SVT));
15183 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15184 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15187 // The return type has to be a 128-bit type with the same element
15188 // type as the input type.
15189 MVT EltVT = VT.getVectorElementType();
15190 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15192 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15193 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15196 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15197 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15198 /// necessary casting for \p Mask when lowering masking intrinsics.
15199 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15200 SDValue PreservedSrc,
15201 const X86Subtarget *Subtarget,
15202 SelectionDAG &DAG) {
15203 EVT VT = Op.getValueType();
15204 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15205 MVT::i1, VT.getVectorNumElements());
15206 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15207 Mask.getValueType().getSizeInBits());
15210 assert(MaskVT.isSimple() && "invalid mask type");
15212 if (isAllOnes(Mask))
15215 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15216 // are extracted by EXTRACT_SUBVECTOR.
15217 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15218 DAG.getBitcast(BitcastVT, Mask),
15219 DAG.getIntPtrConstant(0, dl));
15221 switch (Op.getOpcode()) {
15223 case X86ISD::PCMPEQM:
15224 case X86ISD::PCMPGTM:
15226 case X86ISD::CMPMU:
15227 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15229 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15230 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15231 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15234 /// \brief Creates an SDNode for a predicated scalar operation.
15235 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15236 /// The mask is comming as MVT::i8 and it should be truncated
15237 /// to MVT::i1 while lowering masking intrinsics.
15238 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15239 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15240 /// a scalar instruction.
15241 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15242 SDValue PreservedSrc,
15243 const X86Subtarget *Subtarget,
15244 SelectionDAG &DAG) {
15245 if (isAllOnes(Mask))
15248 EVT VT = Op.getValueType();
15250 // The mask should be of type MVT::i1
15251 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15253 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15254 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15255 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15258 static int getSEHRegistrationNodeSize(const Function *Fn) {
15259 if (!Fn->hasPersonalityFn())
15260 report_fatal_error(
15261 "querying registration node size for function without personality");
15262 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15263 // WinEHStatePass for the full struct definition.
15264 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15265 case EHPersonality::MSVC_X86SEH: return 24;
15266 case EHPersonality::MSVC_CXX: return 16;
15269 report_fatal_error("can only recover FP for MSVC EH personality functions");
15272 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15273 /// function or when returning to a parent frame after catching an exception, we
15274 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15275 /// Here's the math:
15276 /// RegNodeBase = EntryEBP - RegNodeSize
15277 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15278 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15279 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15280 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15281 SDValue EntryEBP) {
15282 MachineFunction &MF = DAG.getMachineFunction();
15285 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15286 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15288 // It's possible that the parent function no longer has a personality function
15289 // if the exceptional code was optimized away, in which case we just return
15290 // the incoming EBP.
15291 if (!Fn->hasPersonalityFn())
15294 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15296 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15298 MCSymbol *OffsetSym =
15299 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15300 GlobalValue::getRealLinkageName(Fn->getName()));
15301 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15302 SDValue RegNodeFrameOffset =
15303 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15305 // RegNodeBase = EntryEBP - RegNodeSize
15306 // ParentFP = RegNodeBase - RegNodeFrameOffset
15307 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15308 DAG.getConstant(RegNodeSize, dl, PtrVT));
15309 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15312 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15313 SelectionDAG &DAG) {
15315 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15316 EVT VT = Op.getValueType();
15317 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15319 switch(IntrData->Type) {
15320 case INTR_TYPE_1OP:
15321 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15322 case INTR_TYPE_2OP:
15323 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15325 case INTR_TYPE_3OP:
15326 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15327 Op.getOperand(2), Op.getOperand(3));
15328 case INTR_TYPE_4OP:
15329 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15330 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15331 case INTR_TYPE_1OP_MASK_RM: {
15332 SDValue Src = Op.getOperand(1);
15333 SDValue PassThru = Op.getOperand(2);
15334 SDValue Mask = Op.getOperand(3);
15335 SDValue RoundingMode;
15336 if (Op.getNumOperands() == 4)
15337 RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15339 RoundingMode = Op.getOperand(4);
15340 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15341 if (IntrWithRoundingModeOpcode != 0) {
15342 unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15343 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15344 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15345 dl, Op.getValueType(), Src, RoundingMode),
15346 Mask, PassThru, Subtarget, DAG);
15348 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15350 Mask, PassThru, Subtarget, DAG);
15352 case INTR_TYPE_1OP_MASK: {
15353 SDValue Src = Op.getOperand(1);
15354 SDValue Passthru = Op.getOperand(2);
15355 SDValue Mask = Op.getOperand(3);
15356 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15357 Mask, Passthru, Subtarget, DAG);
15359 case INTR_TYPE_SCALAR_MASK_RM: {
15360 SDValue Src1 = Op.getOperand(1);
15361 SDValue Src2 = Op.getOperand(2);
15362 SDValue Src0 = Op.getOperand(3);
15363 SDValue Mask = Op.getOperand(4);
15364 // There are 2 kinds of intrinsics in this group:
15365 // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15366 // (2) With rounding mode and sae - 7 operands.
15367 if (Op.getNumOperands() == 6) {
15368 SDValue Sae = Op.getOperand(5);
15369 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15370 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15372 Mask, Src0, Subtarget, DAG);
15374 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15375 SDValue RoundingMode = Op.getOperand(5);
15376 SDValue Sae = Op.getOperand(6);
15377 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15378 RoundingMode, Sae),
15379 Mask, Src0, Subtarget, DAG);
15381 case INTR_TYPE_2OP_MASK: {
15382 SDValue Src1 = Op.getOperand(1);
15383 SDValue Src2 = Op.getOperand(2);
15384 SDValue PassThru = Op.getOperand(3);
15385 SDValue Mask = Op.getOperand(4);
15386 // We specify 2 possible opcodes for intrinsics with rounding modes.
15387 // First, we check if the intrinsic may have non-default rounding mode,
15388 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15389 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15390 if (IntrWithRoundingModeOpcode != 0) {
15391 SDValue Rnd = Op.getOperand(5);
15392 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15393 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15394 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15395 dl, Op.getValueType(),
15397 Mask, PassThru, Subtarget, DAG);
15400 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15402 Mask, PassThru, Subtarget, DAG);
15404 case INTR_TYPE_2OP_MASK_RM: {
15405 SDValue Src1 = Op.getOperand(1);
15406 SDValue Src2 = Op.getOperand(2);
15407 SDValue PassThru = Op.getOperand(3);
15408 SDValue Mask = Op.getOperand(4);
15409 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15410 // First, we check if the intrinsic have rounding mode (6 operands),
15411 // if not, we set rounding mode to "current".
15413 if (Op.getNumOperands() == 6)
15414 Rnd = Op.getOperand(5);
15416 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15417 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15419 Mask, PassThru, Subtarget, DAG);
15421 case INTR_TYPE_3OP_MASK: {
15422 SDValue Src1 = Op.getOperand(1);
15423 SDValue Src2 = Op.getOperand(2);
15424 SDValue Src3 = Op.getOperand(3);
15425 SDValue PassThru = Op.getOperand(4);
15426 SDValue Mask = Op.getOperand(5);
15427 // We specify 2 possible opcodes for intrinsics with rounding modes.
15428 // First, we check if the intrinsic may have non-default rounding mode,
15429 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15430 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15431 if (IntrWithRoundingModeOpcode != 0) {
15432 SDValue Rnd = Op.getOperand(6);
15433 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15434 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15435 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15436 dl, Op.getValueType(),
15437 Src1, Src2, Src3, Rnd),
15438 Mask, PassThru, Subtarget, DAG);
15441 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15443 Mask, PassThru, Subtarget, DAG);
15445 case VPERM_3OP_MASKZ:
15446 case VPERM_3OP_MASK:
15449 case FMA_OP_MASK: {
15450 SDValue Src1 = Op.getOperand(1);
15451 SDValue Src2 = Op.getOperand(2);
15452 SDValue Src3 = Op.getOperand(3);
15453 SDValue Mask = Op.getOperand(4);
15454 EVT VT = Op.getValueType();
15455 SDValue PassThru = SDValue();
15457 // set PassThru element
15458 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15459 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15460 else if (IntrData->Type == FMA_OP_MASK3)
15465 // We specify 2 possible opcodes for intrinsics with rounding modes.
15466 // First, we check if the intrinsic may have non-default rounding mode,
15467 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15468 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15469 if (IntrWithRoundingModeOpcode != 0) {
15470 SDValue Rnd = Op.getOperand(5);
15471 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15472 X86::STATIC_ROUNDING::CUR_DIRECTION)
15473 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15474 dl, Op.getValueType(),
15475 Src1, Src2, Src3, Rnd),
15476 Mask, PassThru, Subtarget, DAG);
15478 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15479 dl, Op.getValueType(),
15481 Mask, PassThru, Subtarget, DAG);
15484 case CMP_MASK_CC: {
15485 // Comparison intrinsics with masks.
15486 // Example of transformation:
15487 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15488 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15490 // (v8i1 (insert_subvector undef,
15491 // (v2i1 (and (PCMPEQM %a, %b),
15492 // (extract_subvector
15493 // (v8i1 (bitcast %mask)), 0))), 0))))
15494 EVT VT = Op.getOperand(1).getValueType();
15495 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15496 VT.getVectorNumElements());
15497 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15498 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15499 Mask.getValueType().getSizeInBits());
15501 if (IntrData->Type == CMP_MASK_CC) {
15502 SDValue CC = Op.getOperand(3);
15503 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15504 // We specify 2 possible opcodes for intrinsics with rounding modes.
15505 // First, we check if the intrinsic may have non-default rounding mode,
15506 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15507 if (IntrData->Opc1 != 0) {
15508 SDValue Rnd = Op.getOperand(5);
15509 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15510 X86::STATIC_ROUNDING::CUR_DIRECTION)
15511 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15512 Op.getOperand(2), CC, Rnd);
15514 //default rounding mode
15516 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15517 Op.getOperand(2), CC);
15520 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15521 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15524 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15525 DAG.getTargetConstant(0, dl,
15528 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15529 DAG.getUNDEF(BitcastVT), CmpMask,
15530 DAG.getIntPtrConstant(0, dl));
15531 return DAG.getBitcast(Op.getValueType(), Res);
15533 case COMI: { // Comparison intrinsics
15534 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15535 SDValue LHS = Op.getOperand(1);
15536 SDValue RHS = Op.getOperand(2);
15537 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15538 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15539 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15540 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15541 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15542 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15545 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15546 Op.getOperand(1), Op.getOperand(2), DAG);
15548 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15549 Op.getSimpleValueType(),
15551 Op.getOperand(2), DAG),
15552 Op.getOperand(4), Op.getOperand(3), Subtarget,
15554 case COMPRESS_EXPAND_IN_REG: {
15555 SDValue Mask = Op.getOperand(3);
15556 SDValue DataToCompress = Op.getOperand(1);
15557 SDValue PassThru = Op.getOperand(2);
15558 if (isAllOnes(Mask)) // return data as is
15559 return Op.getOperand(1);
15561 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15563 Mask, PassThru, Subtarget, DAG);
15566 SDValue Mask = Op.getOperand(3);
15567 EVT VT = Op.getValueType();
15568 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15569 VT.getVectorNumElements());
15570 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15571 Mask.getValueType().getSizeInBits());
15573 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15574 DAG.getBitcast(BitcastVT, Mask),
15575 DAG.getIntPtrConstant(0, dl));
15576 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15585 default: return SDValue(); // Don't custom lower most intrinsics.
15587 case Intrinsic::x86_avx2_permd:
15588 case Intrinsic::x86_avx2_permps:
15589 // Operands intentionally swapped. Mask is last operand to intrinsic,
15590 // but second operand for node/instruction.
15591 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15592 Op.getOperand(2), Op.getOperand(1));
15594 // ptest and testp intrinsics. The intrinsic these come from are designed to
15595 // return an integer value, not just an instruction so lower it to the ptest
15596 // or testp pattern and a setcc for the result.
15597 case Intrinsic::x86_sse41_ptestz:
15598 case Intrinsic::x86_sse41_ptestc:
15599 case Intrinsic::x86_sse41_ptestnzc:
15600 case Intrinsic::x86_avx_ptestz_256:
15601 case Intrinsic::x86_avx_ptestc_256:
15602 case Intrinsic::x86_avx_ptestnzc_256:
15603 case Intrinsic::x86_avx_vtestz_ps:
15604 case Intrinsic::x86_avx_vtestc_ps:
15605 case Intrinsic::x86_avx_vtestnzc_ps:
15606 case Intrinsic::x86_avx_vtestz_pd:
15607 case Intrinsic::x86_avx_vtestc_pd:
15608 case Intrinsic::x86_avx_vtestnzc_pd:
15609 case Intrinsic::x86_avx_vtestz_ps_256:
15610 case Intrinsic::x86_avx_vtestc_ps_256:
15611 case Intrinsic::x86_avx_vtestnzc_ps_256:
15612 case Intrinsic::x86_avx_vtestz_pd_256:
15613 case Intrinsic::x86_avx_vtestc_pd_256:
15614 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15615 bool IsTestPacked = false;
15618 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15619 case Intrinsic::x86_avx_vtestz_ps:
15620 case Intrinsic::x86_avx_vtestz_pd:
15621 case Intrinsic::x86_avx_vtestz_ps_256:
15622 case Intrinsic::x86_avx_vtestz_pd_256:
15623 IsTestPacked = true; // Fallthrough
15624 case Intrinsic::x86_sse41_ptestz:
15625 case Intrinsic::x86_avx_ptestz_256:
15627 X86CC = X86::COND_E;
15629 case Intrinsic::x86_avx_vtestc_ps:
15630 case Intrinsic::x86_avx_vtestc_pd:
15631 case Intrinsic::x86_avx_vtestc_ps_256:
15632 case Intrinsic::x86_avx_vtestc_pd_256:
15633 IsTestPacked = true; // Fallthrough
15634 case Intrinsic::x86_sse41_ptestc:
15635 case Intrinsic::x86_avx_ptestc_256:
15637 X86CC = X86::COND_B;
15639 case Intrinsic::x86_avx_vtestnzc_ps:
15640 case Intrinsic::x86_avx_vtestnzc_pd:
15641 case Intrinsic::x86_avx_vtestnzc_ps_256:
15642 case Intrinsic::x86_avx_vtestnzc_pd_256:
15643 IsTestPacked = true; // Fallthrough
15644 case Intrinsic::x86_sse41_ptestnzc:
15645 case Intrinsic::x86_avx_ptestnzc_256:
15647 X86CC = X86::COND_A;
15651 SDValue LHS = Op.getOperand(1);
15652 SDValue RHS = Op.getOperand(2);
15653 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15654 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15655 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15656 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15657 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15659 case Intrinsic::x86_avx512_kortestz_w:
15660 case Intrinsic::x86_avx512_kortestc_w: {
15661 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15662 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15663 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15664 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15665 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15666 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15667 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15670 case Intrinsic::x86_sse42_pcmpistria128:
15671 case Intrinsic::x86_sse42_pcmpestria128:
15672 case Intrinsic::x86_sse42_pcmpistric128:
15673 case Intrinsic::x86_sse42_pcmpestric128:
15674 case Intrinsic::x86_sse42_pcmpistrio128:
15675 case Intrinsic::x86_sse42_pcmpestrio128:
15676 case Intrinsic::x86_sse42_pcmpistris128:
15677 case Intrinsic::x86_sse42_pcmpestris128:
15678 case Intrinsic::x86_sse42_pcmpistriz128:
15679 case Intrinsic::x86_sse42_pcmpestriz128: {
15683 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15684 case Intrinsic::x86_sse42_pcmpistria128:
15685 Opcode = X86ISD::PCMPISTRI;
15686 X86CC = X86::COND_A;
15688 case Intrinsic::x86_sse42_pcmpestria128:
15689 Opcode = X86ISD::PCMPESTRI;
15690 X86CC = X86::COND_A;
15692 case Intrinsic::x86_sse42_pcmpistric128:
15693 Opcode = X86ISD::PCMPISTRI;
15694 X86CC = X86::COND_B;
15696 case Intrinsic::x86_sse42_pcmpestric128:
15697 Opcode = X86ISD::PCMPESTRI;
15698 X86CC = X86::COND_B;
15700 case Intrinsic::x86_sse42_pcmpistrio128:
15701 Opcode = X86ISD::PCMPISTRI;
15702 X86CC = X86::COND_O;
15704 case Intrinsic::x86_sse42_pcmpestrio128:
15705 Opcode = X86ISD::PCMPESTRI;
15706 X86CC = X86::COND_O;
15708 case Intrinsic::x86_sse42_pcmpistris128:
15709 Opcode = X86ISD::PCMPISTRI;
15710 X86CC = X86::COND_S;
15712 case Intrinsic::x86_sse42_pcmpestris128:
15713 Opcode = X86ISD::PCMPESTRI;
15714 X86CC = X86::COND_S;
15716 case Intrinsic::x86_sse42_pcmpistriz128:
15717 Opcode = X86ISD::PCMPISTRI;
15718 X86CC = X86::COND_E;
15720 case Intrinsic::x86_sse42_pcmpestriz128:
15721 Opcode = X86ISD::PCMPESTRI;
15722 X86CC = X86::COND_E;
15725 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15726 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15727 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15728 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15729 DAG.getConstant(X86CC, dl, MVT::i8),
15730 SDValue(PCMP.getNode(), 1));
15731 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15734 case Intrinsic::x86_sse42_pcmpistri128:
15735 case Intrinsic::x86_sse42_pcmpestri128: {
15737 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15738 Opcode = X86ISD::PCMPISTRI;
15740 Opcode = X86ISD::PCMPESTRI;
15742 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15743 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15744 return DAG.getNode(Opcode, dl, VTs, NewOps);
15747 case Intrinsic::x86_seh_lsda: {
15748 // Compute the symbol for the LSDA. We know it'll get emitted later.
15749 MachineFunction &MF = DAG.getMachineFunction();
15750 SDValue Op1 = Op.getOperand(1);
15751 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15752 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15753 GlobalValue::getRealLinkageName(Fn->getName()));
15755 // Generate a simple absolute symbol reference. This intrinsic is only
15756 // supported on 32-bit Windows, which isn't PIC.
15757 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15758 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15761 case Intrinsic::x86_seh_recoverfp: {
15762 SDValue FnOp = Op.getOperand(1);
15763 SDValue IncomingFPOp = Op.getOperand(2);
15764 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15765 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15767 report_fatal_error(
15768 "llvm.x86.seh.recoverfp must take a function as the first argument");
15769 return recoverFramePointer(DAG, Fn, IncomingFPOp);
15772 case Intrinsic::localaddress: {
15773 // Returns one of the stack, base, or frame pointer registers, depending on
15774 // which is used to reference local variables.
15775 MachineFunction &MF = DAG.getMachineFunction();
15776 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15778 if (RegInfo->hasBasePointer(MF))
15779 Reg = RegInfo->getBaseRegister();
15780 else // This function handles the SP or FP case.
15781 Reg = RegInfo->getPtrSizedFrameRegister(MF);
15782 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15787 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15788 SDValue Src, SDValue Mask, SDValue Base,
15789 SDValue Index, SDValue ScaleOp, SDValue Chain,
15790 const X86Subtarget * Subtarget) {
15792 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15794 llvm_unreachable("Invalid scale type");
15795 unsigned ScaleVal = C->getZExtValue();
15796 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15797 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15799 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15800 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15801 Index.getSimpleValueType().getVectorNumElements());
15803 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15805 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15807 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15808 Mask.getValueType().getSizeInBits());
15810 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15811 // are extracted by EXTRACT_SUBVECTOR.
15812 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15813 DAG.getBitcast(BitcastVT, Mask),
15814 DAG.getIntPtrConstant(0, dl));
15816 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15817 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15818 SDValue Segment = DAG.getRegister(0, MVT::i32);
15819 if (Src.getOpcode() == ISD::UNDEF)
15820 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15821 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15822 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15823 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15824 return DAG.getMergeValues(RetOps, dl);
15827 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15828 SDValue Src, SDValue Mask, SDValue Base,
15829 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15831 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15833 llvm_unreachable("Invalid scale type");
15834 unsigned ScaleVal = C->getZExtValue();
15835 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15836 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15838 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15839 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15840 SDValue Segment = DAG.getRegister(0, MVT::i32);
15841 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15842 Index.getSimpleValueType().getVectorNumElements());
15844 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15846 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15848 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15849 Mask.getValueType().getSizeInBits());
15851 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15852 // are extracted by EXTRACT_SUBVECTOR.
15853 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15854 DAG.getBitcast(BitcastVT, Mask),
15855 DAG.getIntPtrConstant(0, dl));
15857 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15858 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15859 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15860 return SDValue(Res, 1);
15863 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15864 SDValue Mask, SDValue Base, SDValue Index,
15865 SDValue ScaleOp, SDValue Chain) {
15867 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15868 assert(C && "Invalid scale type");
15869 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15870 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15871 SDValue Segment = DAG.getRegister(0, MVT::i32);
15873 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15875 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15877 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15879 MaskInReg = DAG.getBitcast(MaskVT, Mask);
15880 //SDVTList VTs = DAG.getVTList(MVT::Other);
15881 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15882 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15883 return SDValue(Res, 0);
15886 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15887 // read performance monitor counters (x86_rdpmc).
15888 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15889 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15890 SmallVectorImpl<SDValue> &Results) {
15891 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15892 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15895 // The ECX register is used to select the index of the performance counter
15897 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15899 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15901 // Reads the content of a 64-bit performance counter and returns it in the
15902 // registers EDX:EAX.
15903 if (Subtarget->is64Bit()) {
15904 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15905 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15908 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15909 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15912 Chain = HI.getValue(1);
15914 if (Subtarget->is64Bit()) {
15915 // The EAX register is loaded with the low-order 32 bits. The EDX register
15916 // is loaded with the supported high-order bits of the counter.
15917 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15918 DAG.getConstant(32, DL, MVT::i8));
15919 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15920 Results.push_back(Chain);
15924 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15925 SDValue Ops[] = { LO, HI };
15926 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15927 Results.push_back(Pair);
15928 Results.push_back(Chain);
15931 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15932 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15933 // also used to custom lower READCYCLECOUNTER nodes.
15934 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15935 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15936 SmallVectorImpl<SDValue> &Results) {
15937 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15938 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15941 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15942 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15943 // and the EAX register is loaded with the low-order 32 bits.
15944 if (Subtarget->is64Bit()) {
15945 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15946 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15949 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15950 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15953 SDValue Chain = HI.getValue(1);
15955 if (Opcode == X86ISD::RDTSCP_DAG) {
15956 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15958 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15959 // the ECX register. Add 'ecx' explicitly to the chain.
15960 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15962 // Explicitly store the content of ECX at the location passed in input
15963 // to the 'rdtscp' intrinsic.
15964 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15965 MachinePointerInfo(), false, false, 0);
15968 if (Subtarget->is64Bit()) {
15969 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15970 // the EAX register is loaded with the low-order 32 bits.
15971 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15972 DAG.getConstant(32, DL, MVT::i8));
15973 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15974 Results.push_back(Chain);
15978 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15979 SDValue Ops[] = { LO, HI };
15980 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15981 Results.push_back(Pair);
15982 Results.push_back(Chain);
15985 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15986 SelectionDAG &DAG) {
15987 SmallVector<SDValue, 2> Results;
15989 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15991 return DAG.getMergeValues(Results, DL);
15994 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
15995 SelectionDAG &DAG) {
15996 MachineFunction &MF = DAG.getMachineFunction();
15997 const Function *Fn = MF.getFunction();
15999 SDValue Chain = Op.getOperand(0);
16001 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16002 "using llvm.x86.seh.restoreframe requires a frame pointer");
16004 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16005 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16007 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16008 unsigned FrameReg =
16009 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16010 unsigned SPReg = RegInfo->getStackRegister();
16011 unsigned SlotSize = RegInfo->getSlotSize();
16013 // Get incoming EBP.
16014 SDValue IncomingEBP =
16015 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16017 // SP is saved in the first field of every registration node, so load
16018 // [EBP-RegNodeSize] into SP.
16019 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16020 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16021 DAG.getConstant(-RegNodeSize, dl, VT));
16023 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16024 false, VT.getScalarSizeInBits() / 8);
16025 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16027 if (!RegInfo->needsStackRealignment(MF)) {
16028 // Adjust EBP to point back to the original frame position.
16029 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16030 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16032 assert(RegInfo->hasBasePointer(MF) &&
16033 "functions with Win32 EH must use frame or base pointer register");
16035 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16036 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16037 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16039 // Reload the spilled EBP value, now that the stack and base pointers are
16041 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16042 X86FI->setHasSEHFramePtrSave(true);
16043 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16044 X86FI->setSEHFramePtrSaveIndex(FI);
16045 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16046 MachinePointerInfo(), false, false, false,
16047 VT.getScalarSizeInBits() / 8);
16048 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16054 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16055 SelectionDAG &DAG) {
16056 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16058 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16060 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16061 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16066 switch(IntrData->Type) {
16068 llvm_unreachable("Unknown Intrinsic Type");
16072 // Emit the node with the right value type.
16073 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16074 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16076 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16077 // Otherwise return the value from Rand, which is always 0, casted to i32.
16078 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16079 DAG.getConstant(1, dl, Op->getValueType(1)),
16080 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16081 SDValue(Result.getNode(), 1) };
16082 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16083 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16086 // Return { result, isValid, chain }.
16087 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16088 SDValue(Result.getNode(), 2));
16091 //gather(v1, mask, index, base, scale);
16092 SDValue Chain = Op.getOperand(0);
16093 SDValue Src = Op.getOperand(2);
16094 SDValue Base = Op.getOperand(3);
16095 SDValue Index = Op.getOperand(4);
16096 SDValue Mask = Op.getOperand(5);
16097 SDValue Scale = Op.getOperand(6);
16098 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16102 //scatter(base, mask, index, v1, scale);
16103 SDValue Chain = Op.getOperand(0);
16104 SDValue Base = Op.getOperand(2);
16105 SDValue Mask = Op.getOperand(3);
16106 SDValue Index = Op.getOperand(4);
16107 SDValue Src = Op.getOperand(5);
16108 SDValue Scale = Op.getOperand(6);
16109 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16113 SDValue Hint = Op.getOperand(6);
16114 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16115 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16116 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16117 SDValue Chain = Op.getOperand(0);
16118 SDValue Mask = Op.getOperand(2);
16119 SDValue Index = Op.getOperand(3);
16120 SDValue Base = Op.getOperand(4);
16121 SDValue Scale = Op.getOperand(5);
16122 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16124 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16126 SmallVector<SDValue, 2> Results;
16127 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16129 return DAG.getMergeValues(Results, dl);
16131 // Read Performance Monitoring Counters.
16133 SmallVector<SDValue, 2> Results;
16134 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16135 return DAG.getMergeValues(Results, dl);
16137 // XTEST intrinsics.
16139 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16140 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16141 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16142 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16144 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16145 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16146 Ret, SDValue(InTrans.getNode(), 1));
16150 SmallVector<SDValue, 2> Results;
16151 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16152 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16153 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16154 DAG.getConstant(-1, dl, MVT::i8));
16155 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16156 Op.getOperand(4), GenCF.getValue(1));
16157 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16158 Op.getOperand(5), MachinePointerInfo(),
16160 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16161 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16163 Results.push_back(SetCC);
16164 Results.push_back(Store);
16165 return DAG.getMergeValues(Results, dl);
16167 case COMPRESS_TO_MEM: {
16169 SDValue Mask = Op.getOperand(4);
16170 SDValue DataToCompress = Op.getOperand(3);
16171 SDValue Addr = Op.getOperand(2);
16172 SDValue Chain = Op.getOperand(0);
16174 EVT VT = DataToCompress.getValueType();
16175 if (isAllOnes(Mask)) // return just a store
16176 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16177 MachinePointerInfo(), false, false,
16178 VT.getScalarSizeInBits()/8);
16180 SDValue Compressed =
16181 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16182 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16183 return DAG.getStore(Chain, dl, Compressed, Addr,
16184 MachinePointerInfo(), false, false,
16185 VT.getScalarSizeInBits()/8);
16187 case EXPAND_FROM_MEM: {
16189 SDValue Mask = Op.getOperand(4);
16190 SDValue PassThru = Op.getOperand(3);
16191 SDValue Addr = Op.getOperand(2);
16192 SDValue Chain = Op.getOperand(0);
16193 EVT VT = Op.getValueType();
16195 if (isAllOnes(Mask)) // return just a load
16196 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16197 false, VT.getScalarSizeInBits()/8);
16199 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16200 false, false, false,
16201 VT.getScalarSizeInBits()/8);
16203 SDValue Results[] = {
16204 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16205 Mask, PassThru, Subtarget, DAG), Chain};
16206 return DAG.getMergeValues(Results, dl);
16211 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16212 SelectionDAG &DAG) const {
16213 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16214 MFI->setReturnAddressIsTaken(true);
16216 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16219 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16221 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16224 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16225 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16226 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16227 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16228 DAG.getNode(ISD::ADD, dl, PtrVT,
16229 FrameAddr, Offset),
16230 MachinePointerInfo(), false, false, false, 0);
16233 // Just load the return address.
16234 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16235 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16236 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16239 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16240 MachineFunction &MF = DAG.getMachineFunction();
16241 MachineFrameInfo *MFI = MF.getFrameInfo();
16242 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16243 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16244 EVT VT = Op.getValueType();
16246 MFI->setFrameAddressIsTaken(true);
16248 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16249 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16250 // is not possible to crawl up the stack without looking at the unwind codes
16252 int FrameAddrIndex = FuncInfo->getFAIndex();
16253 if (!FrameAddrIndex) {
16254 // Set up a frame object for the return address.
16255 unsigned SlotSize = RegInfo->getSlotSize();
16256 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16257 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16258 FuncInfo->setFAIndex(FrameAddrIndex);
16260 return DAG.getFrameIndex(FrameAddrIndex, VT);
16263 unsigned FrameReg =
16264 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16265 SDLoc dl(Op); // FIXME probably not meaningful
16266 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16267 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16268 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16269 "Invalid Frame Register!");
16270 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16272 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16273 MachinePointerInfo(),
16274 false, false, false, 0);
16278 // FIXME? Maybe this could be a TableGen attribute on some registers and
16279 // this table could be generated automatically from RegInfo.
16280 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16281 SelectionDAG &DAG) const {
16282 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16283 const MachineFunction &MF = DAG.getMachineFunction();
16285 unsigned Reg = StringSwitch<unsigned>(RegName)
16286 .Case("esp", X86::ESP)
16287 .Case("rsp", X86::RSP)
16288 .Case("ebp", X86::EBP)
16289 .Case("rbp", X86::RBP)
16292 if (Reg == X86::EBP || Reg == X86::RBP) {
16293 if (!TFI.hasFP(MF))
16294 report_fatal_error("register " + StringRef(RegName) +
16295 " is allocatable: function has no frame pointer");
16298 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16299 unsigned FrameReg =
16300 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16301 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16302 "Invalid Frame Register!");
16310 report_fatal_error("Invalid register name global variable");
16313 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16314 SelectionDAG &DAG) const {
16315 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16316 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16319 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16320 SDValue Chain = Op.getOperand(0);
16321 SDValue Offset = Op.getOperand(1);
16322 SDValue Handler = Op.getOperand(2);
16325 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16326 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16327 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16328 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16329 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16330 "Invalid Frame Register!");
16331 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16332 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16334 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16335 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16337 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16338 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16340 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16342 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16343 DAG.getRegister(StoreAddrReg, PtrVT));
16346 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16347 SelectionDAG &DAG) const {
16349 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16350 DAG.getVTList(MVT::i32, MVT::Other),
16351 Op.getOperand(0), Op.getOperand(1));
16354 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16355 SelectionDAG &DAG) const {
16357 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16358 Op.getOperand(0), Op.getOperand(1));
16361 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16362 return Op.getOperand(0);
16365 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16366 SelectionDAG &DAG) const {
16367 SDValue Root = Op.getOperand(0);
16368 SDValue Trmp = Op.getOperand(1); // trampoline
16369 SDValue FPtr = Op.getOperand(2); // nested function
16370 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16373 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16374 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16376 if (Subtarget->is64Bit()) {
16377 SDValue OutChains[6];
16379 // Large code-model.
16380 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16381 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16383 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16384 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16386 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16388 // Load the pointer to the nested function into R11.
16389 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16390 SDValue Addr = Trmp;
16391 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16392 Addr, MachinePointerInfo(TrmpAddr),
16395 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16396 DAG.getConstant(2, dl, MVT::i64));
16397 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16398 MachinePointerInfo(TrmpAddr, 2),
16401 // Load the 'nest' parameter value into R10.
16402 // R10 is specified in X86CallingConv.td
16403 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16404 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16405 DAG.getConstant(10, dl, MVT::i64));
16406 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16407 Addr, MachinePointerInfo(TrmpAddr, 10),
16410 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16411 DAG.getConstant(12, dl, MVT::i64));
16412 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16413 MachinePointerInfo(TrmpAddr, 12),
16416 // Jump to the nested function.
16417 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16418 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16419 DAG.getConstant(20, dl, MVT::i64));
16420 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16421 Addr, MachinePointerInfo(TrmpAddr, 20),
16424 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16425 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16426 DAG.getConstant(22, dl, MVT::i64));
16427 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16428 Addr, MachinePointerInfo(TrmpAddr, 22),
16431 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16433 const Function *Func =
16434 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16435 CallingConv::ID CC = Func->getCallingConv();
16440 llvm_unreachable("Unsupported calling convention");
16441 case CallingConv::C:
16442 case CallingConv::X86_StdCall: {
16443 // Pass 'nest' parameter in ECX.
16444 // Must be kept in sync with X86CallingConv.td
16445 NestReg = X86::ECX;
16447 // Check that ECX wasn't needed by an 'inreg' parameter.
16448 FunctionType *FTy = Func->getFunctionType();
16449 const AttributeSet &Attrs = Func->getAttributes();
16451 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16452 unsigned InRegCount = 0;
16455 for (FunctionType::param_iterator I = FTy->param_begin(),
16456 E = FTy->param_end(); I != E; ++I, ++Idx)
16457 if (Attrs.hasAttribute(Idx, Attribute::InReg))
16458 // FIXME: should only count parameters that are lowered to integers.
16459 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16461 if (InRegCount > 2) {
16462 report_fatal_error("Nest register in use - reduce number of inreg"
16468 case CallingConv::X86_FastCall:
16469 case CallingConv::X86_ThisCall:
16470 case CallingConv::Fast:
16471 // Pass 'nest' parameter in EAX.
16472 // Must be kept in sync with X86CallingConv.td
16473 NestReg = X86::EAX;
16477 SDValue OutChains[4];
16478 SDValue Addr, Disp;
16480 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16481 DAG.getConstant(10, dl, MVT::i32));
16482 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16484 // This is storing the opcode for MOV32ri.
16485 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16486 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16487 OutChains[0] = DAG.getStore(Root, dl,
16488 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16489 Trmp, MachinePointerInfo(TrmpAddr),
16492 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16493 DAG.getConstant(1, dl, MVT::i32));
16494 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16495 MachinePointerInfo(TrmpAddr, 1),
16498 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16499 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16500 DAG.getConstant(5, dl, MVT::i32));
16501 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16502 Addr, MachinePointerInfo(TrmpAddr, 5),
16505 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16506 DAG.getConstant(6, dl, MVT::i32));
16507 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16508 MachinePointerInfo(TrmpAddr, 6),
16511 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16515 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16516 SelectionDAG &DAG) const {
16518 The rounding mode is in bits 11:10 of FPSR, and has the following
16520 00 Round to nearest
16525 FLT_ROUNDS, on the other hand, expects the following:
16532 To perform the conversion, we do:
16533 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16536 MachineFunction &MF = DAG.getMachineFunction();
16537 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16538 unsigned StackAlignment = TFI.getStackAlignment();
16539 MVT VT = Op.getSimpleValueType();
16542 // Save FP Control Word to stack slot
16543 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16544 SDValue StackSlot =
16545 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16547 MachineMemOperand *MMO =
16548 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16549 MachineMemOperand::MOStore, 2, 2);
16551 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16552 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16553 DAG.getVTList(MVT::Other),
16554 Ops, MVT::i16, MMO);
16556 // Load FP Control Word from stack slot
16557 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16558 MachinePointerInfo(), false, false, false, 0);
16560 // Transform as necessary
16562 DAG.getNode(ISD::SRL, DL, MVT::i16,
16563 DAG.getNode(ISD::AND, DL, MVT::i16,
16564 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16565 DAG.getConstant(11, DL, MVT::i8));
16567 DAG.getNode(ISD::SRL, DL, MVT::i16,
16568 DAG.getNode(ISD::AND, DL, MVT::i16,
16569 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16570 DAG.getConstant(9, DL, MVT::i8));
16573 DAG.getNode(ISD::AND, DL, MVT::i16,
16574 DAG.getNode(ISD::ADD, DL, MVT::i16,
16575 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16576 DAG.getConstant(1, DL, MVT::i16)),
16577 DAG.getConstant(3, DL, MVT::i16));
16579 return DAG.getNode((VT.getSizeInBits() < 16 ?
16580 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16583 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16584 MVT VT = Op.getSimpleValueType();
16586 unsigned NumBits = VT.getSizeInBits();
16589 Op = Op.getOperand(0);
16590 if (VT == MVT::i8) {
16591 // Zero extend to i32 since there is not an i8 bsr.
16593 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16596 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16597 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16598 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16600 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16603 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16604 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16607 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16609 // Finally xor with NumBits-1.
16610 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16611 DAG.getConstant(NumBits - 1, dl, OpVT));
16614 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16618 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16619 MVT VT = Op.getSimpleValueType();
16621 unsigned NumBits = VT.getSizeInBits();
16624 Op = Op.getOperand(0);
16625 if (VT == MVT::i8) {
16626 // Zero extend to i32 since there is not an i8 bsr.
16628 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16631 // Issue a bsr (scan bits in reverse).
16632 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16633 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16635 // And xor with NumBits-1.
16636 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16637 DAG.getConstant(NumBits - 1, dl, OpVT));
16640 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16644 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16645 MVT VT = Op.getSimpleValueType();
16646 unsigned NumBits = VT.getSizeInBits();
16648 Op = Op.getOperand(0);
16650 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16651 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16652 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16654 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16657 DAG.getConstant(NumBits, dl, VT),
16658 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16661 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16664 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16665 // ones, and then concatenate the result back.
16666 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16667 MVT VT = Op.getSimpleValueType();
16669 assert(VT.is256BitVector() && VT.isInteger() &&
16670 "Unsupported value type for operation");
16672 unsigned NumElems = VT.getVectorNumElements();
16675 // Extract the LHS vectors
16676 SDValue LHS = Op.getOperand(0);
16677 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16678 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16680 // Extract the RHS vectors
16681 SDValue RHS = Op.getOperand(1);
16682 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16683 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16685 MVT EltVT = VT.getVectorElementType();
16686 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16688 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16689 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16690 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16693 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16694 if (Op.getValueType() == MVT::i1)
16695 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16696 Op.getOperand(0), Op.getOperand(1));
16697 assert(Op.getSimpleValueType().is256BitVector() &&
16698 Op.getSimpleValueType().isInteger() &&
16699 "Only handle AVX 256-bit vector integer operation");
16700 return Lower256IntArith(Op, DAG);
16703 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16704 if (Op.getValueType() == MVT::i1)
16705 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16706 Op.getOperand(0), Op.getOperand(1));
16707 assert(Op.getSimpleValueType().is256BitVector() &&
16708 Op.getSimpleValueType().isInteger() &&
16709 "Only handle AVX 256-bit vector integer operation");
16710 return Lower256IntArith(Op, DAG);
16713 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16714 SelectionDAG &DAG) {
16716 MVT VT = Op.getSimpleValueType();
16719 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16721 // Decompose 256-bit ops into smaller 128-bit ops.
16722 if (VT.is256BitVector() && !Subtarget->hasInt256())
16723 return Lower256IntArith(Op, DAG);
16725 SDValue A = Op.getOperand(0);
16726 SDValue B = Op.getOperand(1);
16728 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16729 // pairs, multiply and truncate.
16730 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16731 if (Subtarget->hasInt256()) {
16732 if (VT == MVT::v32i8) {
16733 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16734 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16735 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16736 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16737 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16738 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16739 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16740 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16741 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16742 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16745 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16746 return DAG.getNode(
16747 ISD::TRUNCATE, dl, VT,
16748 DAG.getNode(ISD::MUL, dl, ExVT,
16749 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16750 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16753 assert(VT == MVT::v16i8 &&
16754 "Pre-AVX2 support only supports v16i8 multiplication");
16755 MVT ExVT = MVT::v8i16;
16757 // Extract the lo parts and sign extend to i16
16759 if (Subtarget->hasSSE41()) {
16760 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16761 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16763 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16764 -1, 4, -1, 5, -1, 6, -1, 7};
16765 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16766 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16767 ALo = DAG.getBitcast(ExVT, ALo);
16768 BLo = DAG.getBitcast(ExVT, BLo);
16769 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16770 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16773 // Extract the hi parts and sign extend to i16
16775 if (Subtarget->hasSSE41()) {
16776 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16777 -1, -1, -1, -1, -1, -1, -1, -1};
16778 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16779 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16780 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16781 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16783 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16784 -1, 12, -1, 13, -1, 14, -1, 15};
16785 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16786 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16787 AHi = DAG.getBitcast(ExVT, AHi);
16788 BHi = DAG.getBitcast(ExVT, BHi);
16789 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16790 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16793 // Multiply, mask the lower 8bits of the lo/hi results and pack
16794 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16795 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16796 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16797 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16798 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16801 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16802 if (VT == MVT::v4i32) {
16803 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16804 "Should not custom lower when pmuldq is available!");
16806 // Extract the odd parts.
16807 static const int UnpackMask[] = { 1, -1, 3, -1 };
16808 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16809 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16811 // Multiply the even parts.
16812 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16813 // Now multiply odd parts.
16814 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16816 Evens = DAG.getBitcast(VT, Evens);
16817 Odds = DAG.getBitcast(VT, Odds);
16819 // Merge the two vectors back together with a shuffle. This expands into 2
16821 static const int ShufMask[] = { 0, 4, 2, 6 };
16822 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16825 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16826 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16828 // Ahi = psrlqi(a, 32);
16829 // Bhi = psrlqi(b, 32);
16831 // AloBlo = pmuludq(a, b);
16832 // AloBhi = pmuludq(a, Bhi);
16833 // AhiBlo = pmuludq(Ahi, b);
16835 // AloBhi = psllqi(AloBhi, 32);
16836 // AhiBlo = psllqi(AhiBlo, 32);
16837 // return AloBlo + AloBhi + AhiBlo;
16839 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16840 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16842 SDValue AhiBlo = Ahi;
16843 SDValue AloBhi = Bhi;
16844 // Bit cast to 32-bit vectors for MULUDQ
16845 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16846 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16847 A = DAG.getBitcast(MulVT, A);
16848 B = DAG.getBitcast(MulVT, B);
16849 Ahi = DAG.getBitcast(MulVT, Ahi);
16850 Bhi = DAG.getBitcast(MulVT, Bhi);
16852 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16853 // After shifting right const values the result may be all-zero.
16854 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16855 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16856 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16858 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16859 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16860 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16863 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16864 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16867 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16868 assert(Subtarget->isTargetWin64() && "Unexpected target");
16869 EVT VT = Op.getValueType();
16870 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16871 "Unexpected return type for lowering");
16875 switch (Op->getOpcode()) {
16876 default: llvm_unreachable("Unexpected request for libcall!");
16877 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16878 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16879 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16880 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16881 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16882 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16886 SDValue InChain = DAG.getEntryNode();
16888 TargetLowering::ArgListTy Args;
16889 TargetLowering::ArgListEntry Entry;
16890 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16891 EVT ArgVT = Op->getOperand(i).getValueType();
16892 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16893 "Unexpected argument type for lowering");
16894 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16895 Entry.Node = StackPtr;
16896 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16898 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16899 Entry.Ty = PointerType::get(ArgTy,0);
16900 Entry.isSExt = false;
16901 Entry.isZExt = false;
16902 Args.push_back(Entry);
16905 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16906 getPointerTy(DAG.getDataLayout()));
16908 TargetLowering::CallLoweringInfo CLI(DAG);
16909 CLI.setDebugLoc(dl).setChain(InChain)
16910 .setCallee(getLibcallCallingConv(LC),
16911 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16912 Callee, std::move(Args), 0)
16913 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16915 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16916 return DAG.getBitcast(VT, CallInfo.first);
16919 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16920 SelectionDAG &DAG) {
16921 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16922 EVT VT = Op0.getValueType();
16925 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16926 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16928 // PMULxD operations multiply each even value (starting at 0) of LHS with
16929 // the related value of RHS and produce a widen result.
16930 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16931 // => <2 x i64> <ae|cg>
16933 // In other word, to have all the results, we need to perform two PMULxD:
16934 // 1. one with the even values.
16935 // 2. one with the odd values.
16936 // To achieve #2, with need to place the odd values at an even position.
16938 // Place the odd value at an even position (basically, shift all values 1
16939 // step to the left):
16940 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16941 // <a|b|c|d> => <b|undef|d|undef>
16942 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16943 // <e|f|g|h> => <f|undef|h|undef>
16944 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16946 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16948 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16949 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16951 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16952 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16953 // => <2 x i64> <ae|cg>
16954 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16955 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16956 // => <2 x i64> <bf|dh>
16957 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16959 // Shuffle it back into the right order.
16960 SDValue Highs, Lows;
16961 if (VT == MVT::v8i32) {
16962 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16963 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16964 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16965 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16967 const int HighMask[] = {1, 5, 3, 7};
16968 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16969 const int LowMask[] = {0, 4, 2, 6};
16970 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16973 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16974 // unsigned multiply.
16975 if (IsSigned && !Subtarget->hasSSE41()) {
16976 SDValue ShAmt = DAG.getConstant(
16978 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
16979 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16980 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16981 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16982 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16984 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16985 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16988 // The first result of MUL_LOHI is actually the low value, followed by the
16990 SDValue Ops[] = {Lows, Highs};
16991 return DAG.getMergeValues(Ops, dl);
16994 // Return true if the requred (according to Opcode) shift-imm form is natively
16995 // supported by the Subtarget
16996 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16998 if (VT.getScalarSizeInBits() < 16)
17001 if (VT.is512BitVector() &&
17002 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17005 bool LShift = VT.is128BitVector() ||
17006 (VT.is256BitVector() && Subtarget->hasInt256());
17008 bool AShift = LShift && (Subtarget->hasVLX() ||
17009 (VT != MVT::v2i64 && VT != MVT::v4i64));
17010 return (Opcode == ISD::SRA) ? AShift : LShift;
17013 // The shift amount is a variable, but it is the same for all vector lanes.
17014 // These instrcutions are defined together with shift-immediate.
17016 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17018 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17021 // Return true if the requred (according to Opcode) variable-shift form is
17022 // natively supported by the Subtarget
17023 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17026 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17029 // vXi16 supported only on AVX-512, BWI
17030 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17033 if (VT.is512BitVector() || Subtarget->hasVLX())
17036 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17037 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17038 return (Opcode == ISD::SRA) ? AShift : LShift;
17041 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17042 const X86Subtarget *Subtarget) {
17043 MVT VT = Op.getSimpleValueType();
17045 SDValue R = Op.getOperand(0);
17046 SDValue Amt = Op.getOperand(1);
17048 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17049 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17051 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17052 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17053 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17054 SDValue Ex = DAG.getBitcast(ExVT, R);
17056 if (ShiftAmt >= 32) {
17057 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17059 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17060 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17061 ShiftAmt - 32, DAG);
17062 if (VT == MVT::v2i64)
17063 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17064 if (VT == MVT::v4i64)
17065 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17066 {9, 1, 11, 3, 13, 5, 15, 7});
17068 // SRA upper i32, SHL whole i64 and select lower i32.
17069 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17072 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17073 Lower = DAG.getBitcast(ExVT, Lower);
17074 if (VT == MVT::v2i64)
17075 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17076 if (VT == MVT::v4i64)
17077 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17078 {8, 1, 10, 3, 12, 5, 14, 7});
17080 return DAG.getBitcast(VT, Ex);
17083 // Optimize shl/srl/sra with constant shift amount.
17084 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17085 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17086 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17088 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17089 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17091 // i64 SRA needs to be performed as partial shifts.
17092 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17093 Op.getOpcode() == ISD::SRA)
17094 return ArithmeticShiftRight64(ShiftAmt);
17096 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17097 unsigned NumElts = VT.getVectorNumElements();
17098 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17100 if (Op.getOpcode() == ISD::SHL) {
17101 // Simple i8 add case
17103 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17105 // Make a large shift.
17106 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17108 SHL = DAG.getBitcast(VT, SHL);
17109 // Zero out the rightmost bits.
17110 SmallVector<SDValue, 32> V(
17111 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17112 return DAG.getNode(ISD::AND, dl, VT, SHL,
17113 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17115 if (Op.getOpcode() == ISD::SRL) {
17116 // Make a large shift.
17117 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17119 SRL = DAG.getBitcast(VT, SRL);
17120 // Zero out the leftmost bits.
17121 SmallVector<SDValue, 32> V(
17122 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17123 return DAG.getNode(ISD::AND, dl, VT, SRL,
17124 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17126 if (Op.getOpcode() == ISD::SRA) {
17127 if (ShiftAmt == 7) {
17128 // R s>> 7 === R s< 0
17129 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17130 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17133 // R s>> a === ((R u>> a) ^ m) - m
17134 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17135 SmallVector<SDValue, 32> V(NumElts,
17136 DAG.getConstant(128 >> ShiftAmt, dl,
17138 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17139 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17140 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17143 llvm_unreachable("Unknown shift opcode.");
17148 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17149 if (!Subtarget->is64Bit() &&
17150 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17151 Amt.getOpcode() == ISD::BITCAST &&
17152 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17153 Amt = Amt.getOperand(0);
17154 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17155 VT.getVectorNumElements();
17156 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17157 uint64_t ShiftAmt = 0;
17158 for (unsigned i = 0; i != Ratio; ++i) {
17159 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17163 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17165 // Check remaining shift amounts.
17166 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17167 uint64_t ShAmt = 0;
17168 for (unsigned j = 0; j != Ratio; ++j) {
17169 ConstantSDNode *C =
17170 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17174 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17176 if (ShAmt != ShiftAmt)
17180 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17181 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17183 if (Op.getOpcode() == ISD::SRA)
17184 return ArithmeticShiftRight64(ShiftAmt);
17190 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17191 const X86Subtarget* Subtarget) {
17192 MVT VT = Op.getSimpleValueType();
17194 SDValue R = Op.getOperand(0);
17195 SDValue Amt = Op.getOperand(1);
17197 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17198 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17200 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17201 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17203 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17205 EVT EltVT = VT.getVectorElementType();
17207 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17208 // Check if this build_vector node is doing a splat.
17209 // If so, then set BaseShAmt equal to the splat value.
17210 BaseShAmt = BV->getSplatValue();
17211 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17212 BaseShAmt = SDValue();
17214 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17215 Amt = Amt.getOperand(0);
17217 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17218 if (SVN && SVN->isSplat()) {
17219 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17220 SDValue InVec = Amt.getOperand(0);
17221 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17222 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17223 "Unexpected shuffle index found!");
17224 BaseShAmt = InVec.getOperand(SplatIdx);
17225 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17226 if (ConstantSDNode *C =
17227 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17228 if (C->getZExtValue() == SplatIdx)
17229 BaseShAmt = InVec.getOperand(1);
17234 // Avoid introducing an extract element from a shuffle.
17235 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17236 DAG.getIntPtrConstant(SplatIdx, dl));
17240 if (BaseShAmt.getNode()) {
17241 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17242 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17243 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17244 else if (EltVT.bitsLT(MVT::i32))
17245 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17247 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17251 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17252 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17253 Amt.getOpcode() == ISD::BITCAST &&
17254 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17255 Amt = Amt.getOperand(0);
17256 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17257 VT.getVectorNumElements();
17258 std::vector<SDValue> Vals(Ratio);
17259 for (unsigned i = 0; i != Ratio; ++i)
17260 Vals[i] = Amt.getOperand(i);
17261 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17262 for (unsigned j = 0; j != Ratio; ++j)
17263 if (Vals[j] != Amt.getOperand(i + j))
17267 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17268 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17273 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17274 SelectionDAG &DAG) {
17275 MVT VT = Op.getSimpleValueType();
17277 SDValue R = Op.getOperand(0);
17278 SDValue Amt = Op.getOperand(1);
17280 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17281 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17283 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17286 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17289 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17292 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17293 // shifts per-lane and then shuffle the partial results back together.
17294 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17295 // Splat the shift amounts so the scalar shifts above will catch it.
17296 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17297 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17298 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17299 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17300 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17303 // If possible, lower this packed shift into a vector multiply instead of
17304 // expanding it into a sequence of scalar shifts.
17305 // Do this only if the vector shift count is a constant build_vector.
17306 if (Op.getOpcode() == ISD::SHL &&
17307 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17308 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17309 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17310 SmallVector<SDValue, 8> Elts;
17311 EVT SVT = VT.getScalarType();
17312 unsigned SVTBits = SVT.getSizeInBits();
17313 const APInt &One = APInt(SVTBits, 1);
17314 unsigned NumElems = VT.getVectorNumElements();
17316 for (unsigned i=0; i !=NumElems; ++i) {
17317 SDValue Op = Amt->getOperand(i);
17318 if (Op->getOpcode() == ISD::UNDEF) {
17319 Elts.push_back(Op);
17323 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17324 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17325 uint64_t ShAmt = C.getZExtValue();
17326 if (ShAmt >= SVTBits) {
17327 Elts.push_back(DAG.getUNDEF(SVT));
17330 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17332 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17333 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17336 // Lower SHL with variable shift amount.
17337 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17338 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17340 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17341 DAG.getConstant(0x3f800000U, dl, VT));
17342 Op = DAG.getBitcast(MVT::v4f32, Op);
17343 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17344 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17347 // If possible, lower this shift as a sequence of two shifts by
17348 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17350 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17352 // Could be rewritten as:
17353 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17355 // The advantage is that the two shifts from the example would be
17356 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17357 // the vector shift into four scalar shifts plus four pairs of vector
17359 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17360 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17361 unsigned TargetOpcode = X86ISD::MOVSS;
17362 bool CanBeSimplified;
17363 // The splat value for the first packed shift (the 'X' from the example).
17364 SDValue Amt1 = Amt->getOperand(0);
17365 // The splat value for the second packed shift (the 'Y' from the example).
17366 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17367 Amt->getOperand(2);
17369 // See if it is possible to replace this node with a sequence of
17370 // two shifts followed by a MOVSS/MOVSD
17371 if (VT == MVT::v4i32) {
17372 // Check if it is legal to use a MOVSS.
17373 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17374 Amt2 == Amt->getOperand(3);
17375 if (!CanBeSimplified) {
17376 // Otherwise, check if we can still simplify this node using a MOVSD.
17377 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17378 Amt->getOperand(2) == Amt->getOperand(3);
17379 TargetOpcode = X86ISD::MOVSD;
17380 Amt2 = Amt->getOperand(2);
17383 // Do similar checks for the case where the machine value type
17385 CanBeSimplified = Amt1 == Amt->getOperand(1);
17386 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17387 CanBeSimplified = Amt2 == Amt->getOperand(i);
17389 if (!CanBeSimplified) {
17390 TargetOpcode = X86ISD::MOVSD;
17391 CanBeSimplified = true;
17392 Amt2 = Amt->getOperand(4);
17393 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17394 CanBeSimplified = Amt1 == Amt->getOperand(i);
17395 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17396 CanBeSimplified = Amt2 == Amt->getOperand(j);
17400 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17401 isa<ConstantSDNode>(Amt2)) {
17402 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17403 EVT CastVT = MVT::v4i32;
17405 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17406 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17408 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17409 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17410 if (TargetOpcode == X86ISD::MOVSD)
17411 CastVT = MVT::v2i64;
17412 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17413 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17414 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17416 return DAG.getBitcast(VT, Result);
17420 // v4i32 Non Uniform Shifts.
17421 // If the shift amount is constant we can shift each lane using the SSE2
17422 // immediate shifts, else we need to zero-extend each lane to the lower i64
17423 // and shift using the SSE2 variable shifts.
17424 // The separate results can then be blended together.
17425 if (VT == MVT::v4i32) {
17426 unsigned Opc = Op.getOpcode();
17427 SDValue Amt0, Amt1, Amt2, Amt3;
17428 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17429 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17430 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17431 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17432 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17434 // ISD::SHL is handled above but we include it here for completeness.
17437 llvm_unreachable("Unknown target vector shift node");
17439 Opc = X86ISD::VSHL;
17442 Opc = X86ISD::VSRL;
17445 Opc = X86ISD::VSRA;
17448 // The SSE2 shifts use the lower i64 as the same shift amount for
17449 // all lanes and the upper i64 is ignored. These shuffle masks
17450 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17451 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17452 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17453 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17454 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17455 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17458 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17459 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17460 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17461 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17462 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17463 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17464 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17467 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17468 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17469 unsigned ShiftOpcode = Op->getOpcode();
17471 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17472 // On SSE41 targets we make use of the fact that VSELECT lowers
17473 // to PBLENDVB which selects bytes based just on the sign bit.
17474 if (Subtarget->hasSSE41()) {
17475 V0 = DAG.getBitcast(VT, V0);
17476 V1 = DAG.getBitcast(VT, V1);
17477 Sel = DAG.getBitcast(VT, Sel);
17478 return DAG.getBitcast(SelVT,
17479 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17481 // On pre-SSE41 targets we test for the sign bit by comparing to
17482 // zero - a negative value will set all bits of the lanes to true
17483 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17484 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17485 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17486 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17489 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17490 // We can safely do this using i16 shifts as we're only interested in
17491 // the 3 lower bits of each byte.
17492 Amt = DAG.getBitcast(ExtVT, Amt);
17493 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17494 Amt = DAG.getBitcast(VT, Amt);
17496 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17497 // r = VSELECT(r, shift(r, 4), a);
17499 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17500 R = SignBitSelect(VT, Amt, M, R);
17503 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17505 // r = VSELECT(r, shift(r, 2), a);
17506 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17507 R = SignBitSelect(VT, Amt, M, R);
17510 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17512 // return VSELECT(r, shift(r, 1), a);
17513 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17514 R = SignBitSelect(VT, Amt, M, R);
17518 if (Op->getOpcode() == ISD::SRA) {
17519 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17520 // so we can correctly sign extend. We don't care what happens to the
17522 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17523 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17524 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17525 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17526 ALo = DAG.getBitcast(ExtVT, ALo);
17527 AHi = DAG.getBitcast(ExtVT, AHi);
17528 RLo = DAG.getBitcast(ExtVT, RLo);
17529 RHi = DAG.getBitcast(ExtVT, RHi);
17531 // r = VSELECT(r, shift(r, 4), a);
17532 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17533 DAG.getConstant(4, dl, ExtVT));
17534 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17535 DAG.getConstant(4, dl, ExtVT));
17536 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17537 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17540 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17541 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17543 // r = VSELECT(r, shift(r, 2), a);
17544 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17545 DAG.getConstant(2, dl, ExtVT));
17546 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17547 DAG.getConstant(2, dl, ExtVT));
17548 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17549 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17552 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17553 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17555 // r = VSELECT(r, shift(r, 1), a);
17556 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17557 DAG.getConstant(1, dl, ExtVT));
17558 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17559 DAG.getConstant(1, dl, ExtVT));
17560 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17561 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17563 // Logical shift the result back to the lower byte, leaving a zero upper
17565 // meaning that we can safely pack with PACKUSWB.
17567 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17569 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17570 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17574 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17575 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17576 // solution better.
17577 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17578 MVT ExtVT = MVT::v8i32;
17580 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17581 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17582 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17583 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17584 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17587 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17588 MVT ExtVT = MVT::v8i32;
17589 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17590 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17591 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17592 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17593 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17594 ALo = DAG.getBitcast(ExtVT, ALo);
17595 AHi = DAG.getBitcast(ExtVT, AHi);
17596 RLo = DAG.getBitcast(ExtVT, RLo);
17597 RHi = DAG.getBitcast(ExtVT, RHi);
17598 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17599 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17600 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17601 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17602 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17605 if (VT == MVT::v8i16) {
17606 unsigned ShiftOpcode = Op->getOpcode();
17608 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17609 // On SSE41 targets we make use of the fact that VSELECT lowers
17610 // to PBLENDVB which selects bytes based just on the sign bit.
17611 if (Subtarget->hasSSE41()) {
17612 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17613 V0 = DAG.getBitcast(ExtVT, V0);
17614 V1 = DAG.getBitcast(ExtVT, V1);
17615 Sel = DAG.getBitcast(ExtVT, Sel);
17616 return DAG.getBitcast(
17617 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17619 // On pre-SSE41 targets we splat the sign bit - a negative value will
17620 // set all bits of the lanes to true and VSELECT uses that in
17621 // its OR(AND(V0,C),AND(V1,~C)) lowering.
17623 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17624 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17627 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17628 if (Subtarget->hasSSE41()) {
17629 // On SSE41 targets we need to replicate the shift mask in both
17630 // bytes for PBLENDVB.
17633 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17634 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17636 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17639 // r = VSELECT(r, shift(r, 8), a);
17640 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17641 R = SignBitSelect(Amt, M, R);
17644 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17646 // r = VSELECT(r, shift(r, 4), a);
17647 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17648 R = SignBitSelect(Amt, M, R);
17651 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17653 // r = VSELECT(r, shift(r, 2), a);
17654 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17655 R = SignBitSelect(Amt, M, R);
17658 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17660 // return VSELECT(r, shift(r, 1), a);
17661 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17662 R = SignBitSelect(Amt, M, R);
17666 // Decompose 256-bit shifts into smaller 128-bit shifts.
17667 if (VT.is256BitVector()) {
17668 unsigned NumElems = VT.getVectorNumElements();
17669 MVT EltVT = VT.getVectorElementType();
17670 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17672 // Extract the two vectors
17673 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17674 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17676 // Recreate the shift amount vectors
17677 SDValue Amt1, Amt2;
17678 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17679 // Constant shift amount
17680 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17681 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17682 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17684 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17685 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17687 // Variable shift amount
17688 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17689 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17692 // Issue new vector shifts for the smaller types
17693 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17694 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17696 // Concatenate the result back
17697 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17703 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17704 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17705 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17706 // looks for this combo and may remove the "setcc" instruction if the "setcc"
17707 // has only one use.
17708 SDNode *N = Op.getNode();
17709 SDValue LHS = N->getOperand(0);
17710 SDValue RHS = N->getOperand(1);
17711 unsigned BaseOp = 0;
17714 switch (Op.getOpcode()) {
17715 default: llvm_unreachable("Unknown ovf instruction!");
17717 // A subtract of one will be selected as a INC. Note that INC doesn't
17718 // set CF, so we can't do this for UADDO.
17719 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17721 BaseOp = X86ISD::INC;
17722 Cond = X86::COND_O;
17725 BaseOp = X86ISD::ADD;
17726 Cond = X86::COND_O;
17729 BaseOp = X86ISD::ADD;
17730 Cond = X86::COND_B;
17733 // A subtract of one will be selected as a DEC. Note that DEC doesn't
17734 // set CF, so we can't do this for USUBO.
17735 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17737 BaseOp = X86ISD::DEC;
17738 Cond = X86::COND_O;
17741 BaseOp = X86ISD::SUB;
17742 Cond = X86::COND_O;
17745 BaseOp = X86ISD::SUB;
17746 Cond = X86::COND_B;
17749 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17750 Cond = X86::COND_O;
17752 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17753 if (N->getValueType(0) == MVT::i8) {
17754 BaseOp = X86ISD::UMUL8;
17755 Cond = X86::COND_O;
17758 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17760 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17763 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17764 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17765 SDValue(Sum.getNode(), 2));
17767 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17771 // Also sets EFLAGS.
17772 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17773 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17776 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17777 DAG.getConstant(Cond, DL, MVT::i32),
17778 SDValue(Sum.getNode(), 1));
17780 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17783 /// Returns true if the operand type is exactly twice the native width, and
17784 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17785 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17786 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17787 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17788 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17791 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17792 else if (OpWidth == 128)
17793 return Subtarget->hasCmpxchg16b();
17798 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17799 return needsCmpXchgNb(SI->getValueOperand()->getType());
17802 // Note: this turns large loads into lock cmpxchg8b/16b.
17803 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17804 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17805 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17806 return needsCmpXchgNb(PTy->getElementType());
17809 TargetLoweringBase::AtomicRMWExpansionKind
17810 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17811 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17812 const Type *MemType = AI->getType();
17814 // If the operand is too big, we must see if cmpxchg8/16b is available
17815 // and default to library calls otherwise.
17816 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17817 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17818 : AtomicRMWExpansionKind::None;
17821 AtomicRMWInst::BinOp Op = AI->getOperation();
17824 llvm_unreachable("Unknown atomic operation");
17825 case AtomicRMWInst::Xchg:
17826 case AtomicRMWInst::Add:
17827 case AtomicRMWInst::Sub:
17828 // It's better to use xadd, xsub or xchg for these in all cases.
17829 return AtomicRMWExpansionKind::None;
17830 case AtomicRMWInst::Or:
17831 case AtomicRMWInst::And:
17832 case AtomicRMWInst::Xor:
17833 // If the atomicrmw's result isn't actually used, we can just add a "lock"
17834 // prefix to a normal instruction for these operations.
17835 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17836 : AtomicRMWExpansionKind::None;
17837 case AtomicRMWInst::Nand:
17838 case AtomicRMWInst::Max:
17839 case AtomicRMWInst::Min:
17840 case AtomicRMWInst::UMax:
17841 case AtomicRMWInst::UMin:
17842 // These always require a non-trivial set of data operations on x86. We must
17843 // use a cmpxchg loop.
17844 return AtomicRMWExpansionKind::CmpXChg;
17848 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17849 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17850 // no-sse2). There isn't any reason to disable it if the target processor
17852 return Subtarget.hasSSE2() || Subtarget.is64Bit();
17856 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17857 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17858 const Type *MemType = AI->getType();
17859 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17860 // there is no benefit in turning such RMWs into loads, and it is actually
17861 // harmful as it introduces a mfence.
17862 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17865 auto Builder = IRBuilder<>(AI);
17866 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17867 auto SynchScope = AI->getSynchScope();
17868 // We must restrict the ordering to avoid generating loads with Release or
17869 // ReleaseAcquire orderings.
17870 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17871 auto Ptr = AI->getPointerOperand();
17873 // Before the load we need a fence. Here is an example lifted from
17874 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17877 // x.store(1, relaxed);
17878 // r1 = y.fetch_add(0, release);
17880 // y.fetch_add(42, acquire);
17881 // r2 = x.load(relaxed);
17882 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17883 // lowered to just a load without a fence. A mfence flushes the store buffer,
17884 // making the optimization clearly correct.
17885 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17886 // otherwise, we might be able to be more agressive on relaxed idempotent
17887 // rmw. In practice, they do not look useful, so we don't try to be
17888 // especially clever.
17889 if (SynchScope == SingleThread)
17890 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17891 // the IR level, so we must wrap it in an intrinsic.
17894 if (!hasMFENCE(*Subtarget))
17895 // FIXME: it might make sense to use a locked operation here but on a
17896 // different cache-line to prevent cache-line bouncing. In practice it
17897 // is probably a small win, and x86 processors without mfence are rare
17898 // enough that we do not bother.
17902 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17903 Builder.CreateCall(MFence, {});
17905 // Finally we can emit the atomic load.
17906 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17907 AI->getType()->getPrimitiveSizeInBits());
17908 Loaded->setAtomic(Order, SynchScope);
17909 AI->replaceAllUsesWith(Loaded);
17910 AI->eraseFromParent();
17914 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17915 SelectionDAG &DAG) {
17917 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17918 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17919 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17920 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17922 // The only fence that needs an instruction is a sequentially-consistent
17923 // cross-thread fence.
17924 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17925 if (hasMFENCE(*Subtarget))
17926 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17928 SDValue Chain = Op.getOperand(0);
17929 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17931 DAG.getRegister(X86::ESP, MVT::i32), // Base
17932 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
17933 DAG.getRegister(0, MVT::i32), // Index
17934 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
17935 DAG.getRegister(0, MVT::i32), // Segment.
17939 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17940 return SDValue(Res, 0);
17943 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17944 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17947 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17948 SelectionDAG &DAG) {
17949 MVT T = Op.getSimpleValueType();
17953 switch(T.SimpleTy) {
17954 default: llvm_unreachable("Invalid value type!");
17955 case MVT::i8: Reg = X86::AL; size = 1; break;
17956 case MVT::i16: Reg = X86::AX; size = 2; break;
17957 case MVT::i32: Reg = X86::EAX; size = 4; break;
17959 assert(Subtarget->is64Bit() && "Node not type legal!");
17960 Reg = X86::RAX; size = 8;
17963 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17964 Op.getOperand(2), SDValue());
17965 SDValue Ops[] = { cpIn.getValue(0),
17968 DAG.getTargetConstant(size, DL, MVT::i8),
17969 cpIn.getValue(1) };
17970 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17971 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17972 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17976 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17977 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17978 MVT::i32, cpOut.getValue(2));
17979 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17980 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17983 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17984 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17985 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17989 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17990 SelectionDAG &DAG) {
17991 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17992 MVT DstVT = Op.getSimpleValueType();
17994 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17995 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17996 if (DstVT != MVT::f64)
17997 // This conversion needs to be expanded.
18000 SDValue InVec = Op->getOperand(0);
18002 unsigned NumElts = SrcVT.getVectorNumElements();
18003 EVT SVT = SrcVT.getVectorElementType();
18005 // Widen the vector in input in the case of MVT::v2i32.
18006 // Example: from MVT::v2i32 to MVT::v4i32.
18007 SmallVector<SDValue, 16> Elts;
18008 for (unsigned i = 0, e = NumElts; i != e; ++i)
18009 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18010 DAG.getIntPtrConstant(i, dl)));
18012 // Explicitly mark the extra elements as Undef.
18013 Elts.append(NumElts, DAG.getUNDEF(SVT));
18015 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18016 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18017 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18018 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18019 DAG.getIntPtrConstant(0, dl));
18022 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18023 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18024 assert((DstVT == MVT::i64 ||
18025 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18026 "Unexpected custom BITCAST");
18027 // i64 <=> MMX conversions are Legal.
18028 if (SrcVT==MVT::i64 && DstVT.isVector())
18030 if (DstVT==MVT::i64 && SrcVT.isVector())
18032 // MMX <=> MMX conversions are Legal.
18033 if (SrcVT.isVector() && DstVT.isVector())
18035 // All other conversions need to be expanded.
18039 /// Compute the horizontal sum of bytes in V for the elements of VT.
18041 /// Requires V to be a byte vector and VT to be an integer vector type with
18042 /// wider elements than V's type. The width of the elements of VT determines
18043 /// how many bytes of V are summed horizontally to produce each element of the
18045 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18046 const X86Subtarget *Subtarget,
18047 SelectionDAG &DAG) {
18049 MVT ByteVecVT = V.getSimpleValueType();
18050 MVT EltVT = VT.getVectorElementType();
18051 int NumElts = VT.getVectorNumElements();
18052 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18053 "Expected value to have byte element type.");
18054 assert(EltVT != MVT::i8 &&
18055 "Horizontal byte sum only makes sense for wider elements!");
18056 unsigned VecSize = VT.getSizeInBits();
18057 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18059 // PSADBW instruction horizontally add all bytes and leave the result in i64
18060 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18061 if (EltVT == MVT::i64) {
18062 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18063 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18064 return DAG.getBitcast(VT, V);
18067 if (EltVT == MVT::i32) {
18068 // We unpack the low half and high half into i32s interleaved with zeros so
18069 // that we can use PSADBW to horizontally sum them. The most useful part of
18070 // this is that it lines up the results of two PSADBW instructions to be
18071 // two v2i64 vectors which concatenated are the 4 population counts. We can
18072 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18073 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18074 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18075 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18077 // Do the horizontal sums into two v2i64s.
18078 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18079 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18080 DAG.getBitcast(ByteVecVT, Low), Zeros);
18081 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18082 DAG.getBitcast(ByteVecVT, High), Zeros);
18084 // Merge them together.
18085 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18086 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18087 DAG.getBitcast(ShortVecVT, Low),
18088 DAG.getBitcast(ShortVecVT, High));
18090 return DAG.getBitcast(VT, V);
18093 // The only element type left is i16.
18094 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18096 // To obtain pop count for each i16 element starting from the pop count for
18097 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18098 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18099 // directly supported.
18100 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18101 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18102 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18103 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18104 DAG.getBitcast(ByteVecVT, V));
18105 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18108 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18109 const X86Subtarget *Subtarget,
18110 SelectionDAG &DAG) {
18111 MVT VT = Op.getSimpleValueType();
18112 MVT EltVT = VT.getVectorElementType();
18113 unsigned VecSize = VT.getSizeInBits();
18115 // Implement a lookup table in register by using an algorithm based on:
18116 // http://wm.ite.pl/articles/sse-popcount.html
18118 // The general idea is that every lower byte nibble in the input vector is an
18119 // index into a in-register pre-computed pop count table. We then split up the
18120 // input vector in two new ones: (1) a vector with only the shifted-right
18121 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18122 // masked out higher ones) for each byte. PSHUB is used separately with both
18123 // to index the in-register table. Next, both are added and the result is a
18124 // i8 vector where each element contains the pop count for input byte.
18126 // To obtain the pop count for elements != i8, we follow up with the same
18127 // approach and use additional tricks as described below.
18129 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18130 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18131 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18132 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18134 int NumByteElts = VecSize / 8;
18135 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18136 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18137 SmallVector<SDValue, 16> LUTVec;
18138 for (int i = 0; i < NumByteElts; ++i)
18139 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18140 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18141 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18142 DAG.getConstant(0x0F, DL, MVT::i8));
18143 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18146 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18147 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18148 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18151 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18153 // The input vector is used as the shuffle mask that index elements into the
18154 // LUT. After counting low and high nibbles, add the vector to obtain the
18155 // final pop count per i8 element.
18156 SDValue HighPopCnt =
18157 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18158 SDValue LowPopCnt =
18159 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18160 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18162 if (EltVT == MVT::i8)
18165 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18168 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18169 const X86Subtarget *Subtarget,
18170 SelectionDAG &DAG) {
18171 MVT VT = Op.getSimpleValueType();
18172 assert(VT.is128BitVector() &&
18173 "Only 128-bit vector bitmath lowering supported.");
18175 int VecSize = VT.getSizeInBits();
18176 MVT EltVT = VT.getVectorElementType();
18177 int Len = EltVT.getSizeInBits();
18179 // This is the vectorized version of the "best" algorithm from
18180 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18181 // with a minor tweak to use a series of adds + shifts instead of vector
18182 // multiplications. Implemented for all integer vector types. We only use
18183 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18184 // much faster, even faster than using native popcnt instructions.
18186 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18187 MVT VT = V.getSimpleValueType();
18188 SmallVector<SDValue, 32> Shifters(
18189 VT.getVectorNumElements(),
18190 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18191 return DAG.getNode(OpCode, DL, VT, V,
18192 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18194 auto GetMask = [&](SDValue V, APInt Mask) {
18195 MVT VT = V.getSimpleValueType();
18196 SmallVector<SDValue, 32> Masks(
18197 VT.getVectorNumElements(),
18198 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18199 return DAG.getNode(ISD::AND, DL, VT, V,
18200 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18203 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18204 // x86, so set the SRL type to have elements at least i16 wide. This is
18205 // correct because all of our SRLs are followed immediately by a mask anyways
18206 // that handles any bits that sneak into the high bits of the byte elements.
18207 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18211 // v = v - ((v >> 1) & 0x55555555...)
18213 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18214 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18215 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18217 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18218 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18219 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18220 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18221 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18223 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18224 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18225 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18226 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18228 // At this point, V contains the byte-wise population count, and we are
18229 // merely doing a horizontal sum if necessary to get the wider element
18231 if (EltVT == MVT::i8)
18234 return LowerHorizontalByteSum(
18235 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18239 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18240 SelectionDAG &DAG) {
18241 MVT VT = Op.getSimpleValueType();
18242 // FIXME: Need to add AVX-512 support here!
18243 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18244 "Unknown CTPOP type to handle");
18245 SDLoc DL(Op.getNode());
18246 SDValue Op0 = Op.getOperand(0);
18248 if (!Subtarget->hasSSSE3()) {
18249 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18250 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18251 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18254 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18255 unsigned NumElems = VT.getVectorNumElements();
18257 // Extract each 128-bit vector, compute pop count and concat the result.
18258 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18259 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18261 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18262 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18263 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18266 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18269 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18270 SelectionDAG &DAG) {
18271 assert(Op.getValueType().isVector() &&
18272 "We only do custom lowering for vector population count.");
18273 return LowerVectorCTPOP(Op, Subtarget, DAG);
18276 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18277 SDNode *Node = Op.getNode();
18279 EVT T = Node->getValueType(0);
18280 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18281 DAG.getConstant(0, dl, T), Node->getOperand(2));
18282 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18283 cast<AtomicSDNode>(Node)->getMemoryVT(),
18284 Node->getOperand(0),
18285 Node->getOperand(1), negOp,
18286 cast<AtomicSDNode>(Node)->getMemOperand(),
18287 cast<AtomicSDNode>(Node)->getOrdering(),
18288 cast<AtomicSDNode>(Node)->getSynchScope());
18291 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18292 SDNode *Node = Op.getNode();
18294 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18296 // Convert seq_cst store -> xchg
18297 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18298 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18299 // (The only way to get a 16-byte store is cmpxchg16b)
18300 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18301 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18302 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18303 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18304 cast<AtomicSDNode>(Node)->getMemoryVT(),
18305 Node->getOperand(0),
18306 Node->getOperand(1), Node->getOperand(2),
18307 cast<AtomicSDNode>(Node)->getMemOperand(),
18308 cast<AtomicSDNode>(Node)->getOrdering(),
18309 cast<AtomicSDNode>(Node)->getSynchScope());
18310 return Swap.getValue(1);
18312 // Other atomic stores have a simple pattern.
18316 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18317 EVT VT = Op.getNode()->getSimpleValueType(0);
18319 // Let legalize expand this if it isn't a legal type yet.
18320 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18323 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18326 bool ExtraOp = false;
18327 switch (Op.getOpcode()) {
18328 default: llvm_unreachable("Invalid code");
18329 case ISD::ADDC: Opc = X86ISD::ADD; break;
18330 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18331 case ISD::SUBC: Opc = X86ISD::SUB; break;
18332 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18336 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18338 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18339 Op.getOperand(1), Op.getOperand(2));
18342 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18343 SelectionDAG &DAG) {
18344 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18346 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18347 // which returns the values as { float, float } (in XMM0) or
18348 // { double, double } (which is returned in XMM0, XMM1).
18350 SDValue Arg = Op.getOperand(0);
18351 EVT ArgVT = Arg.getValueType();
18352 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18354 TargetLowering::ArgListTy Args;
18355 TargetLowering::ArgListEntry Entry;
18359 Entry.isSExt = false;
18360 Entry.isZExt = false;
18361 Args.push_back(Entry);
18363 bool isF64 = ArgVT == MVT::f64;
18364 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18365 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18366 // the results are returned via SRet in memory.
18367 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18368 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18370 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18372 Type *RetTy = isF64
18373 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18374 : (Type*)VectorType::get(ArgTy, 4);
18376 TargetLowering::CallLoweringInfo CLI(DAG);
18377 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18378 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18380 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18383 // Returned in xmm0 and xmm1.
18384 return CallResult.first;
18386 // Returned in bits 0:31 and 32:64 xmm0.
18387 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18388 CallResult.first, DAG.getIntPtrConstant(0, dl));
18389 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18390 CallResult.first, DAG.getIntPtrConstant(1, dl));
18391 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18392 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18395 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18396 SelectionDAG &DAG) {
18397 assert(Subtarget->hasAVX512() &&
18398 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18400 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18401 EVT VT = N->getValue().getValueType();
18402 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18405 // X86 scatter kills mask register, so its type should be added to
18406 // the list of return values
18407 if (N->getNumValues() == 1) {
18408 SDValue Index = N->getIndex();
18409 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18410 !Index.getValueType().is512BitVector())
18411 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18413 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18414 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18415 N->getOperand(3), Index };
18417 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18418 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18419 return SDValue(NewScatter.getNode(), 0);
18424 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18425 SelectionDAG &DAG) {
18426 assert(Subtarget->hasAVX512() &&
18427 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18429 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18430 EVT VT = Op.getValueType();
18431 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18434 SDValue Index = N->getIndex();
18435 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18436 !Index.getValueType().is512BitVector()) {
18437 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18438 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18439 N->getOperand(3), Index };
18440 DAG.UpdateNodeOperands(N, Ops);
18445 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18446 SelectionDAG &DAG) const {
18447 // TODO: Eventually, the lowering of these nodes should be informed by or
18448 // deferred to the GC strategy for the function in which they appear. For
18449 // now, however, they must be lowered to something. Since they are logically
18450 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18451 // require special handling for these nodes), lower them as literal NOOPs for
18453 SmallVector<SDValue, 2> Ops;
18455 Ops.push_back(Op.getOperand(0));
18456 if (Op->getGluedNode())
18457 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18460 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18461 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18466 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18467 SelectionDAG &DAG) const {
18468 // TODO: Eventually, the lowering of these nodes should be informed by or
18469 // deferred to the GC strategy for the function in which they appear. For
18470 // now, however, they must be lowered to something. Since they are logically
18471 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18472 // require special handling for these nodes), lower them as literal NOOPs for
18474 SmallVector<SDValue, 2> Ops;
18476 Ops.push_back(Op.getOperand(0));
18477 if (Op->getGluedNode())
18478 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18481 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18482 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18487 /// LowerOperation - Provide custom lowering hooks for some operations.
18489 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18490 switch (Op.getOpcode()) {
18491 default: llvm_unreachable("Should not custom lower this!");
18492 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18493 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18494 return LowerCMP_SWAP(Op, Subtarget, DAG);
18495 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18496 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18497 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18498 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18499 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18500 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18501 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18502 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18503 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18504 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18505 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18506 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18507 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18508 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18509 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18510 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18511 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18512 case ISD::SHL_PARTS:
18513 case ISD::SRA_PARTS:
18514 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18515 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18516 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18517 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18518 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18519 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18520 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18521 case ISD::SIGN_EXTEND_VECTOR_INREG:
18522 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18523 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18524 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18525 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18526 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18528 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18529 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18530 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18531 case ISD::SETCC: return LowerSETCC(Op, DAG);
18532 case ISD::SELECT: return LowerSELECT(Op, DAG);
18533 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18534 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18535 case ISD::VASTART: return LowerVASTART(Op, DAG);
18536 case ISD::VAARG: return LowerVAARG(Op, DAG);
18537 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18538 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18539 case ISD::INTRINSIC_VOID:
18540 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18541 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18542 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18543 case ISD::FRAME_TO_ARGS_OFFSET:
18544 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18545 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18546 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18547 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18548 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18549 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18550 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18551 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18552 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18553 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18554 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18555 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18556 case ISD::UMUL_LOHI:
18557 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18560 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18566 case ISD::UMULO: return LowerXALUO(Op, DAG);
18567 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18568 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18572 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18573 case ISD::ADD: return LowerADD(Op, DAG);
18574 case ISD::SUB: return LowerSUB(Op, DAG);
18575 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18576 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18577 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18578 case ISD::GC_TRANSITION_START:
18579 return LowerGC_TRANSITION_START(Op, DAG);
18580 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18584 /// ReplaceNodeResults - Replace a node with an illegal result type
18585 /// with a new node built out of custom code.
18586 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18587 SmallVectorImpl<SDValue>&Results,
18588 SelectionDAG &DAG) const {
18590 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18591 switch (N->getOpcode()) {
18593 llvm_unreachable("Do not know how to custom type legalize this operation!");
18594 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18595 case X86ISD::FMINC:
18597 case X86ISD::FMAXC:
18598 case X86ISD::FMAX: {
18599 EVT VT = N->getValueType(0);
18600 if (VT != MVT::v2f32)
18601 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18602 SDValue UNDEF = DAG.getUNDEF(VT);
18603 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18604 N->getOperand(0), UNDEF);
18605 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18606 N->getOperand(1), UNDEF);
18607 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18610 case ISD::SIGN_EXTEND_INREG:
18615 // We don't want to expand or promote these.
18622 case ISD::UDIVREM: {
18623 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18624 Results.push_back(V);
18627 case ISD::FP_TO_SINT:
18628 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
18629 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18630 if (N->getOperand(0).getValueType() == MVT::f16)
18633 case ISD::FP_TO_UINT: {
18634 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18636 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18639 std::pair<SDValue,SDValue> Vals =
18640 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18641 SDValue FIST = Vals.first, StackSlot = Vals.second;
18642 if (FIST.getNode()) {
18643 EVT VT = N->getValueType(0);
18644 // Return a load from the stack slot.
18645 if (StackSlot.getNode())
18646 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18647 MachinePointerInfo(),
18648 false, false, false, 0));
18650 Results.push_back(FIST);
18654 case ISD::UINT_TO_FP: {
18655 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18656 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18657 N->getValueType(0) != MVT::v2f32)
18659 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18661 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18663 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18664 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18665 DAG.getBitcast(MVT::v2i64, VBias));
18666 Or = DAG.getBitcast(MVT::v2f64, Or);
18667 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18668 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18671 case ISD::FP_ROUND: {
18672 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18674 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18675 Results.push_back(V);
18678 case ISD::FP_EXTEND: {
18679 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18680 // No other ValueType for FP_EXTEND should reach this point.
18681 assert(N->getValueType(0) == MVT::v2f32 &&
18682 "Do not know how to legalize this Node");
18685 case ISD::INTRINSIC_W_CHAIN: {
18686 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18688 default : llvm_unreachable("Do not know how to custom type "
18689 "legalize this intrinsic operation!");
18690 case Intrinsic::x86_rdtsc:
18691 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18693 case Intrinsic::x86_rdtscp:
18694 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18696 case Intrinsic::x86_rdpmc:
18697 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18700 case ISD::READCYCLECOUNTER: {
18701 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18704 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18705 EVT T = N->getValueType(0);
18706 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18707 bool Regs64bit = T == MVT::i128;
18708 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18709 SDValue cpInL, cpInH;
18710 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18711 DAG.getConstant(0, dl, HalfT));
18712 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18713 DAG.getConstant(1, dl, HalfT));
18714 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18715 Regs64bit ? X86::RAX : X86::EAX,
18717 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18718 Regs64bit ? X86::RDX : X86::EDX,
18719 cpInH, cpInL.getValue(1));
18720 SDValue swapInL, swapInH;
18721 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18722 DAG.getConstant(0, dl, HalfT));
18723 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18724 DAG.getConstant(1, dl, HalfT));
18725 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18726 Regs64bit ? X86::RBX : X86::EBX,
18727 swapInL, cpInH.getValue(1));
18728 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18729 Regs64bit ? X86::RCX : X86::ECX,
18730 swapInH, swapInL.getValue(1));
18731 SDValue Ops[] = { swapInH.getValue(0),
18733 swapInH.getValue(1) };
18734 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18735 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18736 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18737 X86ISD::LCMPXCHG8_DAG;
18738 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18739 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18740 Regs64bit ? X86::RAX : X86::EAX,
18741 HalfT, Result.getValue(1));
18742 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18743 Regs64bit ? X86::RDX : X86::EDX,
18744 HalfT, cpOutL.getValue(2));
18745 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18747 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18748 MVT::i32, cpOutH.getValue(2));
18750 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18751 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18752 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18754 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18755 Results.push_back(Success);
18756 Results.push_back(EFLAGS.getValue(1));
18759 case ISD::ATOMIC_SWAP:
18760 case ISD::ATOMIC_LOAD_ADD:
18761 case ISD::ATOMIC_LOAD_SUB:
18762 case ISD::ATOMIC_LOAD_AND:
18763 case ISD::ATOMIC_LOAD_OR:
18764 case ISD::ATOMIC_LOAD_XOR:
18765 case ISD::ATOMIC_LOAD_NAND:
18766 case ISD::ATOMIC_LOAD_MIN:
18767 case ISD::ATOMIC_LOAD_MAX:
18768 case ISD::ATOMIC_LOAD_UMIN:
18769 case ISD::ATOMIC_LOAD_UMAX:
18770 case ISD::ATOMIC_LOAD: {
18771 // Delegate to generic TypeLegalization. Situations we can really handle
18772 // should have already been dealt with by AtomicExpandPass.cpp.
18775 case ISD::BITCAST: {
18776 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18777 EVT DstVT = N->getValueType(0);
18778 EVT SrcVT = N->getOperand(0)->getValueType(0);
18780 if (SrcVT != MVT::f64 ||
18781 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18784 unsigned NumElts = DstVT.getVectorNumElements();
18785 EVT SVT = DstVT.getVectorElementType();
18786 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18787 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18788 MVT::v2f64, N->getOperand(0));
18789 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18791 if (ExperimentalVectorWideningLegalization) {
18792 // If we are legalizing vectors by widening, we already have the desired
18793 // legal vector type, just return it.
18794 Results.push_back(ToVecInt);
18798 SmallVector<SDValue, 8> Elts;
18799 for (unsigned i = 0, e = NumElts; i != e; ++i)
18800 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18801 ToVecInt, DAG.getIntPtrConstant(i, dl)));
18803 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18808 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18809 switch ((X86ISD::NodeType)Opcode) {
18810 case X86ISD::FIRST_NUMBER: break;
18811 case X86ISD::BSF: return "X86ISD::BSF";
18812 case X86ISD::BSR: return "X86ISD::BSR";
18813 case X86ISD::SHLD: return "X86ISD::SHLD";
18814 case X86ISD::SHRD: return "X86ISD::SHRD";
18815 case X86ISD::FAND: return "X86ISD::FAND";
18816 case X86ISD::FANDN: return "X86ISD::FANDN";
18817 case X86ISD::FOR: return "X86ISD::FOR";
18818 case X86ISD::FXOR: return "X86ISD::FXOR";
18819 case X86ISD::FILD: return "X86ISD::FILD";
18820 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
18821 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18822 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18823 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18824 case X86ISD::FLD: return "X86ISD::FLD";
18825 case X86ISD::FST: return "X86ISD::FST";
18826 case X86ISD::CALL: return "X86ISD::CALL";
18827 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
18828 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
18829 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
18830 case X86ISD::BT: return "X86ISD::BT";
18831 case X86ISD::CMP: return "X86ISD::CMP";
18832 case X86ISD::COMI: return "X86ISD::COMI";
18833 case X86ISD::UCOMI: return "X86ISD::UCOMI";
18834 case X86ISD::CMPM: return "X86ISD::CMPM";
18835 case X86ISD::CMPMU: return "X86ISD::CMPMU";
18836 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
18837 case X86ISD::SETCC: return "X86ISD::SETCC";
18838 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
18839 case X86ISD::FSETCC: return "X86ISD::FSETCC";
18840 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
18841 case X86ISD::CMOV: return "X86ISD::CMOV";
18842 case X86ISD::BRCOND: return "X86ISD::BRCOND";
18843 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
18844 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
18845 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
18846 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
18847 case X86ISD::Wrapper: return "X86ISD::Wrapper";
18848 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
18849 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
18850 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
18851 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
18852 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
18853 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
18854 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
18855 case X86ISD::PINSRB: return "X86ISD::PINSRB";
18856 case X86ISD::PINSRW: return "X86ISD::PINSRW";
18857 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
18858 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
18859 case X86ISD::ANDNP: return "X86ISD::ANDNP";
18860 case X86ISD::PSIGN: return "X86ISD::PSIGN";
18861 case X86ISD::BLENDI: return "X86ISD::BLENDI";
18862 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
18863 case X86ISD::ADDUS: return "X86ISD::ADDUS";
18864 case X86ISD::SUBUS: return "X86ISD::SUBUS";
18865 case X86ISD::HADD: return "X86ISD::HADD";
18866 case X86ISD::HSUB: return "X86ISD::HSUB";
18867 case X86ISD::FHADD: return "X86ISD::FHADD";
18868 case X86ISD::FHSUB: return "X86ISD::FHSUB";
18869 case X86ISD::ABS: return "X86ISD::ABS";
18870 case X86ISD::FMAX: return "X86ISD::FMAX";
18871 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
18872 case X86ISD::FMIN: return "X86ISD::FMIN";
18873 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
18874 case X86ISD::FMAXC: return "X86ISD::FMAXC";
18875 case X86ISD::FMINC: return "X86ISD::FMINC";
18876 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
18877 case X86ISD::FRCP: return "X86ISD::FRCP";
18878 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
18879 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
18880 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
18881 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
18882 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
18883 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
18884 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
18885 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
18886 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
18887 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
18888 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
18889 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
18890 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
18891 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
18892 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
18893 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
18894 case X86ISD::VZEXT: return "X86ISD::VZEXT";
18895 case X86ISD::VSEXT: return "X86ISD::VSEXT";
18896 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
18897 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
18898 case X86ISD::VINSERT: return "X86ISD::VINSERT";
18899 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
18900 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
18901 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
18902 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
18903 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
18904 case X86ISD::VSHL: return "X86ISD::VSHL";
18905 case X86ISD::VSRL: return "X86ISD::VSRL";
18906 case X86ISD::VSRA: return "X86ISD::VSRA";
18907 case X86ISD::VSHLI: return "X86ISD::VSHLI";
18908 case X86ISD::VSRLI: return "X86ISD::VSRLI";
18909 case X86ISD::VSRAI: return "X86ISD::VSRAI";
18910 case X86ISD::CMPP: return "X86ISD::CMPP";
18911 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
18912 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
18913 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
18914 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
18915 case X86ISD::ADD: return "X86ISD::ADD";
18916 case X86ISD::SUB: return "X86ISD::SUB";
18917 case X86ISD::ADC: return "X86ISD::ADC";
18918 case X86ISD::SBB: return "X86ISD::SBB";
18919 case X86ISD::SMUL: return "X86ISD::SMUL";
18920 case X86ISD::UMUL: return "X86ISD::UMUL";
18921 case X86ISD::SMUL8: return "X86ISD::SMUL8";
18922 case X86ISD::UMUL8: return "X86ISD::UMUL8";
18923 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18924 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18925 case X86ISD::INC: return "X86ISD::INC";
18926 case X86ISD::DEC: return "X86ISD::DEC";
18927 case X86ISD::OR: return "X86ISD::OR";
18928 case X86ISD::XOR: return "X86ISD::XOR";
18929 case X86ISD::AND: return "X86ISD::AND";
18930 case X86ISD::BEXTR: return "X86ISD::BEXTR";
18931 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
18932 case X86ISD::PTEST: return "X86ISD::PTEST";
18933 case X86ISD::TESTP: return "X86ISD::TESTP";
18934 case X86ISD::TESTM: return "X86ISD::TESTM";
18935 case X86ISD::TESTNM: return "X86ISD::TESTNM";
18936 case X86ISD::KORTEST: return "X86ISD::KORTEST";
18937 case X86ISD::PACKSS: return "X86ISD::PACKSS";
18938 case X86ISD::PACKUS: return "X86ISD::PACKUS";
18939 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
18940 case X86ISD::VALIGN: return "X86ISD::VALIGN";
18941 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
18942 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
18943 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
18944 case X86ISD::SHUFP: return "X86ISD::SHUFP";
18945 case X86ISD::SHUF128: return "X86ISD::SHUF128";
18946 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
18947 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
18948 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
18949 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
18950 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
18951 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
18952 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
18953 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
18954 case X86ISD::MOVSD: return "X86ISD::MOVSD";
18955 case X86ISD::MOVSS: return "X86ISD::MOVSS";
18956 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
18957 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
18958 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
18959 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
18960 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
18961 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
18962 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
18963 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
18964 case X86ISD::VPERMV: return "X86ISD::VPERMV";
18965 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
18966 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
18967 case X86ISD::VPERMI: return "X86ISD::VPERMI";
18968 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
18969 case X86ISD::VRANGE: return "X86ISD::VRANGE";
18970 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
18971 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
18972 case X86ISD::PSADBW: return "X86ISD::PSADBW";
18973 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18974 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
18975 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
18976 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
18977 case X86ISD::MFENCE: return "X86ISD::MFENCE";
18978 case X86ISD::SFENCE: return "X86ISD::SFENCE";
18979 case X86ISD::LFENCE: return "X86ISD::LFENCE";
18980 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
18981 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
18982 case X86ISD::SAHF: return "X86ISD::SAHF";
18983 case X86ISD::RDRAND: return "X86ISD::RDRAND";
18984 case X86ISD::RDSEED: return "X86ISD::RDSEED";
18985 case X86ISD::FMADD: return "X86ISD::FMADD";
18986 case X86ISD::FMSUB: return "X86ISD::FMSUB";
18987 case X86ISD::FNMADD: return "X86ISD::FNMADD";
18988 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
18989 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
18990 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
18991 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
18992 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
18993 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
18994 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
18995 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
18996 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
18997 case X86ISD::RNDSCALE: return "X86ISD::RNDSCALE";
18998 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
18999 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19000 case X86ISD::XTEST: return "X86ISD::XTEST";
19001 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19002 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19003 case X86ISD::SELECT: return "X86ISD::SELECT";
19004 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19005 case X86ISD::RCP28: return "X86ISD::RCP28";
19006 case X86ISD::EXP2: return "X86ISD::EXP2";
19007 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19008 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19009 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19010 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19011 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19012 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19013 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19014 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19015 case X86ISD::ADDS: return "X86ISD::ADDS";
19016 case X86ISD::SUBS: return "X86ISD::SUBS";
19017 case X86ISD::AVG: return "X86ISD::AVG";
19018 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19019 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19020 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19025 // isLegalAddressingMode - Return true if the addressing mode represented
19026 // by AM is legal for this target, for a load/store of the specified type.
19027 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19028 const AddrMode &AM, Type *Ty,
19029 unsigned AS) const {
19030 // X86 supports extremely general addressing modes.
19031 CodeModel::Model M = getTargetMachine().getCodeModel();
19032 Reloc::Model R = getTargetMachine().getRelocationModel();
19034 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19035 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19040 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19042 // If a reference to this global requires an extra load, we can't fold it.
19043 if (isGlobalStubReference(GVFlags))
19046 // If BaseGV requires a register for the PIC base, we cannot also have a
19047 // BaseReg specified.
19048 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19051 // If lower 4G is not available, then we must use rip-relative addressing.
19052 if ((M != CodeModel::Small || R != Reloc::Static) &&
19053 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19057 switch (AM.Scale) {
19063 // These scales always work.
19068 // These scales are formed with basereg+scalereg. Only accept if there is
19073 default: // Other stuff never works.
19080 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19081 unsigned Bits = Ty->getScalarSizeInBits();
19083 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19084 // particularly cheaper than those without.
19088 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19089 // variable shifts just as cheap as scalar ones.
19090 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19093 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19094 // fully general vector.
19098 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19099 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19101 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19102 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19103 return NumBits1 > NumBits2;
19106 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19107 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19110 if (!isTypeLegal(EVT::getEVT(Ty1)))
19113 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19115 // Assuming the caller doesn't have a zeroext or signext return parameter,
19116 // truncation all the way down to i1 is valid.
19120 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19121 return isInt<32>(Imm);
19124 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19125 // Can also use sub to handle negated immediates.
19126 return isInt<32>(Imm);
19129 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19130 if (!VT1.isInteger() || !VT2.isInteger())
19132 unsigned NumBits1 = VT1.getSizeInBits();
19133 unsigned NumBits2 = VT2.getSizeInBits();
19134 return NumBits1 > NumBits2;
19137 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19138 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19139 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19142 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19143 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19144 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19147 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19148 EVT VT1 = Val.getValueType();
19149 if (isZExtFree(VT1, VT2))
19152 if (Val.getOpcode() != ISD::LOAD)
19155 if (!VT1.isSimple() || !VT1.isInteger() ||
19156 !VT2.isSimple() || !VT2.isInteger())
19159 switch (VT1.getSimpleVT().SimpleTy) {
19164 // X86 has 8, 16, and 32-bit zero-extending loads.
19171 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19174 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19175 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19178 VT = VT.getScalarType();
19180 if (!VT.isSimple())
19183 switch (VT.getSimpleVT().SimpleTy) {
19194 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19195 // i16 instructions are longer (0x66 prefix) and potentially slower.
19196 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19199 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19200 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19201 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19202 /// are assumed to be legal.
19204 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19206 if (!VT.isSimple())
19209 // Not for i1 vectors
19210 if (VT.getScalarType() == MVT::i1)
19213 // Very little shuffling can be done for 64-bit vectors right now.
19214 if (VT.getSizeInBits() == 64)
19217 // We only care that the types being shuffled are legal. The lowering can
19218 // handle any possible shuffle mask that results.
19219 return isTypeLegal(VT.getSimpleVT());
19223 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19225 // Just delegate to the generic legality, clear masks aren't special.
19226 return isShuffleMaskLegal(Mask, VT);
19229 //===----------------------------------------------------------------------===//
19230 // X86 Scheduler Hooks
19231 //===----------------------------------------------------------------------===//
19233 /// Utility function to emit xbegin specifying the start of an RTM region.
19234 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19235 const TargetInstrInfo *TII) {
19236 DebugLoc DL = MI->getDebugLoc();
19238 const BasicBlock *BB = MBB->getBasicBlock();
19239 MachineFunction::iterator I = MBB;
19242 // For the v = xbegin(), we generate
19253 MachineBasicBlock *thisMBB = MBB;
19254 MachineFunction *MF = MBB->getParent();
19255 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19256 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19257 MF->insert(I, mainMBB);
19258 MF->insert(I, sinkMBB);
19260 // Transfer the remainder of BB and its successor edges to sinkMBB.
19261 sinkMBB->splice(sinkMBB->begin(), MBB,
19262 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19263 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19267 // # fallthrough to mainMBB
19268 // # abortion to sinkMBB
19269 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19270 thisMBB->addSuccessor(mainMBB);
19271 thisMBB->addSuccessor(sinkMBB);
19275 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19276 mainMBB->addSuccessor(sinkMBB);
19279 // EAX is live into the sinkMBB
19280 sinkMBB->addLiveIn(X86::EAX);
19281 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19282 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19285 MI->eraseFromParent();
19289 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19290 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19291 // in the .td file.
19292 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19293 const TargetInstrInfo *TII) {
19295 switch (MI->getOpcode()) {
19296 default: llvm_unreachable("illegal opcode!");
19297 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19298 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19299 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19300 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19301 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19302 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19303 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19304 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19307 DebugLoc dl = MI->getDebugLoc();
19308 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19310 unsigned NumArgs = MI->getNumOperands();
19311 for (unsigned i = 1; i < NumArgs; ++i) {
19312 MachineOperand &Op = MI->getOperand(i);
19313 if (!(Op.isReg() && Op.isImplicit()))
19314 MIB.addOperand(Op);
19316 if (MI->hasOneMemOperand())
19317 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19319 BuildMI(*BB, MI, dl,
19320 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19321 .addReg(X86::XMM0);
19323 MI->eraseFromParent();
19327 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19328 // defs in an instruction pattern
19329 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19330 const TargetInstrInfo *TII) {
19332 switch (MI->getOpcode()) {
19333 default: llvm_unreachable("illegal opcode!");
19334 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19335 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19336 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19337 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19338 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19339 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19340 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19341 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19344 DebugLoc dl = MI->getDebugLoc();
19345 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19347 unsigned NumArgs = MI->getNumOperands(); // remove the results
19348 for (unsigned i = 1; i < NumArgs; ++i) {
19349 MachineOperand &Op = MI->getOperand(i);
19350 if (!(Op.isReg() && Op.isImplicit()))
19351 MIB.addOperand(Op);
19353 if (MI->hasOneMemOperand())
19354 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19356 BuildMI(*BB, MI, dl,
19357 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19360 MI->eraseFromParent();
19364 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19365 const X86Subtarget *Subtarget) {
19366 DebugLoc dl = MI->getDebugLoc();
19367 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19368 // Address into RAX/EAX, other two args into ECX, EDX.
19369 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19370 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19371 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19372 for (int i = 0; i < X86::AddrNumOperands; ++i)
19373 MIB.addOperand(MI->getOperand(i));
19375 unsigned ValOps = X86::AddrNumOperands;
19376 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19377 .addReg(MI->getOperand(ValOps).getReg());
19378 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19379 .addReg(MI->getOperand(ValOps+1).getReg());
19381 // The instruction doesn't actually take any operands though.
19382 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19384 MI->eraseFromParent(); // The pseudo is gone now.
19388 MachineBasicBlock *
19389 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19390 MachineBasicBlock *MBB) const {
19391 // Emit va_arg instruction on X86-64.
19393 // Operands to this pseudo-instruction:
19394 // 0 ) Output : destination address (reg)
19395 // 1-5) Input : va_list address (addr, i64mem)
19396 // 6 ) ArgSize : Size (in bytes) of vararg type
19397 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19398 // 8 ) Align : Alignment of type
19399 // 9 ) EFLAGS (implicit-def)
19401 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19402 static_assert(X86::AddrNumOperands == 5,
19403 "VAARG_64 assumes 5 address operands");
19405 unsigned DestReg = MI->getOperand(0).getReg();
19406 MachineOperand &Base = MI->getOperand(1);
19407 MachineOperand &Scale = MI->getOperand(2);
19408 MachineOperand &Index = MI->getOperand(3);
19409 MachineOperand &Disp = MI->getOperand(4);
19410 MachineOperand &Segment = MI->getOperand(5);
19411 unsigned ArgSize = MI->getOperand(6).getImm();
19412 unsigned ArgMode = MI->getOperand(7).getImm();
19413 unsigned Align = MI->getOperand(8).getImm();
19415 // Memory Reference
19416 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19417 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19418 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19420 // Machine Information
19421 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19422 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19423 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19424 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19425 DebugLoc DL = MI->getDebugLoc();
19427 // struct va_list {
19430 // i64 overflow_area (address)
19431 // i64 reg_save_area (address)
19433 // sizeof(va_list) = 24
19434 // alignment(va_list) = 8
19436 unsigned TotalNumIntRegs = 6;
19437 unsigned TotalNumXMMRegs = 8;
19438 bool UseGPOffset = (ArgMode == 1);
19439 bool UseFPOffset = (ArgMode == 2);
19440 unsigned MaxOffset = TotalNumIntRegs * 8 +
19441 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19443 /* Align ArgSize to a multiple of 8 */
19444 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19445 bool NeedsAlign = (Align > 8);
19447 MachineBasicBlock *thisMBB = MBB;
19448 MachineBasicBlock *overflowMBB;
19449 MachineBasicBlock *offsetMBB;
19450 MachineBasicBlock *endMBB;
19452 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19453 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19454 unsigned OffsetReg = 0;
19456 if (!UseGPOffset && !UseFPOffset) {
19457 // If we only pull from the overflow region, we don't create a branch.
19458 // We don't need to alter control flow.
19459 OffsetDestReg = 0; // unused
19460 OverflowDestReg = DestReg;
19462 offsetMBB = nullptr;
19463 overflowMBB = thisMBB;
19466 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19467 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19468 // If not, pull from overflow_area. (branch to overflowMBB)
19473 // offsetMBB overflowMBB
19478 // Registers for the PHI in endMBB
19479 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19480 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19482 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19483 MachineFunction *MF = MBB->getParent();
19484 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19485 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19486 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19488 MachineFunction::iterator MBBIter = MBB;
19491 // Insert the new basic blocks
19492 MF->insert(MBBIter, offsetMBB);
19493 MF->insert(MBBIter, overflowMBB);
19494 MF->insert(MBBIter, endMBB);
19496 // Transfer the remainder of MBB and its successor edges to endMBB.
19497 endMBB->splice(endMBB->begin(), thisMBB,
19498 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19499 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19501 // Make offsetMBB and overflowMBB successors of thisMBB
19502 thisMBB->addSuccessor(offsetMBB);
19503 thisMBB->addSuccessor(overflowMBB);
19505 // endMBB is a successor of both offsetMBB and overflowMBB
19506 offsetMBB->addSuccessor(endMBB);
19507 overflowMBB->addSuccessor(endMBB);
19509 // Load the offset value into a register
19510 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19511 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19515 .addDisp(Disp, UseFPOffset ? 4 : 0)
19516 .addOperand(Segment)
19517 .setMemRefs(MMOBegin, MMOEnd);
19519 // Check if there is enough room left to pull this argument.
19520 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19522 .addImm(MaxOffset + 8 - ArgSizeA8);
19524 // Branch to "overflowMBB" if offset >= max
19525 // Fall through to "offsetMBB" otherwise
19526 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19527 .addMBB(overflowMBB);
19530 // In offsetMBB, emit code to use the reg_save_area.
19532 assert(OffsetReg != 0);
19534 // Read the reg_save_area address.
19535 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19536 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19541 .addOperand(Segment)
19542 .setMemRefs(MMOBegin, MMOEnd);
19544 // Zero-extend the offset
19545 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19546 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19549 .addImm(X86::sub_32bit);
19551 // Add the offset to the reg_save_area to get the final address.
19552 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19553 .addReg(OffsetReg64)
19554 .addReg(RegSaveReg);
19556 // Compute the offset for the next argument
19557 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19558 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19560 .addImm(UseFPOffset ? 16 : 8);
19562 // Store it back into the va_list.
19563 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19567 .addDisp(Disp, UseFPOffset ? 4 : 0)
19568 .addOperand(Segment)
19569 .addReg(NextOffsetReg)
19570 .setMemRefs(MMOBegin, MMOEnd);
19573 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19578 // Emit code to use overflow area
19581 // Load the overflow_area address into a register.
19582 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19583 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19588 .addOperand(Segment)
19589 .setMemRefs(MMOBegin, MMOEnd);
19591 // If we need to align it, do so. Otherwise, just copy the address
19592 // to OverflowDestReg.
19594 // Align the overflow address
19595 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19596 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19598 // aligned_addr = (addr + (align-1)) & ~(align-1)
19599 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19600 .addReg(OverflowAddrReg)
19603 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19605 .addImm(~(uint64_t)(Align-1));
19607 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19608 .addReg(OverflowAddrReg);
19611 // Compute the next overflow address after this argument.
19612 // (the overflow address should be kept 8-byte aligned)
19613 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19614 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19615 .addReg(OverflowDestReg)
19616 .addImm(ArgSizeA8);
19618 // Store the new overflow address.
19619 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19624 .addOperand(Segment)
19625 .addReg(NextAddrReg)
19626 .setMemRefs(MMOBegin, MMOEnd);
19628 // If we branched, emit the PHI to the front of endMBB.
19630 BuildMI(*endMBB, endMBB->begin(), DL,
19631 TII->get(X86::PHI), DestReg)
19632 .addReg(OffsetDestReg).addMBB(offsetMBB)
19633 .addReg(OverflowDestReg).addMBB(overflowMBB);
19636 // Erase the pseudo instruction
19637 MI->eraseFromParent();
19642 MachineBasicBlock *
19643 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19645 MachineBasicBlock *MBB) const {
19646 // Emit code to save XMM registers to the stack. The ABI says that the
19647 // number of registers to save is given in %al, so it's theoretically
19648 // possible to do an indirect jump trick to avoid saving all of them,
19649 // however this code takes a simpler approach and just executes all
19650 // of the stores if %al is non-zero. It's less code, and it's probably
19651 // easier on the hardware branch predictor, and stores aren't all that
19652 // expensive anyway.
19654 // Create the new basic blocks. One block contains all the XMM stores,
19655 // and one block is the final destination regardless of whether any
19656 // stores were performed.
19657 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19658 MachineFunction *F = MBB->getParent();
19659 MachineFunction::iterator MBBIter = MBB;
19661 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19662 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19663 F->insert(MBBIter, XMMSaveMBB);
19664 F->insert(MBBIter, EndMBB);
19666 // Transfer the remainder of MBB and its successor edges to EndMBB.
19667 EndMBB->splice(EndMBB->begin(), MBB,
19668 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19669 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19671 // The original block will now fall through to the XMM save block.
19672 MBB->addSuccessor(XMMSaveMBB);
19673 // The XMMSaveMBB will fall through to the end block.
19674 XMMSaveMBB->addSuccessor(EndMBB);
19676 // Now add the instructions.
19677 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19678 DebugLoc DL = MI->getDebugLoc();
19680 unsigned CountReg = MI->getOperand(0).getReg();
19681 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19682 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19684 if (!Subtarget->isTargetWin64()) {
19685 // If %al is 0, branch around the XMM save block.
19686 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19687 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19688 MBB->addSuccessor(EndMBB);
19691 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19692 // that was just emitted, but clearly shouldn't be "saved".
19693 assert((MI->getNumOperands() <= 3 ||
19694 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19695 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19696 && "Expected last argument to be EFLAGS");
19697 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19698 // In the XMM save block, save all the XMM argument registers.
19699 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19700 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19701 MachineMemOperand *MMO =
19702 F->getMachineMemOperand(
19703 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19704 MachineMemOperand::MOStore,
19705 /*Size=*/16, /*Align=*/16);
19706 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19707 .addFrameIndex(RegSaveFrameIndex)
19708 .addImm(/*Scale=*/1)
19709 .addReg(/*IndexReg=*/0)
19710 .addImm(/*Disp=*/Offset)
19711 .addReg(/*Segment=*/0)
19712 .addReg(MI->getOperand(i).getReg())
19713 .addMemOperand(MMO);
19716 MI->eraseFromParent(); // The pseudo instruction is gone now.
19721 // The EFLAGS operand of SelectItr might be missing a kill marker
19722 // because there were multiple uses of EFLAGS, and ISel didn't know
19723 // which to mark. Figure out whether SelectItr should have had a
19724 // kill marker, and set it if it should. Returns the correct kill
19726 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19727 MachineBasicBlock* BB,
19728 const TargetRegisterInfo* TRI) {
19729 // Scan forward through BB for a use/def of EFLAGS.
19730 MachineBasicBlock::iterator miI(std::next(SelectItr));
19731 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19732 const MachineInstr& mi = *miI;
19733 if (mi.readsRegister(X86::EFLAGS))
19735 if (mi.definesRegister(X86::EFLAGS))
19736 break; // Should have kill-flag - update below.
19739 // If we hit the end of the block, check whether EFLAGS is live into a
19741 if (miI == BB->end()) {
19742 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19743 sEnd = BB->succ_end();
19744 sItr != sEnd; ++sItr) {
19745 MachineBasicBlock* succ = *sItr;
19746 if (succ->isLiveIn(X86::EFLAGS))
19751 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19752 // out. SelectMI should have a kill flag on EFLAGS.
19753 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19757 MachineBasicBlock *
19758 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19759 MachineBasicBlock *BB) const {
19760 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19761 DebugLoc DL = MI->getDebugLoc();
19763 // To "insert" a SELECT_CC instruction, we actually have to insert the
19764 // diamond control-flow pattern. The incoming instruction knows the
19765 // destination vreg to set, the condition code register to branch on, the
19766 // true/false values to select between, and a branch opcode to use.
19767 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19768 MachineFunction::iterator It = BB;
19774 // cmpTY ccX, r1, r2
19776 // fallthrough --> copy0MBB
19777 MachineBasicBlock *thisMBB = BB;
19778 MachineFunction *F = BB->getParent();
19780 // We also lower double CMOVs:
19781 // (CMOV (CMOV F, T, cc1), T, cc2)
19782 // to two successives branches. For that, we look for another CMOV as the
19783 // following instruction.
19785 // Without this, we would add a PHI between the two jumps, which ends up
19786 // creating a few copies all around. For instance, for
19788 // (sitofp (zext (fcmp une)))
19790 // we would generate:
19792 // ucomiss %xmm1, %xmm0
19793 // movss <1.0f>, %xmm0
19794 // movaps %xmm0, %xmm1
19796 // xorps %xmm1, %xmm1
19799 // movaps %xmm1, %xmm0
19803 // because this custom-inserter would have generated:
19815 // A: X = ...; Y = ...
19817 // C: Z = PHI [X, A], [Y, B]
19819 // E: PHI [X, C], [Z, D]
19821 // If we lower both CMOVs in a single step, we can instead generate:
19833 // A: X = ...; Y = ...
19835 // E: PHI [X, A], [X, C], [Y, D]
19837 // Which, in our sitofp/fcmp example, gives us something like:
19839 // ucomiss %xmm1, %xmm0
19840 // movss <1.0f>, %xmm0
19843 // xorps %xmm0, %xmm0
19847 MachineInstr *NextCMOV = nullptr;
19848 MachineBasicBlock::iterator NextMIIt =
19849 std::next(MachineBasicBlock::iterator(MI));
19850 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19851 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19852 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19853 NextCMOV = &*NextMIIt;
19855 MachineBasicBlock *jcc1MBB = nullptr;
19857 // If we have a double CMOV, we lower it to two successive branches to
19858 // the same block. EFLAGS is used by both, so mark it as live in the second.
19860 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19861 F->insert(It, jcc1MBB);
19862 jcc1MBB->addLiveIn(X86::EFLAGS);
19865 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19866 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19867 F->insert(It, copy0MBB);
19868 F->insert(It, sinkMBB);
19870 // If the EFLAGS register isn't dead in the terminator, then claim that it's
19871 // live into the sink and copy blocks.
19872 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19874 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19875 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19876 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19877 copy0MBB->addLiveIn(X86::EFLAGS);
19878 sinkMBB->addLiveIn(X86::EFLAGS);
19881 // Transfer the remainder of BB and its successor edges to sinkMBB.
19882 sinkMBB->splice(sinkMBB->begin(), BB,
19883 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19884 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19886 // Add the true and fallthrough blocks as its successors.
19888 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19889 BB->addSuccessor(jcc1MBB);
19891 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19892 // jump to the sinkMBB.
19893 jcc1MBB->addSuccessor(copy0MBB);
19894 jcc1MBB->addSuccessor(sinkMBB);
19896 BB->addSuccessor(copy0MBB);
19899 // The true block target of the first (or only) branch is always sinkMBB.
19900 BB->addSuccessor(sinkMBB);
19902 // Create the conditional branch instruction.
19904 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19905 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19908 unsigned Opc2 = X86::GetCondBranchFromCond(
19909 (X86::CondCode)NextCMOV->getOperand(3).getImm());
19910 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19914 // %FalseValue = ...
19915 // # fallthrough to sinkMBB
19916 copy0MBB->addSuccessor(sinkMBB);
19919 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19921 MachineInstrBuilder MIB =
19922 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19923 MI->getOperand(0).getReg())
19924 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19925 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19927 // If we have a double CMOV, the second Jcc provides the same incoming
19928 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19930 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19931 // Copy the PHI result to the register defined by the second CMOV.
19932 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19933 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19934 .addReg(MI->getOperand(0).getReg());
19935 NextCMOV->eraseFromParent();
19938 MI->eraseFromParent(); // The pseudo instruction is gone now.
19942 MachineBasicBlock *
19943 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19944 MachineBasicBlock *BB) const {
19945 MachineFunction *MF = BB->getParent();
19946 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19947 DebugLoc DL = MI->getDebugLoc();
19948 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19950 assert(MF->shouldSplitStack());
19952 const bool Is64Bit = Subtarget->is64Bit();
19953 const bool IsLP64 = Subtarget->isTarget64BitLP64();
19955 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19956 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19959 // ... [Till the alloca]
19960 // If stacklet is not large enough, jump to mallocMBB
19963 // Allocate by subtracting from RSP
19964 // Jump to continueMBB
19967 // Allocate by call to runtime
19971 // [rest of original BB]
19974 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19975 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19976 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19978 MachineRegisterInfo &MRI = MF->getRegInfo();
19979 const TargetRegisterClass *AddrRegClass =
19980 getRegClassFor(getPointerTy(MF->getDataLayout()));
19982 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19983 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19984 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19985 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19986 sizeVReg = MI->getOperand(1).getReg(),
19987 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19989 MachineFunction::iterator MBBIter = BB;
19992 MF->insert(MBBIter, bumpMBB);
19993 MF->insert(MBBIter, mallocMBB);
19994 MF->insert(MBBIter, continueMBB);
19996 continueMBB->splice(continueMBB->begin(), BB,
19997 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19998 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20000 // Add code to the main basic block to check if the stack limit has been hit,
20001 // and if so, jump to mallocMBB otherwise to bumpMBB.
20002 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20003 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20004 .addReg(tmpSPVReg).addReg(sizeVReg);
20005 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20006 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20007 .addReg(SPLimitVReg);
20008 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20010 // bumpMBB simply decreases the stack pointer, since we know the current
20011 // stacklet has enough space.
20012 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20013 .addReg(SPLimitVReg);
20014 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20015 .addReg(SPLimitVReg);
20016 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20018 // Calls into a routine in libgcc to allocate more space from the heap.
20019 const uint32_t *RegMask =
20020 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20022 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20024 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20025 .addExternalSymbol("__morestack_allocate_stack_space")
20026 .addRegMask(RegMask)
20027 .addReg(X86::RDI, RegState::Implicit)
20028 .addReg(X86::RAX, RegState::ImplicitDefine);
20029 } else if (Is64Bit) {
20030 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20032 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20033 .addExternalSymbol("__morestack_allocate_stack_space")
20034 .addRegMask(RegMask)
20035 .addReg(X86::EDI, RegState::Implicit)
20036 .addReg(X86::EAX, RegState::ImplicitDefine);
20038 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20040 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20041 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20042 .addExternalSymbol("__morestack_allocate_stack_space")
20043 .addRegMask(RegMask)
20044 .addReg(X86::EAX, RegState::ImplicitDefine);
20048 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20051 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20052 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20053 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20055 // Set up the CFG correctly.
20056 BB->addSuccessor(bumpMBB);
20057 BB->addSuccessor(mallocMBB);
20058 mallocMBB->addSuccessor(continueMBB);
20059 bumpMBB->addSuccessor(continueMBB);
20061 // Take care of the PHI nodes.
20062 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20063 MI->getOperand(0).getReg())
20064 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20065 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20067 // Delete the original pseudo instruction.
20068 MI->eraseFromParent();
20071 return continueMBB;
20074 MachineBasicBlock *
20075 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20076 MachineBasicBlock *BB) const {
20077 DebugLoc DL = MI->getDebugLoc();
20079 assert(!Subtarget->isTargetMachO());
20081 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20084 MI->eraseFromParent(); // The pseudo instruction is gone now.
20088 MachineBasicBlock *
20089 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20090 MachineBasicBlock *BB) const {
20091 // This is pretty easy. We're taking the value that we received from
20092 // our load from the relocation, sticking it in either RDI (x86-64)
20093 // or EAX and doing an indirect call. The return value will then
20094 // be in the normal return register.
20095 MachineFunction *F = BB->getParent();
20096 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20097 DebugLoc DL = MI->getDebugLoc();
20099 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20100 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20102 // Get a register mask for the lowered call.
20103 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20104 // proper register mask.
20105 const uint32_t *RegMask =
20106 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20107 if (Subtarget->is64Bit()) {
20108 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20109 TII->get(X86::MOV64rm), X86::RDI)
20111 .addImm(0).addReg(0)
20112 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20113 MI->getOperand(3).getTargetFlags())
20115 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20116 addDirectMem(MIB, X86::RDI);
20117 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20118 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20119 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20120 TII->get(X86::MOV32rm), X86::EAX)
20122 .addImm(0).addReg(0)
20123 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20124 MI->getOperand(3).getTargetFlags())
20126 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20127 addDirectMem(MIB, X86::EAX);
20128 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20130 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20131 TII->get(X86::MOV32rm), X86::EAX)
20132 .addReg(TII->getGlobalBaseReg(F))
20133 .addImm(0).addReg(0)
20134 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20135 MI->getOperand(3).getTargetFlags())
20137 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20138 addDirectMem(MIB, X86::EAX);
20139 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20142 MI->eraseFromParent(); // The pseudo instruction is gone now.
20146 MachineBasicBlock *
20147 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20148 MachineBasicBlock *MBB) const {
20149 DebugLoc DL = MI->getDebugLoc();
20150 MachineFunction *MF = MBB->getParent();
20151 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20152 MachineRegisterInfo &MRI = MF->getRegInfo();
20154 const BasicBlock *BB = MBB->getBasicBlock();
20155 MachineFunction::iterator I = MBB;
20158 // Memory Reference
20159 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20160 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20163 unsigned MemOpndSlot = 0;
20165 unsigned CurOp = 0;
20167 DstReg = MI->getOperand(CurOp++).getReg();
20168 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20169 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20170 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20171 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20173 MemOpndSlot = CurOp;
20175 MVT PVT = getPointerTy(MF->getDataLayout());
20176 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20177 "Invalid Pointer Size!");
20179 // For v = setjmp(buf), we generate
20182 // buf[LabelOffset] = restoreMBB
20183 // SjLjSetup restoreMBB
20189 // v = phi(main, restore)
20192 // if base pointer being used, load it from frame
20195 MachineBasicBlock *thisMBB = MBB;
20196 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20197 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20198 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20199 MF->insert(I, mainMBB);
20200 MF->insert(I, sinkMBB);
20201 MF->push_back(restoreMBB);
20203 MachineInstrBuilder MIB;
20205 // Transfer the remainder of BB and its successor edges to sinkMBB.
20206 sinkMBB->splice(sinkMBB->begin(), MBB,
20207 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20208 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20211 unsigned PtrStoreOpc = 0;
20212 unsigned LabelReg = 0;
20213 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20214 Reloc::Model RM = MF->getTarget().getRelocationModel();
20215 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20216 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20218 // Prepare IP either in reg or imm.
20219 if (!UseImmLabel) {
20220 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20221 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20222 LabelReg = MRI.createVirtualRegister(PtrRC);
20223 if (Subtarget->is64Bit()) {
20224 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20228 .addMBB(restoreMBB)
20231 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20232 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20233 .addReg(XII->getGlobalBaseReg(MF))
20236 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20240 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20242 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20243 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20244 if (i == X86::AddrDisp)
20245 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20247 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20250 MIB.addReg(LabelReg);
20252 MIB.addMBB(restoreMBB);
20253 MIB.setMemRefs(MMOBegin, MMOEnd);
20255 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20256 .addMBB(restoreMBB);
20258 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20259 MIB.addRegMask(RegInfo->getNoPreservedMask());
20260 thisMBB->addSuccessor(mainMBB);
20261 thisMBB->addSuccessor(restoreMBB);
20265 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20266 mainMBB->addSuccessor(sinkMBB);
20269 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20270 TII->get(X86::PHI), DstReg)
20271 .addReg(mainDstReg).addMBB(mainMBB)
20272 .addReg(restoreDstReg).addMBB(restoreMBB);
20275 if (RegInfo->hasBasePointer(*MF)) {
20276 const bool Uses64BitFramePtr =
20277 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20278 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20279 X86FI->setRestoreBasePointer(MF);
20280 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20281 unsigned BasePtr = RegInfo->getBaseRegister();
20282 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20283 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20284 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20285 .setMIFlag(MachineInstr::FrameSetup);
20287 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20288 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20289 restoreMBB->addSuccessor(sinkMBB);
20291 MI->eraseFromParent();
20295 MachineBasicBlock *
20296 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20297 MachineBasicBlock *MBB) const {
20298 DebugLoc DL = MI->getDebugLoc();
20299 MachineFunction *MF = MBB->getParent();
20300 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20301 MachineRegisterInfo &MRI = MF->getRegInfo();
20303 // Memory Reference
20304 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20305 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20307 MVT PVT = getPointerTy(MF->getDataLayout());
20308 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20309 "Invalid Pointer Size!");
20311 const TargetRegisterClass *RC =
20312 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20313 unsigned Tmp = MRI.createVirtualRegister(RC);
20314 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20315 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20316 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20317 unsigned SP = RegInfo->getStackRegister();
20319 MachineInstrBuilder MIB;
20321 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20322 const int64_t SPOffset = 2 * PVT.getStoreSize();
20324 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20325 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20328 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20329 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20330 MIB.addOperand(MI->getOperand(i));
20331 MIB.setMemRefs(MMOBegin, MMOEnd);
20333 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20334 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20335 if (i == X86::AddrDisp)
20336 MIB.addDisp(MI->getOperand(i), LabelOffset);
20338 MIB.addOperand(MI->getOperand(i));
20340 MIB.setMemRefs(MMOBegin, MMOEnd);
20342 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20343 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20344 if (i == X86::AddrDisp)
20345 MIB.addDisp(MI->getOperand(i), SPOffset);
20347 MIB.addOperand(MI->getOperand(i));
20349 MIB.setMemRefs(MMOBegin, MMOEnd);
20351 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20353 MI->eraseFromParent();
20357 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20358 // accumulator loops. Writing back to the accumulator allows the coalescer
20359 // to remove extra copies in the loop.
20360 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20361 MachineBasicBlock *
20362 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20363 MachineBasicBlock *MBB) const {
20364 MachineOperand &AddendOp = MI->getOperand(3);
20366 // Bail out early if the addend isn't a register - we can't switch these.
20367 if (!AddendOp.isReg())
20370 MachineFunction &MF = *MBB->getParent();
20371 MachineRegisterInfo &MRI = MF.getRegInfo();
20373 // Check whether the addend is defined by a PHI:
20374 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20375 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20376 if (!AddendDef.isPHI())
20379 // Look for the following pattern:
20381 // %addend = phi [%entry, 0], [%loop, %result]
20383 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20387 // %addend = phi [%entry, 0], [%loop, %result]
20389 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20391 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20392 assert(AddendDef.getOperand(i).isReg());
20393 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20394 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20395 if (&PHISrcInst == MI) {
20396 // Found a matching instruction.
20397 unsigned NewFMAOpc = 0;
20398 switch (MI->getOpcode()) {
20399 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20400 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20401 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20402 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20403 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20404 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20405 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20406 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20407 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20408 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20409 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20410 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20411 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20412 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20413 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20414 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20415 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20416 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20417 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20418 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20420 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20421 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20422 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20423 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20424 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20425 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20426 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20427 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20428 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20429 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20430 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20431 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20432 default: llvm_unreachable("Unrecognized FMA variant.");
20435 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20436 MachineInstrBuilder MIB =
20437 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20438 .addOperand(MI->getOperand(0))
20439 .addOperand(MI->getOperand(3))
20440 .addOperand(MI->getOperand(2))
20441 .addOperand(MI->getOperand(1));
20442 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20443 MI->eraseFromParent();
20450 MachineBasicBlock *
20451 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20452 MachineBasicBlock *BB) const {
20453 switch (MI->getOpcode()) {
20454 default: llvm_unreachable("Unexpected instr type to insert");
20455 case X86::TAILJMPd64:
20456 case X86::TAILJMPr64:
20457 case X86::TAILJMPm64:
20458 case X86::TAILJMPd64_REX:
20459 case X86::TAILJMPr64_REX:
20460 case X86::TAILJMPm64_REX:
20461 llvm_unreachable("TAILJMP64 would not be touched here.");
20462 case X86::TCRETURNdi64:
20463 case X86::TCRETURNri64:
20464 case X86::TCRETURNmi64:
20466 case X86::WIN_ALLOCA:
20467 return EmitLoweredWinAlloca(MI, BB);
20468 case X86::SEG_ALLOCA_32:
20469 case X86::SEG_ALLOCA_64:
20470 return EmitLoweredSegAlloca(MI, BB);
20471 case X86::TLSCall_32:
20472 case X86::TLSCall_64:
20473 return EmitLoweredTLSCall(MI, BB);
20474 case X86::CMOV_GR8:
20475 case X86::CMOV_FR32:
20476 case X86::CMOV_FR64:
20477 case X86::CMOV_V4F32:
20478 case X86::CMOV_V2F64:
20479 case X86::CMOV_V2I64:
20480 case X86::CMOV_V8F32:
20481 case X86::CMOV_V4F64:
20482 case X86::CMOV_V4I64:
20483 case X86::CMOV_V16F32:
20484 case X86::CMOV_V8F64:
20485 case X86::CMOV_V8I64:
20486 case X86::CMOV_GR16:
20487 case X86::CMOV_GR32:
20488 case X86::CMOV_RFP32:
20489 case X86::CMOV_RFP64:
20490 case X86::CMOV_RFP80:
20491 case X86::CMOV_V8I1:
20492 case X86::CMOV_V16I1:
20493 case X86::CMOV_V32I1:
20494 case X86::CMOV_V64I1:
20495 return EmitLoweredSelect(MI, BB);
20497 case X86::FP32_TO_INT16_IN_MEM:
20498 case X86::FP32_TO_INT32_IN_MEM:
20499 case X86::FP32_TO_INT64_IN_MEM:
20500 case X86::FP64_TO_INT16_IN_MEM:
20501 case X86::FP64_TO_INT32_IN_MEM:
20502 case X86::FP64_TO_INT64_IN_MEM:
20503 case X86::FP80_TO_INT16_IN_MEM:
20504 case X86::FP80_TO_INT32_IN_MEM:
20505 case X86::FP80_TO_INT64_IN_MEM: {
20506 MachineFunction *F = BB->getParent();
20507 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20508 DebugLoc DL = MI->getDebugLoc();
20510 // Change the floating point control register to use "round towards zero"
20511 // mode when truncating to an integer value.
20512 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20513 addFrameReference(BuildMI(*BB, MI, DL,
20514 TII->get(X86::FNSTCW16m)), CWFrameIdx);
20516 // Load the old value of the high byte of the control word...
20518 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20519 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20522 // Set the high part to be round to zero...
20523 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20526 // Reload the modified control word now...
20527 addFrameReference(BuildMI(*BB, MI, DL,
20528 TII->get(X86::FLDCW16m)), CWFrameIdx);
20530 // Restore the memory image of control word to original value
20531 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20534 // Get the X86 opcode to use.
20536 switch (MI->getOpcode()) {
20537 default: llvm_unreachable("illegal opcode!");
20538 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20539 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20540 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20541 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20542 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20543 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20544 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20545 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20546 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20550 MachineOperand &Op = MI->getOperand(0);
20552 AM.BaseType = X86AddressMode::RegBase;
20553 AM.Base.Reg = Op.getReg();
20555 AM.BaseType = X86AddressMode::FrameIndexBase;
20556 AM.Base.FrameIndex = Op.getIndex();
20558 Op = MI->getOperand(1);
20560 AM.Scale = Op.getImm();
20561 Op = MI->getOperand(2);
20563 AM.IndexReg = Op.getImm();
20564 Op = MI->getOperand(3);
20565 if (Op.isGlobal()) {
20566 AM.GV = Op.getGlobal();
20568 AM.Disp = Op.getImm();
20570 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20571 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20573 // Reload the original control word now.
20574 addFrameReference(BuildMI(*BB, MI, DL,
20575 TII->get(X86::FLDCW16m)), CWFrameIdx);
20577 MI->eraseFromParent(); // The pseudo instruction is gone now.
20580 // String/text processing lowering.
20581 case X86::PCMPISTRM128REG:
20582 case X86::VPCMPISTRM128REG:
20583 case X86::PCMPISTRM128MEM:
20584 case X86::VPCMPISTRM128MEM:
20585 case X86::PCMPESTRM128REG:
20586 case X86::VPCMPESTRM128REG:
20587 case X86::PCMPESTRM128MEM:
20588 case X86::VPCMPESTRM128MEM:
20589 assert(Subtarget->hasSSE42() &&
20590 "Target must have SSE4.2 or AVX features enabled");
20591 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20593 // String/text processing lowering.
20594 case X86::PCMPISTRIREG:
20595 case X86::VPCMPISTRIREG:
20596 case X86::PCMPISTRIMEM:
20597 case X86::VPCMPISTRIMEM:
20598 case X86::PCMPESTRIREG:
20599 case X86::VPCMPESTRIREG:
20600 case X86::PCMPESTRIMEM:
20601 case X86::VPCMPESTRIMEM:
20602 assert(Subtarget->hasSSE42() &&
20603 "Target must have SSE4.2 or AVX features enabled");
20604 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20606 // Thread synchronization.
20608 return EmitMonitor(MI, BB, Subtarget);
20612 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20614 case X86::VASTART_SAVE_XMM_REGS:
20615 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20617 case X86::VAARG_64:
20618 return EmitVAARG64WithCustomInserter(MI, BB);
20620 case X86::EH_SjLj_SetJmp32:
20621 case X86::EH_SjLj_SetJmp64:
20622 return emitEHSjLjSetJmp(MI, BB);
20624 case X86::EH_SjLj_LongJmp32:
20625 case X86::EH_SjLj_LongJmp64:
20626 return emitEHSjLjLongJmp(MI, BB);
20628 case TargetOpcode::STATEPOINT:
20629 // As an implementation detail, STATEPOINT shares the STACKMAP format at
20630 // this point in the process. We diverge later.
20631 return emitPatchPoint(MI, BB);
20633 case TargetOpcode::STACKMAP:
20634 case TargetOpcode::PATCHPOINT:
20635 return emitPatchPoint(MI, BB);
20637 case X86::VFMADDPDr213r:
20638 case X86::VFMADDPSr213r:
20639 case X86::VFMADDSDr213r:
20640 case X86::VFMADDSSr213r:
20641 case X86::VFMSUBPDr213r:
20642 case X86::VFMSUBPSr213r:
20643 case X86::VFMSUBSDr213r:
20644 case X86::VFMSUBSSr213r:
20645 case X86::VFNMADDPDr213r:
20646 case X86::VFNMADDPSr213r:
20647 case X86::VFNMADDSDr213r:
20648 case X86::VFNMADDSSr213r:
20649 case X86::VFNMSUBPDr213r:
20650 case X86::VFNMSUBPSr213r:
20651 case X86::VFNMSUBSDr213r:
20652 case X86::VFNMSUBSSr213r:
20653 case X86::VFMADDSUBPDr213r:
20654 case X86::VFMADDSUBPSr213r:
20655 case X86::VFMSUBADDPDr213r:
20656 case X86::VFMSUBADDPSr213r:
20657 case X86::VFMADDPDr213rY:
20658 case X86::VFMADDPSr213rY:
20659 case X86::VFMSUBPDr213rY:
20660 case X86::VFMSUBPSr213rY:
20661 case X86::VFNMADDPDr213rY:
20662 case X86::VFNMADDPSr213rY:
20663 case X86::VFNMSUBPDr213rY:
20664 case X86::VFNMSUBPSr213rY:
20665 case X86::VFMADDSUBPDr213rY:
20666 case X86::VFMADDSUBPSr213rY:
20667 case X86::VFMSUBADDPDr213rY:
20668 case X86::VFMSUBADDPSr213rY:
20669 return emitFMA3Instr(MI, BB);
20673 //===----------------------------------------------------------------------===//
20674 // X86 Optimization Hooks
20675 //===----------------------------------------------------------------------===//
20677 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20680 const SelectionDAG &DAG,
20681 unsigned Depth) const {
20682 unsigned BitWidth = KnownZero.getBitWidth();
20683 unsigned Opc = Op.getOpcode();
20684 assert((Opc >= ISD::BUILTIN_OP_END ||
20685 Opc == ISD::INTRINSIC_WO_CHAIN ||
20686 Opc == ISD::INTRINSIC_W_CHAIN ||
20687 Opc == ISD::INTRINSIC_VOID) &&
20688 "Should use MaskedValueIsZero if you don't know whether Op"
20689 " is a target node!");
20691 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
20705 // These nodes' second result is a boolean.
20706 if (Op.getResNo() == 0)
20709 case X86ISD::SETCC:
20710 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20712 case ISD::INTRINSIC_WO_CHAIN: {
20713 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20714 unsigned NumLoBits = 0;
20717 case Intrinsic::x86_sse_movmsk_ps:
20718 case Intrinsic::x86_avx_movmsk_ps_256:
20719 case Intrinsic::x86_sse2_movmsk_pd:
20720 case Intrinsic::x86_avx_movmsk_pd_256:
20721 case Intrinsic::x86_mmx_pmovmskb:
20722 case Intrinsic::x86_sse2_pmovmskb_128:
20723 case Intrinsic::x86_avx2_pmovmskb: {
20724 // High bits of movmskp{s|d}, pmovmskb are known zero.
20726 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
20727 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
20728 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
20729 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
20730 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
20731 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
20732 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
20733 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
20735 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20744 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20746 const SelectionDAG &,
20747 unsigned Depth) const {
20748 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20749 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20750 return Op.getValueType().getScalarType().getSizeInBits();
20756 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20757 /// node is a GlobalAddress + offset.
20758 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20759 const GlobalValue* &GA,
20760 int64_t &Offset) const {
20761 if (N->getOpcode() == X86ISD::Wrapper) {
20762 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20763 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20764 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20768 return TargetLowering::isGAPlusOffset(N, GA, Offset);
20771 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20772 /// same as extracting the high 128-bit part of 256-bit vector and then
20773 /// inserting the result into the low part of a new 256-bit vector
20774 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20775 EVT VT = SVOp->getValueType(0);
20776 unsigned NumElems = VT.getVectorNumElements();
20778 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20779 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20780 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20781 SVOp->getMaskElt(j) >= 0)
20787 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20788 /// same as extracting the low 128-bit part of 256-bit vector and then
20789 /// inserting the result into the high part of a new 256-bit vector
20790 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20791 EVT VT = SVOp->getValueType(0);
20792 unsigned NumElems = VT.getVectorNumElements();
20794 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20795 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20796 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20797 SVOp->getMaskElt(j) >= 0)
20803 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20804 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20805 TargetLowering::DAGCombinerInfo &DCI,
20806 const X86Subtarget* Subtarget) {
20808 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20809 SDValue V1 = SVOp->getOperand(0);
20810 SDValue V2 = SVOp->getOperand(1);
20811 EVT VT = SVOp->getValueType(0);
20812 unsigned NumElems = VT.getVectorNumElements();
20814 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20815 V2.getOpcode() == ISD::CONCAT_VECTORS) {
20819 // V UNDEF BUILD_VECTOR UNDEF
20821 // CONCAT_VECTOR CONCAT_VECTOR
20824 // RESULT: V + zero extended
20826 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20827 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20828 V1.getOperand(1).getOpcode() != ISD::UNDEF)
20831 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20834 // To match the shuffle mask, the first half of the mask should
20835 // be exactly the first vector, and all the rest a splat with the
20836 // first element of the second one.
20837 for (unsigned i = 0; i != NumElems/2; ++i)
20838 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20839 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20842 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20843 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20844 if (Ld->hasNUsesOfValue(1, 0)) {
20845 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20846 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20848 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20850 Ld->getPointerInfo(),
20851 Ld->getAlignment(),
20852 false/*isVolatile*/, true/*ReadMem*/,
20853 false/*WriteMem*/);
20855 // Make sure the newly-created LOAD is in the same position as Ld in
20856 // terms of dependency. We create a TokenFactor for Ld and ResNode,
20857 // and update uses of Ld's output chain to use the TokenFactor.
20858 if (Ld->hasAnyUseOfValue(1)) {
20859 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20860 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20861 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20862 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20863 SDValue(ResNode.getNode(), 1));
20866 return DAG.getBitcast(VT, ResNode);
20870 // Emit a zeroed vector and insert the desired subvector on its
20872 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20873 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20874 return DCI.CombineTo(N, InsV);
20877 //===--------------------------------------------------------------------===//
20878 // Combine some shuffles into subvector extracts and inserts:
20881 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20882 if (isShuffleHigh128VectorInsertLow(SVOp)) {
20883 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20884 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20885 return DCI.CombineTo(N, InsV);
20888 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20889 if (isShuffleLow128VectorInsertHigh(SVOp)) {
20890 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20891 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20892 return DCI.CombineTo(N, InsV);
20898 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20901 /// This is the leaf of the recursive combinine below. When we have found some
20902 /// chain of single-use x86 shuffle instructions and accumulated the combined
20903 /// shuffle mask represented by them, this will try to pattern match that mask
20904 /// into either a single instruction if there is a special purpose instruction
20905 /// for this operation, or into a PSHUFB instruction which is a fully general
20906 /// instruction but should only be used to replace chains over a certain depth.
20907 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20908 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20909 TargetLowering::DAGCombinerInfo &DCI,
20910 const X86Subtarget *Subtarget) {
20911 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20913 // Find the operand that enters the chain. Note that multiple uses are OK
20914 // here, we're not going to remove the operand we find.
20915 SDValue Input = Op.getOperand(0);
20916 while (Input.getOpcode() == ISD::BITCAST)
20917 Input = Input.getOperand(0);
20919 MVT VT = Input.getSimpleValueType();
20920 MVT RootVT = Root.getSimpleValueType();
20923 // Just remove no-op shuffle masks.
20924 if (Mask.size() == 1) {
20925 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20930 // Use the float domain if the operand type is a floating point type.
20931 bool FloatDomain = VT.isFloatingPoint();
20933 // For floating point shuffles, we don't have free copies in the shuffle
20934 // instructions or the ability to load as part of the instruction, so
20935 // canonicalize their shuffles to UNPCK or MOV variants.
20937 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20938 // vectors because it can have a load folded into it that UNPCK cannot. This
20939 // doesn't preclude something switching to the shorter encoding post-RA.
20941 // FIXME: Should teach these routines about AVX vector widths.
20942 if (FloatDomain && VT.getSizeInBits() == 128) {
20943 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20944 bool Lo = Mask.equals({0, 0});
20947 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20948 // is no slower than UNPCKLPD but has the option to fold the input operand
20949 // into even an unaligned memory load.
20950 if (Lo && Subtarget->hasSSE3()) {
20951 Shuffle = X86ISD::MOVDDUP;
20952 ShuffleVT = MVT::v2f64;
20954 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20955 // than the UNPCK variants.
20956 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20957 ShuffleVT = MVT::v4f32;
20959 if (Depth == 1 && Root->getOpcode() == Shuffle)
20960 return false; // Nothing to do!
20961 Op = DAG.getBitcast(ShuffleVT, Input);
20962 DCI.AddToWorklist(Op.getNode());
20963 if (Shuffle == X86ISD::MOVDDUP)
20964 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20966 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20967 DCI.AddToWorklist(Op.getNode());
20968 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20972 if (Subtarget->hasSSE3() &&
20973 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20974 bool Lo = Mask.equals({0, 0, 2, 2});
20975 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20976 MVT ShuffleVT = MVT::v4f32;
20977 if (Depth == 1 && Root->getOpcode() == Shuffle)
20978 return false; // Nothing to do!
20979 Op = DAG.getBitcast(ShuffleVT, Input);
20980 DCI.AddToWorklist(Op.getNode());
20981 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20982 DCI.AddToWorklist(Op.getNode());
20983 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20987 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20988 bool Lo = Mask.equals({0, 0, 1, 1});
20989 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20990 MVT ShuffleVT = MVT::v4f32;
20991 if (Depth == 1 && Root->getOpcode() == Shuffle)
20992 return false; // Nothing to do!
20993 Op = DAG.getBitcast(ShuffleVT, Input);
20994 DCI.AddToWorklist(Op.getNode());
20995 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20996 DCI.AddToWorklist(Op.getNode());
20997 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21003 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21004 // variants as none of these have single-instruction variants that are
21005 // superior to the UNPCK formulation.
21006 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21007 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21008 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21009 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21011 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21012 bool Lo = Mask[0] == 0;
21013 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21014 if (Depth == 1 && Root->getOpcode() == Shuffle)
21015 return false; // Nothing to do!
21017 switch (Mask.size()) {
21019 ShuffleVT = MVT::v8i16;
21022 ShuffleVT = MVT::v16i8;
21025 llvm_unreachable("Impossible mask size!");
21027 Op = DAG.getBitcast(ShuffleVT, Input);
21028 DCI.AddToWorklist(Op.getNode());
21029 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21030 DCI.AddToWorklist(Op.getNode());
21031 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21036 // Don't try to re-form single instruction chains under any circumstances now
21037 // that we've done encoding canonicalization for them.
21041 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21042 // can replace them with a single PSHUFB instruction profitably. Intel's
21043 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21044 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21045 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21046 SmallVector<SDValue, 16> PSHUFBMask;
21047 int NumBytes = VT.getSizeInBits() / 8;
21048 int Ratio = NumBytes / Mask.size();
21049 for (int i = 0; i < NumBytes; ++i) {
21050 if (Mask[i / Ratio] == SM_SentinelUndef) {
21051 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21054 int M = Mask[i / Ratio] != SM_SentinelZero
21055 ? Ratio * Mask[i / Ratio] + i % Ratio
21057 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21059 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21060 Op = DAG.getBitcast(ByteVT, Input);
21061 DCI.AddToWorklist(Op.getNode());
21062 SDValue PSHUFBMaskOp =
21063 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21064 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21065 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21066 DCI.AddToWorklist(Op.getNode());
21067 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21072 // Failed to find any combines.
21076 /// \brief Fully generic combining of x86 shuffle instructions.
21078 /// This should be the last combine run over the x86 shuffle instructions. Once
21079 /// they have been fully optimized, this will recursively consider all chains
21080 /// of single-use shuffle instructions, build a generic model of the cumulative
21081 /// shuffle operation, and check for simpler instructions which implement this
21082 /// operation. We use this primarily for two purposes:
21084 /// 1) Collapse generic shuffles to specialized single instructions when
21085 /// equivalent. In most cases, this is just an encoding size win, but
21086 /// sometimes we will collapse multiple generic shuffles into a single
21087 /// special-purpose shuffle.
21088 /// 2) Look for sequences of shuffle instructions with 3 or more total
21089 /// instructions, and replace them with the slightly more expensive SSSE3
21090 /// PSHUFB instruction if available. We do this as the last combining step
21091 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21092 /// a suitable short sequence of other instructions. The PHUFB will either
21093 /// use a register or have to read from memory and so is slightly (but only
21094 /// slightly) more expensive than the other shuffle instructions.
21096 /// Because this is inherently a quadratic operation (for each shuffle in
21097 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21098 /// This should never be an issue in practice as the shuffle lowering doesn't
21099 /// produce sequences of more than 8 instructions.
21101 /// FIXME: We will currently miss some cases where the redundant shuffling
21102 /// would simplify under the threshold for PSHUFB formation because of
21103 /// combine-ordering. To fix this, we should do the redundant instruction
21104 /// combining in this recursive walk.
21105 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21106 ArrayRef<int> RootMask,
21107 int Depth, bool HasPSHUFB,
21109 TargetLowering::DAGCombinerInfo &DCI,
21110 const X86Subtarget *Subtarget) {
21111 // Bound the depth of our recursive combine because this is ultimately
21112 // quadratic in nature.
21116 // Directly rip through bitcasts to find the underlying operand.
21117 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21118 Op = Op.getOperand(0);
21120 MVT VT = Op.getSimpleValueType();
21121 if (!VT.isVector())
21122 return false; // Bail if we hit a non-vector.
21124 assert(Root.getSimpleValueType().isVector() &&
21125 "Shuffles operate on vector types!");
21126 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21127 "Can only combine shuffles of the same vector register size.");
21129 if (!isTargetShuffle(Op.getOpcode()))
21131 SmallVector<int, 16> OpMask;
21133 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21134 // We only can combine unary shuffles which we can decode the mask for.
21135 if (!HaveMask || !IsUnary)
21138 assert(VT.getVectorNumElements() == OpMask.size() &&
21139 "Different mask size from vector size!");
21140 assert(((RootMask.size() > OpMask.size() &&
21141 RootMask.size() % OpMask.size() == 0) ||
21142 (OpMask.size() > RootMask.size() &&
21143 OpMask.size() % RootMask.size() == 0) ||
21144 OpMask.size() == RootMask.size()) &&
21145 "The smaller number of elements must divide the larger.");
21146 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21147 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21148 assert(((RootRatio == 1 && OpRatio == 1) ||
21149 (RootRatio == 1) != (OpRatio == 1)) &&
21150 "Must not have a ratio for both incoming and op masks!");
21152 SmallVector<int, 16> Mask;
21153 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21155 // Merge this shuffle operation's mask into our accumulated mask. Note that
21156 // this shuffle's mask will be the first applied to the input, followed by the
21157 // root mask to get us all the way to the root value arrangement. The reason
21158 // for this order is that we are recursing up the operation chain.
21159 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21160 int RootIdx = i / RootRatio;
21161 if (RootMask[RootIdx] < 0) {
21162 // This is a zero or undef lane, we're done.
21163 Mask.push_back(RootMask[RootIdx]);
21167 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21168 int OpIdx = RootMaskedIdx / OpRatio;
21169 if (OpMask[OpIdx] < 0) {
21170 // The incoming lanes are zero or undef, it doesn't matter which ones we
21172 Mask.push_back(OpMask[OpIdx]);
21176 // Ok, we have non-zero lanes, map them through.
21177 Mask.push_back(OpMask[OpIdx] * OpRatio +
21178 RootMaskedIdx % OpRatio);
21181 // See if we can recurse into the operand to combine more things.
21182 switch (Op.getOpcode()) {
21183 case X86ISD::PSHUFB:
21185 case X86ISD::PSHUFD:
21186 case X86ISD::PSHUFHW:
21187 case X86ISD::PSHUFLW:
21188 if (Op.getOperand(0).hasOneUse() &&
21189 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21190 HasPSHUFB, DAG, DCI, Subtarget))
21194 case X86ISD::UNPCKL:
21195 case X86ISD::UNPCKH:
21196 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21197 // We can't check for single use, we have to check that this shuffle is the only user.
21198 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21199 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21200 HasPSHUFB, DAG, DCI, Subtarget))
21205 // Minor canonicalization of the accumulated shuffle mask to make it easier
21206 // to match below. All this does is detect masks with squential pairs of
21207 // elements, and shrink them to the half-width mask. It does this in a loop
21208 // so it will reduce the size of the mask to the minimal width mask which
21209 // performs an equivalent shuffle.
21210 SmallVector<int, 16> WidenedMask;
21211 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21212 Mask = std::move(WidenedMask);
21213 WidenedMask.clear();
21216 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21220 /// \brief Get the PSHUF-style mask from PSHUF node.
21222 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21223 /// PSHUF-style masks that can be reused with such instructions.
21224 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21225 MVT VT = N.getSimpleValueType();
21226 SmallVector<int, 4> Mask;
21228 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21232 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21233 // matter. Check that the upper masks are repeats and remove them.
21234 if (VT.getSizeInBits() > 128) {
21235 int LaneElts = 128 / VT.getScalarSizeInBits();
21237 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21238 for (int j = 0; j < LaneElts; ++j)
21239 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21240 "Mask doesn't repeat in high 128-bit lanes!");
21242 Mask.resize(LaneElts);
21245 switch (N.getOpcode()) {
21246 case X86ISD::PSHUFD:
21248 case X86ISD::PSHUFLW:
21251 case X86ISD::PSHUFHW:
21252 Mask.erase(Mask.begin(), Mask.begin() + 4);
21253 for (int &M : Mask)
21257 llvm_unreachable("No valid shuffle instruction found!");
21261 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21263 /// We walk up the chain and look for a combinable shuffle, skipping over
21264 /// shuffles that we could hoist this shuffle's transformation past without
21265 /// altering anything.
21267 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21269 TargetLowering::DAGCombinerInfo &DCI) {
21270 assert(N.getOpcode() == X86ISD::PSHUFD &&
21271 "Called with something other than an x86 128-bit half shuffle!");
21274 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21275 // of the shuffles in the chain so that we can form a fresh chain to replace
21277 SmallVector<SDValue, 8> Chain;
21278 SDValue V = N.getOperand(0);
21279 for (; V.hasOneUse(); V = V.getOperand(0)) {
21280 switch (V.getOpcode()) {
21282 return SDValue(); // Nothing combined!
21285 // Skip bitcasts as we always know the type for the target specific
21289 case X86ISD::PSHUFD:
21290 // Found another dword shuffle.
21293 case X86ISD::PSHUFLW:
21294 // Check that the low words (being shuffled) are the identity in the
21295 // dword shuffle, and the high words are self-contained.
21296 if (Mask[0] != 0 || Mask[1] != 1 ||
21297 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21300 Chain.push_back(V);
21303 case X86ISD::PSHUFHW:
21304 // Check that the high words (being shuffled) are the identity in the
21305 // dword shuffle, and the low words are self-contained.
21306 if (Mask[2] != 2 || Mask[3] != 3 ||
21307 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21310 Chain.push_back(V);
21313 case X86ISD::UNPCKL:
21314 case X86ISD::UNPCKH:
21315 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21316 // shuffle into a preceding word shuffle.
21317 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21318 V.getSimpleValueType().getScalarType() != MVT::i16)
21321 // Search for a half-shuffle which we can combine with.
21322 unsigned CombineOp =
21323 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21324 if (V.getOperand(0) != V.getOperand(1) ||
21325 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21327 Chain.push_back(V);
21328 V = V.getOperand(0);
21330 switch (V.getOpcode()) {
21332 return SDValue(); // Nothing to combine.
21334 case X86ISD::PSHUFLW:
21335 case X86ISD::PSHUFHW:
21336 if (V.getOpcode() == CombineOp)
21339 Chain.push_back(V);
21343 V = V.getOperand(0);
21347 } while (V.hasOneUse());
21350 // Break out of the loop if we break out of the switch.
21354 if (!V.hasOneUse())
21355 // We fell out of the loop without finding a viable combining instruction.
21358 // Merge this node's mask and our incoming mask.
21359 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21360 for (int &M : Mask)
21362 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21363 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21365 // Rebuild the chain around this new shuffle.
21366 while (!Chain.empty()) {
21367 SDValue W = Chain.pop_back_val();
21369 if (V.getValueType() != W.getOperand(0).getValueType())
21370 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21372 switch (W.getOpcode()) {
21374 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21376 case X86ISD::UNPCKL:
21377 case X86ISD::UNPCKH:
21378 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21381 case X86ISD::PSHUFD:
21382 case X86ISD::PSHUFLW:
21383 case X86ISD::PSHUFHW:
21384 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21388 if (V.getValueType() != N.getValueType())
21389 V = DAG.getBitcast(N.getValueType(), V);
21391 // Return the new chain to replace N.
21395 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21397 /// We walk up the chain, skipping shuffles of the other half and looking
21398 /// through shuffles which switch halves trying to find a shuffle of the same
21399 /// pair of dwords.
21400 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21402 TargetLowering::DAGCombinerInfo &DCI) {
21404 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21405 "Called with something other than an x86 128-bit half shuffle!");
21407 unsigned CombineOpcode = N.getOpcode();
21409 // Walk up a single-use chain looking for a combinable shuffle.
21410 SDValue V = N.getOperand(0);
21411 for (; V.hasOneUse(); V = V.getOperand(0)) {
21412 switch (V.getOpcode()) {
21414 return false; // Nothing combined!
21417 // Skip bitcasts as we always know the type for the target specific
21421 case X86ISD::PSHUFLW:
21422 case X86ISD::PSHUFHW:
21423 if (V.getOpcode() == CombineOpcode)
21426 // Other-half shuffles are no-ops.
21429 // Break out of the loop if we break out of the switch.
21433 if (!V.hasOneUse())
21434 // We fell out of the loop without finding a viable combining instruction.
21437 // Combine away the bottom node as its shuffle will be accumulated into
21438 // a preceding shuffle.
21439 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21441 // Record the old value.
21444 // Merge this node's mask and our incoming mask (adjusted to account for all
21445 // the pshufd instructions encountered).
21446 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21447 for (int &M : Mask)
21449 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21450 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21452 // Check that the shuffles didn't cancel each other out. If not, we need to
21453 // combine to the new one.
21455 // Replace the combinable shuffle with the combined one, updating all users
21456 // so that we re-evaluate the chain here.
21457 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21462 /// \brief Try to combine x86 target specific shuffles.
21463 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21464 TargetLowering::DAGCombinerInfo &DCI,
21465 const X86Subtarget *Subtarget) {
21467 MVT VT = N.getSimpleValueType();
21468 SmallVector<int, 4> Mask;
21470 switch (N.getOpcode()) {
21471 case X86ISD::PSHUFD:
21472 case X86ISD::PSHUFLW:
21473 case X86ISD::PSHUFHW:
21474 Mask = getPSHUFShuffleMask(N);
21475 assert(Mask.size() == 4);
21481 // Nuke no-op shuffles that show up after combining.
21482 if (isNoopShuffleMask(Mask))
21483 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21485 // Look for simplifications involving one or two shuffle instructions.
21486 SDValue V = N.getOperand(0);
21487 switch (N.getOpcode()) {
21490 case X86ISD::PSHUFLW:
21491 case X86ISD::PSHUFHW:
21492 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21494 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21495 return SDValue(); // We combined away this shuffle, so we're done.
21497 // See if this reduces to a PSHUFD which is no more expensive and can
21498 // combine with more operations. Note that it has to at least flip the
21499 // dwords as otherwise it would have been removed as a no-op.
21500 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21501 int DMask[] = {0, 1, 2, 3};
21502 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21503 DMask[DOffset + 0] = DOffset + 1;
21504 DMask[DOffset + 1] = DOffset + 0;
21505 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21506 V = DAG.getBitcast(DVT, V);
21507 DCI.AddToWorklist(V.getNode());
21508 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21509 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21510 DCI.AddToWorklist(V.getNode());
21511 return DAG.getBitcast(VT, V);
21514 // Look for shuffle patterns which can be implemented as a single unpack.
21515 // FIXME: This doesn't handle the location of the PSHUFD generically, and
21516 // only works when we have a PSHUFD followed by two half-shuffles.
21517 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21518 (V.getOpcode() == X86ISD::PSHUFLW ||
21519 V.getOpcode() == X86ISD::PSHUFHW) &&
21520 V.getOpcode() != N.getOpcode() &&
21522 SDValue D = V.getOperand(0);
21523 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21524 D = D.getOperand(0);
21525 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21526 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21527 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21528 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21529 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21531 for (int i = 0; i < 4; ++i) {
21532 WordMask[i + NOffset] = Mask[i] + NOffset;
21533 WordMask[i + VOffset] = VMask[i] + VOffset;
21535 // Map the word mask through the DWord mask.
21537 for (int i = 0; i < 8; ++i)
21538 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21539 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21540 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21541 // We can replace all three shuffles with an unpack.
21542 V = DAG.getBitcast(VT, D.getOperand(0));
21543 DCI.AddToWorklist(V.getNode());
21544 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21553 case X86ISD::PSHUFD:
21554 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21563 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21565 /// We combine this directly on the abstract vector shuffle nodes so it is
21566 /// easier to generically match. We also insert dummy vector shuffle nodes for
21567 /// the operands which explicitly discard the lanes which are unused by this
21568 /// operation to try to flow through the rest of the combiner the fact that
21569 /// they're unused.
21570 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21572 EVT VT = N->getValueType(0);
21574 // We only handle target-independent shuffles.
21575 // FIXME: It would be easy and harmless to use the target shuffle mask
21576 // extraction tool to support more.
21577 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21580 auto *SVN = cast<ShuffleVectorSDNode>(N);
21581 ArrayRef<int> Mask = SVN->getMask();
21582 SDValue V1 = N->getOperand(0);
21583 SDValue V2 = N->getOperand(1);
21585 // We require the first shuffle operand to be the SUB node, and the second to
21586 // be the ADD node.
21587 // FIXME: We should support the commuted patterns.
21588 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21591 // If there are other uses of these operations we can't fold them.
21592 if (!V1->hasOneUse() || !V2->hasOneUse())
21595 // Ensure that both operations have the same operands. Note that we can
21596 // commute the FADD operands.
21597 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21598 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21599 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21602 // We're looking for blends between FADD and FSUB nodes. We insist on these
21603 // nodes being lined up in a specific expected pattern.
21604 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21605 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21606 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21609 // Only specific types are legal at this point, assert so we notice if and
21610 // when these change.
21611 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21612 VT == MVT::v4f64) &&
21613 "Unknown vector type encountered!");
21615 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21618 /// PerformShuffleCombine - Performs several different shuffle combines.
21619 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21620 TargetLowering::DAGCombinerInfo &DCI,
21621 const X86Subtarget *Subtarget) {
21623 SDValue N0 = N->getOperand(0);
21624 SDValue N1 = N->getOperand(1);
21625 EVT VT = N->getValueType(0);
21627 // Don't create instructions with illegal types after legalize types has run.
21628 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21629 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21632 // If we have legalized the vector types, look for blends of FADD and FSUB
21633 // nodes that we can fuse into an ADDSUB node.
21634 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21635 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21638 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21639 if (Subtarget->hasFp256() && VT.is256BitVector() &&
21640 N->getOpcode() == ISD::VECTOR_SHUFFLE)
21641 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21643 // During Type Legalization, when promoting illegal vector types,
21644 // the backend might introduce new shuffle dag nodes and bitcasts.
21646 // This code performs the following transformation:
21647 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21648 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21650 // We do this only if both the bitcast and the BINOP dag nodes have
21651 // one use. Also, perform this transformation only if the new binary
21652 // operation is legal. This is to avoid introducing dag nodes that
21653 // potentially need to be further expanded (or custom lowered) into a
21654 // less optimal sequence of dag nodes.
21655 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21656 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21657 N0.getOpcode() == ISD::BITCAST) {
21658 SDValue BC0 = N0.getOperand(0);
21659 EVT SVT = BC0.getValueType();
21660 unsigned Opcode = BC0.getOpcode();
21661 unsigned NumElts = VT.getVectorNumElements();
21663 if (BC0.hasOneUse() && SVT.isVector() &&
21664 SVT.getVectorNumElements() * 2 == NumElts &&
21665 TLI.isOperationLegal(Opcode, VT)) {
21666 bool CanFold = false;
21678 unsigned SVTNumElts = SVT.getVectorNumElements();
21679 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21680 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21681 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21682 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21683 CanFold = SVOp->getMaskElt(i) < 0;
21686 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21687 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21688 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21689 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21694 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21695 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21696 // consecutive, non-overlapping, and in the right order.
21697 SmallVector<SDValue, 16> Elts;
21698 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21699 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21701 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21704 if (isTargetShuffle(N->getOpcode())) {
21706 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21707 if (Shuffle.getNode())
21710 // Try recursively combining arbitrary sequences of x86 shuffle
21711 // instructions into higher-order shuffles. We do this after combining
21712 // specific PSHUF instruction sequences into their minimal form so that we
21713 // can evaluate how many specialized shuffle instructions are involved in
21714 // a particular chain.
21715 SmallVector<int, 1> NonceMask; // Just a placeholder.
21716 NonceMask.push_back(0);
21717 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21718 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21720 return SDValue(); // This routine will use CombineTo to replace N.
21726 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21727 /// specific shuffle of a load can be folded into a single element load.
21728 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21729 /// shuffles have been custom lowered so we need to handle those here.
21730 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21731 TargetLowering::DAGCombinerInfo &DCI) {
21732 if (DCI.isBeforeLegalizeOps())
21735 SDValue InVec = N->getOperand(0);
21736 SDValue EltNo = N->getOperand(1);
21738 if (!isa<ConstantSDNode>(EltNo))
21741 EVT OriginalVT = InVec.getValueType();
21743 if (InVec.getOpcode() == ISD::BITCAST) {
21744 // Don't duplicate a load with other uses.
21745 if (!InVec.hasOneUse())
21747 EVT BCVT = InVec.getOperand(0).getValueType();
21748 if (!BCVT.isVector() ||
21749 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21751 InVec = InVec.getOperand(0);
21754 EVT CurrentVT = InVec.getValueType();
21756 if (!isTargetShuffle(InVec.getOpcode()))
21759 // Don't duplicate a load with other uses.
21760 if (!InVec.hasOneUse())
21763 SmallVector<int, 16> ShuffleMask;
21765 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21766 ShuffleMask, UnaryShuffle))
21769 // Select the input vector, guarding against out of range extract vector.
21770 unsigned NumElems = CurrentVT.getVectorNumElements();
21771 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21772 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21773 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21774 : InVec.getOperand(1);
21776 // If inputs to shuffle are the same for both ops, then allow 2 uses
21777 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21778 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21780 if (LdNode.getOpcode() == ISD::BITCAST) {
21781 // Don't duplicate a load with other uses.
21782 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21785 AllowedUses = 1; // only allow 1 load use if we have a bitcast
21786 LdNode = LdNode.getOperand(0);
21789 if (!ISD::isNormalLoad(LdNode.getNode()))
21792 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21794 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21797 EVT EltVT = N->getValueType(0);
21798 // If there's a bitcast before the shuffle, check if the load type and
21799 // alignment is valid.
21800 unsigned Align = LN0->getAlignment();
21801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21802 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21803 EltVT.getTypeForEVT(*DAG.getContext()));
21805 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21808 // All checks match so transform back to vector_shuffle so that DAG combiner
21809 // can finish the job
21812 // Create shuffle node taking into account the case that its a unary shuffle
21813 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21814 : InVec.getOperand(1);
21815 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21816 InVec.getOperand(0), Shuffle,
21818 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21819 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21823 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21824 /// special and don't usually play with other vector types, it's better to
21825 /// handle them early to be sure we emit efficient code by avoiding
21826 /// store-load conversions.
21827 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21828 if (N->getValueType(0) != MVT::x86mmx ||
21829 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21830 N->getOperand(0)->getValueType(0) != MVT::v2i32)
21833 SDValue V = N->getOperand(0);
21834 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21835 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21836 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21837 N->getValueType(0), V.getOperand(0));
21842 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21843 /// generation and convert it from being a bunch of shuffles and extracts
21844 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21845 /// storing the value and loading scalars back, while for x64 we should
21846 /// use 64-bit extracts and shifts.
21847 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21848 TargetLowering::DAGCombinerInfo &DCI) {
21849 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21852 SDValue InputVector = N->getOperand(0);
21853 SDLoc dl(InputVector);
21854 // Detect mmx to i32 conversion through a v2i32 elt extract.
21855 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21856 N->getValueType(0) == MVT::i32 &&
21857 InputVector.getValueType() == MVT::v2i32) {
21859 // The bitcast source is a direct mmx result.
21860 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21861 if (MMXSrc.getValueType() == MVT::x86mmx)
21862 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21863 N->getValueType(0),
21864 InputVector.getNode()->getOperand(0));
21866 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21867 SDValue MMXSrcOp = MMXSrc.getOperand(0);
21868 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21869 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21870 MMXSrcOp.getOpcode() == ISD::BITCAST &&
21871 MMXSrcOp.getValueType() == MVT::v1i64 &&
21872 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21873 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21874 N->getValueType(0),
21875 MMXSrcOp.getOperand(0));
21878 EVT VT = N->getValueType(0);
21880 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21881 InputVector.getOpcode() == ISD::BITCAST &&
21882 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21883 uint64_t ExtractedElt =
21884 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21885 uint64_t InputValue =
21886 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21887 uint64_t Res = (InputValue >> ExtractedElt) & 1;
21888 return DAG.getConstant(Res, dl, MVT::i1);
21890 // Only operate on vectors of 4 elements, where the alternative shuffling
21891 // gets to be more expensive.
21892 if (InputVector.getValueType() != MVT::v4i32)
21895 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21896 // single use which is a sign-extend or zero-extend, and all elements are
21898 SmallVector<SDNode *, 4> Uses;
21899 unsigned ExtractedElements = 0;
21900 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21901 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21902 if (UI.getUse().getResNo() != InputVector.getResNo())
21905 SDNode *Extract = *UI;
21906 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21909 if (Extract->getValueType(0) != MVT::i32)
21911 if (!Extract->hasOneUse())
21913 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21914 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21916 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21919 // Record which element was extracted.
21920 ExtractedElements |=
21921 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21923 Uses.push_back(Extract);
21926 // If not all the elements were used, this may not be worthwhile.
21927 if (ExtractedElements != 15)
21930 // Ok, we've now decided to do the transformation.
21931 // If 64-bit shifts are legal, use the extract-shift sequence,
21932 // otherwise bounce the vector off the cache.
21933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21936 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21937 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21938 auto &DL = DAG.getDataLayout();
21939 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
21940 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21941 DAG.getConstant(0, dl, VecIdxTy));
21942 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21943 DAG.getConstant(1, dl, VecIdxTy));
21945 SDValue ShAmt = DAG.getConstant(
21946 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
21947 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21948 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21949 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21950 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21951 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21952 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21954 // Store the value to a temporary stack slot.
21955 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21956 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21957 MachinePointerInfo(), false, false, 0);
21959 EVT ElementType = InputVector.getValueType().getVectorElementType();
21960 unsigned EltSize = ElementType.getSizeInBits() / 8;
21962 // Replace each use (extract) with a load of the appropriate element.
21963 for (unsigned i = 0; i < 4; ++i) {
21964 uint64_t Offset = EltSize * i;
21965 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
21966 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
21968 SDValue ScalarAddr =
21969 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
21971 // Load the scalar.
21972 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21973 ScalarAddr, MachinePointerInfo(),
21974 false, false, false, 0);
21979 // Replace the extracts
21980 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21981 UE = Uses.end(); UI != UE; ++UI) {
21982 SDNode *Extract = *UI;
21984 SDValue Idx = Extract->getOperand(1);
21985 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21986 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21989 // The replacement was made in place; don't return anything.
21993 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21994 static std::pair<unsigned, bool>
21995 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21996 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21997 if (!VT.isVector())
21998 return std::make_pair(0, false);
22000 bool NeedSplit = false;
22001 switch (VT.getSimpleVT().SimpleTy) {
22002 default: return std::make_pair(0, false);
22005 if (!Subtarget->hasVLX())
22006 return std::make_pair(0, false);
22010 if (!Subtarget->hasBWI())
22011 return std::make_pair(0, false);
22015 if (!Subtarget->hasAVX512())
22016 return std::make_pair(0, false);
22021 if (!Subtarget->hasAVX2())
22023 if (!Subtarget->hasAVX())
22024 return std::make_pair(0, false);
22029 if (!Subtarget->hasSSE2())
22030 return std::make_pair(0, false);
22033 // SSE2 has only a small subset of the operations.
22034 bool hasUnsigned = Subtarget->hasSSE41() ||
22035 (Subtarget->hasSSE2() && VT == MVT::v16i8);
22036 bool hasSigned = Subtarget->hasSSE41() ||
22037 (Subtarget->hasSSE2() && VT == MVT::v8i16);
22039 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22042 // Check for x CC y ? x : y.
22043 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22044 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22049 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22052 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22055 Opc = hasSigned ? ISD::SMIN : 0; break;
22058 Opc = hasSigned ? ISD::SMAX : 0; break;
22060 // Check for x CC y ? y : x -- a min/max with reversed arms.
22061 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22062 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22067 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22070 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22073 Opc = hasSigned ? ISD::SMAX : 0; break;
22076 Opc = hasSigned ? ISD::SMIN : 0; break;
22080 return std::make_pair(Opc, NeedSplit);
22084 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22085 const X86Subtarget *Subtarget) {
22087 SDValue Cond = N->getOperand(0);
22088 SDValue LHS = N->getOperand(1);
22089 SDValue RHS = N->getOperand(2);
22091 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22092 SDValue CondSrc = Cond->getOperand(0);
22093 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22094 Cond = CondSrc->getOperand(0);
22097 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22100 // A vselect where all conditions and data are constants can be optimized into
22101 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22102 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22103 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22106 unsigned MaskValue = 0;
22107 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22110 MVT VT = N->getSimpleValueType(0);
22111 unsigned NumElems = VT.getVectorNumElements();
22112 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22113 for (unsigned i = 0; i < NumElems; ++i) {
22114 // Be sure we emit undef where we can.
22115 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22116 ShuffleMask[i] = -1;
22118 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22122 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22124 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22127 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22129 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22130 TargetLowering::DAGCombinerInfo &DCI,
22131 const X86Subtarget *Subtarget) {
22133 SDValue Cond = N->getOperand(0);
22134 // Get the LHS/RHS of the select.
22135 SDValue LHS = N->getOperand(1);
22136 SDValue RHS = N->getOperand(2);
22137 EVT VT = LHS.getValueType();
22138 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22140 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22141 // instructions match the semantics of the common C idiom x<y?x:y but not
22142 // x<=y?x:y, because of how they handle negative zero (which can be
22143 // ignored in unsafe-math mode).
22144 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22145 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22146 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22147 (Subtarget->hasSSE2() ||
22148 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22149 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22151 unsigned Opcode = 0;
22152 // Check for x CC y ? x : y.
22153 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22154 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22158 // Converting this to a min would handle NaNs incorrectly, and swapping
22159 // the operands would cause it to handle comparisons between positive
22160 // and negative zero incorrectly.
22161 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22162 if (!DAG.getTarget().Options.UnsafeFPMath &&
22163 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22165 std::swap(LHS, RHS);
22167 Opcode = X86ISD::FMIN;
22170 // Converting this to a min would handle comparisons between positive
22171 // and negative zero incorrectly.
22172 if (!DAG.getTarget().Options.UnsafeFPMath &&
22173 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22175 Opcode = X86ISD::FMIN;
22178 // Converting this to a min would handle both negative zeros and NaNs
22179 // incorrectly, but we can swap the operands to fix both.
22180 std::swap(LHS, RHS);
22184 Opcode = X86ISD::FMIN;
22188 // Converting this to a max would handle comparisons between positive
22189 // and negative zero incorrectly.
22190 if (!DAG.getTarget().Options.UnsafeFPMath &&
22191 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22193 Opcode = X86ISD::FMAX;
22196 // Converting this to a max would handle NaNs incorrectly, and swapping
22197 // the operands would cause it to handle comparisons between positive
22198 // and negative zero incorrectly.
22199 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22200 if (!DAG.getTarget().Options.UnsafeFPMath &&
22201 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22203 std::swap(LHS, RHS);
22205 Opcode = X86ISD::FMAX;
22208 // Converting this to a max would handle both negative zeros and NaNs
22209 // incorrectly, but we can swap the operands to fix both.
22210 std::swap(LHS, RHS);
22214 Opcode = X86ISD::FMAX;
22217 // Check for x CC y ? y : x -- a min/max with reversed arms.
22218 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22219 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22223 // Converting this to a min would handle comparisons between positive
22224 // and negative zero incorrectly, and swapping the operands would
22225 // cause it to handle NaNs incorrectly.
22226 if (!DAG.getTarget().Options.UnsafeFPMath &&
22227 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22228 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22230 std::swap(LHS, RHS);
22232 Opcode = X86ISD::FMIN;
22235 // Converting this to a min would handle NaNs incorrectly.
22236 if (!DAG.getTarget().Options.UnsafeFPMath &&
22237 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22239 Opcode = X86ISD::FMIN;
22242 // Converting this to a min would handle both negative zeros and NaNs
22243 // incorrectly, but we can swap the operands to fix both.
22244 std::swap(LHS, RHS);
22248 Opcode = X86ISD::FMIN;
22252 // Converting this to a max would handle NaNs incorrectly.
22253 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22255 Opcode = X86ISD::FMAX;
22258 // Converting this to a max would handle comparisons between positive
22259 // and negative zero incorrectly, and swapping the operands would
22260 // cause it to handle NaNs incorrectly.
22261 if (!DAG.getTarget().Options.UnsafeFPMath &&
22262 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22263 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22265 std::swap(LHS, RHS);
22267 Opcode = X86ISD::FMAX;
22270 // Converting this to a max would handle both negative zeros and NaNs
22271 // incorrectly, but we can swap the operands to fix both.
22272 std::swap(LHS, RHS);
22276 Opcode = X86ISD::FMAX;
22282 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22285 EVT CondVT = Cond.getValueType();
22286 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22287 CondVT.getVectorElementType() == MVT::i1) {
22288 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22289 // lowering on KNL. In this case we convert it to
22290 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22291 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22292 // Since SKX these selects have a proper lowering.
22293 EVT OpVT = LHS.getValueType();
22294 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22295 (OpVT.getVectorElementType() == MVT::i8 ||
22296 OpVT.getVectorElementType() == MVT::i16) &&
22297 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22298 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22299 DCI.AddToWorklist(Cond.getNode());
22300 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22303 // If this is a select between two integer constants, try to do some
22305 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22306 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22307 // Don't do this for crazy integer types.
22308 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22309 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22310 // so that TrueC (the true value) is larger than FalseC.
22311 bool NeedsCondInvert = false;
22313 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22314 // Efficiently invertible.
22315 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22316 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22317 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22318 NeedsCondInvert = true;
22319 std::swap(TrueC, FalseC);
22322 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22323 if (FalseC->getAPIntValue() == 0 &&
22324 TrueC->getAPIntValue().isPowerOf2()) {
22325 if (NeedsCondInvert) // Invert the condition if needed.
22326 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22327 DAG.getConstant(1, DL, Cond.getValueType()));
22329 // Zero extend the condition if needed.
22330 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22332 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22333 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22334 DAG.getConstant(ShAmt, DL, MVT::i8));
22337 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22338 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22339 if (NeedsCondInvert) // Invert the condition if needed.
22340 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22341 DAG.getConstant(1, DL, Cond.getValueType()));
22343 // Zero extend the condition if needed.
22344 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22345 FalseC->getValueType(0), Cond);
22346 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22347 SDValue(FalseC, 0));
22350 // Optimize cases that will turn into an LEA instruction. This requires
22351 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22352 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22353 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22354 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22356 bool isFastMultiplier = false;
22358 switch ((unsigned char)Diff) {
22360 case 1: // result = add base, cond
22361 case 2: // result = lea base( , cond*2)
22362 case 3: // result = lea base(cond, cond*2)
22363 case 4: // result = lea base( , cond*4)
22364 case 5: // result = lea base(cond, cond*4)
22365 case 8: // result = lea base( , cond*8)
22366 case 9: // result = lea base(cond, cond*8)
22367 isFastMultiplier = true;
22372 if (isFastMultiplier) {
22373 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22374 if (NeedsCondInvert) // Invert the condition if needed.
22375 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22376 DAG.getConstant(1, DL, Cond.getValueType()));
22378 // Zero extend the condition if needed.
22379 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22381 // Scale the condition by the difference.
22383 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22384 DAG.getConstant(Diff, DL,
22385 Cond.getValueType()));
22387 // Add the base if non-zero.
22388 if (FalseC->getAPIntValue() != 0)
22389 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22390 SDValue(FalseC, 0));
22397 // Canonicalize max and min:
22398 // (x > y) ? x : y -> (x >= y) ? x : y
22399 // (x < y) ? x : y -> (x <= y) ? x : y
22400 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22401 // the need for an extra compare
22402 // against zero. e.g.
22403 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22405 // testl %edi, %edi
22407 // cmovgl %edi, %eax
22411 // cmovsl %eax, %edi
22412 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22413 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22414 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22415 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22420 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22421 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22422 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22423 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22428 // Early exit check
22429 if (!TLI.isTypeLegal(VT))
22432 // Match VSELECTs into subs with unsigned saturation.
22433 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22434 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22435 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22436 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22437 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22439 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22440 // left side invert the predicate to simplify logic below.
22442 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22444 CC = ISD::getSetCCInverse(CC, true);
22445 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22449 if (Other.getNode() && Other->getNumOperands() == 2 &&
22450 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22451 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22452 SDValue CondRHS = Cond->getOperand(1);
22454 // Look for a general sub with unsigned saturation first.
22455 // x >= y ? x-y : 0 --> subus x, y
22456 // x > y ? x-y : 0 --> subus x, y
22457 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22458 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22459 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22461 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22462 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22463 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22464 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22465 // If the RHS is a constant we have to reverse the const
22466 // canonicalization.
22467 // x > C-1 ? x+-C : 0 --> subus x, C
22468 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22469 CondRHSConst->getAPIntValue() ==
22470 (-OpRHSConst->getAPIntValue() - 1))
22471 return DAG.getNode(
22472 X86ISD::SUBUS, DL, VT, OpLHS,
22473 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22475 // Another special case: If C was a sign bit, the sub has been
22476 // canonicalized into a xor.
22477 // FIXME: Would it be better to use computeKnownBits to determine
22478 // whether it's safe to decanonicalize the xor?
22479 // x s< 0 ? x^C : 0 --> subus x, C
22480 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22481 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22482 OpRHSConst->getAPIntValue().isSignBit())
22483 // Note that we have to rebuild the RHS constant here to ensure we
22484 // don't rely on particular values of undef lanes.
22485 return DAG.getNode(
22486 X86ISD::SUBUS, DL, VT, OpLHS,
22487 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22492 // Try to match a min/max vector operation.
22493 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22494 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22495 unsigned Opc = ret.first;
22496 bool NeedSplit = ret.second;
22498 if (Opc && NeedSplit) {
22499 unsigned NumElems = VT.getVectorNumElements();
22500 // Extract the LHS vectors
22501 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22502 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22504 // Extract the RHS vectors
22505 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22506 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22508 // Create min/max for each subvector
22509 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22510 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22512 // Merge the result
22513 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22515 return DAG.getNode(Opc, DL, VT, LHS, RHS);
22518 // Simplify vector selection if condition value type matches vselect
22520 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22521 assert(Cond.getValueType().isVector() &&
22522 "vector select expects a vector selector!");
22524 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22525 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22527 // Try invert the condition if true value is not all 1s and false value
22529 if (!TValIsAllOnes && !FValIsAllZeros &&
22530 // Check if the selector will be produced by CMPP*/PCMP*
22531 Cond.getOpcode() == ISD::SETCC &&
22532 // Check if SETCC has already been promoted
22533 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22535 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22536 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22538 if (TValIsAllZeros || FValIsAllOnes) {
22539 SDValue CC = Cond.getOperand(2);
22540 ISD::CondCode NewCC =
22541 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22542 Cond.getOperand(0).getValueType().isInteger());
22543 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22544 std::swap(LHS, RHS);
22545 TValIsAllOnes = FValIsAllOnes;
22546 FValIsAllZeros = TValIsAllZeros;
22550 if (TValIsAllOnes || FValIsAllZeros) {
22553 if (TValIsAllOnes && FValIsAllZeros)
22555 else if (TValIsAllOnes)
22557 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22558 else if (FValIsAllZeros)
22559 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22560 DAG.getBitcast(CondVT, LHS));
22562 return DAG.getBitcast(VT, Ret);
22566 // We should generate an X86ISD::BLENDI from a vselect if its argument
22567 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22568 // constants. This specific pattern gets generated when we split a
22569 // selector for a 512 bit vector in a machine without AVX512 (but with
22570 // 256-bit vectors), during legalization:
22572 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22574 // Iff we find this pattern and the build_vectors are built from
22575 // constants, we translate the vselect into a shuffle_vector that we
22576 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22577 if ((N->getOpcode() == ISD::VSELECT ||
22578 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22579 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22580 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22581 if (Shuffle.getNode())
22585 // If this is a *dynamic* select (non-constant condition) and we can match
22586 // this node with one of the variable blend instructions, restructure the
22587 // condition so that the blends can use the high bit of each element and use
22588 // SimplifyDemandedBits to simplify the condition operand.
22589 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22590 !DCI.isBeforeLegalize() &&
22591 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22592 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22594 // Don't optimize vector selects that map to mask-registers.
22598 // We can only handle the cases where VSELECT is directly legal on the
22599 // subtarget. We custom lower VSELECT nodes with constant conditions and
22600 // this makes it hard to see whether a dynamic VSELECT will correctly
22601 // lower, so we both check the operation's status and explicitly handle the
22602 // cases where a *dynamic* blend will fail even though a constant-condition
22603 // blend could be custom lowered.
22604 // FIXME: We should find a better way to handle this class of problems.
22605 // Potentially, we should combine constant-condition vselect nodes
22606 // pre-legalization into shuffles and not mark as many types as custom
22608 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22610 // FIXME: We don't support i16-element blends currently. We could and
22611 // should support them by making *all* the bits in the condition be set
22612 // rather than just the high bit and using an i8-element blend.
22613 if (VT.getScalarType() == MVT::i16)
22615 // Dynamic blending was only available from SSE4.1 onward.
22616 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22618 // Byte blends are only available in AVX2
22619 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22620 !Subtarget->hasAVX2())
22623 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22624 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22626 APInt KnownZero, KnownOne;
22627 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22628 DCI.isBeforeLegalizeOps());
22629 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22630 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22632 // If we changed the computation somewhere in the DAG, this change
22633 // will affect all users of Cond.
22634 // Make sure it is fine and update all the nodes so that we do not
22635 // use the generic VSELECT anymore. Otherwise, we may perform
22636 // wrong optimizations as we messed up with the actual expectation
22637 // for the vector boolean values.
22638 if (Cond != TLO.Old) {
22639 // Check all uses of that condition operand to check whether it will be
22640 // consumed by non-BLEND instructions, which may depend on all bits are
22642 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22644 if (I->getOpcode() != ISD::VSELECT)
22645 // TODO: Add other opcodes eventually lowered into BLEND.
22648 // Update all the users of the condition, before committing the change,
22649 // so that the VSELECT optimizations that expect the correct vector
22650 // boolean value will not be triggered.
22651 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22653 DAG.ReplaceAllUsesOfValueWith(
22655 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22656 Cond, I->getOperand(1), I->getOperand(2)));
22657 DCI.CommitTargetLoweringOpt(TLO);
22660 // At this point, only Cond is changed. Change the condition
22661 // just for N to keep the opportunity to optimize all other
22662 // users their own way.
22663 DAG.ReplaceAllUsesOfValueWith(
22665 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22666 TLO.New, N->getOperand(1), N->getOperand(2)));
22674 // Check whether a boolean test is testing a boolean value generated by
22675 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22678 // Simplify the following patterns:
22679 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22680 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22681 // to (Op EFLAGS Cond)
22683 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22684 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22685 // to (Op EFLAGS !Cond)
22687 // where Op could be BRCOND or CMOV.
22689 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22690 // Quit if not CMP and SUB with its value result used.
22691 if (Cmp.getOpcode() != X86ISD::CMP &&
22692 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22695 // Quit if not used as a boolean value.
22696 if (CC != X86::COND_E && CC != X86::COND_NE)
22699 // Check CMP operands. One of them should be 0 or 1 and the other should be
22700 // an SetCC or extended from it.
22701 SDValue Op1 = Cmp.getOperand(0);
22702 SDValue Op2 = Cmp.getOperand(1);
22705 const ConstantSDNode* C = nullptr;
22706 bool needOppositeCond = (CC == X86::COND_E);
22707 bool checkAgainstTrue = false; // Is it a comparison against 1?
22709 if ((C = dyn_cast<ConstantSDNode>(Op1)))
22711 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22713 else // Quit if all operands are not constants.
22716 if (C->getZExtValue() == 1) {
22717 needOppositeCond = !needOppositeCond;
22718 checkAgainstTrue = true;
22719 } else if (C->getZExtValue() != 0)
22720 // Quit if the constant is neither 0 or 1.
22723 bool truncatedToBoolWithAnd = false;
22724 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22725 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22726 SetCC.getOpcode() == ISD::TRUNCATE ||
22727 SetCC.getOpcode() == ISD::AND) {
22728 if (SetCC.getOpcode() == ISD::AND) {
22730 ConstantSDNode *CS;
22731 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22732 CS->getZExtValue() == 1)
22734 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22735 CS->getZExtValue() == 1)
22739 SetCC = SetCC.getOperand(OpIdx);
22740 truncatedToBoolWithAnd = true;
22742 SetCC = SetCC.getOperand(0);
22745 switch (SetCC.getOpcode()) {
22746 case X86ISD::SETCC_CARRY:
22747 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22748 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22749 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22750 // truncated to i1 using 'and'.
22751 if (checkAgainstTrue && !truncatedToBoolWithAnd)
22753 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22754 "Invalid use of SETCC_CARRY!");
22756 case X86ISD::SETCC:
22757 // Set the condition code or opposite one if necessary.
22758 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22759 if (needOppositeCond)
22760 CC = X86::GetOppositeBranchCondition(CC);
22761 return SetCC.getOperand(1);
22762 case X86ISD::CMOV: {
22763 // Check whether false/true value has canonical one, i.e. 0 or 1.
22764 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22765 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22766 // Quit if true value is not a constant.
22769 // Quit if false value is not a constant.
22771 SDValue Op = SetCC.getOperand(0);
22772 // Skip 'zext' or 'trunc' node.
22773 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22774 Op.getOpcode() == ISD::TRUNCATE)
22775 Op = Op.getOperand(0);
22776 // A special case for rdrand/rdseed, where 0 is set if false cond is
22778 if ((Op.getOpcode() != X86ISD::RDRAND &&
22779 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22782 // Quit if false value is not the constant 0 or 1.
22783 bool FValIsFalse = true;
22784 if (FVal && FVal->getZExtValue() != 0) {
22785 if (FVal->getZExtValue() != 1)
22787 // If FVal is 1, opposite cond is needed.
22788 needOppositeCond = !needOppositeCond;
22789 FValIsFalse = false;
22791 // Quit if TVal is not the constant opposite of FVal.
22792 if (FValIsFalse && TVal->getZExtValue() != 1)
22794 if (!FValIsFalse && TVal->getZExtValue() != 0)
22796 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22797 if (needOppositeCond)
22798 CC = X86::GetOppositeBranchCondition(CC);
22799 return SetCC.getOperand(3);
22806 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22808 /// (X86or (X86setcc) (X86setcc))
22809 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
22810 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22811 X86::CondCode &CC1, SDValue &Flags,
22813 if (Cond->getOpcode() == X86ISD::CMP) {
22814 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22815 if (!CondOp1C || !CondOp1C->isNullValue())
22818 Cond = Cond->getOperand(0);
22823 SDValue SetCC0, SetCC1;
22824 switch (Cond->getOpcode()) {
22825 default: return false;
22832 SetCC0 = Cond->getOperand(0);
22833 SetCC1 = Cond->getOperand(1);
22837 // Make sure we have SETCC nodes, using the same flags value.
22838 if (SetCC0.getOpcode() != X86ISD::SETCC ||
22839 SetCC1.getOpcode() != X86ISD::SETCC ||
22840 SetCC0->getOperand(1) != SetCC1->getOperand(1))
22843 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22844 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22845 Flags = SetCC0->getOperand(1);
22849 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22850 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22851 TargetLowering::DAGCombinerInfo &DCI,
22852 const X86Subtarget *Subtarget) {
22855 // If the flag operand isn't dead, don't touch this CMOV.
22856 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22859 SDValue FalseOp = N->getOperand(0);
22860 SDValue TrueOp = N->getOperand(1);
22861 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22862 SDValue Cond = N->getOperand(3);
22864 if (CC == X86::COND_E || CC == X86::COND_NE) {
22865 switch (Cond.getOpcode()) {
22869 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22870 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22871 return (CC == X86::COND_E) ? FalseOp : TrueOp;
22877 Flags = checkBoolTestSetCCCombine(Cond, CC);
22878 if (Flags.getNode() &&
22879 // Extra check as FCMOV only supports a subset of X86 cond.
22880 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22881 SDValue Ops[] = { FalseOp, TrueOp,
22882 DAG.getConstant(CC, DL, MVT::i8), Flags };
22883 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22886 // If this is a select between two integer constants, try to do some
22887 // optimizations. Note that the operands are ordered the opposite of SELECT
22889 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22890 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22891 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22892 // larger than FalseC (the false value).
22893 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22894 CC = X86::GetOppositeBranchCondition(CC);
22895 std::swap(TrueC, FalseC);
22896 std::swap(TrueOp, FalseOp);
22899 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
22900 // This is efficient for any integer data type (including i8/i16) and
22902 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22903 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22904 DAG.getConstant(CC, DL, MVT::i8), Cond);
22906 // Zero extend the condition if needed.
22907 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22909 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22910 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22911 DAG.getConstant(ShAmt, DL, MVT::i8));
22912 if (N->getNumValues() == 2) // Dead flag value?
22913 return DCI.CombineTo(N, Cond, SDValue());
22917 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
22918 // for any integer data type, including i8/i16.
22919 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22920 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22921 DAG.getConstant(CC, DL, MVT::i8), Cond);
22923 // Zero extend the condition if needed.
22924 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22925 FalseC->getValueType(0), Cond);
22926 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22927 SDValue(FalseC, 0));
22929 if (N->getNumValues() == 2) // Dead flag value?
22930 return DCI.CombineTo(N, Cond, SDValue());
22934 // Optimize cases that will turn into an LEA instruction. This requires
22935 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22936 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22937 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22938 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22940 bool isFastMultiplier = false;
22942 switch ((unsigned char)Diff) {
22944 case 1: // result = add base, cond
22945 case 2: // result = lea base( , cond*2)
22946 case 3: // result = lea base(cond, cond*2)
22947 case 4: // result = lea base( , cond*4)
22948 case 5: // result = lea base(cond, cond*4)
22949 case 8: // result = lea base( , cond*8)
22950 case 9: // result = lea base(cond, cond*8)
22951 isFastMultiplier = true;
22956 if (isFastMultiplier) {
22957 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22958 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22959 DAG.getConstant(CC, DL, MVT::i8), Cond);
22960 // Zero extend the condition if needed.
22961 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22963 // Scale the condition by the difference.
22965 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22966 DAG.getConstant(Diff, DL, Cond.getValueType()));
22968 // Add the base if non-zero.
22969 if (FalseC->getAPIntValue() != 0)
22970 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22971 SDValue(FalseC, 0));
22972 if (N->getNumValues() == 2) // Dead flag value?
22973 return DCI.CombineTo(N, Cond, SDValue());
22980 // Handle these cases:
22981 // (select (x != c), e, c) -> select (x != c), e, x),
22982 // (select (x == c), c, e) -> select (x == c), x, e)
22983 // where the c is an integer constant, and the "select" is the combination
22984 // of CMOV and CMP.
22986 // The rationale for this change is that the conditional-move from a constant
22987 // needs two instructions, however, conditional-move from a register needs
22988 // only one instruction.
22990 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22991 // some instruction-combining opportunities. This opt needs to be
22992 // postponed as late as possible.
22994 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22995 // the DCI.xxxx conditions are provided to postpone the optimization as
22996 // late as possible.
22998 ConstantSDNode *CmpAgainst = nullptr;
22999 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23000 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23001 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23003 if (CC == X86::COND_NE &&
23004 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23005 CC = X86::GetOppositeBranchCondition(CC);
23006 std::swap(TrueOp, FalseOp);
23009 if (CC == X86::COND_E &&
23010 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23011 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23012 DAG.getConstant(CC, DL, MVT::i8), Cond };
23013 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23018 // Fold and/or of setcc's to double CMOV:
23019 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23020 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23022 // This combine lets us generate:
23023 // cmovcc1 (jcc1 if we don't have CMOV)
23029 // cmovne (jne if we don't have CMOV)
23030 // When we can't use the CMOV instruction, it might increase branch
23032 // When we can use CMOV, or when there is no mispredict, this improves
23033 // throughput and reduces register pressure.
23035 if (CC == X86::COND_NE) {
23037 X86::CondCode CC0, CC1;
23039 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23041 std::swap(FalseOp, TrueOp);
23042 CC0 = X86::GetOppositeBranchCondition(CC0);
23043 CC1 = X86::GetOppositeBranchCondition(CC1);
23046 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23048 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23049 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23050 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23051 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23059 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23060 const X86Subtarget *Subtarget) {
23061 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23063 default: return SDValue();
23064 // SSE/AVX/AVX2 blend intrinsics.
23065 case Intrinsic::x86_avx2_pblendvb:
23066 // Don't try to simplify this intrinsic if we don't have AVX2.
23067 if (!Subtarget->hasAVX2())
23070 case Intrinsic::x86_avx_blendv_pd_256:
23071 case Intrinsic::x86_avx_blendv_ps_256:
23072 // Don't try to simplify this intrinsic if we don't have AVX.
23073 if (!Subtarget->hasAVX())
23076 case Intrinsic::x86_sse41_blendvps:
23077 case Intrinsic::x86_sse41_blendvpd:
23078 case Intrinsic::x86_sse41_pblendvb: {
23079 SDValue Op0 = N->getOperand(1);
23080 SDValue Op1 = N->getOperand(2);
23081 SDValue Mask = N->getOperand(3);
23083 // Don't try to simplify this intrinsic if we don't have SSE4.1.
23084 if (!Subtarget->hasSSE41())
23087 // fold (blend A, A, Mask) -> A
23090 // fold (blend A, B, allZeros) -> A
23091 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23093 // fold (blend A, B, allOnes) -> B
23094 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23097 // Simplify the case where the mask is a constant i32 value.
23098 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23099 if (C->isNullValue())
23101 if (C->isAllOnesValue())
23108 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23109 case Intrinsic::x86_sse2_psrai_w:
23110 case Intrinsic::x86_sse2_psrai_d:
23111 case Intrinsic::x86_avx2_psrai_w:
23112 case Intrinsic::x86_avx2_psrai_d:
23113 case Intrinsic::x86_sse2_psra_w:
23114 case Intrinsic::x86_sse2_psra_d:
23115 case Intrinsic::x86_avx2_psra_w:
23116 case Intrinsic::x86_avx2_psra_d: {
23117 SDValue Op0 = N->getOperand(1);
23118 SDValue Op1 = N->getOperand(2);
23119 EVT VT = Op0.getValueType();
23120 assert(VT.isVector() && "Expected a vector type!");
23122 if (isa<BuildVectorSDNode>(Op1))
23123 Op1 = Op1.getOperand(0);
23125 if (!isa<ConstantSDNode>(Op1))
23128 EVT SVT = VT.getVectorElementType();
23129 unsigned SVTBits = SVT.getSizeInBits();
23131 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23132 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23133 uint64_t ShAmt = C.getZExtValue();
23135 // Don't try to convert this shift into a ISD::SRA if the shift
23136 // count is bigger than or equal to the element size.
23137 if (ShAmt >= SVTBits)
23140 // Trivial case: if the shift count is zero, then fold this
23141 // into the first operand.
23145 // Replace this packed shift intrinsic with a target independent
23148 SDValue Splat = DAG.getConstant(C, DL, VT);
23149 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23154 /// PerformMulCombine - Optimize a single multiply with constant into two
23155 /// in order to implement it with two cheaper instructions, e.g.
23156 /// LEA + SHL, LEA + LEA.
23157 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23158 TargetLowering::DAGCombinerInfo &DCI) {
23159 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23162 EVT VT = N->getValueType(0);
23163 if (VT != MVT::i64 && VT != MVT::i32)
23166 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23169 uint64_t MulAmt = C->getZExtValue();
23170 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23173 uint64_t MulAmt1 = 0;
23174 uint64_t MulAmt2 = 0;
23175 if ((MulAmt % 9) == 0) {
23177 MulAmt2 = MulAmt / 9;
23178 } else if ((MulAmt % 5) == 0) {
23180 MulAmt2 = MulAmt / 5;
23181 } else if ((MulAmt % 3) == 0) {
23183 MulAmt2 = MulAmt / 3;
23186 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23189 if (isPowerOf2_64(MulAmt2) &&
23190 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23191 // If second multiplifer is pow2, issue it first. We want the multiply by
23192 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23194 std::swap(MulAmt1, MulAmt2);
23197 if (isPowerOf2_64(MulAmt1))
23198 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23199 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23201 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23202 DAG.getConstant(MulAmt1, DL, VT));
23204 if (isPowerOf2_64(MulAmt2))
23205 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23206 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23208 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23209 DAG.getConstant(MulAmt2, DL, VT));
23211 // Do not add new nodes to DAG combiner worklist.
23212 DCI.CombineTo(N, NewMul, false);
23217 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23218 SDValue N0 = N->getOperand(0);
23219 SDValue N1 = N->getOperand(1);
23220 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23221 EVT VT = N0.getValueType();
23223 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23224 // since the result of setcc_c is all zero's or all ones.
23225 if (VT.isInteger() && !VT.isVector() &&
23226 N1C && N0.getOpcode() == ISD::AND &&
23227 N0.getOperand(1).getOpcode() == ISD::Constant) {
23228 SDValue N00 = N0.getOperand(0);
23229 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23230 ((N00.getOpcode() == ISD::ANY_EXTEND ||
23231 N00.getOpcode() == ISD::ZERO_EXTEND) &&
23232 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23233 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23234 APInt ShAmt = N1C->getAPIntValue();
23235 Mask = Mask.shl(ShAmt);
23238 return DAG.getNode(ISD::AND, DL, VT,
23239 N00, DAG.getConstant(Mask, DL, VT));
23244 // Hardware support for vector shifts is sparse which makes us scalarize the
23245 // vector operations in many cases. Also, on sandybridge ADD is faster than
23247 // (shl V, 1) -> add V,V
23248 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23249 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23250 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23251 // We shift all of the values by one. In many cases we do not have
23252 // hardware support for this operation. This is better expressed as an ADD
23254 if (N1SplatC->getAPIntValue() == 1)
23255 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23261 /// \brief Returns a vector of 0s if the node in input is a vector logical
23262 /// shift by a constant amount which is known to be bigger than or equal
23263 /// to the vector element size in bits.
23264 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23265 const X86Subtarget *Subtarget) {
23266 EVT VT = N->getValueType(0);
23268 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23269 (!Subtarget->hasInt256() ||
23270 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23273 SDValue Amt = N->getOperand(1);
23275 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23276 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23277 APInt ShiftAmt = AmtSplat->getAPIntValue();
23278 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23280 // SSE2/AVX2 logical shifts always return a vector of 0s
23281 // if the shift amount is bigger than or equal to
23282 // the element size. The constant shift amount will be
23283 // encoded as a 8-bit immediate.
23284 if (ShiftAmt.trunc(8).uge(MaxAmount))
23285 return getZeroVector(VT, Subtarget, DAG, DL);
23291 /// PerformShiftCombine - Combine shifts.
23292 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23293 TargetLowering::DAGCombinerInfo &DCI,
23294 const X86Subtarget *Subtarget) {
23295 if (N->getOpcode() == ISD::SHL)
23296 if (SDValue V = PerformSHLCombine(N, DAG))
23299 // Try to fold this logical shift into a zero vector.
23300 if (N->getOpcode() != ISD::SRA)
23301 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23307 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23308 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23309 // and friends. Likewise for OR -> CMPNEQSS.
23310 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23311 TargetLowering::DAGCombinerInfo &DCI,
23312 const X86Subtarget *Subtarget) {
23315 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23316 // we're requiring SSE2 for both.
23317 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23318 SDValue N0 = N->getOperand(0);
23319 SDValue N1 = N->getOperand(1);
23320 SDValue CMP0 = N0->getOperand(1);
23321 SDValue CMP1 = N1->getOperand(1);
23324 // The SETCCs should both refer to the same CMP.
23325 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23328 SDValue CMP00 = CMP0->getOperand(0);
23329 SDValue CMP01 = CMP0->getOperand(1);
23330 EVT VT = CMP00.getValueType();
23332 if (VT == MVT::f32 || VT == MVT::f64) {
23333 bool ExpectingFlags = false;
23334 // Check for any users that want flags:
23335 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23336 !ExpectingFlags && UI != UE; ++UI)
23337 switch (UI->getOpcode()) {
23342 ExpectingFlags = true;
23344 case ISD::CopyToReg:
23345 case ISD::SIGN_EXTEND:
23346 case ISD::ZERO_EXTEND:
23347 case ISD::ANY_EXTEND:
23351 if (!ExpectingFlags) {
23352 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23353 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23355 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23356 X86::CondCode tmp = cc0;
23361 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23362 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23363 // FIXME: need symbolic constants for these magic numbers.
23364 // See X86ATTInstPrinter.cpp:printSSECC().
23365 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23366 if (Subtarget->hasAVX512()) {
23367 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23369 DAG.getConstant(x86cc, DL, MVT::i8));
23370 if (N->getValueType(0) != MVT::i1)
23371 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23375 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23376 CMP00.getValueType(), CMP00, CMP01,
23377 DAG.getConstant(x86cc, DL,
23380 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23381 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23383 if (is64BitFP && !Subtarget->is64Bit()) {
23384 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23385 // 64-bit integer, since that's not a legal type. Since
23386 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23387 // bits, but can do this little dance to extract the lowest 32 bits
23388 // and work with those going forward.
23389 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23391 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23392 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23393 Vector32, DAG.getIntPtrConstant(0, DL));
23397 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23398 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23399 DAG.getConstant(1, DL, IntVT));
23400 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23402 return OneBitOfTruth;
23410 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23411 /// so it can be folded inside ANDNP.
23412 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23413 EVT VT = N->getValueType(0);
23415 // Match direct AllOnes for 128 and 256-bit vectors
23416 if (ISD::isBuildVectorAllOnes(N))
23419 // Look through a bit convert.
23420 if (N->getOpcode() == ISD::BITCAST)
23421 N = N->getOperand(0).getNode();
23423 // Sometimes the operand may come from a insert_subvector building a 256-bit
23425 if (VT.is256BitVector() &&
23426 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23427 SDValue V1 = N->getOperand(0);
23428 SDValue V2 = N->getOperand(1);
23430 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23431 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23432 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23433 ISD::isBuildVectorAllOnes(V2.getNode()))
23440 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23441 // register. In most cases we actually compare or select YMM-sized registers
23442 // and mixing the two types creates horrible code. This method optimizes
23443 // some of the transition sequences.
23444 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23445 TargetLowering::DAGCombinerInfo &DCI,
23446 const X86Subtarget *Subtarget) {
23447 EVT VT = N->getValueType(0);
23448 if (!VT.is256BitVector())
23451 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23452 N->getOpcode() == ISD::ZERO_EXTEND ||
23453 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23455 SDValue Narrow = N->getOperand(0);
23456 EVT NarrowVT = Narrow->getValueType(0);
23457 if (!NarrowVT.is128BitVector())
23460 if (Narrow->getOpcode() != ISD::XOR &&
23461 Narrow->getOpcode() != ISD::AND &&
23462 Narrow->getOpcode() != ISD::OR)
23465 SDValue N0 = Narrow->getOperand(0);
23466 SDValue N1 = Narrow->getOperand(1);
23469 // The Left side has to be a trunc.
23470 if (N0.getOpcode() != ISD::TRUNCATE)
23473 // The type of the truncated inputs.
23474 EVT WideVT = N0->getOperand(0)->getValueType(0);
23478 // The right side has to be a 'trunc' or a constant vector.
23479 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23480 ConstantSDNode *RHSConstSplat = nullptr;
23481 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23482 RHSConstSplat = RHSBV->getConstantSplatNode();
23483 if (!RHSTrunc && !RHSConstSplat)
23486 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23488 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23491 // Set N0 and N1 to hold the inputs to the new wide operation.
23492 N0 = N0->getOperand(0);
23493 if (RHSConstSplat) {
23494 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23495 SDValue(RHSConstSplat, 0));
23496 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23497 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23498 } else if (RHSTrunc) {
23499 N1 = N1->getOperand(0);
23502 // Generate the wide operation.
23503 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23504 unsigned Opcode = N->getOpcode();
23506 case ISD::ANY_EXTEND:
23508 case ISD::ZERO_EXTEND: {
23509 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23510 APInt Mask = APInt::getAllOnesValue(InBits);
23511 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23512 return DAG.getNode(ISD::AND, DL, VT,
23513 Op, DAG.getConstant(Mask, DL, VT));
23515 case ISD::SIGN_EXTEND:
23516 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23517 Op, DAG.getValueType(NarrowVT));
23519 llvm_unreachable("Unexpected opcode");
23523 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23524 TargetLowering::DAGCombinerInfo &DCI,
23525 const X86Subtarget *Subtarget) {
23526 SDValue N0 = N->getOperand(0);
23527 SDValue N1 = N->getOperand(1);
23530 // A vector zext_in_reg may be represented as a shuffle,
23531 // feeding into a bitcast (this represents anyext) feeding into
23532 // an and with a mask.
23533 // We'd like to try to combine that into a shuffle with zero
23534 // plus a bitcast, removing the and.
23535 if (N0.getOpcode() != ISD::BITCAST ||
23536 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23539 // The other side of the AND should be a splat of 2^C, where C
23540 // is the number of bits in the source type.
23541 if (N1.getOpcode() == ISD::BITCAST)
23542 N1 = N1.getOperand(0);
23543 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23545 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23547 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23548 EVT SrcType = Shuffle->getValueType(0);
23550 // We expect a single-source shuffle
23551 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23554 unsigned SrcSize = SrcType.getScalarSizeInBits();
23556 APInt SplatValue, SplatUndef;
23557 unsigned SplatBitSize;
23559 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23560 SplatBitSize, HasAnyUndefs))
23563 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23564 // Make sure the splat matches the mask we expect
23565 if (SplatBitSize > ResSize ||
23566 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23569 // Make sure the input and output size make sense
23570 if (SrcSize >= ResSize || ResSize % SrcSize)
23573 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23574 // The number of u's between each two values depends on the ratio between
23575 // the source and dest type.
23576 unsigned ZextRatio = ResSize / SrcSize;
23577 bool IsZext = true;
23578 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23579 if (i % ZextRatio) {
23580 if (Shuffle->getMaskElt(i) > 0) {
23586 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23587 // Expected element number
23597 // Ok, perform the transformation - replace the shuffle with
23598 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23599 // (instead of undef) where the k elements come from the zero vector.
23600 SmallVector<int, 8> Mask;
23601 unsigned NumElems = SrcType.getVectorNumElements();
23602 for (unsigned i = 0; i < NumElems; ++i)
23604 Mask.push_back(NumElems);
23606 Mask.push_back(i / ZextRatio);
23608 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23609 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23610 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23613 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23614 TargetLowering::DAGCombinerInfo &DCI,
23615 const X86Subtarget *Subtarget) {
23616 if (DCI.isBeforeLegalizeOps())
23619 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23622 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23625 EVT VT = N->getValueType(0);
23626 SDValue N0 = N->getOperand(0);
23627 SDValue N1 = N->getOperand(1);
23630 // Create BEXTR instructions
23631 // BEXTR is ((X >> imm) & (2**size-1))
23632 if (VT == MVT::i32 || VT == MVT::i64) {
23633 // Check for BEXTR.
23634 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23635 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23636 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23637 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23638 if (MaskNode && ShiftNode) {
23639 uint64_t Mask = MaskNode->getZExtValue();
23640 uint64_t Shift = ShiftNode->getZExtValue();
23641 if (isMask_64(Mask)) {
23642 uint64_t MaskSize = countPopulation(Mask);
23643 if (Shift + MaskSize <= VT.getSizeInBits())
23644 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23645 DAG.getConstant(Shift | (MaskSize << 8), DL,
23654 // Want to form ANDNP nodes:
23655 // 1) In the hopes of then easily combining them with OR and AND nodes
23656 // to form PBLEND/PSIGN.
23657 // 2) To match ANDN packed intrinsics
23658 if (VT != MVT::v2i64 && VT != MVT::v4i64)
23661 // Check LHS for vnot
23662 if (N0.getOpcode() == ISD::XOR &&
23663 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23664 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23665 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23667 // Check RHS for vnot
23668 if (N1.getOpcode() == ISD::XOR &&
23669 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23670 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23671 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23676 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23677 TargetLowering::DAGCombinerInfo &DCI,
23678 const X86Subtarget *Subtarget) {
23679 if (DCI.isBeforeLegalizeOps())
23682 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23685 SDValue N0 = N->getOperand(0);
23686 SDValue N1 = N->getOperand(1);
23687 EVT VT = N->getValueType(0);
23689 // look for psign/blend
23690 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23691 if (!Subtarget->hasSSSE3() ||
23692 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23695 // Canonicalize pandn to RHS
23696 if (N0.getOpcode() == X86ISD::ANDNP)
23698 // or (and (m, y), (pandn m, x))
23699 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23700 SDValue Mask = N1.getOperand(0);
23701 SDValue X = N1.getOperand(1);
23703 if (N0.getOperand(0) == Mask)
23704 Y = N0.getOperand(1);
23705 if (N0.getOperand(1) == Mask)
23706 Y = N0.getOperand(0);
23708 // Check to see if the mask appeared in both the AND and ANDNP and
23712 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23713 // Look through mask bitcast.
23714 if (Mask.getOpcode() == ISD::BITCAST)
23715 Mask = Mask.getOperand(0);
23716 if (X.getOpcode() == ISD::BITCAST)
23717 X = X.getOperand(0);
23718 if (Y.getOpcode() == ISD::BITCAST)
23719 Y = Y.getOperand(0);
23721 EVT MaskVT = Mask.getValueType();
23723 // Validate that the Mask operand is a vector sra node.
23724 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23725 // there is no psrai.b
23726 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23727 unsigned SraAmt = ~0;
23728 if (Mask.getOpcode() == ISD::SRA) {
23729 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23730 if (auto *AmtConst = AmtBV->getConstantSplatNode())
23731 SraAmt = AmtConst->getZExtValue();
23732 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23733 SDValue SraC = Mask.getOperand(1);
23734 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
23736 if ((SraAmt + 1) != EltBits)
23741 // Now we know we at least have a plendvb with the mask val. See if
23742 // we can form a psignb/w/d.
23743 // psign = x.type == y.type == mask.type && y = sub(0, x);
23744 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23745 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23746 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23747 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23748 "Unsupported VT for PSIGN");
23749 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23750 return DAG.getBitcast(VT, Mask);
23752 // PBLENDVB only available on SSE 4.1
23753 if (!Subtarget->hasSSE41())
23756 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23758 X = DAG.getBitcast(BlendVT, X);
23759 Y = DAG.getBitcast(BlendVT, Y);
23760 Mask = DAG.getBitcast(BlendVT, Mask);
23761 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23762 return DAG.getBitcast(VT, Mask);
23766 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23769 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23770 MachineFunction &MF = DAG.getMachineFunction();
23772 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23774 // SHLD/SHRD instructions have lower register pressure, but on some
23775 // platforms they have higher latency than the equivalent
23776 // series of shifts/or that would otherwise be generated.
23777 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23778 // have higher latencies and we are not optimizing for size.
23779 if (!OptForSize && Subtarget->isSHLDSlow())
23782 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23784 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23786 if (!N0.hasOneUse() || !N1.hasOneUse())
23789 SDValue ShAmt0 = N0.getOperand(1);
23790 if (ShAmt0.getValueType() != MVT::i8)
23792 SDValue ShAmt1 = N1.getOperand(1);
23793 if (ShAmt1.getValueType() != MVT::i8)
23795 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23796 ShAmt0 = ShAmt0.getOperand(0);
23797 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23798 ShAmt1 = ShAmt1.getOperand(0);
23801 unsigned Opc = X86ISD::SHLD;
23802 SDValue Op0 = N0.getOperand(0);
23803 SDValue Op1 = N1.getOperand(0);
23804 if (ShAmt0.getOpcode() == ISD::SUB) {
23805 Opc = X86ISD::SHRD;
23806 std::swap(Op0, Op1);
23807 std::swap(ShAmt0, ShAmt1);
23810 unsigned Bits = VT.getSizeInBits();
23811 if (ShAmt1.getOpcode() == ISD::SUB) {
23812 SDValue Sum = ShAmt1.getOperand(0);
23813 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23814 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23815 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23816 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23817 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23818 return DAG.getNode(Opc, DL, VT,
23820 DAG.getNode(ISD::TRUNCATE, DL,
23823 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23824 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23826 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23827 return DAG.getNode(Opc, DL, VT,
23828 N0.getOperand(0), N1.getOperand(0),
23829 DAG.getNode(ISD::TRUNCATE, DL,
23836 // Generate NEG and CMOV for integer abs.
23837 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23838 EVT VT = N->getValueType(0);
23840 // Since X86 does not have CMOV for 8-bit integer, we don't convert
23841 // 8-bit integer abs to NEG and CMOV.
23842 if (VT.isInteger() && VT.getSizeInBits() == 8)
23845 SDValue N0 = N->getOperand(0);
23846 SDValue N1 = N->getOperand(1);
23849 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23850 // and change it to SUB and CMOV.
23851 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23852 N0.getOpcode() == ISD::ADD &&
23853 N0.getOperand(1) == N1 &&
23854 N1.getOpcode() == ISD::SRA &&
23855 N1.getOperand(0) == N0.getOperand(0))
23856 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23857 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23858 // Generate SUB & CMOV.
23859 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23860 DAG.getConstant(0, DL, VT), N0.getOperand(0));
23862 SDValue Ops[] = { N0.getOperand(0), Neg,
23863 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23864 SDValue(Neg.getNode(), 1) };
23865 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23870 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23871 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23872 TargetLowering::DAGCombinerInfo &DCI,
23873 const X86Subtarget *Subtarget) {
23874 if (DCI.isBeforeLegalizeOps())
23877 if (Subtarget->hasCMov())
23878 if (SDValue RV = performIntegerAbsCombine(N, DAG))
23884 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23885 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23886 TargetLowering::DAGCombinerInfo &DCI,
23887 const X86Subtarget *Subtarget) {
23888 LoadSDNode *Ld = cast<LoadSDNode>(N);
23889 EVT RegVT = Ld->getValueType(0);
23890 EVT MemVT = Ld->getMemoryVT();
23892 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23894 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23895 // into two 16-byte operations.
23896 ISD::LoadExtType Ext = Ld->getExtensionType();
23897 unsigned Alignment = Ld->getAlignment();
23898 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23899 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23900 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23901 unsigned NumElems = RegVT.getVectorNumElements();
23905 SDValue Ptr = Ld->getBasePtr();
23906 SDValue Increment =
23907 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
23909 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23911 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23912 Ld->getPointerInfo(), Ld->isVolatile(),
23913 Ld->isNonTemporal(), Ld->isInvariant(),
23915 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23916 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23917 Ld->getPointerInfo(), Ld->isVolatile(),
23918 Ld->isNonTemporal(), Ld->isInvariant(),
23919 std::min(16U, Alignment));
23920 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23922 Load2.getValue(1));
23924 SDValue NewVec = DAG.getUNDEF(RegVT);
23925 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23926 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23927 return DCI.CombineTo(N, NewVec, TF, true);
23933 /// PerformMLOADCombine - Resolve extending loads
23934 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23935 TargetLowering::DAGCombinerInfo &DCI,
23936 const X86Subtarget *Subtarget) {
23937 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23938 if (Mld->getExtensionType() != ISD::SEXTLOAD)
23941 EVT VT = Mld->getValueType(0);
23942 unsigned NumElems = VT.getVectorNumElements();
23943 EVT LdVT = Mld->getMemoryVT();
23946 assert(LdVT != VT && "Cannot extend to the same type");
23947 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23948 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23949 // From, To sizes and ElemCount must be pow of two
23950 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23951 "Unexpected size for extending masked load");
23953 unsigned SizeRatio = ToSz / FromSz;
23954 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23956 // Create a type on which we perform the shuffle
23957 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23958 LdVT.getScalarType(), NumElems*SizeRatio);
23959 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23961 // Convert Src0 value
23962 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23963 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23964 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23965 for (unsigned i = 0; i != NumElems; ++i)
23966 ShuffleVec[i] = i * SizeRatio;
23968 // Can't shuffle using an illegal type.
23969 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23970 && "WideVecVT should be legal");
23971 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23972 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23974 // Prepare the new mask
23976 SDValue Mask = Mld->getMask();
23977 if (Mask.getValueType() == VT) {
23978 // Mask and original value have the same type
23979 NewMask = DAG.getBitcast(WideVecVT, Mask);
23980 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23981 for (unsigned i = 0; i != NumElems; ++i)
23982 ShuffleVec[i] = i * SizeRatio;
23983 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23984 ShuffleVec[i] = NumElems*SizeRatio;
23985 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23986 DAG.getConstant(0, dl, WideVecVT),
23990 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23991 unsigned WidenNumElts = NumElems*SizeRatio;
23992 unsigned MaskNumElts = VT.getVectorNumElements();
23993 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23996 unsigned NumConcat = WidenNumElts / MaskNumElts;
23997 SmallVector<SDValue, 16> Ops(NumConcat);
23998 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24000 for (unsigned i = 1; i != NumConcat; ++i)
24003 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24006 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24007 Mld->getBasePtr(), NewMask, WideSrc0,
24008 Mld->getMemoryVT(), Mld->getMemOperand(),
24010 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24011 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24014 /// PerformMSTORECombine - Resolve truncating stores
24015 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24016 const X86Subtarget *Subtarget) {
24017 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24018 if (!Mst->isTruncatingStore())
24021 EVT VT = Mst->getValue().getValueType();
24022 unsigned NumElems = VT.getVectorNumElements();
24023 EVT StVT = Mst->getMemoryVT();
24026 assert(StVT != VT && "Cannot truncate to the same type");
24027 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24028 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24030 // From, To sizes and ElemCount must be pow of two
24031 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24032 "Unexpected size for truncating masked store");
24033 // We are going to use the original vector elt for storing.
24034 // Accumulated smaller vector elements must be a multiple of the store size.
24035 assert (((NumElems * FromSz) % ToSz) == 0 &&
24036 "Unexpected ratio for truncating masked store");
24038 unsigned SizeRatio = FromSz / ToSz;
24039 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24041 // Create a type on which we perform the shuffle
24042 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24043 StVT.getScalarType(), NumElems*SizeRatio);
24045 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24047 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24048 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24049 for (unsigned i = 0; i != NumElems; ++i)
24050 ShuffleVec[i] = i * SizeRatio;
24052 // Can't shuffle using an illegal type.
24053 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24054 && "WideVecVT should be legal");
24056 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24057 DAG.getUNDEF(WideVecVT),
24061 SDValue Mask = Mst->getMask();
24062 if (Mask.getValueType() == VT) {
24063 // Mask and original value have the same type
24064 NewMask = DAG.getBitcast(WideVecVT, Mask);
24065 for (unsigned i = 0; i != NumElems; ++i)
24066 ShuffleVec[i] = i * SizeRatio;
24067 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24068 ShuffleVec[i] = NumElems*SizeRatio;
24069 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24070 DAG.getConstant(0, dl, WideVecVT),
24074 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24075 unsigned WidenNumElts = NumElems*SizeRatio;
24076 unsigned MaskNumElts = VT.getVectorNumElements();
24077 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24080 unsigned NumConcat = WidenNumElts / MaskNumElts;
24081 SmallVector<SDValue, 16> Ops(NumConcat);
24082 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24084 for (unsigned i = 1; i != NumConcat; ++i)
24087 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24090 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24091 NewMask, StVT, Mst->getMemOperand(), false);
24093 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24094 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24095 const X86Subtarget *Subtarget) {
24096 StoreSDNode *St = cast<StoreSDNode>(N);
24097 EVT VT = St->getValue().getValueType();
24098 EVT StVT = St->getMemoryVT();
24100 SDValue StoredVal = St->getOperand(1);
24101 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24103 // If we are saving a concatenation of two XMM registers and 32-byte stores
24104 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24105 unsigned Alignment = St->getAlignment();
24106 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24107 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24108 StVT == VT && !IsAligned) {
24109 unsigned NumElems = VT.getVectorNumElements();
24113 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24114 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24117 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24118 SDValue Ptr0 = St->getBasePtr();
24119 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24121 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24122 St->getPointerInfo(), St->isVolatile(),
24123 St->isNonTemporal(), Alignment);
24124 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24125 St->getPointerInfo(), St->isVolatile(),
24126 St->isNonTemporal(),
24127 std::min(16U, Alignment));
24128 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24131 // Optimize trunc store (of multiple scalars) to shuffle and store.
24132 // First, pack all of the elements in one place. Next, store to memory
24133 // in fewer chunks.
24134 if (St->isTruncatingStore() && VT.isVector()) {
24135 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24136 unsigned NumElems = VT.getVectorNumElements();
24137 assert(StVT != VT && "Cannot truncate to the same type");
24138 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24139 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24141 // From, To sizes and ElemCount must be pow of two
24142 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24143 // We are going to use the original vector elt for storing.
24144 // Accumulated smaller vector elements must be a multiple of the store size.
24145 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24147 unsigned SizeRatio = FromSz / ToSz;
24149 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24151 // Create a type on which we perform the shuffle
24152 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24153 StVT.getScalarType(), NumElems*SizeRatio);
24155 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24157 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24158 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24159 for (unsigned i = 0; i != NumElems; ++i)
24160 ShuffleVec[i] = i * SizeRatio;
24162 // Can't shuffle using an illegal type.
24163 if (!TLI.isTypeLegal(WideVecVT))
24166 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24167 DAG.getUNDEF(WideVecVT),
24169 // At this point all of the data is stored at the bottom of the
24170 // register. We now need to save it to mem.
24172 // Find the largest store unit
24173 MVT StoreType = MVT::i8;
24174 for (MVT Tp : MVT::integer_valuetypes()) {
24175 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24179 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24180 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24181 (64 <= NumElems * ToSz))
24182 StoreType = MVT::f64;
24184 // Bitcast the original vector into a vector of store-size units
24185 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24186 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24187 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24188 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24189 SmallVector<SDValue, 8> Chains;
24190 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24191 TLI.getPointerTy(DAG.getDataLayout()));
24192 SDValue Ptr = St->getBasePtr();
24194 // Perform one or more big stores into memory.
24195 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24196 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24197 StoreType, ShuffWide,
24198 DAG.getIntPtrConstant(i, dl));
24199 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24200 St->getPointerInfo(), St->isVolatile(),
24201 St->isNonTemporal(), St->getAlignment());
24202 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24203 Chains.push_back(Ch);
24206 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24209 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24210 // the FP state in cases where an emms may be missing.
24211 // A preferable solution to the general problem is to figure out the right
24212 // places to insert EMMS. This qualifies as a quick hack.
24214 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24215 if (VT.getSizeInBits() != 64)
24218 const Function *F = DAG.getMachineFunction().getFunction();
24219 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24221 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24222 if ((VT.isVector() ||
24223 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24224 isa<LoadSDNode>(St->getValue()) &&
24225 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24226 St->getChain().hasOneUse() && !St->isVolatile()) {
24227 SDNode* LdVal = St->getValue().getNode();
24228 LoadSDNode *Ld = nullptr;
24229 int TokenFactorIndex = -1;
24230 SmallVector<SDValue, 8> Ops;
24231 SDNode* ChainVal = St->getChain().getNode();
24232 // Must be a store of a load. We currently handle two cases: the load
24233 // is a direct child, and it's under an intervening TokenFactor. It is
24234 // possible to dig deeper under nested TokenFactors.
24235 if (ChainVal == LdVal)
24236 Ld = cast<LoadSDNode>(St->getChain());
24237 else if (St->getValue().hasOneUse() &&
24238 ChainVal->getOpcode() == ISD::TokenFactor) {
24239 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24240 if (ChainVal->getOperand(i).getNode() == LdVal) {
24241 TokenFactorIndex = i;
24242 Ld = cast<LoadSDNode>(St->getValue());
24244 Ops.push_back(ChainVal->getOperand(i));
24248 if (!Ld || !ISD::isNormalLoad(Ld))
24251 // If this is not the MMX case, i.e. we are just turning i64 load/store
24252 // into f64 load/store, avoid the transformation if there are multiple
24253 // uses of the loaded value.
24254 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24259 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24260 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24262 if (Subtarget->is64Bit() || F64IsLegal) {
24263 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24264 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24265 Ld->getPointerInfo(), Ld->isVolatile(),
24266 Ld->isNonTemporal(), Ld->isInvariant(),
24267 Ld->getAlignment());
24268 SDValue NewChain = NewLd.getValue(1);
24269 if (TokenFactorIndex != -1) {
24270 Ops.push_back(NewChain);
24271 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24273 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24274 St->getPointerInfo(),
24275 St->isVolatile(), St->isNonTemporal(),
24276 St->getAlignment());
24279 // Otherwise, lower to two pairs of 32-bit loads / stores.
24280 SDValue LoAddr = Ld->getBasePtr();
24281 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24282 DAG.getConstant(4, LdDL, MVT::i32));
24284 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24285 Ld->getPointerInfo(),
24286 Ld->isVolatile(), Ld->isNonTemporal(),
24287 Ld->isInvariant(), Ld->getAlignment());
24288 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24289 Ld->getPointerInfo().getWithOffset(4),
24290 Ld->isVolatile(), Ld->isNonTemporal(),
24292 MinAlign(Ld->getAlignment(), 4));
24294 SDValue NewChain = LoLd.getValue(1);
24295 if (TokenFactorIndex != -1) {
24296 Ops.push_back(LoLd);
24297 Ops.push_back(HiLd);
24298 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24301 LoAddr = St->getBasePtr();
24302 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24303 DAG.getConstant(4, StDL, MVT::i32));
24305 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24306 St->getPointerInfo(),
24307 St->isVolatile(), St->isNonTemporal(),
24308 St->getAlignment());
24309 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24310 St->getPointerInfo().getWithOffset(4),
24312 St->isNonTemporal(),
24313 MinAlign(St->getAlignment(), 4));
24314 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24317 // This is similar to the above case, but here we handle a scalar 64-bit
24318 // integer store that is extracted from a vector on a 32-bit target.
24319 // If we have SSE2, then we can treat it like a floating-point double
24320 // to get past legalization. The execution dependencies fixup pass will
24321 // choose the optimal machine instruction for the store if this really is
24322 // an integer or v2f32 rather than an f64.
24323 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24324 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24325 SDValue OldExtract = St->getOperand(1);
24326 SDValue ExtOp0 = OldExtract.getOperand(0);
24327 unsigned VecSize = ExtOp0.getValueSizeInBits();
24328 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24329 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24330 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24331 BitCast, OldExtract.getOperand(1));
24332 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24333 St->getPointerInfo(), St->isVolatile(),
24334 St->isNonTemporal(), St->getAlignment());
24340 /// Return 'true' if this vector operation is "horizontal"
24341 /// and return the operands for the horizontal operation in LHS and RHS. A
24342 /// horizontal operation performs the binary operation on successive elements
24343 /// of its first operand, then on successive elements of its second operand,
24344 /// returning the resulting values in a vector. For example, if
24345 /// A = < float a0, float a1, float a2, float a3 >
24347 /// B = < float b0, float b1, float b2, float b3 >
24348 /// then the result of doing a horizontal operation on A and B is
24349 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24350 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24351 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24352 /// set to A, RHS to B, and the routine returns 'true'.
24353 /// Note that the binary operation should have the property that if one of the
24354 /// operands is UNDEF then the result is UNDEF.
24355 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24356 // Look for the following pattern: if
24357 // A = < float a0, float a1, float a2, float a3 >
24358 // B = < float b0, float b1, float b2, float b3 >
24360 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24361 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24362 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24363 // which is A horizontal-op B.
24365 // At least one of the operands should be a vector shuffle.
24366 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24367 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24370 MVT VT = LHS.getSimpleValueType();
24372 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24373 "Unsupported vector type for horizontal add/sub");
24375 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24376 // operate independently on 128-bit lanes.
24377 unsigned NumElts = VT.getVectorNumElements();
24378 unsigned NumLanes = VT.getSizeInBits()/128;
24379 unsigned NumLaneElts = NumElts / NumLanes;
24380 assert((NumLaneElts % 2 == 0) &&
24381 "Vector type should have an even number of elements in each lane");
24382 unsigned HalfLaneElts = NumLaneElts/2;
24384 // View LHS in the form
24385 // LHS = VECTOR_SHUFFLE A, B, LMask
24386 // If LHS is not a shuffle then pretend it is the shuffle
24387 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24388 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24391 SmallVector<int, 16> LMask(NumElts);
24392 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24393 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24394 A = LHS.getOperand(0);
24395 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24396 B = LHS.getOperand(1);
24397 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24398 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24400 if (LHS.getOpcode() != ISD::UNDEF)
24402 for (unsigned i = 0; i != NumElts; ++i)
24406 // Likewise, view RHS in the form
24407 // RHS = VECTOR_SHUFFLE C, D, RMask
24409 SmallVector<int, 16> RMask(NumElts);
24410 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24411 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24412 C = RHS.getOperand(0);
24413 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24414 D = RHS.getOperand(1);
24415 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24416 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24418 if (RHS.getOpcode() != ISD::UNDEF)
24420 for (unsigned i = 0; i != NumElts; ++i)
24424 // Check that the shuffles are both shuffling the same vectors.
24425 if (!(A == C && B == D) && !(A == D && B == C))
24428 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24429 if (!A.getNode() && !B.getNode())
24432 // If A and B occur in reverse order in RHS, then "swap" them (which means
24433 // rewriting the mask).
24435 ShuffleVectorSDNode::commuteMask(RMask);
24437 // At this point LHS and RHS are equivalent to
24438 // LHS = VECTOR_SHUFFLE A, B, LMask
24439 // RHS = VECTOR_SHUFFLE A, B, RMask
24440 // Check that the masks correspond to performing a horizontal operation.
24441 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24442 for (unsigned i = 0; i != NumLaneElts; ++i) {
24443 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24445 // Ignore any UNDEF components.
24446 if (LIdx < 0 || RIdx < 0 ||
24447 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24448 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24451 // Check that successive elements are being operated on. If not, this is
24452 // not a horizontal operation.
24453 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24454 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24455 if (!(LIdx == Index && RIdx == Index + 1) &&
24456 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24461 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24462 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24466 /// Do target-specific dag combines on floating point adds.
24467 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24468 const X86Subtarget *Subtarget) {
24469 EVT VT = N->getValueType(0);
24470 SDValue LHS = N->getOperand(0);
24471 SDValue RHS = N->getOperand(1);
24473 // Try to synthesize horizontal adds from adds of shuffles.
24474 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24475 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24476 isHorizontalBinOp(LHS, RHS, true))
24477 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24481 /// Do target-specific dag combines on floating point subs.
24482 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24483 const X86Subtarget *Subtarget) {
24484 EVT VT = N->getValueType(0);
24485 SDValue LHS = N->getOperand(0);
24486 SDValue RHS = N->getOperand(1);
24488 // Try to synthesize horizontal subs from subs of shuffles.
24489 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24490 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24491 isHorizontalBinOp(LHS, RHS, false))
24492 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24496 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24497 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24498 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24500 // F[X]OR(0.0, x) -> x
24501 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24502 if (C->getValueAPF().isPosZero())
24503 return N->getOperand(1);
24505 // F[X]OR(x, 0.0) -> x
24506 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24507 if (C->getValueAPF().isPosZero())
24508 return N->getOperand(0);
24512 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24513 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24514 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24516 // Only perform optimizations if UnsafeMath is used.
24517 if (!DAG.getTarget().Options.UnsafeFPMath)
24520 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24521 // into FMINC and FMAXC, which are Commutative operations.
24522 unsigned NewOp = 0;
24523 switch (N->getOpcode()) {
24524 default: llvm_unreachable("unknown opcode");
24525 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24526 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24529 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24530 N->getOperand(0), N->getOperand(1));
24533 /// Do target-specific dag combines on X86ISD::FAND nodes.
24534 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24535 // FAND(0.0, x) -> 0.0
24536 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24537 if (C->getValueAPF().isPosZero())
24538 return N->getOperand(0);
24540 // FAND(x, 0.0) -> 0.0
24541 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24542 if (C->getValueAPF().isPosZero())
24543 return N->getOperand(1);
24548 /// Do target-specific dag combines on X86ISD::FANDN nodes
24549 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24550 // FANDN(0.0, x) -> x
24551 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24552 if (C->getValueAPF().isPosZero())
24553 return N->getOperand(1);
24555 // FANDN(x, 0.0) -> 0.0
24556 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24557 if (C->getValueAPF().isPosZero())
24558 return N->getOperand(1);
24563 static SDValue PerformBTCombine(SDNode *N,
24565 TargetLowering::DAGCombinerInfo &DCI) {
24566 // BT ignores high bits in the bit index operand.
24567 SDValue Op1 = N->getOperand(1);
24568 if (Op1.hasOneUse()) {
24569 unsigned BitWidth = Op1.getValueSizeInBits();
24570 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24571 APInt KnownZero, KnownOne;
24572 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24573 !DCI.isBeforeLegalizeOps());
24574 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24575 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24576 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24577 DCI.CommitTargetLoweringOpt(TLO);
24582 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24583 SDValue Op = N->getOperand(0);
24584 if (Op.getOpcode() == ISD::BITCAST)
24585 Op = Op.getOperand(0);
24586 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24587 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24588 VT.getVectorElementType().getSizeInBits() ==
24589 OpVT.getVectorElementType().getSizeInBits()) {
24590 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24595 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24596 const X86Subtarget *Subtarget) {
24597 EVT VT = N->getValueType(0);
24598 if (!VT.isVector())
24601 SDValue N0 = N->getOperand(0);
24602 SDValue N1 = N->getOperand(1);
24603 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24606 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24607 // both SSE and AVX2 since there is no sign-extended shift right
24608 // operation on a vector with 64-bit elements.
24609 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24610 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24611 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24612 N0.getOpcode() == ISD::SIGN_EXTEND)) {
24613 SDValue N00 = N0.getOperand(0);
24615 // EXTLOAD has a better solution on AVX2,
24616 // it may be replaced with X86ISD::VSEXT node.
24617 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24618 if (!ISD::isNormalLoad(N00.getNode()))
24621 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24622 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24624 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24630 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24631 TargetLowering::DAGCombinerInfo &DCI,
24632 const X86Subtarget *Subtarget) {
24633 SDValue N0 = N->getOperand(0);
24634 EVT VT = N->getValueType(0);
24635 EVT SVT = VT.getScalarType();
24636 EVT InVT = N0.getValueType();
24637 EVT InSVT = InVT.getScalarType();
24640 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24641 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24642 // This exposes the sext to the sdivrem lowering, so that it directly extends
24643 // from AH (which we otherwise need to do contortions to access).
24644 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24645 InVT == MVT::i8 && VT == MVT::i32) {
24646 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24647 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24648 N0.getOperand(0), N0.getOperand(1));
24649 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24650 return R.getValue(1);
24653 if (!DCI.isBeforeLegalizeOps()) {
24654 if (InVT == MVT::i1) {
24655 SDValue Zero = DAG.getConstant(0, DL, VT);
24657 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24658 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24663 if (VT.isVector() && Subtarget->hasSSE2()) {
24664 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24665 EVT InVT = N.getValueType();
24666 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24667 Size / InVT.getScalarSizeInBits());
24668 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24669 DAG.getUNDEF(InVT));
24671 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24674 // If target-size is less than 128-bits, extend to a type that would extend
24675 // to 128 bits, extend that and extract the original target vector.
24676 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24677 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24678 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24679 unsigned Scale = 128 / VT.getSizeInBits();
24681 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24682 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24683 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24684 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24685 DAG.getIntPtrConstant(0, DL));
24688 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24689 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24690 if (VT.getSizeInBits() == 128 &&
24691 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24692 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24693 SDValue ExOp = ExtendVecSize(DL, N0, 128);
24694 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24697 // On pre-AVX2 targets, split into 128-bit nodes of
24698 // ISD::SIGN_EXTEND_VECTOR_INREG.
24699 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24700 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24701 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24702 unsigned NumVecs = VT.getSizeInBits() / 128;
24703 unsigned NumSubElts = 128 / SVT.getSizeInBits();
24704 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24705 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24707 SmallVector<SDValue, 8> Opnds;
24708 for (unsigned i = 0, Offset = 0; i != NumVecs;
24709 ++i, Offset += NumSubElts) {
24710 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24711 DAG.getIntPtrConstant(Offset, DL));
24712 SrcVec = ExtendVecSize(DL, SrcVec, 128);
24713 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24714 Opnds.push_back(SrcVec);
24716 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24720 if (!Subtarget->hasFp256())
24723 if (VT.isVector() && VT.getSizeInBits() == 256)
24724 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24730 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24731 const X86Subtarget* Subtarget) {
24733 EVT VT = N->getValueType(0);
24735 // Let legalize expand this if it isn't a legal type yet.
24736 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24739 EVT ScalarVT = VT.getScalarType();
24740 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24741 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24742 !Subtarget->hasAVX512()))
24745 SDValue A = N->getOperand(0);
24746 SDValue B = N->getOperand(1);
24747 SDValue C = N->getOperand(2);
24749 bool NegA = (A.getOpcode() == ISD::FNEG);
24750 bool NegB = (B.getOpcode() == ISD::FNEG);
24751 bool NegC = (C.getOpcode() == ISD::FNEG);
24753 // Negative multiplication when NegA xor NegB
24754 bool NegMul = (NegA != NegB);
24756 A = A.getOperand(0);
24758 B = B.getOperand(0);
24760 C = C.getOperand(0);
24764 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24766 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24768 return DAG.getNode(Opcode, dl, VT, A, B, C);
24771 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24772 TargetLowering::DAGCombinerInfo &DCI,
24773 const X86Subtarget *Subtarget) {
24774 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
24775 // (and (i32 x86isd::setcc_carry), 1)
24776 // This eliminates the zext. This transformation is necessary because
24777 // ISD::SETCC is always legalized to i8.
24779 SDValue N0 = N->getOperand(0);
24780 EVT VT = N->getValueType(0);
24782 if (N0.getOpcode() == ISD::AND &&
24784 N0.getOperand(0).hasOneUse()) {
24785 SDValue N00 = N0.getOperand(0);
24786 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24787 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24788 if (!C || C->getZExtValue() != 1)
24790 return DAG.getNode(ISD::AND, dl, VT,
24791 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24792 N00.getOperand(0), N00.getOperand(1)),
24793 DAG.getConstant(1, dl, VT));
24797 if (N0.getOpcode() == ISD::TRUNCATE &&
24799 N0.getOperand(0).hasOneUse()) {
24800 SDValue N00 = N0.getOperand(0);
24801 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24802 return DAG.getNode(ISD::AND, dl, VT,
24803 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24804 N00.getOperand(0), N00.getOperand(1)),
24805 DAG.getConstant(1, dl, VT));
24809 if (VT.is256BitVector())
24810 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24813 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24814 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24815 // This exposes the zext to the udivrem lowering, so that it directly extends
24816 // from AH (which we otherwise need to do contortions to access).
24817 if (N0.getOpcode() == ISD::UDIVREM &&
24818 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24819 (VT == MVT::i32 || VT == MVT::i64)) {
24820 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24821 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24822 N0.getOperand(0), N0.getOperand(1));
24823 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24824 return R.getValue(1);
24830 // Optimize x == -y --> x+y == 0
24831 // x != -y --> x+y != 0
24832 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24833 const X86Subtarget* Subtarget) {
24834 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24835 SDValue LHS = N->getOperand(0);
24836 SDValue RHS = N->getOperand(1);
24837 EVT VT = N->getValueType(0);
24840 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24841 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24842 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24843 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24844 LHS.getOperand(1));
24845 return DAG.getSetCC(DL, N->getValueType(0), addV,
24846 DAG.getConstant(0, DL, addV.getValueType()), CC);
24848 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24850 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24851 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24852 RHS.getOperand(1));
24853 return DAG.getSetCC(DL, N->getValueType(0), addV,
24854 DAG.getConstant(0, DL, addV.getValueType()), CC);
24857 if (VT.getScalarType() == MVT::i1 &&
24858 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24860 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24861 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24862 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24864 if (!IsSEXT0 || !IsVZero1) {
24865 // Swap the operands and update the condition code.
24866 std::swap(LHS, RHS);
24867 CC = ISD::getSetCCSwappedOperands(CC);
24869 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24870 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24871 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24874 if (IsSEXT0 && IsVZero1) {
24875 assert(VT == LHS.getOperand(0).getValueType() &&
24876 "Uexpected operand type");
24877 if (CC == ISD::SETGT)
24878 return DAG.getConstant(0, DL, VT);
24879 if (CC == ISD::SETLE)
24880 return DAG.getConstant(1, DL, VT);
24881 if (CC == ISD::SETEQ || CC == ISD::SETGE)
24882 return DAG.getNOT(DL, LHS.getOperand(0), VT);
24884 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24885 "Unexpected condition code!");
24886 return LHS.getOperand(0);
24893 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24894 SelectionDAG &DAG) {
24896 MVT VT = Load->getSimpleValueType(0);
24897 MVT EVT = VT.getVectorElementType();
24898 SDValue Addr = Load->getOperand(1);
24899 SDValue NewAddr = DAG.getNode(
24900 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24901 DAG.getConstant(Index * EVT.getStoreSize(), dl,
24902 Addr.getSimpleValueType()));
24905 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24906 DAG.getMachineFunction().getMachineMemOperand(
24907 Load->getMemOperand(), 0, EVT.getStoreSize()));
24911 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24912 const X86Subtarget *Subtarget) {
24914 MVT VT = N->getOperand(1)->getSimpleValueType(0);
24915 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24916 "X86insertps is only defined for v4x32");
24918 SDValue Ld = N->getOperand(1);
24919 if (MayFoldLoad(Ld)) {
24920 // Extract the countS bits from the immediate so we can get the proper
24921 // address when narrowing the vector load to a specific element.
24922 // When the second source op is a memory address, insertps doesn't use
24923 // countS and just gets an f32 from that address.
24924 unsigned DestIndex =
24925 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24927 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24929 // Create this as a scalar to vector to match the instruction pattern.
24930 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24931 // countS bits are ignored when loading from memory on insertps, which
24932 // means we don't need to explicitly set them to 0.
24933 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24934 LoadScalarToVector, N->getOperand(2));
24939 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24940 SDValue V0 = N->getOperand(0);
24941 SDValue V1 = N->getOperand(1);
24943 EVT VT = N->getValueType(0);
24945 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24946 // operands and changing the mask to 1. This saves us a bunch of
24947 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24948 // x86InstrInfo knows how to commute this back after instruction selection
24949 // if it would help register allocation.
24951 // TODO: If optimizing for size or a processor that doesn't suffer from
24952 // partial register update stalls, this should be transformed into a MOVSD
24953 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24955 if (VT == MVT::v2f64)
24956 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24957 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24958 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24959 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24965 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24966 // as "sbb reg,reg", since it can be extended without zext and produces
24967 // an all-ones bit which is more useful than 0/1 in some cases.
24968 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24971 return DAG.getNode(ISD::AND, DL, VT,
24972 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24973 DAG.getConstant(X86::COND_B, DL, MVT::i8),
24975 DAG.getConstant(1, DL, VT));
24976 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24977 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24978 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24979 DAG.getConstant(X86::COND_B, DL, MVT::i8),
24983 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24984 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24985 TargetLowering::DAGCombinerInfo &DCI,
24986 const X86Subtarget *Subtarget) {
24988 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24989 SDValue EFLAGS = N->getOperand(1);
24991 if (CC == X86::COND_A) {
24992 // Try to convert COND_A into COND_B in an attempt to facilitate
24993 // materializing "setb reg".
24995 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24996 // cannot take an immediate as its first operand.
24998 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24999 EFLAGS.getValueType().isInteger() &&
25000 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25001 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25002 EFLAGS.getNode()->getVTList(),
25003 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25004 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25005 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25009 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25010 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25012 if (CC == X86::COND_B)
25013 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25015 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25016 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25017 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25023 // Optimize branch condition evaluation.
25025 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25026 TargetLowering::DAGCombinerInfo &DCI,
25027 const X86Subtarget *Subtarget) {
25029 SDValue Chain = N->getOperand(0);
25030 SDValue Dest = N->getOperand(1);
25031 SDValue EFLAGS = N->getOperand(3);
25032 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25034 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25035 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25036 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25043 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25044 SelectionDAG &DAG) {
25045 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25046 // optimize away operation when it's from a constant.
25048 // The general transformation is:
25049 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25050 // AND(VECTOR_CMP(x,y), constant2)
25051 // constant2 = UNARYOP(constant)
25053 // Early exit if this isn't a vector operation, the operand of the
25054 // unary operation isn't a bitwise AND, or if the sizes of the operations
25055 // aren't the same.
25056 EVT VT = N->getValueType(0);
25057 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25058 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25059 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25062 // Now check that the other operand of the AND is a constant. We could
25063 // make the transformation for non-constant splats as well, but it's unclear
25064 // that would be a benefit as it would not eliminate any operations, just
25065 // perform one more step in scalar code before moving to the vector unit.
25066 if (BuildVectorSDNode *BV =
25067 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25068 // Bail out if the vector isn't a constant.
25069 if (!BV->isConstant())
25072 // Everything checks out. Build up the new and improved node.
25074 EVT IntVT = BV->getValueType(0);
25075 // Create a new constant of the appropriate type for the transformed
25077 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25078 // The AND node needs bitcasts to/from an integer vector type around it.
25079 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25080 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25081 N->getOperand(0)->getOperand(0), MaskConst);
25082 SDValue Res = DAG.getBitcast(VT, NewAnd);
25089 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25090 const X86Subtarget *Subtarget) {
25091 SDValue Op0 = N->getOperand(0);
25092 EVT VT = N->getValueType(0);
25093 EVT InVT = Op0.getValueType();
25094 EVT InSVT = InVT.getScalarType();
25095 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25097 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25098 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25099 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25101 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25102 InVT.getVectorNumElements());
25103 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25105 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25106 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25108 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25114 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25115 const X86Subtarget *Subtarget) {
25116 // First try to optimize away the conversion entirely when it's
25117 // conditionally from a constant. Vectors only.
25118 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25121 // Now move on to more general possibilities.
25122 SDValue Op0 = N->getOperand(0);
25123 EVT VT = N->getValueType(0);
25124 EVT InVT = Op0.getValueType();
25125 EVT InSVT = InVT.getScalarType();
25127 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25128 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25129 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25131 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25132 InVT.getVectorNumElements());
25133 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25134 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25137 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25138 // a 32-bit target where SSE doesn't support i64->FP operations.
25139 if (Op0.getOpcode() == ISD::LOAD) {
25140 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25141 EVT LdVT = Ld->getValueType(0);
25143 // This transformation is not supported if the result type is f16
25144 if (VT == MVT::f16)
25147 if (!Ld->isVolatile() && !VT.isVector() &&
25148 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25149 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25150 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25151 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25152 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25159 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25160 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25161 X86TargetLowering::DAGCombinerInfo &DCI) {
25162 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25163 // the result is either zero or one (depending on the input carry bit).
25164 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25165 if (X86::isZeroNode(N->getOperand(0)) &&
25166 X86::isZeroNode(N->getOperand(1)) &&
25167 // We don't have a good way to replace an EFLAGS use, so only do this when
25169 SDValue(N, 1).use_empty()) {
25171 EVT VT = N->getValueType(0);
25172 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25173 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25174 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25175 DAG.getConstant(X86::COND_B, DL,
25178 DAG.getConstant(1, DL, VT));
25179 return DCI.CombineTo(N, Res1, CarryOut);
25185 // fold (add Y, (sete X, 0)) -> adc 0, Y
25186 // (add Y, (setne X, 0)) -> sbb -1, Y
25187 // (sub (sete X, 0), Y) -> sbb 0, Y
25188 // (sub (setne X, 0), Y) -> adc -1, Y
25189 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25192 // Look through ZExts.
25193 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25194 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25197 SDValue SetCC = Ext.getOperand(0);
25198 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25201 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25202 if (CC != X86::COND_E && CC != X86::COND_NE)
25205 SDValue Cmp = SetCC.getOperand(1);
25206 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25207 !X86::isZeroNode(Cmp.getOperand(1)) ||
25208 !Cmp.getOperand(0).getValueType().isInteger())
25211 SDValue CmpOp0 = Cmp.getOperand(0);
25212 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25213 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25215 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25216 if (CC == X86::COND_NE)
25217 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25218 DL, OtherVal.getValueType(), OtherVal,
25219 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25221 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25222 DL, OtherVal.getValueType(), OtherVal,
25223 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25226 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25227 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25228 const X86Subtarget *Subtarget) {
25229 EVT VT = N->getValueType(0);
25230 SDValue Op0 = N->getOperand(0);
25231 SDValue Op1 = N->getOperand(1);
25233 // Try to synthesize horizontal adds from adds of shuffles.
25234 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25235 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25236 isHorizontalBinOp(Op0, Op1, true))
25237 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25239 return OptimizeConditionalInDecrement(N, DAG);
25242 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25243 const X86Subtarget *Subtarget) {
25244 SDValue Op0 = N->getOperand(0);
25245 SDValue Op1 = N->getOperand(1);
25247 // X86 can't encode an immediate LHS of a sub. See if we can push the
25248 // negation into a preceding instruction.
25249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25250 // If the RHS of the sub is a XOR with one use and a constant, invert the
25251 // immediate. Then add one to the LHS of the sub so we can turn
25252 // X-Y -> X+~Y+1, saving one register.
25253 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25254 isa<ConstantSDNode>(Op1.getOperand(1))) {
25255 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25256 EVT VT = Op0.getValueType();
25257 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25259 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25260 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25261 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25265 // Try to synthesize horizontal adds from adds of shuffles.
25266 EVT VT = N->getValueType(0);
25267 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25268 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25269 isHorizontalBinOp(Op0, Op1, true))
25270 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25272 return OptimizeConditionalInDecrement(N, DAG);
25275 /// performVZEXTCombine - Performs build vector combines
25276 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25277 TargetLowering::DAGCombinerInfo &DCI,
25278 const X86Subtarget *Subtarget) {
25280 MVT VT = N->getSimpleValueType(0);
25281 SDValue Op = N->getOperand(0);
25282 MVT OpVT = Op.getSimpleValueType();
25283 MVT OpEltVT = OpVT.getVectorElementType();
25284 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25286 // (vzext (bitcast (vzext (x)) -> (vzext x)
25288 while (V.getOpcode() == ISD::BITCAST)
25289 V = V.getOperand(0);
25291 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25292 MVT InnerVT = V.getSimpleValueType();
25293 MVT InnerEltVT = InnerVT.getVectorElementType();
25295 // If the element sizes match exactly, we can just do one larger vzext. This
25296 // is always an exact type match as vzext operates on integer types.
25297 if (OpEltVT == InnerEltVT) {
25298 assert(OpVT == InnerVT && "Types must match for vzext!");
25299 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25302 // The only other way we can combine them is if only a single element of the
25303 // inner vzext is used in the input to the outer vzext.
25304 if (InnerEltVT.getSizeInBits() < InputBits)
25307 // In this case, the inner vzext is completely dead because we're going to
25308 // only look at bits inside of the low element. Just do the outer vzext on
25309 // a bitcast of the input to the inner.
25310 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25313 // Check if we can bypass extracting and re-inserting an element of an input
25314 // vector. Essentialy:
25315 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25316 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25317 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25318 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25319 SDValue ExtractedV = V.getOperand(0);
25320 SDValue OrigV = ExtractedV.getOperand(0);
25321 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25322 if (ExtractIdx->getZExtValue() == 0) {
25323 MVT OrigVT = OrigV.getSimpleValueType();
25324 // Extract a subvector if necessary...
25325 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25326 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25327 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25328 OrigVT.getVectorNumElements() / Ratio);
25329 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25330 DAG.getIntPtrConstant(0, DL));
25332 Op = DAG.getBitcast(OpVT, OrigV);
25333 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25340 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25341 DAGCombinerInfo &DCI) const {
25342 SelectionDAG &DAG = DCI.DAG;
25343 switch (N->getOpcode()) {
25345 case ISD::EXTRACT_VECTOR_ELT:
25346 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25349 case X86ISD::SHRUNKBLEND:
25350 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25351 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25352 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25353 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25354 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25355 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25356 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25359 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25360 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25361 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25362 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25363 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25364 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25365 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25366 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25367 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25368 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25369 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25370 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25372 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25374 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25375 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25376 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25377 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25378 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25379 case ISD::ANY_EXTEND:
25380 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25381 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25382 case ISD::SIGN_EXTEND_INREG:
25383 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25384 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25385 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25386 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25387 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25388 case X86ISD::SHUFP: // Handle all target specific shuffles
25389 case X86ISD::PALIGNR:
25390 case X86ISD::UNPCKH:
25391 case X86ISD::UNPCKL:
25392 case X86ISD::MOVHLPS:
25393 case X86ISD::MOVLHPS:
25394 case X86ISD::PSHUFB:
25395 case X86ISD::PSHUFD:
25396 case X86ISD::PSHUFHW:
25397 case X86ISD::PSHUFLW:
25398 case X86ISD::MOVSS:
25399 case X86ISD::MOVSD:
25400 case X86ISD::VPERMILPI:
25401 case X86ISD::VPERM2X128:
25402 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25403 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25404 case ISD::INTRINSIC_WO_CHAIN:
25405 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25406 case X86ISD::INSERTPS: {
25407 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25408 return PerformINSERTPSCombine(N, DAG, Subtarget);
25411 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25417 /// isTypeDesirableForOp - Return true if the target has native support for
25418 /// the specified value type and it is 'desirable' to use the type for the
25419 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25420 /// instruction encodings are longer and some i16 instructions are slow.
25421 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25422 if (!isTypeLegal(VT))
25424 if (VT != MVT::i16)
25431 case ISD::SIGN_EXTEND:
25432 case ISD::ZERO_EXTEND:
25433 case ISD::ANY_EXTEND:
25446 /// IsDesirableToPromoteOp - This method query the target whether it is
25447 /// beneficial for dag combiner to promote the specified node. If true, it
25448 /// should return the desired promotion type by reference.
25449 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25450 EVT VT = Op.getValueType();
25451 if (VT != MVT::i16)
25454 bool Promote = false;
25455 bool Commute = false;
25456 switch (Op.getOpcode()) {
25459 LoadSDNode *LD = cast<LoadSDNode>(Op);
25460 // If the non-extending load has a single use and it's not live out, then it
25461 // might be folded.
25462 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25463 Op.hasOneUse()*/) {
25464 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25465 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25466 // The only case where we'd want to promote LOAD (rather then it being
25467 // promoted as an operand is when it's only use is liveout.
25468 if (UI->getOpcode() != ISD::CopyToReg)
25475 case ISD::SIGN_EXTEND:
25476 case ISD::ZERO_EXTEND:
25477 case ISD::ANY_EXTEND:
25482 SDValue N0 = Op.getOperand(0);
25483 // Look out for (store (shl (load), x)).
25484 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25497 SDValue N0 = Op.getOperand(0);
25498 SDValue N1 = Op.getOperand(1);
25499 if (!Commute && MayFoldLoad(N1))
25501 // Avoid disabling potential load folding opportunities.
25502 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25504 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25514 //===----------------------------------------------------------------------===//
25515 // X86 Inline Assembly Support
25516 //===----------------------------------------------------------------------===//
25518 // Helper to match a string separated by whitespace.
25519 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25520 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25522 for (StringRef Piece : Pieces) {
25523 if (!S.startswith(Piece)) // Check if the piece matches.
25526 S = S.substr(Piece.size());
25527 StringRef::size_type Pos = S.find_first_not_of(" \t");
25528 if (Pos == 0) // We matched a prefix.
25537 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25539 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25540 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25541 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25542 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25544 if (AsmPieces.size() == 3)
25546 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25553 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25554 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25556 std::string AsmStr = IA->getAsmString();
25558 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25559 if (!Ty || Ty->getBitWidth() % 16 != 0)
25562 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25563 SmallVector<StringRef, 4> AsmPieces;
25564 SplitString(AsmStr, AsmPieces, ";\n");
25566 switch (AsmPieces.size()) {
25567 default: return false;
25569 // FIXME: this should verify that we are targeting a 486 or better. If not,
25570 // we will turn this bswap into something that will be lowered to logical
25571 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25572 // lower so don't worry about this.
25574 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25575 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25576 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25577 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25578 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25579 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25580 // No need to check constraints, nothing other than the equivalent of
25581 // "=r,0" would be valid here.
25582 return IntrinsicLowering::LowerToByteSwap(CI);
25585 // rorw $$8, ${0:w} --> llvm.bswap.i16
25586 if (CI->getType()->isIntegerTy(16) &&
25587 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25588 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25589 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25591 StringRef ConstraintsStr = IA->getConstraintString();
25592 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25593 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25594 if (clobbersFlagRegisters(AsmPieces))
25595 return IntrinsicLowering::LowerToByteSwap(CI);
25599 if (CI->getType()->isIntegerTy(32) &&
25600 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25601 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25602 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25603 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25605 StringRef ConstraintsStr = IA->getConstraintString();
25606 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25607 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25608 if (clobbersFlagRegisters(AsmPieces))
25609 return IntrinsicLowering::LowerToByteSwap(CI);
25612 if (CI->getType()->isIntegerTy(64)) {
25613 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25614 if (Constraints.size() >= 2 &&
25615 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25616 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25617 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
25618 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25619 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25620 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25621 return IntrinsicLowering::LowerToByteSwap(CI);
25629 /// getConstraintType - Given a constraint letter, return the type of
25630 /// constraint it is for this target.
25631 X86TargetLowering::ConstraintType
25632 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25633 if (Constraint.size() == 1) {
25634 switch (Constraint[0]) {
25645 return C_RegisterClass;
25669 return TargetLowering::getConstraintType(Constraint);
25672 /// Examine constraint type and operand type and determine a weight value.
25673 /// This object must already have been set up with the operand type
25674 /// and the current alternative constraint selected.
25675 TargetLowering::ConstraintWeight
25676 X86TargetLowering::getSingleConstraintMatchWeight(
25677 AsmOperandInfo &info, const char *constraint) const {
25678 ConstraintWeight weight = CW_Invalid;
25679 Value *CallOperandVal = info.CallOperandVal;
25680 // If we don't have a value, we can't do a match,
25681 // but allow it at the lowest weight.
25682 if (!CallOperandVal)
25684 Type *type = CallOperandVal->getType();
25685 // Look at the constraint type.
25686 switch (*constraint) {
25688 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25699 if (CallOperandVal->getType()->isIntegerTy())
25700 weight = CW_SpecificReg;
25705 if (type->isFloatingPointTy())
25706 weight = CW_SpecificReg;
25709 if (type->isX86_MMXTy() && Subtarget->hasMMX())
25710 weight = CW_SpecificReg;
25714 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25715 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25716 weight = CW_Register;
25719 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25720 if (C->getZExtValue() <= 31)
25721 weight = CW_Constant;
25725 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25726 if (C->getZExtValue() <= 63)
25727 weight = CW_Constant;
25731 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25732 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25733 weight = CW_Constant;
25737 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25738 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25739 weight = CW_Constant;
25743 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25744 if (C->getZExtValue() <= 3)
25745 weight = CW_Constant;
25749 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25750 if (C->getZExtValue() <= 0xff)
25751 weight = CW_Constant;
25756 if (isa<ConstantFP>(CallOperandVal)) {
25757 weight = CW_Constant;
25761 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25762 if ((C->getSExtValue() >= -0x80000000LL) &&
25763 (C->getSExtValue() <= 0x7fffffffLL))
25764 weight = CW_Constant;
25768 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25769 if (C->getZExtValue() <= 0xffffffff)
25770 weight = CW_Constant;
25777 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25778 /// with another that has more specific requirements based on the type of the
25779 /// corresponding operand.
25780 const char *X86TargetLowering::
25781 LowerXConstraint(EVT ConstraintVT) const {
25782 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25783 // 'f' like normal targets.
25784 if (ConstraintVT.isFloatingPoint()) {
25785 if (Subtarget->hasSSE2())
25787 if (Subtarget->hasSSE1())
25791 return TargetLowering::LowerXConstraint(ConstraintVT);
25794 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25795 /// vector. If it is invalid, don't add anything to Ops.
25796 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25797 std::string &Constraint,
25798 std::vector<SDValue>&Ops,
25799 SelectionDAG &DAG) const {
25802 // Only support length 1 constraints for now.
25803 if (Constraint.length() > 1) return;
25805 char ConstraintLetter = Constraint[0];
25806 switch (ConstraintLetter) {
25809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25810 if (C->getZExtValue() <= 31) {
25811 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25812 Op.getValueType());
25818 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25819 if (C->getZExtValue() <= 63) {
25820 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25821 Op.getValueType());
25827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25828 if (isInt<8>(C->getSExtValue())) {
25829 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25830 Op.getValueType());
25836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25837 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25838 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25839 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25840 Op.getValueType());
25846 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25847 if (C->getZExtValue() <= 3) {
25848 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25849 Op.getValueType());
25855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25856 if (C->getZExtValue() <= 255) {
25857 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25858 Op.getValueType());
25864 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25865 if (C->getZExtValue() <= 127) {
25866 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25867 Op.getValueType());
25873 // 32-bit signed value
25874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25875 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25876 C->getSExtValue())) {
25877 // Widen to 64 bits here to get it sign extended.
25878 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25881 // FIXME gcc accepts some relocatable values here too, but only in certain
25882 // memory models; it's complicated.
25887 // 32-bit unsigned value
25888 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25889 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25890 C->getZExtValue())) {
25891 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25892 Op.getValueType());
25896 // FIXME gcc accepts some relocatable values here too, but only in certain
25897 // memory models; it's complicated.
25901 // Literal immediates are always ok.
25902 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25903 // Widen to 64 bits here to get it sign extended.
25904 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25908 // In any sort of PIC mode addresses need to be computed at runtime by
25909 // adding in a register or some sort of table lookup. These can't
25910 // be used as immediates.
25911 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25914 // If we are in non-pic codegen mode, we allow the address of a global (with
25915 // an optional displacement) to be used with 'i'.
25916 GlobalAddressSDNode *GA = nullptr;
25917 int64_t Offset = 0;
25919 // Match either (GA), (GA+C), (GA+C1+C2), etc.
25921 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25922 Offset += GA->getOffset();
25924 } else if (Op.getOpcode() == ISD::ADD) {
25925 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25926 Offset += C->getZExtValue();
25927 Op = Op.getOperand(0);
25930 } else if (Op.getOpcode() == ISD::SUB) {
25931 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25932 Offset += -C->getZExtValue();
25933 Op = Op.getOperand(0);
25938 // Otherwise, this isn't something we can handle, reject it.
25942 const GlobalValue *GV = GA->getGlobal();
25943 // If we require an extra load to get this address, as in PIC mode, we
25944 // can't accept it.
25945 if (isGlobalStubReference(
25946 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25949 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25950 GA->getValueType(0), Offset);
25955 if (Result.getNode()) {
25956 Ops.push_back(Result);
25959 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25962 std::pair<unsigned, const TargetRegisterClass *>
25963 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25964 StringRef Constraint,
25966 // First, see if this is a constraint that directly corresponds to an LLVM
25968 if (Constraint.size() == 1) {
25969 // GCC Constraint Letters
25970 switch (Constraint[0]) {
25972 // TODO: Slight differences here in allocation order and leaving
25973 // RIP in the class. Do they matter any more here than they do
25974 // in the normal allocation?
25975 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25976 if (Subtarget->is64Bit()) {
25977 if (VT == MVT::i32 || VT == MVT::f32)
25978 return std::make_pair(0U, &X86::GR32RegClass);
25979 if (VT == MVT::i16)
25980 return std::make_pair(0U, &X86::GR16RegClass);
25981 if (VT == MVT::i8 || VT == MVT::i1)
25982 return std::make_pair(0U, &X86::GR8RegClass);
25983 if (VT == MVT::i64 || VT == MVT::f64)
25984 return std::make_pair(0U, &X86::GR64RegClass);
25987 // 32-bit fallthrough
25988 case 'Q': // Q_REGS
25989 if (VT == MVT::i32 || VT == MVT::f32)
25990 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25991 if (VT == MVT::i16)
25992 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25993 if (VT == MVT::i8 || VT == MVT::i1)
25994 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25995 if (VT == MVT::i64)
25996 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25998 case 'r': // GENERAL_REGS
25999 case 'l': // INDEX_REGS
26000 if (VT == MVT::i8 || VT == MVT::i1)
26001 return std::make_pair(0U, &X86::GR8RegClass);
26002 if (VT == MVT::i16)
26003 return std::make_pair(0U, &X86::GR16RegClass);
26004 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26005 return std::make_pair(0U, &X86::GR32RegClass);
26006 return std::make_pair(0U, &X86::GR64RegClass);
26007 case 'R': // LEGACY_REGS
26008 if (VT == MVT::i8 || VT == MVT::i1)
26009 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26010 if (VT == MVT::i16)
26011 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26012 if (VT == MVT::i32 || !Subtarget->is64Bit())
26013 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26014 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26015 case 'f': // FP Stack registers.
26016 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26017 // value to the correct fpstack register class.
26018 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26019 return std::make_pair(0U, &X86::RFP32RegClass);
26020 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26021 return std::make_pair(0U, &X86::RFP64RegClass);
26022 return std::make_pair(0U, &X86::RFP80RegClass);
26023 case 'y': // MMX_REGS if MMX allowed.
26024 if (!Subtarget->hasMMX()) break;
26025 return std::make_pair(0U, &X86::VR64RegClass);
26026 case 'Y': // SSE_REGS if SSE2 allowed
26027 if (!Subtarget->hasSSE2()) break;
26029 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26030 if (!Subtarget->hasSSE1()) break;
26032 switch (VT.SimpleTy) {
26034 // Scalar SSE types.
26037 return std::make_pair(0U, &X86::FR32RegClass);
26040 return std::make_pair(0U, &X86::FR64RegClass);
26048 return std::make_pair(0U, &X86::VR128RegClass);
26056 return std::make_pair(0U, &X86::VR256RegClass);
26061 return std::make_pair(0U, &X86::VR512RegClass);
26067 // Use the default implementation in TargetLowering to convert the register
26068 // constraint into a member of a register class.
26069 std::pair<unsigned, const TargetRegisterClass*> Res;
26070 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26072 // Not found as a standard register?
26074 // Map st(0) -> st(7) -> ST0
26075 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26076 tolower(Constraint[1]) == 's' &&
26077 tolower(Constraint[2]) == 't' &&
26078 Constraint[3] == '(' &&
26079 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26080 Constraint[5] == ')' &&
26081 Constraint[6] == '}') {
26083 Res.first = X86::FP0+Constraint[4]-'0';
26084 Res.second = &X86::RFP80RegClass;
26088 // GCC allows "st(0)" to be called just plain "st".
26089 if (StringRef("{st}").equals_lower(Constraint)) {
26090 Res.first = X86::FP0;
26091 Res.second = &X86::RFP80RegClass;
26096 if (StringRef("{flags}").equals_lower(Constraint)) {
26097 Res.first = X86::EFLAGS;
26098 Res.second = &X86::CCRRegClass;
26102 // 'A' means EAX + EDX.
26103 if (Constraint == "A") {
26104 Res.first = X86::EAX;
26105 Res.second = &X86::GR32_ADRegClass;
26111 // Otherwise, check to see if this is a register class of the wrong value
26112 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26113 // turn into {ax},{dx}.
26114 // MVT::Other is used to specify clobber names.
26115 if (Res.second->hasType(VT) || VT == MVT::Other)
26116 return Res; // Correct type already, nothing to do.
26118 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26119 // return "eax". This should even work for things like getting 64bit integer
26120 // registers when given an f64 type.
26121 const TargetRegisterClass *Class = Res.second;
26122 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26123 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26124 unsigned Size = VT.getSizeInBits();
26125 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26126 : Size == 16 ? MVT::i16
26127 : Size == 32 ? MVT::i32
26128 : Size == 64 ? MVT::i64
26130 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26132 Res.first = DestReg;
26133 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26134 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26135 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26136 : &X86::GR64RegClass;
26137 assert(Res.second->contains(Res.first) && "Register in register class");
26139 // No register found/type mismatch.
26141 Res.second = nullptr;
26143 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26144 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26145 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26146 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26147 Class == &X86::VR512RegClass) {
26148 // Handle references to XMM physical registers that got mapped into the
26149 // wrong class. This can happen with constraints like {xmm0} where the
26150 // target independent register mapper will just pick the first match it can
26151 // find, ignoring the required type.
26153 if (VT == MVT::f32 || VT == MVT::i32)
26154 Res.second = &X86::FR32RegClass;
26155 else if (VT == MVT::f64 || VT == MVT::i64)
26156 Res.second = &X86::FR64RegClass;
26157 else if (X86::VR128RegClass.hasType(VT))
26158 Res.second = &X86::VR128RegClass;
26159 else if (X86::VR256RegClass.hasType(VT))
26160 Res.second = &X86::VR256RegClass;
26161 else if (X86::VR512RegClass.hasType(VT))
26162 Res.second = &X86::VR512RegClass;
26164 // Type mismatch and not a clobber: Return an error;
26166 Res.second = nullptr;
26173 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26174 const AddrMode &AM, Type *Ty,
26175 unsigned AS) const {
26176 // Scaling factors are not free at all.
26177 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26178 // will take 2 allocations in the out of order engine instead of 1
26179 // for plain addressing mode, i.e. inst (reg1).
26181 // vaddps (%rsi,%drx), %ymm0, %ymm1
26182 // Requires two allocations (one for the load, one for the computation)
26184 // vaddps (%rsi), %ymm0, %ymm1
26185 // Requires just 1 allocation, i.e., freeing allocations for other operations
26186 // and having less micro operations to execute.
26188 // For some X86 architectures, this is even worse because for instance for
26189 // stores, the complex addressing mode forces the instruction to use the
26190 // "load" ports instead of the dedicated "store" port.
26191 // E.g., on Haswell:
26192 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26193 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26194 if (isLegalAddressingMode(DL, AM, Ty, AS))
26195 // Scale represents reg2 * scale, thus account for 1
26196 // as soon as we use a second register.
26197 return AM.Scale != 0;
26201 bool X86TargetLowering::isTargetFTOL() const {
26202 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();