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 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71 "x86-recip-refinement-steps", cl::init(1),
72 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73 "result of the hardware reciprocal estimate instruction."),
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81 const X86Subtarget &STI)
82 : TargetLowering(TM), Subtarget(&STI) {
83 X86ScalarSSEf64 = Subtarget->hasSSE2();
84 X86ScalarSSEf32 = Subtarget->hasSSE1();
87 // Set up the TargetLowering object.
88 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
90 // X86 is weird. It always uses i8 for shift amounts and setcc results.
91 setBooleanContents(ZeroOrOneBooleanContent);
92 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
95 // For 64-bit, since we have so many registers, use the ILP scheduler.
96 // For 32-bit, use the register pressure specific scheduling.
97 // For Atom, always use ILP scheduling.
98 if (Subtarget->isAtom())
99 setSchedulingPreference(Sched::ILP);
100 else if (Subtarget->is64Bit())
101 setSchedulingPreference(Sched::ILP);
103 setSchedulingPreference(Sched::RegPressure);
104 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
107 // Bypass expensive divides on Atom when compiling with O2.
108 if (TM.getOptLevel() >= CodeGenOpt::Default) {
109 if (Subtarget->hasSlowDivide32())
110 addBypassSlowDiv(32, 8);
111 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112 addBypassSlowDiv(64, 16);
115 if (Subtarget->isTargetKnownWindowsMSVC()) {
116 // Setup Windows compiler runtime calls.
117 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119 setLibcallName(RTLIB::SREM_I64, "_allrem");
120 setLibcallName(RTLIB::UREM_I64, "_aullrem");
121 setLibcallName(RTLIB::MUL_I64, "_allmul");
122 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
128 // The _ftol2 runtime function has an unusual calling conv, which
129 // is modeled by a special pseudo-instruction.
130 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
136 if (Subtarget->isTargetDarwin()) {
137 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138 setUseUnderscoreSetJmp(false);
139 setUseUnderscoreLongJmp(false);
140 } else if (Subtarget->isTargetWindowsGNU()) {
141 // MS runtime is weird: it exports _setjmp, but longjmp!
142 setUseUnderscoreSetJmp(true);
143 setUseUnderscoreLongJmp(false);
145 setUseUnderscoreSetJmp(true);
146 setUseUnderscoreLongJmp(true);
149 // Set up the register classes.
150 addRegisterClass(MVT::i8, &X86::GR8RegClass);
151 addRegisterClass(MVT::i16, &X86::GR16RegClass);
152 addRegisterClass(MVT::i32, &X86::GR32RegClass);
153 if (Subtarget->is64Bit())
154 addRegisterClass(MVT::i64, &X86::GR64RegClass);
156 for (MVT VT : MVT::integer_valuetypes())
157 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
159 // We don't accept any truncstore of integer registers.
160 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
167 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
169 // SETOEQ and SETUNE require checking two conditions.
170 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
177 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
179 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
180 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
181 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
183 if (Subtarget->is64Bit()) {
184 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
185 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
186 } else if (!TM.Options.UseSoftFloat) {
187 // We have an algorithm for SSE2->double, and we turn this into a
188 // 64-bit FILD followed by conditional FADD for other targets.
189 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
190 // We have an algorithm for SSE2, and we turn this into a 64-bit
191 // FILD for other targets.
192 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
195 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
197 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
200 if (!TM.Options.UseSoftFloat) {
201 // SSE has no i16 to fp conversion, only i32
202 if (X86ScalarSSEf32) {
203 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
204 // f32 and f64 cases are Legal, f80 case is not
205 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
207 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
208 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
211 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
215 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
216 // are Legal, f80 is custom lowered.
217 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
218 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
220 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
222 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
223 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
225 if (X86ScalarSSEf32) {
226 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
227 // f32 and f64 cases are Legal, f80 case is not
228 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
230 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
231 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
234 // Handle FP_TO_UINT by promoting the destination to a larger signed
236 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
237 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
238 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
240 if (Subtarget->is64Bit()) {
241 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
242 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
243 } else if (!TM.Options.UseSoftFloat) {
244 // Since AVX is a superset of SSE3, only check for SSE here.
245 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246 // Expand FP_TO_UINT into a select.
247 // FIXME: We would like to use a Custom expander here eventually to do
248 // the optimal thing for SSE vs. the default expansion in the legalizer.
249 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
251 // With SSE3 we can use fisttpll to convert to a signed i64; without
252 // SSE, we're stuck with a fistpll.
253 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
256 if (isTargetFTOL()) {
257 // Use the _ftol2 runtime function, which has a pseudo-instruction
258 // to handle its weird calling convention.
259 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
262 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263 if (!X86ScalarSSEf64) {
264 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
265 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
266 if (Subtarget->is64Bit()) {
267 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
268 // Without SSE, i64->f64 goes through memory.
269 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
273 // Scalar integer divide and remainder are lowered to use operations that
274 // produce two results, to match the available instructions. This exposes
275 // the two-result form to trivial CSE, which is able to combine x/y and x%y
276 // into a single instruction.
278 // Scalar integer multiply-high is also lowered to use two-result
279 // operations, to match the available instructions. However, plain multiply
280 // (low) operations are left as Legal, as there are single-result
281 // instructions for this in x86. Using the two-result multiply instructions
282 // when both high and low results are needed must be arranged by dagcombine.
283 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
285 setOperationAction(ISD::MULHS, VT, Expand);
286 setOperationAction(ISD::MULHU, VT, Expand);
287 setOperationAction(ISD::SDIV, VT, Expand);
288 setOperationAction(ISD::UDIV, VT, Expand);
289 setOperationAction(ISD::SREM, VT, Expand);
290 setOperationAction(ISD::UREM, VT, Expand);
292 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293 setOperationAction(ISD::ADDC, VT, Custom);
294 setOperationAction(ISD::ADDE, VT, Custom);
295 setOperationAction(ISD::SUBC, VT, Custom);
296 setOperationAction(ISD::SUBE, VT, Custom);
299 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
300 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
301 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
302 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
303 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
304 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
305 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
306 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
307 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
309 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
310 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
311 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
312 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
313 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
314 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
315 if (Subtarget->is64Bit())
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
318 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
319 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
320 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
321 setOperationAction(ISD::FREM , MVT::f32 , Expand);
322 setOperationAction(ISD::FREM , MVT::f64 , Expand);
323 setOperationAction(ISD::FREM , MVT::f80 , Expand);
324 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
326 // Promote the i8 variants and force them on up to i32 which has a shorter
328 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
329 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
331 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
332 if (Subtarget->hasBMI()) {
333 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
334 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
335 if (Subtarget->is64Bit())
336 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
338 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
339 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
340 if (Subtarget->is64Bit())
341 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
344 if (Subtarget->hasLZCNT()) {
345 // When promoting the i8 variants, force them to i32 for a shorter
347 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
348 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
350 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
352 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
353 if (Subtarget->is64Bit())
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
356 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
357 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
358 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
362 if (Subtarget->is64Bit()) {
363 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
364 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
368 // Special handling for half-precision floating point conversions.
369 // If we don't have F16C support, then lower half float conversions
370 // into library calls.
371 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
372 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
376 // There's never any support for operations beyond MVT::f32.
377 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
382 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
389 if (Subtarget->hasPOPCNT()) {
390 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
392 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
393 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
394 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
399 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
401 if (!Subtarget->hasMOVBE())
402 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
404 // These should be promoted to a larger select which is supported.
405 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
406 // X86 wants to expand cmov itself.
407 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
408 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
409 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
410 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
411 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
412 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
413 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
414 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
416 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
417 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
418 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
421 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
423 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
424 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426 // support continuation, user-level threading, and etc.. As a result, no
427 // other SjLj exception interfaces are implemented and please don't build
428 // your own exception handling based on them.
429 // LLVM/Clang supports zero-cost DWARF exception handling.
430 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
434 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
435 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
436 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
437 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
438 if (Subtarget->is64Bit())
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
442 if (Subtarget->is64Bit()) {
443 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
444 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
445 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
446 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
447 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
449 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
451 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
452 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
455 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
456 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
459 if (Subtarget->hasSSE1())
460 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
462 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
464 // Expand certain atomics
465 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
472 if (Subtarget->hasCmpxchg16b()) {
473 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
476 // FIXME - use subtarget debug flags
477 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
482 if (Subtarget->is64Bit()) {
483 setExceptionPointerRegister(X86::RAX);
484 setExceptionSelectorRegister(X86::RDX);
486 setExceptionPointerRegister(X86::EAX);
487 setExceptionSelectorRegister(X86::EDX);
489 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499 setOperationAction(ISD::VASTART , MVT::Other, Custom);
500 setOperationAction(ISD::VAEND , MVT::Other, Expand);
501 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502 // TargetInfo::X86_64ABIBuiltinVaList
503 setOperationAction(ISD::VAARG , MVT::Other, Custom);
504 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
506 // TargetInfo::CharPtrBuiltinVaList
507 setOperationAction(ISD::VAARG , MVT::Other, Expand);
508 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
511 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
512 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
514 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
516 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
520 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
521 // f32 and f64 use SSE.
522 // Set up the FP register classes.
523 addRegisterClass(MVT::f32, &X86::FR32RegClass);
524 addRegisterClass(MVT::f64, &X86::FR64RegClass);
526 // Use ANDPD to simulate FABS.
527 setOperationAction(ISD::FABS , MVT::f64, Custom);
528 setOperationAction(ISD::FABS , MVT::f32, Custom);
530 // Use XORP to simulate FNEG.
531 setOperationAction(ISD::FNEG , MVT::f64, Custom);
532 setOperationAction(ISD::FNEG , MVT::f32, Custom);
534 // Use ANDPD and ORPD to simulate FCOPYSIGN.
535 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
538 // Lower this to FGETSIGNx86 plus an AND.
539 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
542 // We don't support sin/cos/fmod
543 setOperationAction(ISD::FSIN , MVT::f64, Expand);
544 setOperationAction(ISD::FCOS , MVT::f64, Expand);
545 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546 setOperationAction(ISD::FSIN , MVT::f32, Expand);
547 setOperationAction(ISD::FCOS , MVT::f32, Expand);
548 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
550 // Expand FP immediates into loads from the stack, except for the special
552 addLegalFPImmediate(APFloat(+0.0)); // xorpd
553 addLegalFPImmediate(APFloat(+0.0f)); // xorps
554 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
555 // Use SSE for f32, x87 for f64.
556 // Set up the FP register classes.
557 addRegisterClass(MVT::f32, &X86::FR32RegClass);
558 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
560 // Use ANDPS to simulate FABS.
561 setOperationAction(ISD::FABS , MVT::f32, Custom);
563 // Use XORP to simulate FNEG.
564 setOperationAction(ISD::FNEG , MVT::f32, Custom);
566 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
568 // Use ANDPS and ORPS to simulate FCOPYSIGN.
569 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
572 // We don't support sin/cos/fmod
573 setOperationAction(ISD::FSIN , MVT::f32, Expand);
574 setOperationAction(ISD::FCOS , MVT::f32, Expand);
575 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
577 // Special cases we handle for FP constants.
578 addLegalFPImmediate(APFloat(+0.0f)); // xorps
579 addLegalFPImmediate(APFloat(+0.0)); // FLD0
580 addLegalFPImmediate(APFloat(+1.0)); // FLD1
581 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
584 if (!TM.Options.UnsafeFPMath) {
585 setOperationAction(ISD::FSIN , MVT::f64, Expand);
586 setOperationAction(ISD::FCOS , MVT::f64, Expand);
587 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
589 } else if (!TM.Options.UseSoftFloat) {
590 // f32 and f64 in x87.
591 // Set up the FP register classes.
592 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
595 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
596 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
600 if (!TM.Options.UnsafeFPMath) {
601 setOperationAction(ISD::FSIN , MVT::f64, Expand);
602 setOperationAction(ISD::FSIN , MVT::f32, Expand);
603 setOperationAction(ISD::FCOS , MVT::f64, Expand);
604 setOperationAction(ISD::FCOS , MVT::f32, Expand);
605 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
608 addLegalFPImmediate(APFloat(+0.0)); // FLD0
609 addLegalFPImmediate(APFloat(+1.0)); // FLD1
610 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
618 // We don't support FMA.
619 setOperationAction(ISD::FMA, MVT::f64, Expand);
620 setOperationAction(ISD::FMA, MVT::f32, Expand);
622 // Long double always uses X87.
623 if (!TM.Options.UseSoftFloat) {
624 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
626 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
628 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629 addLegalFPImmediate(TmpFlt); // FLD0
631 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
634 APFloat TmpFlt2(+1.0);
635 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
637 addLegalFPImmediate(TmpFlt2); // FLD1
638 TmpFlt2.changeSign();
639 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
642 if (!TM.Options.UnsafeFPMath) {
643 setOperationAction(ISD::FSIN , MVT::f80, Expand);
644 setOperationAction(ISD::FCOS , MVT::f80, Expand);
645 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
648 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
650 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651 setOperationAction(ISD::FRINT, MVT::f80, Expand);
652 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653 setOperationAction(ISD::FMA, MVT::f80, Expand);
656 // Always use a library call for pow.
657 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
658 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
659 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
661 setOperationAction(ISD::FLOG, MVT::f80, Expand);
662 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664 setOperationAction(ISD::FEXP, MVT::f80, Expand);
665 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
669 // First set operation action for all vector types to either promote
670 // (for widening) or expand (for scalarization). Then we will selectively
671 // turn on ones that can be effectively codegen'd.
672 for (MVT VT : MVT::vector_valuetypes()) {
673 setOperationAction(ISD::ADD , VT, Expand);
674 setOperationAction(ISD::SUB , VT, Expand);
675 setOperationAction(ISD::FADD, VT, Expand);
676 setOperationAction(ISD::FNEG, VT, Expand);
677 setOperationAction(ISD::FSUB, VT, Expand);
678 setOperationAction(ISD::MUL , VT, Expand);
679 setOperationAction(ISD::FMUL, VT, Expand);
680 setOperationAction(ISD::SDIV, VT, Expand);
681 setOperationAction(ISD::UDIV, VT, Expand);
682 setOperationAction(ISD::FDIV, VT, Expand);
683 setOperationAction(ISD::SREM, VT, Expand);
684 setOperationAction(ISD::UREM, VT, Expand);
685 setOperationAction(ISD::LOAD, VT, Expand);
686 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691 setOperationAction(ISD::FABS, VT, Expand);
692 setOperationAction(ISD::FSIN, VT, Expand);
693 setOperationAction(ISD::FSINCOS, VT, Expand);
694 setOperationAction(ISD::FCOS, VT, Expand);
695 setOperationAction(ISD::FSINCOS, VT, Expand);
696 setOperationAction(ISD::FREM, VT, Expand);
697 setOperationAction(ISD::FMA, VT, Expand);
698 setOperationAction(ISD::FPOWI, VT, Expand);
699 setOperationAction(ISD::FSQRT, VT, Expand);
700 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701 setOperationAction(ISD::FFLOOR, VT, Expand);
702 setOperationAction(ISD::FCEIL, VT, Expand);
703 setOperationAction(ISD::FTRUNC, VT, Expand);
704 setOperationAction(ISD::FRINT, VT, Expand);
705 setOperationAction(ISD::FNEARBYINT, VT, Expand);
706 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707 setOperationAction(ISD::MULHS, VT, Expand);
708 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709 setOperationAction(ISD::MULHU, VT, Expand);
710 setOperationAction(ISD::SDIVREM, VT, Expand);
711 setOperationAction(ISD::UDIVREM, VT, Expand);
712 setOperationAction(ISD::FPOW, VT, Expand);
713 setOperationAction(ISD::CTPOP, VT, Expand);
714 setOperationAction(ISD::CTTZ, VT, Expand);
715 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716 setOperationAction(ISD::CTLZ, VT, Expand);
717 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718 setOperationAction(ISD::SHL, VT, Expand);
719 setOperationAction(ISD::SRA, VT, Expand);
720 setOperationAction(ISD::SRL, VT, Expand);
721 setOperationAction(ISD::ROTL, VT, Expand);
722 setOperationAction(ISD::ROTR, VT, Expand);
723 setOperationAction(ISD::BSWAP, VT, Expand);
724 setOperationAction(ISD::SETCC, VT, Expand);
725 setOperationAction(ISD::FLOG, VT, Expand);
726 setOperationAction(ISD::FLOG2, VT, Expand);
727 setOperationAction(ISD::FLOG10, VT, Expand);
728 setOperationAction(ISD::FEXP, VT, Expand);
729 setOperationAction(ISD::FEXP2, VT, Expand);
730 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735 setOperationAction(ISD::TRUNCATE, VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739 setOperationAction(ISD::VSELECT, VT, Expand);
740 setOperationAction(ISD::SELECT_CC, VT, Expand);
741 for (MVT InnerVT : MVT::vector_valuetypes()) {
742 setTruncStoreAction(InnerVT, VT, Expand);
744 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
747 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748 // types, we have to deal with them whether we ask for Expansion or not.
749 // Setting Expand causes its own optimisation problems though, so leave
751 if (VT.getVectorElementType() == MVT::i1)
752 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
756 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
757 // with -msoft-float, disable use of MMX as well.
758 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
759 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
760 // No operations on x86mmx supported, everything uses intrinsics.
763 // MMX-sized vectors (other than x86mmx) are expected to be expanded
764 // into smaller operations.
765 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
766 setOperationAction(ISD::MULHS, MMXTy, Expand);
767 setOperationAction(ISD::AND, MMXTy, Expand);
768 setOperationAction(ISD::OR, MMXTy, Expand);
769 setOperationAction(ISD::XOR, MMXTy, Expand);
770 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
771 setOperationAction(ISD::SELECT, MMXTy, Expand);
772 setOperationAction(ISD::BITCAST, MMXTy, Expand);
774 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
776 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
777 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
779 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
780 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
781 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
782 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
783 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
784 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
785 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
786 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
787 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
788 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
789 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
790 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
791 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
792 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
795 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
796 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
798 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
799 // registers cannot be used even for integer operations.
800 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
801 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
802 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
803 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
805 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
806 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
807 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
808 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
809 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
810 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
811 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
812 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
813 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
814 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
815 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
816 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
817 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
818 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
819 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
820 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
821 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
822 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
823 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
824 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
825 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
826 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
827 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
829 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
830 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
831 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
832 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
838 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
840 // Only provide customized ctpop vector bit twiddling for vector types we
841 // know to perform better than using the popcnt instructions on each vector
842 // element. If popcnt isn't supported, always provide the custom version.
843 if (!Subtarget->hasPOPCNT()) {
844 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
845 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
848 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
849 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
850 MVT VT = (MVT::SimpleValueType)i;
851 // Do not attempt to custom lower non-power-of-2 vectors
852 if (!isPowerOf2_32(VT.getVectorNumElements()))
854 // Do not attempt to custom lower non-128-bit vectors
855 if (!VT.is128BitVector())
857 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
858 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
859 setOperationAction(ISD::VSELECT, VT, Custom);
860 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
863 // We support custom legalizing of sext and anyext loads for specific
864 // memory vector types which we can load as a scalar (or sequence of
865 // scalars) and extend in-register to a legal 128-bit vector type. For sext
866 // loads these must work with a single scalar load.
867 for (MVT VT : MVT::integer_vector_valuetypes()) {
868 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
869 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
870 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
871 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
872 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
873 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
874 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
875 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
879 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
880 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
881 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
882 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
883 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
884 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
885 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
886 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888 if (Subtarget->is64Bit()) {
889 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
890 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
893 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
894 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895 MVT VT = (MVT::SimpleValueType)i;
897 // Do not attempt to promote non-128-bit vectors
898 if (!VT.is128BitVector())
901 setOperationAction(ISD::AND, VT, Promote);
902 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
903 setOperationAction(ISD::OR, VT, Promote);
904 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
905 setOperationAction(ISD::XOR, VT, Promote);
906 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
907 setOperationAction(ISD::LOAD, VT, Promote);
908 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
909 setOperationAction(ISD::SELECT, VT, Promote);
910 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
913 // Custom lower v2i64 and v2f64 selects.
914 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
915 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
916 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
917 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
919 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
920 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
922 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
923 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
924 // As there is no 64-bit GPR available, we need build a special custom
925 // sequence to convert from v2i32 to v2f32.
926 if (!Subtarget->is64Bit())
927 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
929 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
930 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
932 for (MVT VT : MVT::fp_vector_valuetypes())
933 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
935 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
936 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
937 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
940 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
941 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
942 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
943 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
944 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
945 setOperationAction(ISD::FRINT, RoundedTy, Legal);
946 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
949 // FIXME: Do we need to handle scalar-to-vector here?
950 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
952 // We directly match byte blends in the backend as they match the VSELECT
954 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
956 // SSE41 brings specific instructions for doing vector sign extend even in
957 // cases where we don't have SRA.
958 for (MVT VT : MVT::integer_vector_valuetypes()) {
959 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
960 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
961 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
964 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
965 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
966 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
967 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
968 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
969 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
970 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
972 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
973 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
974 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
975 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
976 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
977 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
979 // i8 and i16 vectors are custom because the source register and source
980 // source memory operand types are not the same width. f32 vectors are
981 // custom since the immediate controlling the insert encodes additional
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
984 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
993 // FIXME: these should be Legal, but that's only for the case where
994 // the index is constant. For now custom expand to deal with that.
995 if (Subtarget->is64Bit()) {
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1001 if (Subtarget->hasSSE2()) {
1002 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1003 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1005 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1006 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1008 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1009 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1011 // In the customized shift lowering, the legal cases in AVX2 will be
1013 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1014 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1016 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1017 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1019 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1022 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1023 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1024 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1025 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1026 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1027 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1028 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1030 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1031 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1032 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1034 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1035 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1036 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1037 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1038 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1039 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1040 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1041 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1042 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1043 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1045 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1047 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1048 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1049 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1050 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1051 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1058 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1060 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1061 // even though v8i16 is a legal type.
1062 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1063 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1064 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1066 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1067 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1068 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1070 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1071 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1073 for (MVT VT : MVT::fp_vector_valuetypes())
1074 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1076 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1077 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1079 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1080 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1082 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1083 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1085 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1086 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1087 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1088 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1090 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1091 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1092 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1094 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1095 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1096 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1097 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1098 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1099 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1100 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1101 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1102 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1103 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1104 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1105 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1107 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1108 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1109 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1110 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1111 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1112 setOperationAction(ISD::FMA, MVT::f32, Legal);
1113 setOperationAction(ISD::FMA, MVT::f64, Legal);
1116 if (Subtarget->hasInt256()) {
1117 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1118 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1119 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1120 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1122 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1123 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1124 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1125 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1127 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1128 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1129 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1130 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1132 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1133 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1134 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1135 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1137 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1138 // when we have a 256bit-wide blend with immediate.
1139 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1141 // Only provide customized ctpop vector bit twiddling for vector types we
1142 // know to perform better than using the popcnt instructions on each
1143 // vector element. If popcnt isn't supported, always provide the custom
1145 if (!Subtarget->hasPOPCNT())
1146 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1148 // Custom CTPOP always performs better on natively supported v8i32
1149 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1151 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1152 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1153 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1154 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1155 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1156 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1157 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1159 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1160 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1161 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1162 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1163 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1164 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1166 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1167 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1168 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1169 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1171 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1172 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1173 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1174 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1176 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1177 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1178 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1179 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1182 // In the customized shift lowering, the legal cases in AVX2 will be
1184 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1187 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1188 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1190 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1192 // Custom lower several nodes for 256-bit types.
1193 for (MVT VT : MVT::vector_valuetypes()) {
1194 if (VT.getScalarSizeInBits() >= 32) {
1195 setOperationAction(ISD::MLOAD, VT, Legal);
1196 setOperationAction(ISD::MSTORE, VT, Legal);
1198 // Extract subvector is special because the value type
1199 // (result) is 128-bit but the source is 256-bit wide.
1200 if (VT.is128BitVector()) {
1201 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1203 // Do not attempt to custom lower other non-256-bit vectors
1204 if (!VT.is256BitVector())
1207 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1208 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1209 setOperationAction(ISD::VSELECT, VT, Custom);
1210 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1211 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1212 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1213 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1214 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1217 if (Subtarget->hasInt256())
1218 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1221 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1222 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1223 MVT VT = (MVT::SimpleValueType)i;
1225 // Do not attempt to promote non-256-bit vectors
1226 if (!VT.is256BitVector())
1229 setOperationAction(ISD::AND, VT, Promote);
1230 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1231 setOperationAction(ISD::OR, VT, Promote);
1232 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1233 setOperationAction(ISD::XOR, VT, Promote);
1234 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1235 setOperationAction(ISD::LOAD, VT, Promote);
1236 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1237 setOperationAction(ISD::SELECT, VT, Promote);
1238 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1242 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1243 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1244 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1245 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1246 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1248 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1249 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1250 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1252 for (MVT VT : MVT::fp_vector_valuetypes())
1253 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1255 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1256 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1257 setOperationAction(ISD::XOR, MVT::i1, Legal);
1258 setOperationAction(ISD::OR, MVT::i1, Legal);
1259 setOperationAction(ISD::AND, MVT::i1, Legal);
1260 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1261 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1262 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1263 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1264 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1266 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1267 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1268 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1269 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1270 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1271 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1273 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1274 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1275 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1276 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1277 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1278 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1279 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1280 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1282 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1283 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1284 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1285 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1286 if (Subtarget->is64Bit()) {
1287 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1288 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1289 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1290 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1292 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1293 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1294 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1295 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1296 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1297 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1298 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1299 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1300 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1301 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1302 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1303 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1304 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1305 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1306 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1307 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1309 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1310 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1311 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1312 if (Subtarget->hasDQI()) {
1313 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1314 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1316 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1317 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1318 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1319 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1320 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1321 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1322 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1323 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1324 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1325 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1326 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1327 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1328 if (Subtarget->hasDQI()) {
1329 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1330 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1332 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1337 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1339 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1341 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1343 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1344 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1345 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1346 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1347 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1349 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1350 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1352 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1354 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1355 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1356 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1357 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1358 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1359 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1360 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1361 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1362 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1364 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1365 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1367 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1368 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1370 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1372 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1373 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1375 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1376 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1378 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1379 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1381 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1382 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1383 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1384 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1385 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1386 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1388 if (Subtarget->hasCDI()) {
1389 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1390 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1392 if (Subtarget->hasDQI()) {
1393 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1394 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1395 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1397 // Custom lower several nodes.
1398 for (MVT VT : MVT::vector_valuetypes()) {
1399 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1401 setOperationAction(ISD::AND, VT, Legal);
1402 setOperationAction(ISD::OR, VT, Legal);
1403 setOperationAction(ISD::XOR, VT, Legal);
1405 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1406 setOperationAction(ISD::MGATHER, VT, Custom);
1407 setOperationAction(ISD::MSCATTER, VT, Custom);
1409 // Extract subvector is special because the value type
1410 // (result) is 256/128-bit but the source is 512-bit wide.
1411 if (VT.is128BitVector() || VT.is256BitVector()) {
1412 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1414 if (VT.getVectorElementType() == MVT::i1)
1415 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1417 // Do not attempt to custom lower other non-512-bit vectors
1418 if (!VT.is512BitVector())
1421 if (EltSize >= 32) {
1422 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1423 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1424 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1425 setOperationAction(ISD::VSELECT, VT, Legal);
1426 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1427 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1428 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1429 setOperationAction(ISD::MLOAD, VT, Legal);
1430 setOperationAction(ISD::MSTORE, VT, Legal);
1433 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1434 MVT VT = (MVT::SimpleValueType)i;
1436 // Do not attempt to promote non-512-bit vectors.
1437 if (!VT.is512BitVector())
1440 setOperationAction(ISD::SELECT, VT, Promote);
1441 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1445 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1446 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1447 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1449 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1450 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1452 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1453 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1454 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1455 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1456 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1457 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1458 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1459 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1460 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1461 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1462 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1463 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1464 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1466 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1467 const MVT VT = (MVT::SimpleValueType)i;
1469 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1471 // Do not attempt to promote non-512-bit vectors.
1472 if (!VT.is512BitVector())
1476 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1477 setOperationAction(ISD::VSELECT, VT, Legal);
1482 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1483 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1484 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1486 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1487 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1488 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1489 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1490 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1491 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1493 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1494 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1495 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1496 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1497 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1498 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1501 // We want to custom lower some of our intrinsics.
1502 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1503 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1504 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1505 if (!Subtarget->is64Bit())
1506 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1508 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1509 // handle type legalization for these operations here.
1511 // FIXME: We really should do custom legalization for addition and
1512 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1513 // than generic legalization for 64-bit multiplication-with-overflow, though.
1514 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1515 // Add/Sub/Mul with overflow operations are custom lowered.
1517 setOperationAction(ISD::SADDO, VT, Custom);
1518 setOperationAction(ISD::UADDO, VT, Custom);
1519 setOperationAction(ISD::SSUBO, VT, Custom);
1520 setOperationAction(ISD::USUBO, VT, Custom);
1521 setOperationAction(ISD::SMULO, VT, Custom);
1522 setOperationAction(ISD::UMULO, VT, Custom);
1526 if (!Subtarget->is64Bit()) {
1527 // These libcalls are not available in 32-bit.
1528 setLibcallName(RTLIB::SHL_I128, nullptr);
1529 setLibcallName(RTLIB::SRL_I128, nullptr);
1530 setLibcallName(RTLIB::SRA_I128, nullptr);
1533 // Combine sin / cos into one node or libcall if possible.
1534 if (Subtarget->hasSinCos()) {
1535 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1536 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1537 if (Subtarget->isTargetDarwin()) {
1538 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1539 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1540 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1541 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1545 if (Subtarget->isTargetWin64()) {
1546 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1547 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1548 setOperationAction(ISD::SREM, MVT::i128, Custom);
1549 setOperationAction(ISD::UREM, MVT::i128, Custom);
1550 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1551 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1554 // We have target-specific dag combine patterns for the following nodes:
1555 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1556 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1557 setTargetDAGCombine(ISD::BITCAST);
1558 setTargetDAGCombine(ISD::VSELECT);
1559 setTargetDAGCombine(ISD::SELECT);
1560 setTargetDAGCombine(ISD::SHL);
1561 setTargetDAGCombine(ISD::SRA);
1562 setTargetDAGCombine(ISD::SRL);
1563 setTargetDAGCombine(ISD::OR);
1564 setTargetDAGCombine(ISD::AND);
1565 setTargetDAGCombine(ISD::ADD);
1566 setTargetDAGCombine(ISD::FADD);
1567 setTargetDAGCombine(ISD::FSUB);
1568 setTargetDAGCombine(ISD::FMA);
1569 setTargetDAGCombine(ISD::SUB);
1570 setTargetDAGCombine(ISD::LOAD);
1571 setTargetDAGCombine(ISD::MLOAD);
1572 setTargetDAGCombine(ISD::STORE);
1573 setTargetDAGCombine(ISD::MSTORE);
1574 setTargetDAGCombine(ISD::ZERO_EXTEND);
1575 setTargetDAGCombine(ISD::ANY_EXTEND);
1576 setTargetDAGCombine(ISD::SIGN_EXTEND);
1577 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1578 setTargetDAGCombine(ISD::TRUNCATE);
1579 setTargetDAGCombine(ISD::SINT_TO_FP);
1580 setTargetDAGCombine(ISD::SETCC);
1581 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1582 setTargetDAGCombine(ISD::BUILD_VECTOR);
1583 setTargetDAGCombine(ISD::MUL);
1584 setTargetDAGCombine(ISD::XOR);
1586 computeRegisterProperties(Subtarget->getRegisterInfo());
1588 // On Darwin, -Os means optimize for size without hurting performance,
1589 // do not reduce the limit.
1590 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1591 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1592 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1593 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1594 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1595 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1596 setPrefLoopAlignment(4); // 2^4 bytes.
1598 // Predictable cmov don't hurt on atom because it's in-order.
1599 PredictableSelectIsExpensive = !Subtarget->isAtom();
1600 EnableExtLdPromotion = true;
1601 setPrefFunctionAlignment(4); // 2^4 bytes.
1603 verifyIntrinsicTables();
1606 // This has so far only been implemented for 64-bit MachO.
1607 bool X86TargetLowering::useLoadStackGuardNode() const {
1608 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1611 TargetLoweringBase::LegalizeTypeAction
1612 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1613 if (ExperimentalVectorWideningLegalization &&
1614 VT.getVectorNumElements() != 1 &&
1615 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1616 return TypeWidenVector;
1618 return TargetLoweringBase::getPreferredVectorAction(VT);
1621 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1623 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1625 const unsigned NumElts = VT.getVectorNumElements();
1626 const EVT EltVT = VT.getVectorElementType();
1627 if (VT.is512BitVector()) {
1628 if (Subtarget->hasAVX512())
1629 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1630 EltVT == MVT::f32 || EltVT == MVT::f64)
1632 case 8: return MVT::v8i1;
1633 case 16: return MVT::v16i1;
1635 if (Subtarget->hasBWI())
1636 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1638 case 32: return MVT::v32i1;
1639 case 64: return MVT::v64i1;
1643 if (VT.is256BitVector() || VT.is128BitVector()) {
1644 if (Subtarget->hasVLX())
1645 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1646 EltVT == MVT::f32 || EltVT == MVT::f64)
1648 case 2: return MVT::v2i1;
1649 case 4: return MVT::v4i1;
1650 case 8: return MVT::v8i1;
1652 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1653 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1655 case 8: return MVT::v8i1;
1656 case 16: return MVT::v16i1;
1657 case 32: return MVT::v32i1;
1661 return VT.changeVectorElementTypeToInteger();
1664 /// Helper for getByValTypeAlignment to determine
1665 /// the desired ByVal argument alignment.
1666 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1669 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1670 if (VTy->getBitWidth() == 128)
1672 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1673 unsigned EltAlign = 0;
1674 getMaxByValAlign(ATy->getElementType(), EltAlign);
1675 if (EltAlign > MaxAlign)
1676 MaxAlign = EltAlign;
1677 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1678 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1679 unsigned EltAlign = 0;
1680 getMaxByValAlign(STy->getElementType(i), EltAlign);
1681 if (EltAlign > MaxAlign)
1682 MaxAlign = EltAlign;
1689 /// Return the desired alignment for ByVal aggregate
1690 /// function arguments in the caller parameter area. For X86, aggregates
1691 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1692 /// are at 4-byte boundaries.
1693 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1694 if (Subtarget->is64Bit()) {
1695 // Max of 8 and alignment of type.
1696 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1703 if (Subtarget->hasSSE1())
1704 getMaxByValAlign(Ty, Align);
1708 /// Returns the target specific optimal type for load
1709 /// and store operations as a result of memset, memcpy, and memmove
1710 /// lowering. If DstAlign is zero that means it's safe to destination
1711 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1712 /// means there isn't a need to check it against alignment requirement,
1713 /// probably because the source does not need to be loaded. If 'IsMemset' is
1714 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1715 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1716 /// source is constant so it does not need to be loaded.
1717 /// It returns EVT::Other if the type should be determined using generic
1718 /// target-independent logic.
1720 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1721 unsigned DstAlign, unsigned SrcAlign,
1722 bool IsMemset, bool ZeroMemset,
1724 MachineFunction &MF) const {
1725 const Function *F = MF.getFunction();
1726 if ((!IsMemset || ZeroMemset) &&
1727 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1729 (Subtarget->isUnalignedMemAccessFast() ||
1730 ((DstAlign == 0 || DstAlign >= 16) &&
1731 (SrcAlign == 0 || SrcAlign >= 16)))) {
1733 if (Subtarget->hasInt256())
1735 if (Subtarget->hasFp256())
1738 if (Subtarget->hasSSE2())
1740 if (Subtarget->hasSSE1())
1742 } else if (!MemcpyStrSrc && Size >= 8 &&
1743 !Subtarget->is64Bit() &&
1744 Subtarget->hasSSE2()) {
1745 // Do not use f64 to lower memcpy if source is string constant. It's
1746 // better to use i32 to avoid the loads.
1750 if (Subtarget->is64Bit() && Size >= 8)
1755 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1757 return X86ScalarSSEf32;
1758 else if (VT == MVT::f64)
1759 return X86ScalarSSEf64;
1764 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1769 *Fast = Subtarget->isUnalignedMemAccessFast();
1773 /// Return the entry encoding for a jump table in the
1774 /// current function. The returned value is a member of the
1775 /// MachineJumpTableInfo::JTEntryKind enum.
1776 unsigned X86TargetLowering::getJumpTableEncoding() const {
1777 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1779 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1780 Subtarget->isPICStyleGOT())
1781 return MachineJumpTableInfo::EK_Custom32;
1783 // Otherwise, use the normal jump table encoding heuristics.
1784 return TargetLowering::getJumpTableEncoding();
1788 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1789 const MachineBasicBlock *MBB,
1790 unsigned uid,MCContext &Ctx) const{
1791 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1792 Subtarget->isPICStyleGOT());
1793 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1795 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1796 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1799 /// Returns relocation base for the given PIC jumptable.
1800 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1801 SelectionDAG &DAG) const {
1802 if (!Subtarget->is64Bit())
1803 // This doesn't have SDLoc associated with it, but is not really the
1804 // same as a Register.
1805 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1809 /// This returns the relocation base for the given PIC jumptable,
1810 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1811 const MCExpr *X86TargetLowering::
1812 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1813 MCContext &Ctx) const {
1814 // X86-64 uses RIP relative addressing based on the jump table label.
1815 if (Subtarget->isPICStyleRIPRel())
1816 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1818 // Otherwise, the reference is relative to the PIC base.
1819 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1822 std::pair<const TargetRegisterClass *, uint8_t>
1823 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1825 const TargetRegisterClass *RRC = nullptr;
1827 switch (VT.SimpleTy) {
1829 return TargetLowering::findRepresentativeClass(TRI, VT);
1830 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1831 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1834 RRC = &X86::VR64RegClass;
1836 case MVT::f32: case MVT::f64:
1837 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1838 case MVT::v4f32: case MVT::v2f64:
1839 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1841 RRC = &X86::VR128RegClass;
1844 return std::make_pair(RRC, Cost);
1847 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1848 unsigned &Offset) const {
1849 if (!Subtarget->isTargetLinux())
1852 if (Subtarget->is64Bit()) {
1853 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1855 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1867 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1868 unsigned DestAS) const {
1869 assert(SrcAS != DestAS && "Expected different address spaces!");
1871 return SrcAS < 256 && DestAS < 256;
1874 //===----------------------------------------------------------------------===//
1875 // Return Value Calling Convention Implementation
1876 //===----------------------------------------------------------------------===//
1878 #include "X86GenCallingConv.inc"
1881 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1882 MachineFunction &MF, bool isVarArg,
1883 const SmallVectorImpl<ISD::OutputArg> &Outs,
1884 LLVMContext &Context) const {
1885 SmallVector<CCValAssign, 16> RVLocs;
1886 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1887 return CCInfo.CheckReturn(Outs, RetCC_X86);
1890 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1891 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1896 X86TargetLowering::LowerReturn(SDValue Chain,
1897 CallingConv::ID CallConv, bool isVarArg,
1898 const SmallVectorImpl<ISD::OutputArg> &Outs,
1899 const SmallVectorImpl<SDValue> &OutVals,
1900 SDLoc dl, SelectionDAG &DAG) const {
1901 MachineFunction &MF = DAG.getMachineFunction();
1902 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1904 SmallVector<CCValAssign, 16> RVLocs;
1905 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1906 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1909 SmallVector<SDValue, 6> RetOps;
1910 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1911 // Operand #1 = Bytes To Pop
1912 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1915 // Copy the result values into the output registers.
1916 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1917 CCValAssign &VA = RVLocs[i];
1918 assert(VA.isRegLoc() && "Can only return in registers!");
1919 SDValue ValToCopy = OutVals[i];
1920 EVT ValVT = ValToCopy.getValueType();
1922 // Promote values to the appropriate types.
1923 if (VA.getLocInfo() == CCValAssign::SExt)
1924 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1925 else if (VA.getLocInfo() == CCValAssign::ZExt)
1926 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1927 else if (VA.getLocInfo() == CCValAssign::AExt) {
1928 if (ValVT.getScalarType() == MVT::i1)
1929 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1931 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1933 else if (VA.getLocInfo() == CCValAssign::BCvt)
1934 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1936 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1937 "Unexpected FP-extend for return value.");
1939 // If this is x86-64, and we disabled SSE, we can't return FP values,
1940 // or SSE or MMX vectors.
1941 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1942 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1943 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1944 report_fatal_error("SSE register return with SSE disabled");
1946 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1947 // llvm-gcc has never done it right and no one has noticed, so this
1948 // should be OK for now.
1949 if (ValVT == MVT::f64 &&
1950 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1951 report_fatal_error("SSE2 register return with SSE2 disabled");
1953 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1954 // the RET instruction and handled by the FP Stackifier.
1955 if (VA.getLocReg() == X86::FP0 ||
1956 VA.getLocReg() == X86::FP1) {
1957 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1958 // change the value to the FP stack register class.
1959 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1960 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1961 RetOps.push_back(ValToCopy);
1962 // Don't emit a copytoreg.
1966 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1967 // which is returned in RAX / RDX.
1968 if (Subtarget->is64Bit()) {
1969 if (ValVT == MVT::x86mmx) {
1970 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1971 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1972 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1974 // If we don't have SSE2 available, convert to v4f32 so the generated
1975 // register is legal.
1976 if (!Subtarget->hasSSE2())
1977 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1982 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1983 Flag = Chain.getValue(1);
1984 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1987 // The x86-64 ABIs require that for returning structs by value we copy
1988 // the sret argument into %rax/%eax (depending on ABI) for the return.
1989 // Win32 requires us to put the sret argument to %eax as well.
1990 // We saved the argument into a virtual register in the entry block,
1991 // so now we copy the value out and into %rax/%eax.
1993 // Checking Function.hasStructRetAttr() here is insufficient because the IR
1994 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
1995 // false, then an sret argument may be implicitly inserted in the SelDAG. In
1996 // either case FuncInfo->setSRetReturnReg() will have been called.
1997 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
1998 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
1999 "No need for an sret register");
2000 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2003 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2004 X86::RAX : X86::EAX;
2005 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2006 Flag = Chain.getValue(1);
2008 // RAX/EAX now acts like a return value.
2009 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2012 RetOps[0] = Chain; // Update chain.
2014 // Add the flag if we have it.
2016 RetOps.push_back(Flag);
2018 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2021 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2022 if (N->getNumValues() != 1)
2024 if (!N->hasNUsesOfValue(1, 0))
2027 SDValue TCChain = Chain;
2028 SDNode *Copy = *N->use_begin();
2029 if (Copy->getOpcode() == ISD::CopyToReg) {
2030 // If the copy has a glue operand, we conservatively assume it isn't safe to
2031 // perform a tail call.
2032 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2034 TCChain = Copy->getOperand(0);
2035 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2038 bool HasRet = false;
2039 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2041 if (UI->getOpcode() != X86ISD::RET_FLAG)
2043 // If we are returning more than one value, we can definitely
2044 // not make a tail call see PR19530
2045 if (UI->getNumOperands() > 4)
2047 if (UI->getNumOperands() == 4 &&
2048 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2061 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2062 ISD::NodeType ExtendKind) const {
2064 // TODO: Is this also valid on 32-bit?
2065 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2066 ReturnMVT = MVT::i8;
2068 ReturnMVT = MVT::i32;
2070 EVT MinVT = getRegisterType(Context, ReturnMVT);
2071 return VT.bitsLT(MinVT) ? MinVT : VT;
2074 /// Lower the result values of a call into the
2075 /// appropriate copies out of appropriate physical registers.
2078 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2079 CallingConv::ID CallConv, bool isVarArg,
2080 const SmallVectorImpl<ISD::InputArg> &Ins,
2081 SDLoc dl, SelectionDAG &DAG,
2082 SmallVectorImpl<SDValue> &InVals) const {
2084 // Assign locations to each value returned by this call.
2085 SmallVector<CCValAssign, 16> RVLocs;
2086 bool Is64Bit = Subtarget->is64Bit();
2087 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2089 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2091 // Copy all of the result registers out of their specified physreg.
2092 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2093 CCValAssign &VA = RVLocs[i];
2094 EVT CopyVT = VA.getLocVT();
2096 // If this is x86-64, and we disabled SSE, we can't return FP values
2097 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2098 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2099 report_fatal_error("SSE register return with SSE disabled");
2102 // If we prefer to use the value in xmm registers, copy it out as f80 and
2103 // use a truncate to move it from fp stack reg to xmm reg.
2104 bool RoundAfterCopy = false;
2105 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2106 isScalarFPTypeInSSEReg(VA.getValVT())) {
2108 RoundAfterCopy = (CopyVT != VA.getLocVT());
2111 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2112 CopyVT, InFlag).getValue(1);
2113 SDValue Val = Chain.getValue(0);
2116 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2117 // This truncation won't change the value.
2118 DAG.getIntPtrConstant(1, dl));
2120 InFlag = Chain.getValue(2);
2121 InVals.push_back(Val);
2127 //===----------------------------------------------------------------------===//
2128 // C & StdCall & Fast Calling Convention implementation
2129 //===----------------------------------------------------------------------===//
2130 // StdCall calling convention seems to be standard for many Windows' API
2131 // routines and around. It differs from C calling convention just a little:
2132 // callee should clean up the stack, not caller. Symbols should be also
2133 // decorated in some fancy way :) It doesn't support any vector arguments.
2134 // For info on fast calling convention see Fast Calling Convention (tail call)
2135 // implementation LowerX86_32FastCCCallTo.
2137 /// CallIsStructReturn - Determines whether a call uses struct return
2139 enum StructReturnType {
2144 static StructReturnType
2145 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2147 return NotStructReturn;
2149 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2150 if (!Flags.isSRet())
2151 return NotStructReturn;
2152 if (Flags.isInReg())
2153 return RegStructReturn;
2154 return StackStructReturn;
2157 /// Determines whether a function uses struct return semantics.
2158 static StructReturnType
2159 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2161 return NotStructReturn;
2163 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2164 if (!Flags.isSRet())
2165 return NotStructReturn;
2166 if (Flags.isInReg())
2167 return RegStructReturn;
2168 return StackStructReturn;
2171 /// Make a copy of an aggregate at address specified by "Src" to address
2172 /// "Dst" with size and alignment information specified by the specific
2173 /// parameter attribute. The copy will be passed as a byval function parameter.
2175 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2176 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2178 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2180 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2181 /*isVolatile*/false, /*AlwaysInline=*/true,
2182 /*isTailCall*/false,
2183 MachinePointerInfo(), MachinePointerInfo());
2186 /// Return true if the calling convention is one that
2187 /// supports tail call optimization.
2188 static bool IsTailCallConvention(CallingConv::ID CC) {
2189 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2190 CC == CallingConv::HiPE);
2193 /// \brief Return true if the calling convention is a C calling convention.
2194 static bool IsCCallConvention(CallingConv::ID CC) {
2195 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2196 CC == CallingConv::X86_64_SysV);
2199 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2200 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2204 CallingConv::ID CalleeCC = CS.getCallingConv();
2205 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2211 /// Return true if the function is being made into
2212 /// a tailcall target by changing its ABI.
2213 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2214 bool GuaranteedTailCallOpt) {
2215 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2219 X86TargetLowering::LowerMemArgument(SDValue Chain,
2220 CallingConv::ID CallConv,
2221 const SmallVectorImpl<ISD::InputArg> &Ins,
2222 SDLoc dl, SelectionDAG &DAG,
2223 const CCValAssign &VA,
2224 MachineFrameInfo *MFI,
2226 // Create the nodes corresponding to a load from this parameter slot.
2227 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2228 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2229 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2230 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2233 // If value is passed by pointer we have address passed instead of the value
2235 if (VA.getLocInfo() == CCValAssign::Indirect)
2236 ValVT = VA.getLocVT();
2238 ValVT = VA.getValVT();
2240 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2241 // changed with more analysis.
2242 // In case of tail call optimization mark all arguments mutable. Since they
2243 // could be overwritten by lowering of arguments in case of a tail call.
2244 if (Flags.isByVal()) {
2245 unsigned Bytes = Flags.getByValSize();
2246 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2247 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2248 return DAG.getFrameIndex(FI, getPointerTy());
2250 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2251 VA.getLocMemOffset(), isImmutable);
2252 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2253 return DAG.getLoad(ValVT, dl, Chain, FIN,
2254 MachinePointerInfo::getFixedStack(FI),
2255 false, false, false, 0);
2259 // FIXME: Get this from tablegen.
2260 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2261 const X86Subtarget *Subtarget) {
2262 assert(Subtarget->is64Bit());
2264 if (Subtarget->isCallingConvWin64(CallConv)) {
2265 static const MCPhysReg GPR64ArgRegsWin64[] = {
2266 X86::RCX, X86::RDX, X86::R8, X86::R9
2268 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2271 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2272 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2274 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2277 // FIXME: Get this from tablegen.
2278 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2279 CallingConv::ID CallConv,
2280 const X86Subtarget *Subtarget) {
2281 assert(Subtarget->is64Bit());
2282 if (Subtarget->isCallingConvWin64(CallConv)) {
2283 // The XMM registers which might contain var arg parameters are shadowed
2284 // in their paired GPR. So we only need to save the GPR to their home
2286 // TODO: __vectorcall will change this.
2290 const Function *Fn = MF.getFunction();
2291 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2292 bool isSoftFloat = MF.getTarget().Options.UseSoftFloat;
2293 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2294 "SSE register cannot be used when SSE is disabled!");
2295 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2296 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2300 static const MCPhysReg XMMArgRegs64Bit[] = {
2301 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2302 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2304 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2308 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2309 CallingConv::ID CallConv,
2311 const SmallVectorImpl<ISD::InputArg> &Ins,
2314 SmallVectorImpl<SDValue> &InVals)
2316 MachineFunction &MF = DAG.getMachineFunction();
2317 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2318 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2320 const Function* Fn = MF.getFunction();
2321 if (Fn->hasExternalLinkage() &&
2322 Subtarget->isTargetCygMing() &&
2323 Fn->getName() == "main")
2324 FuncInfo->setForceFramePointer(true);
2326 MachineFrameInfo *MFI = MF.getFrameInfo();
2327 bool Is64Bit = Subtarget->is64Bit();
2328 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2330 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2331 "Var args not supported with calling convention fastcc, ghc or hipe");
2333 // Assign locations to all of the incoming arguments.
2334 SmallVector<CCValAssign, 16> ArgLocs;
2335 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2337 // Allocate shadow area for Win64
2339 CCInfo.AllocateStack(32, 8);
2341 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2343 unsigned LastVal = ~0U;
2345 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2346 CCValAssign &VA = ArgLocs[i];
2347 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2349 assert(VA.getValNo() != LastVal &&
2350 "Don't support value assigned to multiple locs yet");
2352 LastVal = VA.getValNo();
2354 if (VA.isRegLoc()) {
2355 EVT RegVT = VA.getLocVT();
2356 const TargetRegisterClass *RC;
2357 if (RegVT == MVT::i32)
2358 RC = &X86::GR32RegClass;
2359 else if (Is64Bit && RegVT == MVT::i64)
2360 RC = &X86::GR64RegClass;
2361 else if (RegVT == MVT::f32)
2362 RC = &X86::FR32RegClass;
2363 else if (RegVT == MVT::f64)
2364 RC = &X86::FR64RegClass;
2365 else if (RegVT.is512BitVector())
2366 RC = &X86::VR512RegClass;
2367 else if (RegVT.is256BitVector())
2368 RC = &X86::VR256RegClass;
2369 else if (RegVT.is128BitVector())
2370 RC = &X86::VR128RegClass;
2371 else if (RegVT == MVT::x86mmx)
2372 RC = &X86::VR64RegClass;
2373 else if (RegVT == MVT::i1)
2374 RC = &X86::VK1RegClass;
2375 else if (RegVT == MVT::v8i1)
2376 RC = &X86::VK8RegClass;
2377 else if (RegVT == MVT::v16i1)
2378 RC = &X86::VK16RegClass;
2379 else if (RegVT == MVT::v32i1)
2380 RC = &X86::VK32RegClass;
2381 else if (RegVT == MVT::v64i1)
2382 RC = &X86::VK64RegClass;
2384 llvm_unreachable("Unknown argument type!");
2386 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2387 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2389 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2390 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2392 if (VA.getLocInfo() == CCValAssign::SExt)
2393 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2394 DAG.getValueType(VA.getValVT()));
2395 else if (VA.getLocInfo() == CCValAssign::ZExt)
2396 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2397 DAG.getValueType(VA.getValVT()));
2398 else if (VA.getLocInfo() == CCValAssign::BCvt)
2399 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2401 if (VA.isExtInLoc()) {
2402 // Handle MMX values passed in XMM regs.
2403 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2404 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2406 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2409 assert(VA.isMemLoc());
2410 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2413 // If value is passed via pointer - do a load.
2414 if (VA.getLocInfo() == CCValAssign::Indirect)
2415 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2416 MachinePointerInfo(), false, false, false, 0);
2418 InVals.push_back(ArgValue);
2421 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2422 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2423 // The x86-64 ABIs require that for returning structs by value we copy
2424 // the sret argument into %rax/%eax (depending on ABI) for the return.
2425 // Win32 requires us to put the sret argument to %eax as well.
2426 // Save the argument into a virtual register so that we can access it
2427 // from the return points.
2428 if (Ins[i].Flags.isSRet()) {
2429 unsigned Reg = FuncInfo->getSRetReturnReg();
2431 MVT PtrTy = getPointerTy();
2432 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2433 FuncInfo->setSRetReturnReg(Reg);
2435 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2436 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2442 unsigned StackSize = CCInfo.getNextStackOffset();
2443 // Align stack specially for tail calls.
2444 if (FuncIsMadeTailCallSafe(CallConv,
2445 MF.getTarget().Options.GuaranteedTailCallOpt))
2446 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2448 // If the function takes variable number of arguments, make a frame index for
2449 // the start of the first vararg value... for expansion of llvm.va_start. We
2450 // can skip this if there are no va_start calls.
2451 if (MFI->hasVAStart() &&
2452 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2453 CallConv != CallingConv::X86_ThisCall))) {
2454 FuncInfo->setVarArgsFrameIndex(
2455 MFI->CreateFixedObject(1, StackSize, true));
2458 MachineModuleInfo &MMI = MF.getMMI();
2459 const Function *WinEHParent = nullptr;
2460 if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2461 WinEHParent = MMI.getWinEHParent(Fn);
2462 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2463 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2465 // Figure out if XMM registers are in use.
2466 assert(!(MF.getTarget().Options.UseSoftFloat &&
2467 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2468 "SSE register cannot be used when SSE is disabled!");
2470 // 64-bit calling conventions support varargs and register parameters, so we
2471 // have to do extra work to spill them in the prologue.
2472 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2473 // Find the first unallocated argument registers.
2474 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2475 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2476 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2477 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2478 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2479 "SSE register cannot be used when SSE is disabled!");
2481 // Gather all the live in physical registers.
2482 SmallVector<SDValue, 6> LiveGPRs;
2483 SmallVector<SDValue, 8> LiveXMMRegs;
2485 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2486 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2488 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2490 if (!ArgXMMs.empty()) {
2491 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2492 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2493 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2494 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2495 LiveXMMRegs.push_back(
2496 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2501 // Get to the caller-allocated home save location. Add 8 to account
2502 // for the return address.
2503 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2504 FuncInfo->setRegSaveFrameIndex(
2505 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2506 // Fixup to set vararg frame on shadow area (4 x i64).
2508 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2510 // For X86-64, if there are vararg parameters that are passed via
2511 // registers, then we must store them to their spots on the stack so
2512 // they may be loaded by deferencing the result of va_next.
2513 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2514 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2515 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2516 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2519 // Store the integer parameter registers.
2520 SmallVector<SDValue, 8> MemOps;
2521 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2523 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2524 for (SDValue Val : LiveGPRs) {
2525 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2526 DAG.getIntPtrConstant(Offset, dl));
2528 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2529 MachinePointerInfo::getFixedStack(
2530 FuncInfo->getRegSaveFrameIndex(), Offset),
2532 MemOps.push_back(Store);
2536 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2537 // Now store the XMM (fp + vector) parameter registers.
2538 SmallVector<SDValue, 12> SaveXMMOps;
2539 SaveXMMOps.push_back(Chain);
2540 SaveXMMOps.push_back(ALVal);
2541 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2542 FuncInfo->getRegSaveFrameIndex(), dl));
2543 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2544 FuncInfo->getVarArgsFPOffset(), dl));
2545 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2547 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2548 MVT::Other, SaveXMMOps));
2551 if (!MemOps.empty())
2552 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2553 } else if (IsWinEHOutlined) {
2554 // Get to the caller-allocated home save location. Add 8 to account
2555 // for the return address.
2556 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2557 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2558 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2560 MMI.getWinEHFuncInfo(Fn)
2561 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2562 FuncInfo->getRegSaveFrameIndex();
2564 // Store the second integer parameter (rdx) into rsp+16 relative to the
2565 // stack pointer at the entry of the function.
2567 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2568 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2569 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2570 Chain = DAG.getStore(
2571 Val.getValue(1), dl, Val, RSFIN,
2572 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2573 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2576 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2577 // Find the largest legal vector type.
2578 MVT VecVT = MVT::Other;
2579 // FIXME: Only some x86_32 calling conventions support AVX512.
2580 if (Subtarget->hasAVX512() &&
2581 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2582 CallConv == CallingConv::Intel_OCL_BI)))
2583 VecVT = MVT::v16f32;
2584 else if (Subtarget->hasAVX())
2586 else if (Subtarget->hasSSE2())
2589 // We forward some GPRs and some vector types.
2590 SmallVector<MVT, 2> RegParmTypes;
2591 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2592 RegParmTypes.push_back(IntVT);
2593 if (VecVT != MVT::Other)
2594 RegParmTypes.push_back(VecVT);
2596 // Compute the set of forwarded registers. The rest are scratch.
2597 SmallVectorImpl<ForwardedRegister> &Forwards =
2598 FuncInfo->getForwardedMustTailRegParms();
2599 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2601 // Conservatively forward AL on x86_64, since it might be used for varargs.
2602 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2603 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2604 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2607 // Copy all forwards from physical to virtual registers.
2608 for (ForwardedRegister &F : Forwards) {
2609 // FIXME: Can we use a less constrained schedule?
2610 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2611 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2612 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2616 // Some CCs need callee pop.
2617 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2618 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2619 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2621 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2622 // If this is an sret function, the return should pop the hidden pointer.
2623 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2624 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2625 argsAreStructReturn(Ins) == StackStructReturn)
2626 FuncInfo->setBytesToPopOnReturn(4);
2630 // RegSaveFrameIndex is X86-64 only.
2631 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2632 if (CallConv == CallingConv::X86_FastCall ||
2633 CallConv == CallingConv::X86_ThisCall)
2634 // fastcc functions can't have varargs.
2635 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2638 FuncInfo->setArgumentStackSize(StackSize);
2640 if (IsWinEHParent) {
2641 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2642 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2643 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2644 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2645 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2646 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2647 /*isVolatile=*/true,
2648 /*isNonTemporal=*/false, /*Alignment=*/0);
2655 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2656 SDValue StackPtr, SDValue Arg,
2657 SDLoc dl, SelectionDAG &DAG,
2658 const CCValAssign &VA,
2659 ISD::ArgFlagsTy Flags) const {
2660 unsigned LocMemOffset = VA.getLocMemOffset();
2661 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2662 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2663 if (Flags.isByVal())
2664 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2666 return DAG.getStore(Chain, dl, Arg, PtrOff,
2667 MachinePointerInfo::getStack(LocMemOffset),
2671 /// Emit a load of return address if tail call
2672 /// optimization is performed and it is required.
2674 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2675 SDValue &OutRetAddr, SDValue Chain,
2676 bool IsTailCall, bool Is64Bit,
2677 int FPDiff, SDLoc dl) const {
2678 // Adjust the Return address stack slot.
2679 EVT VT = getPointerTy();
2680 OutRetAddr = getReturnAddressFrameIndex(DAG);
2682 // Load the "old" Return address.
2683 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2684 false, false, false, 0);
2685 return SDValue(OutRetAddr.getNode(), 1);
2688 /// Emit a store of the return address if tail call
2689 /// optimization is performed and it is required (FPDiff!=0).
2690 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2691 SDValue Chain, SDValue RetAddrFrIdx,
2692 EVT PtrVT, unsigned SlotSize,
2693 int FPDiff, SDLoc dl) {
2694 // Store the return address to the appropriate stack slot.
2695 if (!FPDiff) return Chain;
2696 // Calculate the new stack slot for the return address.
2697 int NewReturnAddrFI =
2698 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2700 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2701 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2702 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2708 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2709 SmallVectorImpl<SDValue> &InVals) const {
2710 SelectionDAG &DAG = CLI.DAG;
2712 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2713 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2714 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2715 SDValue Chain = CLI.Chain;
2716 SDValue Callee = CLI.Callee;
2717 CallingConv::ID CallConv = CLI.CallConv;
2718 bool &isTailCall = CLI.IsTailCall;
2719 bool isVarArg = CLI.IsVarArg;
2721 MachineFunction &MF = DAG.getMachineFunction();
2722 bool Is64Bit = Subtarget->is64Bit();
2723 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2724 StructReturnType SR = callIsStructReturn(Outs);
2725 bool IsSibcall = false;
2726 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2728 if (MF.getTarget().Options.DisableTailCalls)
2731 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2733 // Force this to be a tail call. The verifier rules are enough to ensure
2734 // that we can lower this successfully without moving the return address
2737 } else if (isTailCall) {
2738 // Check if it's really possible to do a tail call.
2739 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2740 isVarArg, SR != NotStructReturn,
2741 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2742 Outs, OutVals, Ins, DAG);
2744 // Sibcalls are automatically detected tailcalls which do not require
2746 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2753 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2754 "Var args not supported with calling convention fastcc, ghc or hipe");
2756 // Analyze operands of the call, assigning locations to each operand.
2757 SmallVector<CCValAssign, 16> ArgLocs;
2758 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2760 // Allocate shadow area for Win64
2762 CCInfo.AllocateStack(32, 8);
2764 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2766 // Get a count of how many bytes are to be pushed on the stack.
2767 unsigned NumBytes = CCInfo.getNextStackOffset();
2769 // This is a sibcall. The memory operands are available in caller's
2770 // own caller's stack.
2772 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2773 IsTailCallConvention(CallConv))
2774 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2777 if (isTailCall && !IsSibcall && !IsMustTail) {
2778 // Lower arguments at fp - stackoffset + fpdiff.
2779 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2781 FPDiff = NumBytesCallerPushed - NumBytes;
2783 // Set the delta of movement of the returnaddr stackslot.
2784 // But only set if delta is greater than previous delta.
2785 if (FPDiff < X86Info->getTCReturnAddrDelta())
2786 X86Info->setTCReturnAddrDelta(FPDiff);
2789 unsigned NumBytesToPush = NumBytes;
2790 unsigned NumBytesToPop = NumBytes;
2792 // If we have an inalloca argument, all stack space has already been allocated
2793 // for us and be right at the top of the stack. We don't support multiple
2794 // arguments passed in memory when using inalloca.
2795 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2797 if (!ArgLocs.back().isMemLoc())
2798 report_fatal_error("cannot use inalloca attribute on a register "
2800 if (ArgLocs.back().getLocMemOffset() != 0)
2801 report_fatal_error("any parameter with the inalloca attribute must be "
2802 "the only memory argument");
2806 Chain = DAG.getCALLSEQ_START(
2807 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2809 SDValue RetAddrFrIdx;
2810 // Load return address for tail calls.
2811 if (isTailCall && FPDiff)
2812 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2813 Is64Bit, FPDiff, dl);
2815 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2816 SmallVector<SDValue, 8> MemOpChains;
2819 // Walk the register/memloc assignments, inserting copies/loads. In the case
2820 // of tail call optimization arguments are handle later.
2821 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2822 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2823 // Skip inalloca arguments, they have already been written.
2824 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2825 if (Flags.isInAlloca())
2828 CCValAssign &VA = ArgLocs[i];
2829 EVT RegVT = VA.getLocVT();
2830 SDValue Arg = OutVals[i];
2831 bool isByVal = Flags.isByVal();
2833 // Promote the value if needed.
2834 switch (VA.getLocInfo()) {
2835 default: llvm_unreachable("Unknown loc info!");
2836 case CCValAssign::Full: break;
2837 case CCValAssign::SExt:
2838 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2840 case CCValAssign::ZExt:
2841 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2843 case CCValAssign::AExt:
2844 if (Arg.getValueType().getScalarType() == MVT::i1)
2845 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2846 else if (RegVT.is128BitVector()) {
2847 // Special case: passing MMX values in XMM registers.
2848 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2849 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2850 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2852 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2854 case CCValAssign::BCvt:
2855 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2857 case CCValAssign::Indirect: {
2858 // Store the argument.
2859 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2860 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2861 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2862 MachinePointerInfo::getFixedStack(FI),
2869 if (VA.isRegLoc()) {
2870 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2871 if (isVarArg && IsWin64) {
2872 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2873 // shadow reg if callee is a varargs function.
2874 unsigned ShadowReg = 0;
2875 switch (VA.getLocReg()) {
2876 case X86::XMM0: ShadowReg = X86::RCX; break;
2877 case X86::XMM1: ShadowReg = X86::RDX; break;
2878 case X86::XMM2: ShadowReg = X86::R8; break;
2879 case X86::XMM3: ShadowReg = X86::R9; break;
2882 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2884 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2885 assert(VA.isMemLoc());
2886 if (!StackPtr.getNode())
2887 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2889 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2890 dl, DAG, VA, Flags));
2894 if (!MemOpChains.empty())
2895 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2897 if (Subtarget->isPICStyleGOT()) {
2898 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2901 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2902 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2904 // If we are tail calling and generating PIC/GOT style code load the
2905 // address of the callee into ECX. The value in ecx is used as target of
2906 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2907 // for tail calls on PIC/GOT architectures. Normally we would just put the
2908 // address of GOT into ebx and then call target@PLT. But for tail calls
2909 // ebx would be restored (since ebx is callee saved) before jumping to the
2912 // Note: The actual moving to ECX is done further down.
2913 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2914 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2915 !G->getGlobal()->hasProtectedVisibility())
2916 Callee = LowerGlobalAddress(Callee, DAG);
2917 else if (isa<ExternalSymbolSDNode>(Callee))
2918 Callee = LowerExternalSymbol(Callee, DAG);
2922 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2923 // From AMD64 ABI document:
2924 // For calls that may call functions that use varargs or stdargs
2925 // (prototype-less calls or calls to functions containing ellipsis (...) in
2926 // the declaration) %al is used as hidden argument to specify the number
2927 // of SSE registers used. The contents of %al do not need to match exactly
2928 // the number of registers, but must be an ubound on the number of SSE
2929 // registers used and is in the range 0 - 8 inclusive.
2931 // Count the number of XMM registers allocated.
2932 static const MCPhysReg XMMArgRegs[] = {
2933 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2934 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2936 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2937 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2938 && "SSE registers cannot be used when SSE is disabled");
2940 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2941 DAG.getConstant(NumXMMRegs, dl,
2945 if (isVarArg && IsMustTail) {
2946 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2947 for (const auto &F : Forwards) {
2948 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2949 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2953 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2954 // don't need this because the eligibility check rejects calls that require
2955 // shuffling arguments passed in memory.
2956 if (!IsSibcall && isTailCall) {
2957 // Force all the incoming stack arguments to be loaded from the stack
2958 // before any new outgoing arguments are stored to the stack, because the
2959 // outgoing stack slots may alias the incoming argument stack slots, and
2960 // the alias isn't otherwise explicit. This is slightly more conservative
2961 // than necessary, because it means that each store effectively depends
2962 // on every argument instead of just those arguments it would clobber.
2963 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2965 SmallVector<SDValue, 8> MemOpChains2;
2968 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2969 CCValAssign &VA = ArgLocs[i];
2972 assert(VA.isMemLoc());
2973 SDValue Arg = OutVals[i];
2974 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2975 // Skip inalloca arguments. They don't require any work.
2976 if (Flags.isInAlloca())
2978 // Create frame index.
2979 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2980 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2981 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2982 FIN = DAG.getFrameIndex(FI, getPointerTy());
2984 if (Flags.isByVal()) {
2985 // Copy relative to framepointer.
2986 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
2987 if (!StackPtr.getNode())
2988 StackPtr = DAG.getCopyFromReg(Chain, dl,
2989 RegInfo->getStackRegister(),
2991 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2993 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2997 // Store relative to framepointer.
2998 MemOpChains2.push_back(
2999 DAG.getStore(ArgChain, dl, Arg, FIN,
3000 MachinePointerInfo::getFixedStack(FI),
3005 if (!MemOpChains2.empty())
3006 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3008 // Store the return address to the appropriate stack slot.
3009 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3010 getPointerTy(), RegInfo->getSlotSize(),
3014 // Build a sequence of copy-to-reg nodes chained together with token chain
3015 // and flag operands which copy the outgoing args into registers.
3017 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3018 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3019 RegsToPass[i].second, InFlag);
3020 InFlag = Chain.getValue(1);
3023 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3024 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3025 // In the 64-bit large code model, we have to make all calls
3026 // through a register, since the call instruction's 32-bit
3027 // pc-relative offset may not be large enough to hold the whole
3029 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3030 // If the callee is a GlobalAddress node (quite common, every direct call
3031 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3033 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3035 // We should use extra load for direct calls to dllimported functions in
3037 const GlobalValue *GV = G->getGlobal();
3038 if (!GV->hasDLLImportStorageClass()) {
3039 unsigned char OpFlags = 0;
3040 bool ExtraLoad = false;
3041 unsigned WrapperKind = ISD::DELETED_NODE;
3043 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3044 // external symbols most go through the PLT in PIC mode. If the symbol
3045 // has hidden or protected visibility, or if it is static or local, then
3046 // we don't need to use the PLT - we can directly call it.
3047 if (Subtarget->isTargetELF() &&
3048 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3049 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3050 OpFlags = X86II::MO_PLT;
3051 } else if (Subtarget->isPICStyleStubAny() &&
3052 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3053 (!Subtarget->getTargetTriple().isMacOSX() ||
3054 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3055 // PC-relative references to external symbols should go through $stub,
3056 // unless we're building with the leopard linker or later, which
3057 // automatically synthesizes these stubs.
3058 OpFlags = X86II::MO_DARWIN_STUB;
3059 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3060 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3061 // If the function is marked as non-lazy, generate an indirect call
3062 // which loads from the GOT directly. This avoids runtime overhead
3063 // at the cost of eager binding (and one extra byte of encoding).
3064 OpFlags = X86II::MO_GOTPCREL;
3065 WrapperKind = X86ISD::WrapperRIP;
3069 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3070 G->getOffset(), OpFlags);
3072 // Add a wrapper if needed.
3073 if (WrapperKind != ISD::DELETED_NODE)
3074 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3075 // Add extra indirection if needed.
3077 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3078 MachinePointerInfo::getGOT(),
3079 false, false, false, 0);
3081 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3082 unsigned char OpFlags = 0;
3084 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3085 // external symbols should go through the PLT.
3086 if (Subtarget->isTargetELF() &&
3087 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3088 OpFlags = X86II::MO_PLT;
3089 } else if (Subtarget->isPICStyleStubAny() &&
3090 (!Subtarget->getTargetTriple().isMacOSX() ||
3091 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3092 // PC-relative references to external symbols should go through $stub,
3093 // unless we're building with the leopard linker or later, which
3094 // automatically synthesizes these stubs.
3095 OpFlags = X86II::MO_DARWIN_STUB;
3098 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3100 } else if (Subtarget->isTarget64BitILP32() &&
3101 Callee->getValueType(0) == MVT::i32) {
3102 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3103 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3106 // Returns a chain & a flag for retval copy to use.
3107 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3108 SmallVector<SDValue, 8> Ops;
3110 if (!IsSibcall && isTailCall) {
3111 Chain = DAG.getCALLSEQ_END(Chain,
3112 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3113 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3114 InFlag = Chain.getValue(1);
3117 Ops.push_back(Chain);
3118 Ops.push_back(Callee);
3121 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3123 // Add argument registers to the end of the list so that they are known live
3125 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3126 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3127 RegsToPass[i].second.getValueType()));
3129 // Add a register mask operand representing the call-preserved registers.
3130 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3131 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3132 assert(Mask && "Missing call preserved mask for calling convention");
3133 Ops.push_back(DAG.getRegisterMask(Mask));
3135 if (InFlag.getNode())
3136 Ops.push_back(InFlag);
3140 //// If this is the first return lowered for this function, add the regs
3141 //// to the liveout set for the function.
3142 // This isn't right, although it's probably harmless on x86; liveouts
3143 // should be computed from returns not tail calls. Consider a void
3144 // function making a tail call to a function returning int.
3145 MF.getFrameInfo()->setHasTailCall();
3146 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3149 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3150 InFlag = Chain.getValue(1);
3152 // Create the CALLSEQ_END node.
3153 unsigned NumBytesForCalleeToPop;
3154 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3155 DAG.getTarget().Options.GuaranteedTailCallOpt))
3156 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3157 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3158 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3159 SR == StackStructReturn)
3160 // If this is a call to a struct-return function, the callee
3161 // pops the hidden struct pointer, so we have to push it back.
3162 // This is common for Darwin/X86, Linux & Mingw32 targets.
3163 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3164 NumBytesForCalleeToPop = 4;
3166 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3168 // Returns a flag for retval copy to use.
3170 Chain = DAG.getCALLSEQ_END(Chain,
3171 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3172 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3175 InFlag = Chain.getValue(1);
3178 // Handle result values, copying them out of physregs into vregs that we
3180 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3181 Ins, dl, DAG, InVals);
3184 //===----------------------------------------------------------------------===//
3185 // Fast Calling Convention (tail call) implementation
3186 //===----------------------------------------------------------------------===//
3188 // Like std call, callee cleans arguments, convention except that ECX is
3189 // reserved for storing the tail called function address. Only 2 registers are
3190 // free for argument passing (inreg). Tail call optimization is performed
3192 // * tailcallopt is enabled
3193 // * caller/callee are fastcc
3194 // On X86_64 architecture with GOT-style position independent code only local
3195 // (within module) calls are supported at the moment.
3196 // To keep the stack aligned according to platform abi the function
3197 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3198 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3199 // If a tail called function callee has more arguments than the caller the
3200 // caller needs to make sure that there is room to move the RETADDR to. This is
3201 // achieved by reserving an area the size of the argument delta right after the
3202 // original RETADDR, but before the saved framepointer or the spilled registers
3203 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3215 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3216 /// for a 16 byte align requirement.
3218 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3219 SelectionDAG& DAG) const {
3220 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3221 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3222 unsigned StackAlignment = TFI.getStackAlignment();
3223 uint64_t AlignMask = StackAlignment - 1;
3224 int64_t Offset = StackSize;
3225 unsigned SlotSize = RegInfo->getSlotSize();
3226 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3227 // Number smaller than 12 so just add the difference.
3228 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3230 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3231 Offset = ((~AlignMask) & Offset) + StackAlignment +
3232 (StackAlignment-SlotSize);
3237 /// MatchingStackOffset - Return true if the given stack call argument is
3238 /// already available in the same position (relatively) of the caller's
3239 /// incoming argument stack.
3241 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3242 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3243 const X86InstrInfo *TII) {
3244 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3246 if (Arg.getOpcode() == ISD::CopyFromReg) {
3247 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3248 if (!TargetRegisterInfo::isVirtualRegister(VR))
3250 MachineInstr *Def = MRI->getVRegDef(VR);
3253 if (!Flags.isByVal()) {
3254 if (!TII->isLoadFromStackSlot(Def, FI))
3257 unsigned Opcode = Def->getOpcode();
3258 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3259 Opcode == X86::LEA64_32r) &&
3260 Def->getOperand(1).isFI()) {
3261 FI = Def->getOperand(1).getIndex();
3262 Bytes = Flags.getByValSize();
3266 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3267 if (Flags.isByVal())
3268 // ByVal argument is passed in as a pointer but it's now being
3269 // dereferenced. e.g.
3270 // define @foo(%struct.X* %A) {
3271 // tail call @bar(%struct.X* byval %A)
3274 SDValue Ptr = Ld->getBasePtr();
3275 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3278 FI = FINode->getIndex();
3279 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3280 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3281 FI = FINode->getIndex();
3282 Bytes = Flags.getByValSize();
3286 assert(FI != INT_MAX);
3287 if (!MFI->isFixedObjectIndex(FI))
3289 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3292 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3293 /// for tail call optimization. Targets which want to do tail call
3294 /// optimization should implement this function.
3296 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3297 CallingConv::ID CalleeCC,
3299 bool isCalleeStructRet,
3300 bool isCallerStructRet,
3302 const SmallVectorImpl<ISD::OutputArg> &Outs,
3303 const SmallVectorImpl<SDValue> &OutVals,
3304 const SmallVectorImpl<ISD::InputArg> &Ins,
3305 SelectionDAG &DAG) const {
3306 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3309 // If -tailcallopt is specified, make fastcc functions tail-callable.
3310 const MachineFunction &MF = DAG.getMachineFunction();
3311 const Function *CallerF = MF.getFunction();
3313 // If the function return type is x86_fp80 and the callee return type is not,
3314 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3315 // perform a tailcall optimization here.
3316 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3319 CallingConv::ID CallerCC = CallerF->getCallingConv();
3320 bool CCMatch = CallerCC == CalleeCC;
3321 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3322 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3324 // Win64 functions have extra shadow space for argument homing. Don't do the
3325 // sibcall if the caller and callee have mismatched expectations for this
3327 if (IsCalleeWin64 != IsCallerWin64)
3330 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3331 if (IsTailCallConvention(CalleeCC) && CCMatch)
3336 // Look for obvious safe cases to perform tail call optimization that do not
3337 // require ABI changes. This is what gcc calls sibcall.
3339 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3340 // emit a special epilogue.
3341 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3342 if (RegInfo->needsStackRealignment(MF))
3345 // Also avoid sibcall optimization if either caller or callee uses struct
3346 // return semantics.
3347 if (isCalleeStructRet || isCallerStructRet)
3350 // An stdcall/thiscall caller is expected to clean up its arguments; the
3351 // callee isn't going to do that.
3352 // FIXME: this is more restrictive than needed. We could produce a tailcall
3353 // when the stack adjustment matches. For example, with a thiscall that takes
3354 // only one argument.
3355 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3356 CallerCC == CallingConv::X86_ThisCall))
3359 // Do not sibcall optimize vararg calls unless all arguments are passed via
3361 if (isVarArg && !Outs.empty()) {
3363 // Optimizing for varargs on Win64 is unlikely to be safe without
3364 // additional testing.
3365 if (IsCalleeWin64 || IsCallerWin64)
3368 SmallVector<CCValAssign, 16> ArgLocs;
3369 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3372 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3373 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3374 if (!ArgLocs[i].isRegLoc())
3378 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3379 // stack. Therefore, if it's not used by the call it is not safe to optimize
3380 // this into a sibcall.
3381 bool Unused = false;
3382 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3389 SmallVector<CCValAssign, 16> RVLocs;
3390 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3392 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3393 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3394 CCValAssign &VA = RVLocs[i];
3395 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3400 // If the calling conventions do not match, then we'd better make sure the
3401 // results are returned in the same way as what the caller expects.
3403 SmallVector<CCValAssign, 16> RVLocs1;
3404 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3406 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3408 SmallVector<CCValAssign, 16> RVLocs2;
3409 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3411 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3413 if (RVLocs1.size() != RVLocs2.size())
3415 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3416 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3418 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3420 if (RVLocs1[i].isRegLoc()) {
3421 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3424 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3430 // If the callee takes no arguments then go on to check the results of the
3432 if (!Outs.empty()) {
3433 // Check if stack adjustment is needed. For now, do not do this if any
3434 // argument is passed on the stack.
3435 SmallVector<CCValAssign, 16> ArgLocs;
3436 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3439 // Allocate shadow area for Win64
3441 CCInfo.AllocateStack(32, 8);
3443 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3444 if (CCInfo.getNextStackOffset()) {
3445 MachineFunction &MF = DAG.getMachineFunction();
3446 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3449 // Check if the arguments are already laid out in the right way as
3450 // the caller's fixed stack objects.
3451 MachineFrameInfo *MFI = MF.getFrameInfo();
3452 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3453 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3454 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3455 CCValAssign &VA = ArgLocs[i];
3456 SDValue Arg = OutVals[i];
3457 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3458 if (VA.getLocInfo() == CCValAssign::Indirect)
3460 if (!VA.isRegLoc()) {
3461 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3468 // If the tailcall address may be in a register, then make sure it's
3469 // possible to register allocate for it. In 32-bit, the call address can
3470 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3471 // callee-saved registers are restored. These happen to be the same
3472 // registers used to pass 'inreg' arguments so watch out for those.
3473 if (!Subtarget->is64Bit() &&
3474 ((!isa<GlobalAddressSDNode>(Callee) &&
3475 !isa<ExternalSymbolSDNode>(Callee)) ||
3476 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3477 unsigned NumInRegs = 0;
3478 // In PIC we need an extra register to formulate the address computation
3480 unsigned MaxInRegs =
3481 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3483 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3484 CCValAssign &VA = ArgLocs[i];
3487 unsigned Reg = VA.getLocReg();
3490 case X86::EAX: case X86::EDX: case X86::ECX:
3491 if (++NumInRegs == MaxInRegs)
3503 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3504 const TargetLibraryInfo *libInfo) const {
3505 return X86::createFastISel(funcInfo, libInfo);
3508 //===----------------------------------------------------------------------===//
3509 // Other Lowering Hooks
3510 //===----------------------------------------------------------------------===//
3512 static bool MayFoldLoad(SDValue Op) {
3513 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3516 static bool MayFoldIntoStore(SDValue Op) {
3517 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3520 static bool isTargetShuffle(unsigned Opcode) {
3522 default: return false;
3523 case X86ISD::BLENDI:
3524 case X86ISD::PSHUFB:
3525 case X86ISD::PSHUFD:
3526 case X86ISD::PSHUFHW:
3527 case X86ISD::PSHUFLW:
3529 case X86ISD::PALIGNR:
3530 case X86ISD::MOVLHPS:
3531 case X86ISD::MOVLHPD:
3532 case X86ISD::MOVHLPS:
3533 case X86ISD::MOVLPS:
3534 case X86ISD::MOVLPD:
3535 case X86ISD::MOVSHDUP:
3536 case X86ISD::MOVSLDUP:
3537 case X86ISD::MOVDDUP:
3540 case X86ISD::UNPCKL:
3541 case X86ISD::UNPCKH:
3542 case X86ISD::VPERMILPI:
3543 case X86ISD::VPERM2X128:
3544 case X86ISD::VPERMI:
3549 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3550 SDValue V1, unsigned TargetMask,
3551 SelectionDAG &DAG) {
3553 default: llvm_unreachable("Unknown x86 shuffle node");
3554 case X86ISD::PSHUFD:
3555 case X86ISD::PSHUFHW:
3556 case X86ISD::PSHUFLW:
3557 case X86ISD::VPERMILPI:
3558 case X86ISD::VPERMI:
3559 return DAG.getNode(Opc, dl, VT, V1,
3560 DAG.getConstant(TargetMask, dl, MVT::i8));
3564 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3565 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3567 default: llvm_unreachable("Unknown x86 shuffle node");
3568 case X86ISD::MOVLHPS:
3569 case X86ISD::MOVLHPD:
3570 case X86ISD::MOVHLPS:
3571 case X86ISD::MOVLPS:
3572 case X86ISD::MOVLPD:
3575 case X86ISD::UNPCKL:
3576 case X86ISD::UNPCKH:
3577 return DAG.getNode(Opc, dl, VT, V1, V2);
3581 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3582 MachineFunction &MF = DAG.getMachineFunction();
3583 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3584 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3585 int ReturnAddrIndex = FuncInfo->getRAIndex();
3587 if (ReturnAddrIndex == 0) {
3588 // Set up a frame object for the return address.
3589 unsigned SlotSize = RegInfo->getSlotSize();
3590 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3593 FuncInfo->setRAIndex(ReturnAddrIndex);
3596 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3599 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3600 bool hasSymbolicDisplacement) {
3601 // Offset should fit into 32 bit immediate field.
3602 if (!isInt<32>(Offset))
3605 // If we don't have a symbolic displacement - we don't have any extra
3607 if (!hasSymbolicDisplacement)
3610 // FIXME: Some tweaks might be needed for medium code model.
3611 if (M != CodeModel::Small && M != CodeModel::Kernel)
3614 // For small code model we assume that latest object is 16MB before end of 31
3615 // bits boundary. We may also accept pretty large negative constants knowing
3616 // that all objects are in the positive half of address space.
3617 if (M == CodeModel::Small && Offset < 16*1024*1024)
3620 // For kernel code model we know that all object resist in the negative half
3621 // of 32bits address space. We may not accept negative offsets, since they may
3622 // be just off and we may accept pretty large positive ones.
3623 if (M == CodeModel::Kernel && Offset >= 0)
3629 /// isCalleePop - Determines whether the callee is required to pop its
3630 /// own arguments. Callee pop is necessary to support tail calls.
3631 bool X86::isCalleePop(CallingConv::ID CallingConv,
3632 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3633 switch (CallingConv) {
3636 case CallingConv::X86_StdCall:
3637 case CallingConv::X86_FastCall:
3638 case CallingConv::X86_ThisCall:
3640 case CallingConv::Fast:
3641 case CallingConv::GHC:
3642 case CallingConv::HiPE:
3649 /// \brief Return true if the condition is an unsigned comparison operation.
3650 static bool isX86CCUnsigned(unsigned X86CC) {
3652 default: llvm_unreachable("Invalid integer condition!");
3653 case X86::COND_E: return true;
3654 case X86::COND_G: return false;
3655 case X86::COND_GE: return false;
3656 case X86::COND_L: return false;
3657 case X86::COND_LE: return false;
3658 case X86::COND_NE: return true;
3659 case X86::COND_B: return true;
3660 case X86::COND_A: return true;
3661 case X86::COND_BE: return true;
3662 case X86::COND_AE: return true;
3664 llvm_unreachable("covered switch fell through?!");
3667 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3668 /// specific condition code, returning the condition code and the LHS/RHS of the
3669 /// comparison to make.
3670 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3671 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3673 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3674 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3675 // X > -1 -> X == 0, jump !sign.
3676 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3677 return X86::COND_NS;
3679 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3680 // X < 0 -> X == 0, jump on sign.
3683 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3685 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3686 return X86::COND_LE;
3690 switch (SetCCOpcode) {
3691 default: llvm_unreachable("Invalid integer condition!");
3692 case ISD::SETEQ: return X86::COND_E;
3693 case ISD::SETGT: return X86::COND_G;
3694 case ISD::SETGE: return X86::COND_GE;
3695 case ISD::SETLT: return X86::COND_L;
3696 case ISD::SETLE: return X86::COND_LE;
3697 case ISD::SETNE: return X86::COND_NE;
3698 case ISD::SETULT: return X86::COND_B;
3699 case ISD::SETUGT: return X86::COND_A;
3700 case ISD::SETULE: return X86::COND_BE;
3701 case ISD::SETUGE: return X86::COND_AE;
3705 // First determine if it is required or is profitable to flip the operands.
3707 // If LHS is a foldable load, but RHS is not, flip the condition.
3708 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3709 !ISD::isNON_EXTLoad(RHS.getNode())) {
3710 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3711 std::swap(LHS, RHS);
3714 switch (SetCCOpcode) {
3720 std::swap(LHS, RHS);
3724 // On a floating point condition, the flags are set as follows:
3726 // 0 | 0 | 0 | X > Y
3727 // 0 | 0 | 1 | X < Y
3728 // 1 | 0 | 0 | X == Y
3729 // 1 | 1 | 1 | unordered
3730 switch (SetCCOpcode) {
3731 default: llvm_unreachable("Condcode should be pre-legalized away");
3733 case ISD::SETEQ: return X86::COND_E;
3734 case ISD::SETOLT: // flipped
3736 case ISD::SETGT: return X86::COND_A;
3737 case ISD::SETOLE: // flipped
3739 case ISD::SETGE: return X86::COND_AE;
3740 case ISD::SETUGT: // flipped
3742 case ISD::SETLT: return X86::COND_B;
3743 case ISD::SETUGE: // flipped
3745 case ISD::SETLE: return X86::COND_BE;
3747 case ISD::SETNE: return X86::COND_NE;
3748 case ISD::SETUO: return X86::COND_P;
3749 case ISD::SETO: return X86::COND_NP;
3751 case ISD::SETUNE: return X86::COND_INVALID;
3755 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3756 /// code. Current x86 isa includes the following FP cmov instructions:
3757 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3758 static bool hasFPCMov(unsigned X86CC) {
3774 /// isFPImmLegal - Returns true if the target can instruction select the
3775 /// specified FP immediate natively. If false, the legalizer will
3776 /// materialize the FP immediate as a load from a constant pool.
3777 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3778 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3779 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3785 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3786 ISD::LoadExtType ExtTy,
3788 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3789 // relocation target a movq or addq instruction: don't let the load shrink.
3790 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3791 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3792 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3793 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3797 /// \brief Returns true if it is beneficial to convert a load of a constant
3798 /// to just the constant itself.
3799 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3801 assert(Ty->isIntegerTy());
3803 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3804 if (BitSize == 0 || BitSize > 64)
3809 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3810 unsigned Index) const {
3811 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3814 return (Index == 0 || Index == ResVT.getVectorNumElements());
3817 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3818 // Speculate cttz only if we can directly use TZCNT.
3819 return Subtarget->hasBMI();
3822 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3823 // Speculate ctlz only if we can directly use LZCNT.
3824 return Subtarget->hasLZCNT();
3827 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3828 /// the specified range (L, H].
3829 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3830 return (Val < 0) || (Val >= Low && Val < Hi);
3833 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3834 /// specified value.
3835 static bool isUndefOrEqual(int Val, int CmpVal) {
3836 return (Val < 0 || Val == CmpVal);
3839 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3840 /// from position Pos and ending in Pos+Size, falls within the specified
3841 /// sequential range (Low, Low+Size]. or is undef.
3842 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3843 unsigned Pos, unsigned Size, int Low) {
3844 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3845 if (!isUndefOrEqual(Mask[i], Low))
3850 /// isVEXTRACTIndex - Return true if the specified
3851 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3852 /// suitable for instruction that extract 128 or 256 bit vectors
3853 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3854 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3855 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3858 // The index should be aligned on a vecWidth-bit boundary.
3860 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3862 MVT VT = N->getSimpleValueType(0);
3863 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3864 bool Result = (Index * ElSize) % vecWidth == 0;
3869 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3870 /// operand specifies a subvector insert that is suitable for input to
3871 /// insertion of 128 or 256-bit subvectors
3872 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3873 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3874 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3876 // The index should be aligned on a vecWidth-bit boundary.
3878 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3880 MVT VT = N->getSimpleValueType(0);
3881 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3882 bool Result = (Index * ElSize) % vecWidth == 0;
3887 bool X86::isVINSERT128Index(SDNode *N) {
3888 return isVINSERTIndex(N, 128);
3891 bool X86::isVINSERT256Index(SDNode *N) {
3892 return isVINSERTIndex(N, 256);
3895 bool X86::isVEXTRACT128Index(SDNode *N) {
3896 return isVEXTRACTIndex(N, 128);
3899 bool X86::isVEXTRACT256Index(SDNode *N) {
3900 return isVEXTRACTIndex(N, 256);
3903 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3904 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3905 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3906 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3909 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3911 MVT VecVT = N->getOperand(0).getSimpleValueType();
3912 MVT ElVT = VecVT.getVectorElementType();
3914 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3915 return Index / NumElemsPerChunk;
3918 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3919 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3920 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3921 llvm_unreachable("Illegal insert subvector for VINSERT");
3924 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3926 MVT VecVT = N->getSimpleValueType(0);
3927 MVT ElVT = VecVT.getVectorElementType();
3929 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3930 return Index / NumElemsPerChunk;
3933 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3934 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3935 /// and VINSERTI128 instructions.
3936 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3937 return getExtractVEXTRACTImmediate(N, 128);
3940 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3941 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3942 /// and VINSERTI64x4 instructions.
3943 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3944 return getExtractVEXTRACTImmediate(N, 256);
3947 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3948 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3949 /// and VINSERTI128 instructions.
3950 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3951 return getInsertVINSERTImmediate(N, 128);
3954 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3955 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3956 /// and VINSERTI64x4 instructions.
3957 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3958 return getInsertVINSERTImmediate(N, 256);
3961 /// isZero - Returns true if Elt is a constant integer zero
3962 static bool isZero(SDValue V) {
3963 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3964 return C && C->isNullValue();
3967 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3969 bool X86::isZeroNode(SDValue Elt) {
3972 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3973 return CFP->getValueAPF().isPosZero();
3977 /// getZeroVector - Returns a vector of specified type with all zero elements.
3979 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3980 SelectionDAG &DAG, SDLoc dl) {
3981 assert(VT.isVector() && "Expected a vector type");
3983 // Always build SSE zero vectors as <4 x i32> bitcasted
3984 // to their dest type. This ensures they get CSE'd.
3986 if (VT.is128BitVector()) { // SSE
3987 if (Subtarget->hasSSE2()) { // SSE2
3988 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3989 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3991 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
3992 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3994 } else if (VT.is256BitVector()) { // AVX
3995 if (Subtarget->hasInt256()) { // AVX2
3996 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3997 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3998 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4000 // 256-bit logic and arithmetic instructions in AVX are all
4001 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4002 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4003 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4004 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4006 } else if (VT.is512BitVector()) { // AVX-512
4007 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4008 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4009 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4010 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4011 } else if (VT.getScalarType() == MVT::i1) {
4013 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4014 && "Unexpected vector type");
4015 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4016 && "Unexpected vector type");
4017 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4018 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4019 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4021 llvm_unreachable("Unexpected vector type");
4023 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4026 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4027 SelectionDAG &DAG, SDLoc dl,
4028 unsigned vectorWidth) {
4029 assert((vectorWidth == 128 || vectorWidth == 256) &&
4030 "Unsupported vector width");
4031 EVT VT = Vec.getValueType();
4032 EVT ElVT = VT.getVectorElementType();
4033 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4034 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4035 VT.getVectorNumElements()/Factor);
4037 // Extract from UNDEF is UNDEF.
4038 if (Vec.getOpcode() == ISD::UNDEF)
4039 return DAG.getUNDEF(ResultVT);
4041 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4042 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4044 // This is the index of the first element of the vectorWidth-bit chunk
4046 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4049 // If the input is a buildvector just emit a smaller one.
4050 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4051 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4052 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4055 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4056 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4059 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4060 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4061 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4062 /// instructions or a simple subregister reference. Idx is an index in the
4063 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4064 /// lowering EXTRACT_VECTOR_ELT operations easier.
4065 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4066 SelectionDAG &DAG, SDLoc dl) {
4067 assert((Vec.getValueType().is256BitVector() ||
4068 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4069 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4072 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4073 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4074 SelectionDAG &DAG, SDLoc dl) {
4075 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4076 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4079 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4080 unsigned IdxVal, SelectionDAG &DAG,
4081 SDLoc dl, unsigned vectorWidth) {
4082 assert((vectorWidth == 128 || vectorWidth == 256) &&
4083 "Unsupported vector width");
4084 // Inserting UNDEF is Result
4085 if (Vec.getOpcode() == ISD::UNDEF)
4087 EVT VT = Vec.getValueType();
4088 EVT ElVT = VT.getVectorElementType();
4089 EVT ResultVT = Result.getValueType();
4091 // Insert the relevant vectorWidth bits.
4092 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4094 // This is the index of the first element of the vectorWidth-bit chunk
4096 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4099 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4100 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4103 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4104 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4105 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4106 /// simple superregister reference. Idx is an index in the 128 bits
4107 /// we want. It need not be aligned to a 128-bit boundary. That makes
4108 /// lowering INSERT_VECTOR_ELT operations easier.
4109 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4110 SelectionDAG &DAG, SDLoc dl) {
4111 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4113 // For insertion into the zero index (low half) of a 256-bit vector, it is
4114 // more efficient to generate a blend with immediate instead of an insert*128.
4115 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4116 // extend the subvector to the size of the result vector. Make sure that
4117 // we are not recursing on that node by checking for undef here.
4118 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4119 Result.getOpcode() != ISD::UNDEF) {
4120 EVT ResultVT = Result.getValueType();
4121 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4122 SDValue Undef = DAG.getUNDEF(ResultVT);
4123 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4126 // The blend instruction, and therefore its mask, depend on the data type.
4127 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4128 if (ScalarType.isFloatingPoint()) {
4129 // Choose either vblendps (float) or vblendpd (double).
4130 unsigned ScalarSize = ScalarType.getSizeInBits();
4131 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4132 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4133 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4134 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4137 const X86Subtarget &Subtarget =
4138 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4140 // AVX2 is needed for 256-bit integer blend support.
4141 // Integers must be cast to 32-bit because there is only vpblendd;
4142 // vpblendw can't be used for this because it has a handicapped mask.
4144 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4145 // is still more efficient than using the wrong domain vinsertf128 that
4146 // will be created by InsertSubVector().
4147 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4149 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4150 Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4151 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4152 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4155 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4158 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4159 SelectionDAG &DAG, SDLoc dl) {
4160 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4161 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4164 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4165 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4166 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4167 /// large BUILD_VECTORS.
4168 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4169 unsigned NumElems, SelectionDAG &DAG,
4171 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4172 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4175 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4176 unsigned NumElems, SelectionDAG &DAG,
4178 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4179 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4182 /// getOnesVector - Returns a vector of specified type with all bits set.
4183 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4184 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4185 /// Then bitcast to their original type, ensuring they get CSE'd.
4186 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4188 assert(VT.isVector() && "Expected a vector type");
4190 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4192 if (VT.is256BitVector()) {
4193 if (HasInt256) { // AVX2
4194 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4195 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4197 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4198 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4200 } else if (VT.is128BitVector()) {
4201 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4203 llvm_unreachable("Unexpected vector type");
4205 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4208 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4209 /// operation of specified width.
4210 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4212 unsigned NumElems = VT.getVectorNumElements();
4213 SmallVector<int, 8> Mask;
4214 Mask.push_back(NumElems);
4215 for (unsigned i = 1; i != NumElems; ++i)
4217 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4220 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4221 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4223 unsigned NumElems = VT.getVectorNumElements();
4224 SmallVector<int, 8> Mask;
4225 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4227 Mask.push_back(i + NumElems);
4229 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4232 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4233 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4235 unsigned NumElems = VT.getVectorNumElements();
4236 SmallVector<int, 8> Mask;
4237 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4238 Mask.push_back(i + Half);
4239 Mask.push_back(i + NumElems + Half);
4241 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4244 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4245 /// vector of zero or undef vector. This produces a shuffle where the low
4246 /// element of V2 is swizzled into the zero/undef vector, landing at element
4247 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4248 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4250 const X86Subtarget *Subtarget,
4251 SelectionDAG &DAG) {
4252 MVT VT = V2.getSimpleValueType();
4254 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4255 unsigned NumElems = VT.getVectorNumElements();
4256 SmallVector<int, 16> MaskVec;
4257 for (unsigned i = 0; i != NumElems; ++i)
4258 // If this is the insertion idx, put the low elt of V2 here.
4259 MaskVec.push_back(i == Idx ? NumElems : i);
4260 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4263 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4264 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4265 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4266 /// shuffles which use a single input multiple times, and in those cases it will
4267 /// adjust the mask to only have indices within that single input.
4268 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4269 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4270 unsigned NumElems = VT.getVectorNumElements();
4274 bool IsFakeUnary = false;
4275 switch(N->getOpcode()) {
4276 case X86ISD::BLENDI:
4277 ImmN = N->getOperand(N->getNumOperands()-1);
4278 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4281 ImmN = N->getOperand(N->getNumOperands()-1);
4282 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4283 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4285 case X86ISD::UNPCKH:
4286 DecodeUNPCKHMask(VT, Mask);
4287 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4289 case X86ISD::UNPCKL:
4290 DecodeUNPCKLMask(VT, Mask);
4291 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4293 case X86ISD::MOVHLPS:
4294 DecodeMOVHLPSMask(NumElems, Mask);
4295 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4297 case X86ISD::MOVLHPS:
4298 DecodeMOVLHPSMask(NumElems, Mask);
4299 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4301 case X86ISD::PALIGNR:
4302 ImmN = N->getOperand(N->getNumOperands()-1);
4303 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4305 case X86ISD::PSHUFD:
4306 case X86ISD::VPERMILPI:
4307 ImmN = N->getOperand(N->getNumOperands()-1);
4308 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4311 case X86ISD::PSHUFHW:
4312 ImmN = N->getOperand(N->getNumOperands()-1);
4313 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4316 case X86ISD::PSHUFLW:
4317 ImmN = N->getOperand(N->getNumOperands()-1);
4318 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4321 case X86ISD::PSHUFB: {
4323 SDValue MaskNode = N->getOperand(1);
4324 while (MaskNode->getOpcode() == ISD::BITCAST)
4325 MaskNode = MaskNode->getOperand(0);
4327 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4328 // If we have a build-vector, then things are easy.
4329 EVT VT = MaskNode.getValueType();
4330 assert(VT.isVector() &&
4331 "Can't produce a non-vector with a build_vector!");
4332 if (!VT.isInteger())
4335 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4337 SmallVector<uint64_t, 32> RawMask;
4338 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4339 SDValue Op = MaskNode->getOperand(i);
4340 if (Op->getOpcode() == ISD::UNDEF) {
4341 RawMask.push_back((uint64_t)SM_SentinelUndef);
4344 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4347 APInt MaskElement = CN->getAPIntValue();
4349 // We now have to decode the element which could be any integer size and
4350 // extract each byte of it.
4351 for (int j = 0; j < NumBytesPerElement; ++j) {
4352 // Note that this is x86 and so always little endian: the low byte is
4353 // the first byte of the mask.
4354 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4355 MaskElement = MaskElement.lshr(8);
4358 DecodePSHUFBMask(RawMask, Mask);
4362 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4366 SDValue Ptr = MaskLoad->getBasePtr();
4367 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4368 Ptr->getOpcode() == X86ISD::WrapperRIP)
4369 Ptr = Ptr->getOperand(0);
4371 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4372 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4375 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4376 DecodePSHUFBMask(C, Mask);
4384 case X86ISD::VPERMI:
4385 ImmN = N->getOperand(N->getNumOperands()-1);
4386 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4391 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4393 case X86ISD::VPERM2X128:
4394 ImmN = N->getOperand(N->getNumOperands()-1);
4395 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4396 if (Mask.empty()) return false;
4398 case X86ISD::MOVSLDUP:
4399 DecodeMOVSLDUPMask(VT, Mask);
4402 case X86ISD::MOVSHDUP:
4403 DecodeMOVSHDUPMask(VT, Mask);
4406 case X86ISD::MOVDDUP:
4407 DecodeMOVDDUPMask(VT, Mask);
4410 case X86ISD::MOVLHPD:
4411 case X86ISD::MOVLPD:
4412 case X86ISD::MOVLPS:
4413 // Not yet implemented
4415 default: llvm_unreachable("unknown target shuffle node");
4418 // If we have a fake unary shuffle, the shuffle mask is spread across two
4419 // inputs that are actually the same node. Re-map the mask to always point
4420 // into the first input.
4423 if (M >= (int)Mask.size())
4429 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4430 /// element of the result of the vector shuffle.
4431 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4434 return SDValue(); // Limit search depth.
4436 SDValue V = SDValue(N, 0);
4437 EVT VT = V.getValueType();
4438 unsigned Opcode = V.getOpcode();
4440 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4441 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4442 int Elt = SV->getMaskElt(Index);
4445 return DAG.getUNDEF(VT.getVectorElementType());
4447 unsigned NumElems = VT.getVectorNumElements();
4448 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4449 : SV->getOperand(1);
4450 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4453 // Recurse into target specific vector shuffles to find scalars.
4454 if (isTargetShuffle(Opcode)) {
4455 MVT ShufVT = V.getSimpleValueType();
4456 unsigned NumElems = ShufVT.getVectorNumElements();
4457 SmallVector<int, 16> ShuffleMask;
4460 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4463 int Elt = ShuffleMask[Index];
4465 return DAG.getUNDEF(ShufVT.getVectorElementType());
4467 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4469 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4473 // Actual nodes that may contain scalar elements
4474 if (Opcode == ISD::BITCAST) {
4475 V = V.getOperand(0);
4476 EVT SrcVT = V.getValueType();
4477 unsigned NumElems = VT.getVectorNumElements();
4479 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4483 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4484 return (Index == 0) ? V.getOperand(0)
4485 : DAG.getUNDEF(VT.getVectorElementType());
4487 if (V.getOpcode() == ISD::BUILD_VECTOR)
4488 return V.getOperand(Index);
4493 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4495 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4496 unsigned NumNonZero, unsigned NumZero,
4498 const X86Subtarget* Subtarget,
4499 const TargetLowering &TLI) {
4507 // SSE4.1 - use PINSRB to insert each byte directly.
4508 if (Subtarget->hasSSE41()) {
4509 for (unsigned i = 0; i < 16; ++i) {
4510 bool isNonZero = (NonZeros & (1 << i)) != 0;
4514 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4516 V = DAG.getUNDEF(MVT::v16i8);
4519 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4520 MVT::v16i8, V, Op.getOperand(i),
4521 DAG.getIntPtrConstant(i, dl));
4528 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4529 for (unsigned i = 0; i < 16; ++i) {
4530 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4531 if (ThisIsNonZero && First) {
4533 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4535 V = DAG.getUNDEF(MVT::v8i16);
4540 SDValue ThisElt, LastElt;
4541 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4542 if (LastIsNonZero) {
4543 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4544 MVT::i16, Op.getOperand(i-1));
4546 if (ThisIsNonZero) {
4547 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4548 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4549 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4551 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4555 if (ThisElt.getNode())
4556 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4557 DAG.getIntPtrConstant(i/2, dl));
4561 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4564 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4566 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4567 unsigned NumNonZero, unsigned NumZero,
4569 const X86Subtarget* Subtarget,
4570 const TargetLowering &TLI) {
4577 for (unsigned i = 0; i < 8; ++i) {
4578 bool isNonZero = (NonZeros & (1 << i)) != 0;
4582 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4584 V = DAG.getUNDEF(MVT::v8i16);
4587 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4588 MVT::v8i16, V, Op.getOperand(i),
4589 DAG.getIntPtrConstant(i, dl));
4596 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4597 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4598 const X86Subtarget *Subtarget,
4599 const TargetLowering &TLI) {
4600 // Find all zeroable elements.
4601 std::bitset<4> Zeroable;
4602 for (int i=0; i < 4; ++i) {
4603 SDValue Elt = Op->getOperand(i);
4604 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4606 assert(Zeroable.size() - Zeroable.count() > 1 &&
4607 "We expect at least two non-zero elements!");
4609 // We only know how to deal with build_vector nodes where elements are either
4610 // zeroable or extract_vector_elt with constant index.
4611 SDValue FirstNonZero;
4612 unsigned FirstNonZeroIdx;
4613 for (unsigned i=0; i < 4; ++i) {
4616 SDValue Elt = Op->getOperand(i);
4617 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4618 !isa<ConstantSDNode>(Elt.getOperand(1)))
4620 // Make sure that this node is extracting from a 128-bit vector.
4621 MVT VT = Elt.getOperand(0).getSimpleValueType();
4622 if (!VT.is128BitVector())
4624 if (!FirstNonZero.getNode()) {
4626 FirstNonZeroIdx = i;
4630 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4631 SDValue V1 = FirstNonZero.getOperand(0);
4632 MVT VT = V1.getSimpleValueType();
4634 // See if this build_vector can be lowered as a blend with zero.
4636 unsigned EltMaskIdx, EltIdx;
4638 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4639 if (Zeroable[EltIdx]) {
4640 // The zero vector will be on the right hand side.
4641 Mask[EltIdx] = EltIdx+4;
4645 Elt = Op->getOperand(EltIdx);
4646 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4647 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4648 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4650 Mask[EltIdx] = EltIdx;
4654 // Let the shuffle legalizer deal with blend operations.
4655 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4656 if (V1.getSimpleValueType() != VT)
4657 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4658 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4661 // See if we can lower this build_vector to a INSERTPS.
4662 if (!Subtarget->hasSSE41())
4665 SDValue V2 = Elt.getOperand(0);
4666 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4669 bool CanFold = true;
4670 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4674 SDValue Current = Op->getOperand(i);
4675 SDValue SrcVector = Current->getOperand(0);
4678 CanFold = SrcVector == V1 &&
4679 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4685 assert(V1.getNode() && "Expected at least two non-zero elements!");
4686 if (V1.getSimpleValueType() != MVT::v4f32)
4687 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4688 if (V2.getSimpleValueType() != MVT::v4f32)
4689 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4691 // Ok, we can emit an INSERTPS instruction.
4692 unsigned ZMask = Zeroable.to_ulong();
4694 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4695 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4697 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4698 DAG.getIntPtrConstant(InsertPSMask, DL));
4699 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4702 /// Return a vector logical shift node.
4703 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4704 unsigned NumBits, SelectionDAG &DAG,
4705 const TargetLowering &TLI, SDLoc dl) {
4706 assert(VT.is128BitVector() && "Unknown type for VShift");
4707 MVT ShVT = MVT::v2i64;
4708 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4709 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4710 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4711 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4712 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4713 return DAG.getNode(ISD::BITCAST, dl, VT,
4714 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4718 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4720 // Check if the scalar load can be widened into a vector load. And if
4721 // the address is "base + cst" see if the cst can be "absorbed" into
4722 // the shuffle mask.
4723 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4724 SDValue Ptr = LD->getBasePtr();
4725 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4727 EVT PVT = LD->getValueType(0);
4728 if (PVT != MVT::i32 && PVT != MVT::f32)
4733 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4734 FI = FINode->getIndex();
4736 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4737 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4738 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4739 Offset = Ptr.getConstantOperandVal(1);
4740 Ptr = Ptr.getOperand(0);
4745 // FIXME: 256-bit vector instructions don't require a strict alignment,
4746 // improve this code to support it better.
4747 unsigned RequiredAlign = VT.getSizeInBits()/8;
4748 SDValue Chain = LD->getChain();
4749 // Make sure the stack object alignment is at least 16 or 32.
4750 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4751 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4752 if (MFI->isFixedObjectIndex(FI)) {
4753 // Can't change the alignment. FIXME: It's possible to compute
4754 // the exact stack offset and reference FI + adjust offset instead.
4755 // If someone *really* cares about this. That's the way to implement it.
4758 MFI->setObjectAlignment(FI, RequiredAlign);
4762 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4763 // Ptr + (Offset & ~15).
4766 if ((Offset % RequiredAlign) & 3)
4768 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4771 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4772 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4775 int EltNo = (Offset - StartOffset) >> 2;
4776 unsigned NumElems = VT.getVectorNumElements();
4778 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4779 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4780 LD->getPointerInfo().getWithOffset(StartOffset),
4781 false, false, false, 0);
4783 SmallVector<int, 8> Mask(NumElems, EltNo);
4785 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4791 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4792 /// elements can be replaced by a single large load which has the same value as
4793 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4795 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4797 /// FIXME: we'd also like to handle the case where the last elements are zero
4798 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4799 /// There's even a handy isZeroNode for that purpose.
4800 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4801 SDLoc &DL, SelectionDAG &DAG,
4802 bool isAfterLegalize) {
4803 unsigned NumElems = Elts.size();
4805 LoadSDNode *LDBase = nullptr;
4806 unsigned LastLoadedElt = -1U;
4808 // For each element in the initializer, see if we've found a load or an undef.
4809 // If we don't find an initial load element, or later load elements are
4810 // non-consecutive, bail out.
4811 for (unsigned i = 0; i < NumElems; ++i) {
4812 SDValue Elt = Elts[i];
4813 // Look through a bitcast.
4814 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4815 Elt = Elt.getOperand(0);
4816 if (!Elt.getNode() ||
4817 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4820 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4822 LDBase = cast<LoadSDNode>(Elt.getNode());
4826 if (Elt.getOpcode() == ISD::UNDEF)
4829 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4830 EVT LdVT = Elt.getValueType();
4831 // Each loaded element must be the correct fractional portion of the
4832 // requested vector load.
4833 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4835 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4840 // If we have found an entire vector of loads and undefs, then return a large
4841 // load of the entire vector width starting at the base pointer. If we found
4842 // consecutive loads for the low half, generate a vzext_load node.
4843 if (LastLoadedElt == NumElems - 1) {
4844 assert(LDBase && "Did not find base load for merging consecutive loads");
4845 EVT EltVT = LDBase->getValueType(0);
4846 // Ensure that the input vector size for the merged loads matches the
4847 // cumulative size of the input elements.
4848 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4851 if (isAfterLegalize &&
4852 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4855 SDValue NewLd = SDValue();
4857 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4858 LDBase->getPointerInfo(), LDBase->isVolatile(),
4859 LDBase->isNonTemporal(), LDBase->isInvariant(),
4860 LDBase->getAlignment());
4862 if (LDBase->hasAnyUseOfValue(1)) {
4863 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4865 SDValue(NewLd.getNode(), 1));
4866 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4867 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4868 SDValue(NewLd.getNode(), 1));
4874 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4875 //of a v4i32 / v4f32. It's probably worth generalizing.
4876 EVT EltVT = VT.getVectorElementType();
4877 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4878 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4879 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4880 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4882 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4883 LDBase->getPointerInfo(),
4884 LDBase->getAlignment(),
4885 false/*isVolatile*/, true/*ReadMem*/,
4888 // Make sure the newly-created LOAD is in the same position as LDBase in
4889 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4890 // update uses of LDBase's output chain to use the TokenFactor.
4891 if (LDBase->hasAnyUseOfValue(1)) {
4892 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4893 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4894 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4895 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4896 SDValue(ResNode.getNode(), 1));
4899 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4904 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4905 /// to generate a splat value for the following cases:
4906 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4907 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4908 /// a scalar load, or a constant.
4909 /// The VBROADCAST node is returned when a pattern is found,
4910 /// or SDValue() otherwise.
4911 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4912 SelectionDAG &DAG) {
4913 // VBROADCAST requires AVX.
4914 // TODO: Splats could be generated for non-AVX CPUs using SSE
4915 // instructions, but there's less potential gain for only 128-bit vectors.
4916 if (!Subtarget->hasAVX())
4919 MVT VT = Op.getSimpleValueType();
4922 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4923 "Unsupported vector type for broadcast.");
4928 switch (Op.getOpcode()) {
4930 // Unknown pattern found.
4933 case ISD::BUILD_VECTOR: {
4934 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4935 BitVector UndefElements;
4936 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4938 // We need a splat of a single value to use broadcast, and it doesn't
4939 // make any sense if the value is only in one element of the vector.
4940 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4944 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4945 Ld.getOpcode() == ISD::ConstantFP);
4947 // Make sure that all of the users of a non-constant load are from the
4948 // BUILD_VECTOR node.
4949 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4954 case ISD::VECTOR_SHUFFLE: {
4955 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4957 // Shuffles must have a splat mask where the first element is
4959 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4962 SDValue Sc = Op.getOperand(0);
4963 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4964 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4966 if (!Subtarget->hasInt256())
4969 // Use the register form of the broadcast instruction available on AVX2.
4970 if (VT.getSizeInBits() >= 256)
4971 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4972 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4975 Ld = Sc.getOperand(0);
4976 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4977 Ld.getOpcode() == ISD::ConstantFP);
4979 // The scalar_to_vector node and the suspected
4980 // load node must have exactly one user.
4981 // Constants may have multiple users.
4983 // AVX-512 has register version of the broadcast
4984 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4985 Ld.getValueType().getSizeInBits() >= 32;
4986 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4993 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4994 bool IsGE256 = (VT.getSizeInBits() >= 256);
4996 // When optimizing for size, generate up to 5 extra bytes for a broadcast
4997 // instruction to save 8 or more bytes of constant pool data.
4998 // TODO: If multiple splats are generated to load the same constant,
4999 // it may be detrimental to overall size. There needs to be a way to detect
5000 // that condition to know if this is truly a size win.
5001 const Function *F = DAG.getMachineFunction().getFunction();
5002 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5004 // Handle broadcasting a single constant scalar from the constant pool
5006 // On Sandybridge (no AVX2), it is still better to load a constant vector
5007 // from the constant pool and not to broadcast it from a scalar.
5008 // But override that restriction when optimizing for size.
5009 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5010 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5011 EVT CVT = Ld.getValueType();
5012 assert(!CVT.isVector() && "Must not broadcast a vector type");
5014 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5015 // For size optimization, also splat v2f64 and v2i64, and for size opt
5016 // with AVX2, also splat i8 and i16.
5017 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5018 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5019 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5020 const Constant *C = nullptr;
5021 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5022 C = CI->getConstantIntValue();
5023 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5024 C = CF->getConstantFPValue();
5026 assert(C && "Invalid constant type");
5028 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5029 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5030 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5031 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5032 MachinePointerInfo::getConstantPool(),
5033 false, false, false, Alignment);
5035 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5039 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5041 // Handle AVX2 in-register broadcasts.
5042 if (!IsLoad && Subtarget->hasInt256() &&
5043 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5044 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5046 // The scalar source must be a normal load.
5050 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5051 (Subtarget->hasVLX() && ScalarSize == 64))
5052 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5054 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5055 // double since there is no vbroadcastsd xmm
5056 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5057 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5058 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5061 // Unsupported broadcast.
5065 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5066 /// underlying vector and index.
5068 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5070 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5072 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5073 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5076 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5078 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5080 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5081 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5084 // In this case the vector is the extract_subvector expression and the index
5085 // is 2, as specified by the shuffle.
5086 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5087 SDValue ShuffleVec = SVOp->getOperand(0);
5088 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5089 assert(ShuffleVecVT.getVectorElementType() ==
5090 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5092 int ShuffleIdx = SVOp->getMaskElt(Idx);
5093 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5094 ExtractedFromVec = ShuffleVec;
5100 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5101 MVT VT = Op.getSimpleValueType();
5103 // Skip if insert_vec_elt is not supported.
5104 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5105 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5109 unsigned NumElems = Op.getNumOperands();
5113 SmallVector<unsigned, 4> InsertIndices;
5114 SmallVector<int, 8> Mask(NumElems, -1);
5116 for (unsigned i = 0; i != NumElems; ++i) {
5117 unsigned Opc = Op.getOperand(i).getOpcode();
5119 if (Opc == ISD::UNDEF)
5122 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5123 // Quit if more than 1 elements need inserting.
5124 if (InsertIndices.size() > 1)
5127 InsertIndices.push_back(i);
5131 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5132 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5133 // Quit if non-constant index.
5134 if (!isa<ConstantSDNode>(ExtIdx))
5136 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5138 // Quit if extracted from vector of different type.
5139 if (ExtractedFromVec.getValueType() != VT)
5142 if (!VecIn1.getNode())
5143 VecIn1 = ExtractedFromVec;
5144 else if (VecIn1 != ExtractedFromVec) {
5145 if (!VecIn2.getNode())
5146 VecIn2 = ExtractedFromVec;
5147 else if (VecIn2 != ExtractedFromVec)
5148 // Quit if more than 2 vectors to shuffle
5152 if (ExtractedFromVec == VecIn1)
5154 else if (ExtractedFromVec == VecIn2)
5155 Mask[i] = Idx + NumElems;
5158 if (!VecIn1.getNode())
5161 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5162 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5163 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5164 unsigned Idx = InsertIndices[i];
5165 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5166 DAG.getIntPtrConstant(Idx, DL));
5172 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5174 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5176 MVT VT = Op.getSimpleValueType();
5177 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5178 "Unexpected type in LowerBUILD_VECTORvXi1!");
5181 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5182 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5183 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5184 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5187 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5188 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5189 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5190 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5193 bool AllContants = true;
5194 uint64_t Immediate = 0;
5195 int NonConstIdx = -1;
5196 bool IsSplat = true;
5197 unsigned NumNonConsts = 0;
5198 unsigned NumConsts = 0;
5199 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5200 SDValue In = Op.getOperand(idx);
5201 if (In.getOpcode() == ISD::UNDEF)
5203 if (!isa<ConstantSDNode>(In)) {
5204 AllContants = false;
5209 if (cast<ConstantSDNode>(In)->getZExtValue())
5210 Immediate |= (1ULL << idx);
5212 if (In != Op.getOperand(0))
5217 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5218 DAG.getConstant(Immediate, dl, MVT::i16));
5219 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5220 DAG.getIntPtrConstant(0, dl));
5223 if (NumNonConsts == 1 && NonConstIdx != 0) {
5226 SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5227 MVT::getIntegerVT(VT.getSizeInBits()));
5228 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5231 DstVec = DAG.getUNDEF(VT);
5232 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5233 Op.getOperand(NonConstIdx),
5234 DAG.getIntPtrConstant(NonConstIdx, dl));
5236 if (!IsSplat && (NonConstIdx != 0))
5237 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5238 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5241 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5242 DAG.getConstant(-1, dl, SelectVT),
5243 DAG.getConstant(0, dl, SelectVT));
5245 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5246 DAG.getConstant((Immediate | 1), dl, SelectVT),
5247 DAG.getConstant(Immediate, dl, SelectVT));
5248 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5251 /// \brief Return true if \p N implements a horizontal binop and return the
5252 /// operands for the horizontal binop into V0 and V1.
5254 /// This is a helper function of LowerToHorizontalOp().
5255 /// This function checks that the build_vector \p N in input implements a
5256 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5257 /// operation to match.
5258 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5259 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5260 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5263 /// This function only analyzes elements of \p N whose indices are
5264 /// in range [BaseIdx, LastIdx).
5265 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5267 unsigned BaseIdx, unsigned LastIdx,
5268 SDValue &V0, SDValue &V1) {
5269 EVT VT = N->getValueType(0);
5271 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5272 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5273 "Invalid Vector in input!");
5275 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5276 bool CanFold = true;
5277 unsigned ExpectedVExtractIdx = BaseIdx;
5278 unsigned NumElts = LastIdx - BaseIdx;
5279 V0 = DAG.getUNDEF(VT);
5280 V1 = DAG.getUNDEF(VT);
5282 // Check if N implements a horizontal binop.
5283 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5284 SDValue Op = N->getOperand(i + BaseIdx);
5287 if (Op->getOpcode() == ISD::UNDEF) {
5288 // Update the expected vector extract index.
5289 if (i * 2 == NumElts)
5290 ExpectedVExtractIdx = BaseIdx;
5291 ExpectedVExtractIdx += 2;
5295 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5300 SDValue Op0 = Op.getOperand(0);
5301 SDValue Op1 = Op.getOperand(1);
5303 // Try to match the following pattern:
5304 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5305 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5306 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5307 Op0.getOperand(0) == Op1.getOperand(0) &&
5308 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5309 isa<ConstantSDNode>(Op1.getOperand(1)));
5313 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5314 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5316 if (i * 2 < NumElts) {
5317 if (V0.getOpcode() == ISD::UNDEF) {
5318 V0 = Op0.getOperand(0);
5319 if (V0.getValueType() != VT)
5323 if (V1.getOpcode() == ISD::UNDEF) {
5324 V1 = Op0.getOperand(0);
5325 if (V1.getValueType() != VT)
5328 if (i * 2 == NumElts)
5329 ExpectedVExtractIdx = BaseIdx;
5332 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5333 if (I0 == ExpectedVExtractIdx)
5334 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5335 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5336 // Try to match the following dag sequence:
5337 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5338 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5342 ExpectedVExtractIdx += 2;
5348 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5349 /// a concat_vector.
5351 /// This is a helper function of LowerToHorizontalOp().
5352 /// This function expects two 256-bit vectors called V0 and V1.
5353 /// At first, each vector is split into two separate 128-bit vectors.
5354 /// Then, the resulting 128-bit vectors are used to implement two
5355 /// horizontal binary operations.
5357 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5359 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5360 /// the two new horizontal binop.
5361 /// When Mode is set, the first horizontal binop dag node would take as input
5362 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5363 /// horizontal binop dag node would take as input the lower 128-bit of V1
5364 /// and the upper 128-bit of V1.
5366 /// HADD V0_LO, V0_HI
5367 /// HADD V1_LO, V1_HI
5369 /// Otherwise, the first horizontal binop dag node takes as input the lower
5370 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5371 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5373 /// HADD V0_LO, V1_LO
5374 /// HADD V0_HI, V1_HI
5376 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5377 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5378 /// the upper 128-bits of the result.
5379 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5380 SDLoc DL, SelectionDAG &DAG,
5381 unsigned X86Opcode, bool Mode,
5382 bool isUndefLO, bool isUndefHI) {
5383 EVT VT = V0.getValueType();
5384 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5385 "Invalid nodes in input!");
5387 unsigned NumElts = VT.getVectorNumElements();
5388 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5389 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5390 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5391 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5392 EVT NewVT = V0_LO.getValueType();
5394 SDValue LO = DAG.getUNDEF(NewVT);
5395 SDValue HI = DAG.getUNDEF(NewVT);
5398 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5399 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5400 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5401 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5402 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5404 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5405 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5406 V1_LO->getOpcode() != ISD::UNDEF))
5407 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5409 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5410 V1_HI->getOpcode() != ISD::UNDEF))
5411 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5414 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5417 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5419 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5420 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5421 EVT VT = BV->getValueType(0);
5422 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5423 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5427 unsigned NumElts = VT.getVectorNumElements();
5428 SDValue InVec0 = DAG.getUNDEF(VT);
5429 SDValue InVec1 = DAG.getUNDEF(VT);
5431 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5432 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5434 // Odd-numbered elements in the input build vector are obtained from
5435 // adding two integer/float elements.
5436 // Even-numbered elements in the input build vector are obtained from
5437 // subtracting two integer/float elements.
5438 unsigned ExpectedOpcode = ISD::FSUB;
5439 unsigned NextExpectedOpcode = ISD::FADD;
5440 bool AddFound = false;
5441 bool SubFound = false;
5443 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5444 SDValue Op = BV->getOperand(i);
5446 // Skip 'undef' values.
5447 unsigned Opcode = Op.getOpcode();
5448 if (Opcode == ISD::UNDEF) {
5449 std::swap(ExpectedOpcode, NextExpectedOpcode);
5453 // Early exit if we found an unexpected opcode.
5454 if (Opcode != ExpectedOpcode)
5457 SDValue Op0 = Op.getOperand(0);
5458 SDValue Op1 = Op.getOperand(1);
5460 // Try to match the following pattern:
5461 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5462 // Early exit if we cannot match that sequence.
5463 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5464 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5465 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5466 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5467 Op0.getOperand(1) != Op1.getOperand(1))
5470 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5474 // We found a valid add/sub node. Update the information accordingly.
5480 // Update InVec0 and InVec1.
5481 if (InVec0.getOpcode() == ISD::UNDEF) {
5482 InVec0 = Op0.getOperand(0);
5483 if (InVec0.getValueType() != VT)
5486 if (InVec1.getOpcode() == ISD::UNDEF) {
5487 InVec1 = Op1.getOperand(0);
5488 if (InVec1.getValueType() != VT)
5492 // Make sure that operands in input to each add/sub node always
5493 // come from a same pair of vectors.
5494 if (InVec0 != Op0.getOperand(0)) {
5495 if (ExpectedOpcode == ISD::FSUB)
5498 // FADD is commutable. Try to commute the operands
5499 // and then test again.
5500 std::swap(Op0, Op1);
5501 if (InVec0 != Op0.getOperand(0))
5505 if (InVec1 != Op1.getOperand(0))
5508 // Update the pair of expected opcodes.
5509 std::swap(ExpectedOpcode, NextExpectedOpcode);
5512 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5513 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5514 InVec1.getOpcode() != ISD::UNDEF)
5515 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5520 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5521 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5522 const X86Subtarget *Subtarget,
5523 SelectionDAG &DAG) {
5524 EVT VT = BV->getValueType(0);
5525 unsigned NumElts = VT.getVectorNumElements();
5526 unsigned NumUndefsLO = 0;
5527 unsigned NumUndefsHI = 0;
5528 unsigned Half = NumElts/2;
5530 // Count the number of UNDEF operands in the build_vector in input.
5531 for (unsigned i = 0, e = Half; i != e; ++i)
5532 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5535 for (unsigned i = Half, e = NumElts; i != e; ++i)
5536 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5539 // Early exit if this is either a build_vector of all UNDEFs or all the
5540 // operands but one are UNDEF.
5541 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5545 SDValue InVec0, InVec1;
5546 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5547 // Try to match an SSE3 float HADD/HSUB.
5548 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5549 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5551 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5552 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5553 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5554 // Try to match an SSSE3 integer HADD/HSUB.
5555 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5556 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5558 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5559 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5562 if (!Subtarget->hasAVX())
5565 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5566 // Try to match an AVX horizontal add/sub of packed single/double
5567 // precision floating point values from 256-bit vectors.
5568 SDValue InVec2, InVec3;
5569 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5570 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5571 ((InVec0.getOpcode() == ISD::UNDEF ||
5572 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5573 ((InVec1.getOpcode() == ISD::UNDEF ||
5574 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5575 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5577 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5578 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5579 ((InVec0.getOpcode() == ISD::UNDEF ||
5580 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5581 ((InVec1.getOpcode() == ISD::UNDEF ||
5582 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5583 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5584 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5585 // Try to match an AVX2 horizontal add/sub of signed integers.
5586 SDValue InVec2, InVec3;
5588 bool CanFold = true;
5590 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5591 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5592 ((InVec0.getOpcode() == ISD::UNDEF ||
5593 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5594 ((InVec1.getOpcode() == ISD::UNDEF ||
5595 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5596 X86Opcode = X86ISD::HADD;
5597 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5598 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5599 ((InVec0.getOpcode() == ISD::UNDEF ||
5600 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5601 ((InVec1.getOpcode() == ISD::UNDEF ||
5602 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5603 X86Opcode = X86ISD::HSUB;
5608 // Fold this build_vector into a single horizontal add/sub.
5609 // Do this only if the target has AVX2.
5610 if (Subtarget->hasAVX2())
5611 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5613 // Do not try to expand this build_vector into a pair of horizontal
5614 // add/sub if we can emit a pair of scalar add/sub.
5615 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5618 // Convert this build_vector into a pair of horizontal binop followed by
5620 bool isUndefLO = NumUndefsLO == Half;
5621 bool isUndefHI = NumUndefsHI == Half;
5622 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5623 isUndefLO, isUndefHI);
5627 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5628 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5630 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5631 X86Opcode = X86ISD::HADD;
5632 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5633 X86Opcode = X86ISD::HSUB;
5634 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5635 X86Opcode = X86ISD::FHADD;
5636 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5637 X86Opcode = X86ISD::FHSUB;
5641 // Don't try to expand this build_vector into a pair of horizontal add/sub
5642 // if we can simply emit a pair of scalar add/sub.
5643 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5646 // Convert this build_vector into two horizontal add/sub followed by
5648 bool isUndefLO = NumUndefsLO == Half;
5649 bool isUndefHI = NumUndefsHI == Half;
5650 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5651 isUndefLO, isUndefHI);
5658 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5661 MVT VT = Op.getSimpleValueType();
5662 MVT ExtVT = VT.getVectorElementType();
5663 unsigned NumElems = Op.getNumOperands();
5665 // Generate vectors for predicate vectors.
5666 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5667 return LowerBUILD_VECTORvXi1(Op, DAG);
5669 // Vectors containing all zeros can be matched by pxor and xorps later
5670 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5671 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5672 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5673 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5676 return getZeroVector(VT, Subtarget, DAG, dl);
5679 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5680 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5681 // vpcmpeqd on 256-bit vectors.
5682 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5683 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5686 if (!VT.is512BitVector())
5687 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5690 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5691 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5693 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5694 return HorizontalOp;
5695 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5698 unsigned EVTBits = ExtVT.getSizeInBits();
5700 unsigned NumZero = 0;
5701 unsigned NumNonZero = 0;
5702 unsigned NonZeros = 0;
5703 bool IsAllConstants = true;
5704 SmallSet<SDValue, 8> Values;
5705 for (unsigned i = 0; i < NumElems; ++i) {
5706 SDValue Elt = Op.getOperand(i);
5707 if (Elt.getOpcode() == ISD::UNDEF)
5710 if (Elt.getOpcode() != ISD::Constant &&
5711 Elt.getOpcode() != ISD::ConstantFP)
5712 IsAllConstants = false;
5713 if (X86::isZeroNode(Elt))
5716 NonZeros |= (1 << i);
5721 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5722 if (NumNonZero == 0)
5723 return DAG.getUNDEF(VT);
5725 // Special case for single non-zero, non-undef, element.
5726 if (NumNonZero == 1) {
5727 unsigned Idx = countTrailingZeros(NonZeros);
5728 SDValue Item = Op.getOperand(Idx);
5730 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5731 // the value are obviously zero, truncate the value to i32 and do the
5732 // insertion that way. Only do this if the value is non-constant or if the
5733 // value is a constant being inserted into element 0. It is cheaper to do
5734 // a constant pool load than it is to do a movd + shuffle.
5735 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5736 (!IsAllConstants || Idx == 0)) {
5737 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5739 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5740 EVT VecVT = MVT::v4i32;
5742 // Truncate the value (which may itself be a constant) to i32, and
5743 // convert it to a vector with movd (S2V+shuffle to zero extend).
5744 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5745 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5747 ISD::BITCAST, dl, VT,
5748 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5752 // If we have a constant or non-constant insertion into the low element of
5753 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5754 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5755 // depending on what the source datatype is.
5758 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5760 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5761 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5762 if (VT.is512BitVector()) {
5763 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5764 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5765 Item, DAG.getIntPtrConstant(0, dl));
5767 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5768 "Expected an SSE value type!");
5769 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5770 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5771 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5774 // We can't directly insert an i8 or i16 into a vector, so zero extend
5776 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5777 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5778 if (VT.is256BitVector()) {
5779 if (Subtarget->hasAVX()) {
5780 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5781 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5783 // Without AVX, we need to extend to a 128-bit vector and then
5784 // insert into the 256-bit vector.
5785 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5786 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5787 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5790 assert(VT.is128BitVector() && "Expected an SSE value type!");
5791 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5792 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5794 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5798 // Is it a vector logical left shift?
5799 if (NumElems == 2 && Idx == 1 &&
5800 X86::isZeroNode(Op.getOperand(0)) &&
5801 !X86::isZeroNode(Op.getOperand(1))) {
5802 unsigned NumBits = VT.getSizeInBits();
5803 return getVShift(true, VT,
5804 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5805 VT, Op.getOperand(1)),
5806 NumBits/2, DAG, *this, dl);
5809 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5812 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5813 // is a non-constant being inserted into an element other than the low one,
5814 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5815 // movd/movss) to move this into the low element, then shuffle it into
5817 if (EVTBits == 32) {
5818 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5819 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5823 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5824 if (Values.size() == 1) {
5825 if (EVTBits == 32) {
5826 // Instead of a shuffle like this:
5827 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5828 // Check if it's possible to issue this instead.
5829 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5830 unsigned Idx = countTrailingZeros(NonZeros);
5831 SDValue Item = Op.getOperand(Idx);
5832 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5833 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5838 // A vector full of immediates; various special cases are already
5839 // handled, so this is best done with a single constant-pool load.
5843 // For AVX-length vectors, see if we can use a vector load to get all of the
5844 // elements, otherwise build the individual 128-bit pieces and use
5845 // shuffles to put them in place.
5846 if (VT.is256BitVector() || VT.is512BitVector()) {
5847 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5849 // Check for a build vector of consecutive loads.
5850 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5853 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5855 // Build both the lower and upper subvector.
5856 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5857 makeArrayRef(&V[0], NumElems/2));
5858 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5859 makeArrayRef(&V[NumElems / 2], NumElems/2));
5861 // Recreate the wider vector with the lower and upper part.
5862 if (VT.is256BitVector())
5863 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5864 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5867 // Let legalizer expand 2-wide build_vectors.
5868 if (EVTBits == 64) {
5869 if (NumNonZero == 1) {
5870 // One half is zero or undef.
5871 unsigned Idx = countTrailingZeros(NonZeros);
5872 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5873 Op.getOperand(Idx));
5874 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5879 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5880 if (EVTBits == 8 && NumElems == 16)
5881 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5885 if (EVTBits == 16 && NumElems == 8)
5886 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5890 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5891 if (EVTBits == 32 && NumElems == 4)
5892 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5895 // If element VT is == 32 bits, turn it into a number of shuffles.
5896 SmallVector<SDValue, 8> V(NumElems);
5897 if (NumElems == 4 && NumZero > 0) {
5898 for (unsigned i = 0; i < 4; ++i) {
5899 bool isZero = !(NonZeros & (1 << i));
5901 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5903 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5906 for (unsigned i = 0; i < 2; ++i) {
5907 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5910 V[i] = V[i*2]; // Must be a zero vector.
5913 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5916 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5919 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5924 bool Reverse1 = (NonZeros & 0x3) == 2;
5925 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5929 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5930 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5932 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5935 if (Values.size() > 1 && VT.is128BitVector()) {
5936 // Check for a build vector of consecutive loads.
5937 for (unsigned i = 0; i < NumElems; ++i)
5938 V[i] = Op.getOperand(i);
5940 // Check for elements which are consecutive loads.
5941 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5944 // Check for a build vector from mostly shuffle plus few inserting.
5945 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5948 // For SSE 4.1, use insertps to put the high elements into the low element.
5949 if (Subtarget->hasSSE41()) {
5951 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5952 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5954 Result = DAG.getUNDEF(VT);
5956 for (unsigned i = 1; i < NumElems; ++i) {
5957 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5958 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5959 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5964 // Otherwise, expand into a number of unpckl*, start by extending each of
5965 // our (non-undef) elements to the full vector width with the element in the
5966 // bottom slot of the vector (which generates no code for SSE).
5967 for (unsigned i = 0; i < NumElems; ++i) {
5968 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5969 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5971 V[i] = DAG.getUNDEF(VT);
5974 // Next, we iteratively mix elements, e.g. for v4f32:
5975 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5976 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5977 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5978 unsigned EltStride = NumElems >> 1;
5979 while (EltStride != 0) {
5980 for (unsigned i = 0; i < EltStride; ++i) {
5981 // If V[i+EltStride] is undef and this is the first round of mixing,
5982 // then it is safe to just drop this shuffle: V[i] is already in the
5983 // right place, the one element (since it's the first round) being
5984 // inserted as undef can be dropped. This isn't safe for successive
5985 // rounds because they will permute elements within both vectors.
5986 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5987 EltStride == NumElems/2)
5990 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5999 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6000 // to create 256-bit vectors from two other 128-bit ones.
6001 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6003 MVT ResVT = Op.getSimpleValueType();
6005 assert((ResVT.is256BitVector() ||
6006 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6008 SDValue V1 = Op.getOperand(0);
6009 SDValue V2 = Op.getOperand(1);
6010 unsigned NumElems = ResVT.getVectorNumElements();
6011 if (ResVT.is256BitVector())
6012 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6014 if (Op.getNumOperands() == 4) {
6015 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6016 ResVT.getVectorNumElements()/2);
6017 SDValue V3 = Op.getOperand(2);
6018 SDValue V4 = Op.getOperand(3);
6019 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6020 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6022 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6025 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6026 const X86Subtarget *Subtarget,
6027 SelectionDAG & DAG) {
6029 MVT ResVT = Op.getSimpleValueType();
6030 unsigned NumOfOperands = Op.getNumOperands();
6032 assert(isPowerOf2_32(NumOfOperands) &&
6033 "Unexpected number of operands in CONCAT_VECTORS");
6035 if (NumOfOperands > 2) {
6036 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6037 ResVT.getVectorNumElements()/2);
6038 SmallVector<SDValue, 2> Ops;
6039 for (unsigned i = 0; i < NumOfOperands/2; i++)
6040 Ops.push_back(Op.getOperand(i));
6041 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6043 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6044 Ops.push_back(Op.getOperand(i));
6045 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6046 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6049 SDValue V1 = Op.getOperand(0);
6050 SDValue V2 = Op.getOperand(1);
6051 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6052 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6054 if (IsZeroV1 && IsZeroV2)
6055 return getZeroVector(ResVT, Subtarget, DAG, dl);
6057 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6058 SDValue Undef = DAG.getUNDEF(ResVT);
6059 unsigned NumElems = ResVT.getVectorNumElements();
6060 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6062 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6063 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6067 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6068 // Zero the upper bits of V1
6069 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6070 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6073 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6076 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6077 const X86Subtarget *Subtarget,
6078 SelectionDAG &DAG) {
6079 MVT VT = Op.getSimpleValueType();
6080 if (VT.getVectorElementType() == MVT::i1)
6081 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6083 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6084 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6085 Op.getNumOperands() == 4)));
6087 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6088 // from two other 128-bit ones.
6090 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6091 return LowerAVXCONCAT_VECTORS(Op, DAG);
6095 //===----------------------------------------------------------------------===//
6096 // Vector shuffle lowering
6098 // This is an experimental code path for lowering vector shuffles on x86. It is
6099 // designed to handle arbitrary vector shuffles and blends, gracefully
6100 // degrading performance as necessary. It works hard to recognize idiomatic
6101 // shuffles and lower them to optimal instruction patterns without leaving
6102 // a framework that allows reasonably efficient handling of all vector shuffle
6104 //===----------------------------------------------------------------------===//
6106 /// \brief Tiny helper function to identify a no-op mask.
6108 /// This is a somewhat boring predicate function. It checks whether the mask
6109 /// array input, which is assumed to be a single-input shuffle mask of the kind
6110 /// used by the X86 shuffle instructions (not a fully general
6111 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6112 /// in-place shuffle are 'no-op's.
6113 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6114 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6115 if (Mask[i] != -1 && Mask[i] != i)
6120 /// \brief Helper function to classify a mask as a single-input mask.
6122 /// This isn't a generic single-input test because in the vector shuffle
6123 /// lowering we canonicalize single inputs to be the first input operand. This
6124 /// means we can more quickly test for a single input by only checking whether
6125 /// an input from the second operand exists. We also assume that the size of
6126 /// mask corresponds to the size of the input vectors which isn't true in the
6127 /// fully general case.
6128 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6130 if (M >= (int)Mask.size())
6135 /// \brief Test whether there are elements crossing 128-bit lanes in this
6138 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6139 /// and we routinely test for these.
6140 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6141 int LaneSize = 128 / VT.getScalarSizeInBits();
6142 int Size = Mask.size();
6143 for (int i = 0; i < Size; ++i)
6144 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6149 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6151 /// This checks a shuffle mask to see if it is performing the same
6152 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6153 /// that it is also not lane-crossing. It may however involve a blend from the
6154 /// same lane of a second vector.
6156 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6157 /// non-trivial to compute in the face of undef lanes. The representation is
6158 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6159 /// entries from both V1 and V2 inputs to the wider mask.
6161 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6162 SmallVectorImpl<int> &RepeatedMask) {
6163 int LaneSize = 128 / VT.getScalarSizeInBits();
6164 RepeatedMask.resize(LaneSize, -1);
6165 int Size = Mask.size();
6166 for (int i = 0; i < Size; ++i) {
6169 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6170 // This entry crosses lanes, so there is no way to model this shuffle.
6173 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6174 if (RepeatedMask[i % LaneSize] == -1)
6175 // This is the first non-undef entry in this slot of a 128-bit lane.
6176 RepeatedMask[i % LaneSize] =
6177 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6178 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6179 // Found a mismatch with the repeated mask.
6185 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6188 /// This is a fast way to test a shuffle mask against a fixed pattern:
6190 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6192 /// It returns true if the mask is exactly as wide as the argument list, and
6193 /// each element of the mask is either -1 (signifying undef) or the value given
6194 /// in the argument.
6195 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6196 ArrayRef<int> ExpectedMask) {
6197 if (Mask.size() != ExpectedMask.size())
6200 int Size = Mask.size();
6202 // If the values are build vectors, we can look through them to find
6203 // equivalent inputs that make the shuffles equivalent.
6204 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6205 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6207 for (int i = 0; i < Size; ++i)
6208 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6209 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6210 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6211 if (!MaskBV || !ExpectedBV ||
6212 MaskBV->getOperand(Mask[i] % Size) !=
6213 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6220 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6222 /// This helper function produces an 8-bit shuffle immediate corresponding to
6223 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6224 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6227 /// NB: We rely heavily on "undef" masks preserving the input lane.
6228 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6229 SelectionDAG &DAG) {
6230 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6231 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6232 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6233 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6234 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6237 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6238 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6239 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6240 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6241 return DAG.getConstant(Imm, DL, MVT::i8);
6244 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6246 /// This is used as a fallback approach when first class blend instructions are
6247 /// unavailable. Currently it is only suitable for integer vectors, but could
6248 /// be generalized for floating point vectors if desirable.
6249 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6250 SDValue V2, ArrayRef<int> Mask,
6251 SelectionDAG &DAG) {
6252 assert(VT.isInteger() && "Only supports integer vector types!");
6253 MVT EltVT = VT.getScalarType();
6254 int NumEltBits = EltVT.getSizeInBits();
6255 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6256 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6258 SmallVector<SDValue, 16> MaskOps;
6259 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6260 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6261 return SDValue(); // Shuffled input!
6262 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6265 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6266 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6267 // We have to cast V2 around.
6268 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6269 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6270 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6271 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6272 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6273 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6276 /// \brief Try to emit a blend instruction for a shuffle.
6278 /// This doesn't do any checks for the availability of instructions for blending
6279 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6280 /// be matched in the backend with the type given. What it does check for is
6281 /// that the shuffle mask is in fact a blend.
6282 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6283 SDValue V2, ArrayRef<int> Mask,
6284 const X86Subtarget *Subtarget,
6285 SelectionDAG &DAG) {
6286 unsigned BlendMask = 0;
6287 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6288 if (Mask[i] >= Size) {
6289 if (Mask[i] != i + Size)
6290 return SDValue(); // Shuffled V2 input!
6291 BlendMask |= 1u << i;
6294 if (Mask[i] >= 0 && Mask[i] != i)
6295 return SDValue(); // Shuffled V1 input!
6297 switch (VT.SimpleTy) {
6302 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6303 DAG.getConstant(BlendMask, DL, MVT::i8));
6307 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6311 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6312 // that instruction.
6313 if (Subtarget->hasAVX2()) {
6314 // Scale the blend by the number of 32-bit dwords per element.
6315 int Scale = VT.getScalarSizeInBits() / 32;
6317 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6318 if (Mask[i] >= Size)
6319 for (int j = 0; j < Scale; ++j)
6320 BlendMask |= 1u << (i * Scale + j);
6322 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6323 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6324 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6325 return DAG.getNode(ISD::BITCAST, DL, VT,
6326 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6327 DAG.getConstant(BlendMask, DL, MVT::i8)));
6331 // For integer shuffles we need to expand the mask and cast the inputs to
6332 // v8i16s prior to blending.
6333 int Scale = 8 / VT.getVectorNumElements();
6335 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6336 if (Mask[i] >= Size)
6337 for (int j = 0; j < Scale; ++j)
6338 BlendMask |= 1u << (i * Scale + j);
6340 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6341 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6342 return DAG.getNode(ISD::BITCAST, DL, VT,
6343 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6344 DAG.getConstant(BlendMask, DL, MVT::i8)));
6348 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6349 SmallVector<int, 8> RepeatedMask;
6350 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6351 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6352 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6354 for (int i = 0; i < 8; ++i)
6355 if (RepeatedMask[i] >= 16)
6356 BlendMask |= 1u << i;
6357 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6358 DAG.getConstant(BlendMask, DL, MVT::i8));
6364 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6365 "256-bit byte-blends require AVX2 support!");
6367 // Scale the blend by the number of bytes per element.
6368 int Scale = VT.getScalarSizeInBits() / 8;
6370 // This form of blend is always done on bytes. Compute the byte vector
6372 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6374 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6375 // mix of LLVM's code generator and the x86 backend. We tell the code
6376 // generator that boolean values in the elements of an x86 vector register
6377 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6378 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6379 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6380 // of the element (the remaining are ignored) and 0 in that high bit would
6381 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6382 // the LLVM model for boolean values in vector elements gets the relevant
6383 // bit set, it is set backwards and over constrained relative to x86's
6385 SmallVector<SDValue, 32> VSELECTMask;
6386 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6387 for (int j = 0; j < Scale; ++j)
6388 VSELECTMask.push_back(
6389 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6390 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6393 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6394 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6396 ISD::BITCAST, DL, VT,
6397 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6398 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6403 llvm_unreachable("Not a supported integer vector type!");
6407 /// \brief Try to lower as a blend of elements from two inputs followed by
6408 /// a single-input permutation.
6410 /// This matches the pattern where we can blend elements from two inputs and
6411 /// then reduce the shuffle to a single-input permutation.
6412 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6415 SelectionDAG &DAG) {
6416 // We build up the blend mask while checking whether a blend is a viable way
6417 // to reduce the shuffle.
6418 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6419 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6421 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6425 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6427 if (BlendMask[Mask[i] % Size] == -1)
6428 BlendMask[Mask[i] % Size] = Mask[i];
6429 else if (BlendMask[Mask[i] % Size] != Mask[i])
6430 return SDValue(); // Can't blend in the needed input!
6432 PermuteMask[i] = Mask[i] % Size;
6435 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6436 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6439 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6440 /// blends and permutes.
6442 /// This matches the extremely common pattern for handling combined
6443 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6444 /// operations. It will try to pick the best arrangement of shuffles and
6446 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6450 SelectionDAG &DAG) {
6451 // Shuffle the input elements into the desired positions in V1 and V2 and
6452 // blend them together.
6453 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6454 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6455 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6456 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6457 if (Mask[i] >= 0 && Mask[i] < Size) {
6458 V1Mask[i] = Mask[i];
6460 } else if (Mask[i] >= Size) {
6461 V2Mask[i] = Mask[i] - Size;
6462 BlendMask[i] = i + Size;
6465 // Try to lower with the simpler initial blend strategy unless one of the
6466 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6467 // shuffle may be able to fold with a load or other benefit. However, when
6468 // we'll have to do 2x as many shuffles in order to achieve this, blending
6469 // first is a better strategy.
6470 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6471 if (SDValue BlendPerm =
6472 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6475 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6476 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6477 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6480 /// \brief Try to lower a vector shuffle as a byte rotation.
6482 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6483 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6484 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6485 /// try to generically lower a vector shuffle through such an pattern. It
6486 /// does not check for the profitability of lowering either as PALIGNR or
6487 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6488 /// This matches shuffle vectors that look like:
6490 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6492 /// Essentially it concatenates V1 and V2, shifts right by some number of
6493 /// elements, and takes the low elements as the result. Note that while this is
6494 /// specified as a *right shift* because x86 is little-endian, it is a *left
6495 /// rotate* of the vector lanes.
6496 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6499 const X86Subtarget *Subtarget,
6500 SelectionDAG &DAG) {
6501 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6503 int NumElts = Mask.size();
6504 int NumLanes = VT.getSizeInBits() / 128;
6505 int NumLaneElts = NumElts / NumLanes;
6507 // We need to detect various ways of spelling a rotation:
6508 // [11, 12, 13, 14, 15, 0, 1, 2]
6509 // [-1, 12, 13, 14, -1, -1, 1, -1]
6510 // [-1, -1, -1, -1, -1, -1, 1, 2]
6511 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6512 // [-1, 4, 5, 6, -1, -1, 9, -1]
6513 // [-1, 4, 5, 6, -1, -1, -1, -1]
6516 for (int l = 0; l < NumElts; l += NumLaneElts) {
6517 for (int i = 0; i < NumLaneElts; ++i) {
6518 if (Mask[l + i] == -1)
6520 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6522 // Get the mod-Size index and lane correct it.
6523 int LaneIdx = (Mask[l + i] % NumElts) - l;
6524 // Make sure it was in this lane.
6525 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6528 // Determine where a rotated vector would have started.
6529 int StartIdx = i - LaneIdx;
6531 // The identity rotation isn't interesting, stop.
6534 // If we found the tail of a vector the rotation must be the missing
6535 // front. If we found the head of a vector, it must be how much of the
6537 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6540 Rotation = CandidateRotation;
6541 else if (Rotation != CandidateRotation)
6542 // The rotations don't match, so we can't match this mask.
6545 // Compute which value this mask is pointing at.
6546 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6548 // Compute which of the two target values this index should be assigned
6549 // to. This reflects whether the high elements are remaining or the low
6550 // elements are remaining.
6551 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6553 // Either set up this value if we've not encountered it before, or check
6554 // that it remains consistent.
6557 else if (TargetV != MaskV)
6558 // This may be a rotation, but it pulls from the inputs in some
6559 // unsupported interleaving.
6564 // Check that we successfully analyzed the mask, and normalize the results.
6565 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6566 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6572 // The actual rotate instruction rotates bytes, so we need to scale the
6573 // rotation based on how many bytes are in the vector lane.
6574 int Scale = 16 / NumLaneElts;
6576 // SSSE3 targets can use the palignr instruction.
6577 if (Subtarget->hasSSSE3()) {
6578 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6579 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6580 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6581 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6583 return DAG.getNode(ISD::BITCAST, DL, VT,
6584 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6585 DAG.getConstant(Rotation * Scale, DL,
6589 assert(VT.getSizeInBits() == 128 &&
6590 "Rotate-based lowering only supports 128-bit lowering!");
6591 assert(Mask.size() <= 16 &&
6592 "Can shuffle at most 16 bytes in a 128-bit vector!");
6594 // Default SSE2 implementation
6595 int LoByteShift = 16 - Rotation * Scale;
6596 int HiByteShift = Rotation * Scale;
6598 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6599 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6600 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6602 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6603 DAG.getConstant(LoByteShift, DL, MVT::i8));
6604 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6605 DAG.getConstant(HiByteShift, DL, MVT::i8));
6606 return DAG.getNode(ISD::BITCAST, DL, VT,
6607 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6610 /// \brief Compute whether each element of a shuffle is zeroable.
6612 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6613 /// Either it is an undef element in the shuffle mask, the element of the input
6614 /// referenced is undef, or the element of the input referenced is known to be
6615 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6616 /// as many lanes with this technique as possible to simplify the remaining
6618 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6619 SDValue V1, SDValue V2) {
6620 SmallBitVector Zeroable(Mask.size(), false);
6622 while (V1.getOpcode() == ISD::BITCAST)
6623 V1 = V1->getOperand(0);
6624 while (V2.getOpcode() == ISD::BITCAST)
6625 V2 = V2->getOperand(0);
6627 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6628 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6630 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6632 // Handle the easy cases.
6633 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6638 // If this is an index into a build_vector node (which has the same number
6639 // of elements), dig out the input value and use it.
6640 SDValue V = M < Size ? V1 : V2;
6641 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6644 SDValue Input = V.getOperand(M % Size);
6645 // The UNDEF opcode check really should be dead code here, but not quite
6646 // worth asserting on (it isn't invalid, just unexpected).
6647 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6654 /// \brief Try to emit a bitmask instruction for a shuffle.
6656 /// This handles cases where we can model a blend exactly as a bitmask due to
6657 /// one of the inputs being zeroable.
6658 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6659 SDValue V2, ArrayRef<int> Mask,
6660 SelectionDAG &DAG) {
6661 MVT EltVT = VT.getScalarType();
6662 int NumEltBits = EltVT.getSizeInBits();
6663 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6664 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6665 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6667 if (EltVT.isFloatingPoint()) {
6668 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6669 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6671 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6672 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6674 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6677 if (Mask[i] % Size != i)
6678 return SDValue(); // Not a blend.
6680 V = Mask[i] < Size ? V1 : V2;
6681 else if (V != (Mask[i] < Size ? V1 : V2))
6682 return SDValue(); // Can only let one input through the mask.
6684 VMaskOps[i] = AllOnes;
6687 return SDValue(); // No non-zeroable elements!
6689 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6690 V = DAG.getNode(VT.isFloatingPoint()
6691 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6696 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6698 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6699 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6700 /// matches elements from one of the input vectors shuffled to the left or
6701 /// right with zeroable elements 'shifted in'. It handles both the strictly
6702 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6705 /// PSHL : (little-endian) left bit shift.
6706 /// [ zz, 0, zz, 2 ]
6707 /// [ -1, 4, zz, -1 ]
6708 /// PSRL : (little-endian) right bit shift.
6710 /// [ -1, -1, 7, zz]
6711 /// PSLLDQ : (little-endian) left byte shift
6712 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6713 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6714 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6715 /// PSRLDQ : (little-endian) right byte shift
6716 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6717 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6718 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6719 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6720 SDValue V2, ArrayRef<int> Mask,
6721 SelectionDAG &DAG) {
6722 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6724 int Size = Mask.size();
6725 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6727 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6728 for (int i = 0; i < Size; i += Scale)
6729 for (int j = 0; j < Shift; ++j)
6730 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6736 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6737 for (int i = 0; i != Size; i += Scale) {
6738 unsigned Pos = Left ? i + Shift : i;
6739 unsigned Low = Left ? i : i + Shift;
6740 unsigned Len = Scale - Shift;
6741 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6742 Low + (V == V1 ? 0 : Size)))
6746 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6747 bool ByteShift = ShiftEltBits > 64;
6748 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6749 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6750 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6752 // Normalize the scale for byte shifts to still produce an i64 element
6754 Scale = ByteShift ? Scale / 2 : Scale;
6756 // We need to round trip through the appropriate type for the shift.
6757 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6758 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6759 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6760 "Illegal integer vector type");
6761 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6763 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6764 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6765 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6768 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6769 // keep doubling the size of the integer elements up to that. We can
6770 // then shift the elements of the integer vector by whole multiples of
6771 // their width within the elements of the larger integer vector. Test each
6772 // multiple to see if we can find a match with the moved element indices
6773 // and that the shifted in elements are all zeroable.
6774 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6775 for (int Shift = 1; Shift != Scale; ++Shift)
6776 for (bool Left : {true, false})
6777 if (CheckZeros(Shift, Scale, Left))
6778 for (SDValue V : {V1, V2})
6779 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6786 /// \brief Lower a vector shuffle as a zero or any extension.
6788 /// Given a specific number of elements, element bit width, and extension
6789 /// stride, produce either a zero or any extension based on the available
6790 /// features of the subtarget.
6791 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6792 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6793 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6794 assert(Scale > 1 && "Need a scale to extend.");
6795 int NumElements = VT.getVectorNumElements();
6796 int EltBits = VT.getScalarSizeInBits();
6797 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6798 "Only 8, 16, and 32 bit elements can be extended.");
6799 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6801 // Found a valid zext mask! Try various lowering strategies based on the
6802 // input type and available ISA extensions.
6803 if (Subtarget->hasSSE41()) {
6804 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6805 NumElements / Scale);
6806 return DAG.getNode(ISD::BITCAST, DL, VT,
6807 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6810 // For any extends we can cheat for larger element sizes and use shuffle
6811 // instructions that can fold with a load and/or copy.
6812 if (AnyExt && EltBits == 32) {
6813 int PSHUFDMask[4] = {0, -1, 1, -1};
6815 ISD::BITCAST, DL, VT,
6816 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6817 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6818 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6820 if (AnyExt && EltBits == 16 && Scale > 2) {
6821 int PSHUFDMask[4] = {0, -1, 0, -1};
6822 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6823 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6824 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6825 int PSHUFHWMask[4] = {1, -1, -1, -1};
6827 ISD::BITCAST, DL, VT,
6828 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6829 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6830 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6833 // If this would require more than 2 unpack instructions to expand, use
6834 // pshufb when available. We can only use more than 2 unpack instructions
6835 // when zero extending i8 elements which also makes it easier to use pshufb.
6836 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6837 assert(NumElements == 16 && "Unexpected byte vector width!");
6838 SDValue PSHUFBMask[16];
6839 for (int i = 0; i < 16; ++i)
6841 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6842 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6843 return DAG.getNode(ISD::BITCAST, DL, VT,
6844 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6845 DAG.getNode(ISD::BUILD_VECTOR, DL,
6846 MVT::v16i8, PSHUFBMask)));
6849 // Otherwise emit a sequence of unpacks.
6851 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6852 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6853 : getZeroVector(InputVT, Subtarget, DAG, DL);
6854 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6855 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6859 } while (Scale > 1);
6860 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6863 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6865 /// This routine will try to do everything in its power to cleverly lower
6866 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6867 /// check for the profitability of this lowering, it tries to aggressively
6868 /// match this pattern. It will use all of the micro-architectural details it
6869 /// can to emit an efficient lowering. It handles both blends with all-zero
6870 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6871 /// masking out later).
6873 /// The reason we have dedicated lowering for zext-style shuffles is that they
6874 /// are both incredibly common and often quite performance sensitive.
6875 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6876 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6877 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6878 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6880 int Bits = VT.getSizeInBits();
6881 int NumElements = VT.getVectorNumElements();
6882 assert(VT.getScalarSizeInBits() <= 32 &&
6883 "Exceeds 32-bit integer zero extension limit");
6884 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6886 // Define a helper function to check a particular ext-scale and lower to it if
6888 auto Lower = [&](int Scale) -> SDValue {
6891 for (int i = 0; i < NumElements; ++i) {
6893 continue; // Valid anywhere but doesn't tell us anything.
6894 if (i % Scale != 0) {
6895 // Each of the extended elements need to be zeroable.
6899 // We no longer are in the anyext case.
6904 // Each of the base elements needs to be consecutive indices into the
6905 // same input vector.
6906 SDValue V = Mask[i] < NumElements ? V1 : V2;
6909 else if (InputV != V)
6910 return SDValue(); // Flip-flopping inputs.
6912 if (Mask[i] % NumElements != i / Scale)
6913 return SDValue(); // Non-consecutive strided elements.
6916 // If we fail to find an input, we have a zero-shuffle which should always
6917 // have already been handled.
6918 // FIXME: Maybe handle this here in case during blending we end up with one?
6922 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6923 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6926 // The widest scale possible for extending is to a 64-bit integer.
6927 assert(Bits % 64 == 0 &&
6928 "The number of bits in a vector must be divisible by 64 on x86!");
6929 int NumExtElements = Bits / 64;
6931 // Each iteration, try extending the elements half as much, but into twice as
6933 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6934 assert(NumElements % NumExtElements == 0 &&
6935 "The input vector size must be divisible by the extended size.");
6936 if (SDValue V = Lower(NumElements / NumExtElements))
6940 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6944 // Returns one of the source operands if the shuffle can be reduced to a
6945 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6946 auto CanZExtLowHalf = [&]() {
6947 for (int i = NumElements / 2; i != NumElements; ++i)
6950 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6952 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6957 if (SDValue V = CanZExtLowHalf()) {
6958 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6959 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6960 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6963 // No viable ext lowering found.
6967 /// \brief Try to get a scalar value for a specific element of a vector.
6969 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6970 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6971 SelectionDAG &DAG) {
6972 MVT VT = V.getSimpleValueType();
6973 MVT EltVT = VT.getVectorElementType();
6974 while (V.getOpcode() == ISD::BITCAST)
6975 V = V.getOperand(0);
6976 // If the bitcasts shift the element size, we can't extract an equivalent
6978 MVT NewVT = V.getSimpleValueType();
6979 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6982 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6983 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6984 // Ensure the scalar operand is the same size as the destination.
6985 // FIXME: Add support for scalar truncation where possible.
6986 SDValue S = V.getOperand(Idx);
6987 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6988 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
6994 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6996 /// This is particularly important because the set of instructions varies
6997 /// significantly based on whether the operand is a load or not.
6998 static bool isShuffleFoldableLoad(SDValue V) {
6999 while (V.getOpcode() == ISD::BITCAST)
7000 V = V.getOperand(0);
7002 return ISD::isNON_EXTLoad(V.getNode());
7005 /// \brief Try to lower insertion of a single element into a zero vector.
7007 /// This is a common pattern that we have especially efficient patterns to lower
7008 /// across all subtarget feature sets.
7009 static SDValue lowerVectorShuffleAsElementInsertion(
7010 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7011 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7012 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7014 MVT EltVT = VT.getVectorElementType();
7016 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7017 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7019 bool IsV1Zeroable = true;
7020 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7021 if (i != V2Index && !Zeroable[i]) {
7022 IsV1Zeroable = false;
7026 // Check for a single input from a SCALAR_TO_VECTOR node.
7027 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7028 // all the smarts here sunk into that routine. However, the current
7029 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7030 // vector shuffle lowering is dead.
7031 if (SDValue V2S = getScalarValueForVectorElement(
7032 V2, Mask[V2Index] - Mask.size(), DAG)) {
7033 // We need to zext the scalar if it is smaller than an i32.
7034 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7035 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7036 // Using zext to expand a narrow element won't work for non-zero
7041 // Zero-extend directly to i32.
7043 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7045 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7046 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7047 EltVT == MVT::i16) {
7048 // Either not inserting from the low element of the input or the input
7049 // element size is too small to use VZEXT_MOVL to clear the high bits.
7053 if (!IsV1Zeroable) {
7054 // If V1 can't be treated as a zero vector we have fewer options to lower
7055 // this. We can't support integer vectors or non-zero targets cheaply, and
7056 // the V1 elements can't be permuted in any way.
7057 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7058 if (!VT.isFloatingPoint() || V2Index != 0)
7060 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7061 V1Mask[V2Index] = -1;
7062 if (!isNoopShuffleMask(V1Mask))
7064 // This is essentially a special case blend operation, but if we have
7065 // general purpose blend operations, they are always faster. Bail and let
7066 // the rest of the lowering handle these as blends.
7067 if (Subtarget->hasSSE41())
7070 // Otherwise, use MOVSD or MOVSS.
7071 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7072 "Only two types of floating point element types to handle!");
7073 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7077 // This lowering only works for the low element with floating point vectors.
7078 if (VT.isFloatingPoint() && V2Index != 0)
7081 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7083 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7086 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7087 // the desired position. Otherwise it is more efficient to do a vector
7088 // shift left. We know that we can do a vector shift left because all
7089 // the inputs are zero.
7090 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7091 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7092 V2Shuffle[V2Index] = 0;
7093 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7095 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7097 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7099 V2Index * EltVT.getSizeInBits()/8, DL,
7100 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7101 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7107 /// \brief Try to lower broadcast of a single element.
7109 /// For convenience, this code also bundles all of the subtarget feature set
7110 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7111 /// a convenient way to factor it out.
7112 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7114 const X86Subtarget *Subtarget,
7115 SelectionDAG &DAG) {
7116 if (!Subtarget->hasAVX())
7118 if (VT.isInteger() && !Subtarget->hasAVX2())
7121 // Check that the mask is a broadcast.
7122 int BroadcastIdx = -1;
7124 if (M >= 0 && BroadcastIdx == -1)
7126 else if (M >= 0 && M != BroadcastIdx)
7129 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7130 "a sorted mask where the broadcast "
7133 // Go up the chain of (vector) values to find a scalar load that we can
7134 // combine with the broadcast.
7136 switch (V.getOpcode()) {
7137 case ISD::CONCAT_VECTORS: {
7138 int OperandSize = Mask.size() / V.getNumOperands();
7139 V = V.getOperand(BroadcastIdx / OperandSize);
7140 BroadcastIdx %= OperandSize;
7144 case ISD::INSERT_SUBVECTOR: {
7145 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7146 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7150 int BeginIdx = (int)ConstantIdx->getZExtValue();
7152 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7153 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7154 BroadcastIdx -= BeginIdx;
7165 // Check if this is a broadcast of a scalar. We special case lowering
7166 // for scalars so that we can more effectively fold with loads.
7167 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7168 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7169 V = V.getOperand(BroadcastIdx);
7171 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7172 // Only AVX2 has register broadcasts.
7173 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7175 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7176 // We can't broadcast from a vector register without AVX2, and we can only
7177 // broadcast from the zero-element of a vector register.
7181 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7184 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7185 // INSERTPS when the V1 elements are already in the correct locations
7186 // because otherwise we can just always use two SHUFPS instructions which
7187 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7188 // perform INSERTPS if a single V1 element is out of place and all V2
7189 // elements are zeroable.
7190 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7192 SelectionDAG &DAG) {
7193 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7194 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7195 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7196 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7198 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7201 int V1DstIndex = -1;
7202 int V2DstIndex = -1;
7203 bool V1UsedInPlace = false;
7205 for (int i = 0; i < 4; ++i) {
7206 // Synthesize a zero mask from the zeroable elements (includes undefs).
7212 // Flag if we use any V1 inputs in place.
7214 V1UsedInPlace = true;
7218 // We can only insert a single non-zeroable element.
7219 if (V1DstIndex != -1 || V2DstIndex != -1)
7223 // V1 input out of place for insertion.
7226 // V2 input for insertion.
7231 // Don't bother if we have no (non-zeroable) element for insertion.
7232 if (V1DstIndex == -1 && V2DstIndex == -1)
7235 // Determine element insertion src/dst indices. The src index is from the
7236 // start of the inserted vector, not the start of the concatenated vector.
7237 unsigned V2SrcIndex = 0;
7238 if (V1DstIndex != -1) {
7239 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7240 // and don't use the original V2 at all.
7241 V2SrcIndex = Mask[V1DstIndex];
7242 V2DstIndex = V1DstIndex;
7245 V2SrcIndex = Mask[V2DstIndex] - 4;
7248 // If no V1 inputs are used in place, then the result is created only from
7249 // the zero mask and the V2 insertion - so remove V1 dependency.
7251 V1 = DAG.getUNDEF(MVT::v4f32);
7253 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7254 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7256 // Insert the V2 element into the desired position.
7258 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7259 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7262 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7263 /// UNPCK instruction.
7265 /// This specifically targets cases where we end up with alternating between
7266 /// the two inputs, and so can permute them into something that feeds a single
7267 /// UNPCK instruction. Note that this routine only targets integer vectors
7268 /// because for floating point vectors we have a generalized SHUFPS lowering
7269 /// strategy that handles everything that doesn't *exactly* match an unpack,
7270 /// making this clever lowering unnecessary.
7271 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7272 SDValue V2, ArrayRef<int> Mask,
7273 SelectionDAG &DAG) {
7274 assert(!VT.isFloatingPoint() &&
7275 "This routine only supports integer vectors.");
7276 assert(!isSingleInputShuffleMask(Mask) &&
7277 "This routine should only be used when blending two inputs.");
7278 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7280 int Size = Mask.size();
7282 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7283 return M >= 0 && M % Size < Size / 2;
7285 int NumHiInputs = std::count_if(
7286 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7288 bool UnpackLo = NumLoInputs >= NumHiInputs;
7290 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7291 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7292 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7294 for (int i = 0; i < Size; ++i) {
7298 // Each element of the unpack contains Scale elements from this mask.
7299 int UnpackIdx = i / Scale;
7301 // We only handle the case where V1 feeds the first slots of the unpack.
7302 // We rely on canonicalization to ensure this is the case.
7303 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7306 // Setup the mask for this input. The indexing is tricky as we have to
7307 // handle the unpack stride.
7308 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7309 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7313 // If we will have to shuffle both inputs to use the unpack, check whether
7314 // we can just unpack first and shuffle the result. If so, skip this unpack.
7315 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7316 !isNoopShuffleMask(V2Mask))
7319 // Shuffle the inputs into place.
7320 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7321 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7323 // Cast the inputs to the type we will use to unpack them.
7324 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7325 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7327 // Unpack the inputs and cast the result back to the desired type.
7328 return DAG.getNode(ISD::BITCAST, DL, VT,
7329 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7330 DL, UnpackVT, V1, V2));
7333 // We try each unpack from the largest to the smallest to try and find one
7334 // that fits this mask.
7335 int OrigNumElements = VT.getVectorNumElements();
7336 int OrigScalarSize = VT.getScalarSizeInBits();
7337 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7338 int Scale = ScalarSize / OrigScalarSize;
7339 int NumElements = OrigNumElements / Scale;
7340 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7341 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7345 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7347 if (NumLoInputs == 0 || NumHiInputs == 0) {
7348 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7349 "We have to have *some* inputs!");
7350 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7352 // FIXME: We could consider the total complexity of the permute of each
7353 // possible unpacking. Or at the least we should consider how many
7354 // half-crossings are created.
7355 // FIXME: We could consider commuting the unpacks.
7357 SmallVector<int, 32> PermMask;
7358 PermMask.assign(Size, -1);
7359 for (int i = 0; i < Size; ++i) {
7363 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7366 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7368 return DAG.getVectorShuffle(
7369 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7371 DAG.getUNDEF(VT), PermMask);
7377 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7379 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7380 /// support for floating point shuffles but not integer shuffles. These
7381 /// instructions will incur a domain crossing penalty on some chips though so
7382 /// it is better to avoid lowering through this for integer vectors where
7384 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7385 const X86Subtarget *Subtarget,
7386 SelectionDAG &DAG) {
7388 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7389 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7390 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7391 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7392 ArrayRef<int> Mask = SVOp->getMask();
7393 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7395 if (isSingleInputShuffleMask(Mask)) {
7396 // Use low duplicate instructions for masks that match their pattern.
7397 if (Subtarget->hasSSE3())
7398 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7399 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7401 // Straight shuffle of a single input vector. Simulate this by using the
7402 // single input as both of the "inputs" to this instruction..
7403 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7405 if (Subtarget->hasAVX()) {
7406 // If we have AVX, we can use VPERMILPS which will allow folding a load
7407 // into the shuffle.
7408 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7409 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7412 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7413 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7415 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7416 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7418 // If we have a single input, insert that into V1 if we can do so cheaply.
7419 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7420 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7421 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7423 // Try inverting the insertion since for v2 masks it is easy to do and we
7424 // can't reliably sort the mask one way or the other.
7425 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7426 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7427 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7428 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7432 // Try to use one of the special instruction patterns to handle two common
7433 // blend patterns if a zero-blend above didn't work.
7434 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7435 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7436 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7437 // We can either use a special instruction to load over the low double or
7438 // to move just the low double.
7440 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7442 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7444 if (Subtarget->hasSSE41())
7445 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7449 // Use dedicated unpack instructions for masks that match their pattern.
7450 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7451 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7452 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7453 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7455 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7456 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7457 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7460 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7462 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7463 /// the integer unit to minimize domain crossing penalties. However, for blends
7464 /// it falls back to the floating point shuffle operation with appropriate bit
7466 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7467 const X86Subtarget *Subtarget,
7468 SelectionDAG &DAG) {
7470 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7471 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7472 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7473 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7474 ArrayRef<int> Mask = SVOp->getMask();
7475 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7477 if (isSingleInputShuffleMask(Mask)) {
7478 // Check for being able to broadcast a single element.
7479 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7480 Mask, Subtarget, DAG))
7483 // Straight shuffle of a single input vector. For everything from SSE2
7484 // onward this has a single fast instruction with no scary immediates.
7485 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7486 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7487 int WidenedMask[4] = {
7488 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7489 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7491 ISD::BITCAST, DL, MVT::v2i64,
7492 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7493 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7495 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7496 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7497 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7498 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7500 // If we have a blend of two PACKUS operations an the blend aligns with the
7501 // low and half halves, we can just merge the PACKUS operations. This is
7502 // particularly important as it lets us merge shuffles that this routine itself
7504 auto GetPackNode = [](SDValue V) {
7505 while (V.getOpcode() == ISD::BITCAST)
7506 V = V.getOperand(0);
7508 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7510 if (SDValue V1Pack = GetPackNode(V1))
7511 if (SDValue V2Pack = GetPackNode(V2))
7512 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7513 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7514 Mask[0] == 0 ? V1Pack.getOperand(0)
7515 : V1Pack.getOperand(1),
7516 Mask[1] == 2 ? V2Pack.getOperand(0)
7517 : V2Pack.getOperand(1)));
7519 // Try to use shift instructions.
7521 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7524 // When loading a scalar and then shuffling it into a vector we can often do
7525 // the insertion cheaply.
7526 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7527 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7529 // Try inverting the insertion since for v2 masks it is easy to do and we
7530 // can't reliably sort the mask one way or the other.
7531 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7532 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7533 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7536 // We have different paths for blend lowering, but they all must use the
7537 // *exact* same predicate.
7538 bool IsBlendSupported = Subtarget->hasSSE41();
7539 if (IsBlendSupported)
7540 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7544 // Use dedicated unpack instructions for masks that match their pattern.
7545 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7546 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7547 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7548 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7550 // Try to use byte rotation instructions.
7551 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7552 if (Subtarget->hasSSSE3())
7553 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7554 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7557 // If we have direct support for blends, we should lower by decomposing into
7558 // a permute. That will be faster than the domain cross.
7559 if (IsBlendSupported)
7560 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7563 // We implement this with SHUFPD which is pretty lame because it will likely
7564 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7565 // However, all the alternatives are still more cycles and newer chips don't
7566 // have this problem. It would be really nice if x86 had better shuffles here.
7567 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7568 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7569 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7570 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7573 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7575 /// This is used to disable more specialized lowerings when the shufps lowering
7576 /// will happen to be efficient.
7577 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7578 // This routine only handles 128-bit shufps.
7579 assert(Mask.size() == 4 && "Unsupported mask size!");
7581 // To lower with a single SHUFPS we need to have the low half and high half
7582 // each requiring a single input.
7583 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7585 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7591 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7593 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7594 /// It makes no assumptions about whether this is the *best* lowering, it simply
7596 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7597 ArrayRef<int> Mask, SDValue V1,
7598 SDValue V2, SelectionDAG &DAG) {
7599 SDValue LowV = V1, HighV = V2;
7600 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7603 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7605 if (NumV2Elements == 1) {
7607 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7610 // Compute the index adjacent to V2Index and in the same half by toggling
7612 int V2AdjIndex = V2Index ^ 1;
7614 if (Mask[V2AdjIndex] == -1) {
7615 // Handles all the cases where we have a single V2 element and an undef.
7616 // This will only ever happen in the high lanes because we commute the
7617 // vector otherwise.
7619 std::swap(LowV, HighV);
7620 NewMask[V2Index] -= 4;
7622 // Handle the case where the V2 element ends up adjacent to a V1 element.
7623 // To make this work, blend them together as the first step.
7624 int V1Index = V2AdjIndex;
7625 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7626 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7627 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7629 // Now proceed to reconstruct the final blend as we have the necessary
7630 // high or low half formed.
7637 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7638 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7640 } else if (NumV2Elements == 2) {
7641 if (Mask[0] < 4 && Mask[1] < 4) {
7642 // Handle the easy case where we have V1 in the low lanes and V2 in the
7646 } else if (Mask[2] < 4 && Mask[3] < 4) {
7647 // We also handle the reversed case because this utility may get called
7648 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7649 // arrange things in the right direction.
7655 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7656 // trying to place elements directly, just blend them and set up the final
7657 // shuffle to place them.
7659 // The first two blend mask elements are for V1, the second two are for
7661 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7662 Mask[2] < 4 ? Mask[2] : Mask[3],
7663 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7664 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7665 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7666 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7668 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7671 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7672 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7673 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7674 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7677 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7678 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7681 /// \brief Lower 4-lane 32-bit floating point shuffles.
7683 /// Uses instructions exclusively from the floating point unit to minimize
7684 /// domain crossing penalties, as these are sufficient to implement all v4f32
7686 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7687 const X86Subtarget *Subtarget,
7688 SelectionDAG &DAG) {
7690 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7691 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7692 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7693 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7694 ArrayRef<int> Mask = SVOp->getMask();
7695 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7698 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7700 if (NumV2Elements == 0) {
7701 // Check for being able to broadcast a single element.
7702 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7703 Mask, Subtarget, DAG))
7706 // Use even/odd duplicate instructions for masks that match their pattern.
7707 if (Subtarget->hasSSE3()) {
7708 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7709 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7710 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7711 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7714 if (Subtarget->hasAVX()) {
7715 // If we have AVX, we can use VPERMILPS which will allow folding a load
7716 // into the shuffle.
7717 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7718 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7721 // Otherwise, use a straight shuffle of a single input vector. We pass the
7722 // input vector to both operands to simulate this with a SHUFPS.
7723 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7724 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7727 // There are special ways we can lower some single-element blends. However, we
7728 // have custom ways we can lower more complex single-element blends below that
7729 // we defer to if both this and BLENDPS fail to match, so restrict this to
7730 // when the V2 input is targeting element 0 of the mask -- that is the fast
7732 if (NumV2Elements == 1 && Mask[0] >= 4)
7733 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7734 Mask, Subtarget, DAG))
7737 if (Subtarget->hasSSE41()) {
7738 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7742 // Use INSERTPS if we can complete the shuffle efficiently.
7743 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7746 if (!isSingleSHUFPSMask(Mask))
7747 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7748 DL, MVT::v4f32, V1, V2, Mask, DAG))
7752 // Use dedicated unpack instructions for masks that match their pattern.
7753 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7754 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7755 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7756 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7757 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7758 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7759 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7760 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7762 // Otherwise fall back to a SHUFPS lowering strategy.
7763 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7766 /// \brief Lower 4-lane i32 vector shuffles.
7768 /// We try to handle these with integer-domain shuffles where we can, but for
7769 /// blends we use the floating point domain blend instructions.
7770 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7771 const X86Subtarget *Subtarget,
7772 SelectionDAG &DAG) {
7774 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7775 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7776 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7777 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7778 ArrayRef<int> Mask = SVOp->getMask();
7779 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7781 // Whenever we can lower this as a zext, that instruction is strictly faster
7782 // than any alternative. It also allows us to fold memory operands into the
7783 // shuffle in many cases.
7784 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7785 Mask, Subtarget, DAG))
7789 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7791 if (NumV2Elements == 0) {
7792 // Check for being able to broadcast a single element.
7793 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7794 Mask, Subtarget, DAG))
7797 // Straight shuffle of a single input vector. For everything from SSE2
7798 // onward this has a single fast instruction with no scary immediates.
7799 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7800 // but we aren't actually going to use the UNPCK instruction because doing
7801 // so prevents folding a load into this instruction or making a copy.
7802 const int UnpackLoMask[] = {0, 0, 1, 1};
7803 const int UnpackHiMask[] = {2, 2, 3, 3};
7804 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7805 Mask = UnpackLoMask;
7806 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7807 Mask = UnpackHiMask;
7809 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7810 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7813 // Try to use shift instructions.
7815 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7818 // There are special ways we can lower some single-element blends.
7819 if (NumV2Elements == 1)
7820 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7821 Mask, Subtarget, DAG))
7824 // We have different paths for blend lowering, but they all must use the
7825 // *exact* same predicate.
7826 bool IsBlendSupported = Subtarget->hasSSE41();
7827 if (IsBlendSupported)
7828 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7832 if (SDValue Masked =
7833 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7836 // Use dedicated unpack instructions for masks that match their pattern.
7837 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7838 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7839 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7840 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7841 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7842 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7843 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7844 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7846 // Try to use byte rotation instructions.
7847 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7848 if (Subtarget->hasSSSE3())
7849 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7850 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7853 // If we have direct support for blends, we should lower by decomposing into
7854 // a permute. That will be faster than the domain cross.
7855 if (IsBlendSupported)
7856 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7859 // Try to lower by permuting the inputs into an unpack instruction.
7860 if (SDValue Unpack =
7861 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7864 // We implement this with SHUFPS because it can blend from two vectors.
7865 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7866 // up the inputs, bypassing domain shift penalties that we would encur if we
7867 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7869 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7870 DAG.getVectorShuffle(
7872 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7873 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7876 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7877 /// shuffle lowering, and the most complex part.
7879 /// The lowering strategy is to try to form pairs of input lanes which are
7880 /// targeted at the same half of the final vector, and then use a dword shuffle
7881 /// to place them onto the right half, and finally unpack the paired lanes into
7882 /// their final position.
7884 /// The exact breakdown of how to form these dword pairs and align them on the
7885 /// correct sides is really tricky. See the comments within the function for
7886 /// more of the details.
7888 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7889 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7890 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7891 /// vector, form the analogous 128-bit 8-element Mask.
7892 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7893 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7894 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7895 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7896 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7898 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7899 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7900 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7902 SmallVector<int, 4> LoInputs;
7903 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7904 [](int M) { return M >= 0; });
7905 std::sort(LoInputs.begin(), LoInputs.end());
7906 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7907 SmallVector<int, 4> HiInputs;
7908 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7909 [](int M) { return M >= 0; });
7910 std::sort(HiInputs.begin(), HiInputs.end());
7911 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7913 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7914 int NumHToL = LoInputs.size() - NumLToL;
7916 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7917 int NumHToH = HiInputs.size() - NumLToH;
7918 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7919 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7920 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7921 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7923 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7924 // such inputs we can swap two of the dwords across the half mark and end up
7925 // with <=2 inputs to each half in each half. Once there, we can fall through
7926 // to the generic code below. For example:
7928 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7929 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7931 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7932 // and an existing 2-into-2 on the other half. In this case we may have to
7933 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7934 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7935 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7936 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7937 // half than the one we target for fixing) will be fixed when we re-enter this
7938 // path. We will also combine away any sequence of PSHUFD instructions that
7939 // result into a single instruction. Here is an example of the tricky case:
7941 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7942 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7944 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7946 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7947 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7949 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7950 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7952 // The result is fine to be handled by the generic logic.
7953 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7954 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7955 int AOffset, int BOffset) {
7956 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7957 "Must call this with A having 3 or 1 inputs from the A half.");
7958 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7959 "Must call this with B having 1 or 3 inputs from the B half.");
7960 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7961 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7963 // Compute the index of dword with only one word among the three inputs in
7964 // a half by taking the sum of the half with three inputs and subtracting
7965 // the sum of the actual three inputs. The difference is the remaining
7968 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7969 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7970 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7971 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7972 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7973 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7974 int TripleNonInputIdx =
7975 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7976 TripleDWord = TripleNonInputIdx / 2;
7978 // We use xor with one to compute the adjacent DWord to whichever one the
7980 OneInputDWord = (OneInput / 2) ^ 1;
7982 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7983 // and BToA inputs. If there is also such a problem with the BToB and AToB
7984 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7985 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7986 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7987 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7988 // Compute how many inputs will be flipped by swapping these DWords. We
7990 // to balance this to ensure we don't form a 3-1 shuffle in the other
7992 int NumFlippedAToBInputs =
7993 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7994 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7995 int NumFlippedBToBInputs =
7996 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7997 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7998 if ((NumFlippedAToBInputs == 1 &&
7999 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8000 (NumFlippedBToBInputs == 1 &&
8001 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8002 // We choose whether to fix the A half or B half based on whether that
8003 // half has zero flipped inputs. At zero, we may not be able to fix it
8004 // with that half. We also bias towards fixing the B half because that
8005 // will more commonly be the high half, and we have to bias one way.
8006 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8007 ArrayRef<int> Inputs) {
8008 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8009 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8010 PinnedIdx ^ 1) != Inputs.end();
8011 // Determine whether the free index is in the flipped dword or the
8012 // unflipped dword based on where the pinned index is. We use this bit
8013 // in an xor to conditionally select the adjacent dword.
8014 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8015 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8016 FixFreeIdx) != Inputs.end();
8017 if (IsFixIdxInput == IsFixFreeIdxInput)
8019 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8020 FixFreeIdx) != Inputs.end();
8021 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8022 "We need to be changing the number of flipped inputs!");
8023 int PSHUFHalfMask[] = {0, 1, 2, 3};
8024 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8025 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8027 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8030 if (M != -1 && M == FixIdx)
8032 else if (M != -1 && M == FixFreeIdx)
8035 if (NumFlippedBToBInputs != 0) {
8037 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8038 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8040 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8042 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8043 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8048 int PSHUFDMask[] = {0, 1, 2, 3};
8049 PSHUFDMask[ADWord] = BDWord;
8050 PSHUFDMask[BDWord] = ADWord;
8051 V = DAG.getNode(ISD::BITCAST, DL, VT,
8052 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8053 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8054 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8057 // Adjust the mask to match the new locations of A and B.
8059 if (M != -1 && M/2 == ADWord)
8060 M = 2 * BDWord + M % 2;
8061 else if (M != -1 && M/2 == BDWord)
8062 M = 2 * ADWord + M % 2;
8064 // Recurse back into this routine to re-compute state now that this isn't
8065 // a 3 and 1 problem.
8066 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8069 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8070 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8071 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8072 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8074 // At this point there are at most two inputs to the low and high halves from
8075 // each half. That means the inputs can always be grouped into dwords and
8076 // those dwords can then be moved to the correct half with a dword shuffle.
8077 // We use at most one low and one high word shuffle to collect these paired
8078 // inputs into dwords, and finally a dword shuffle to place them.
8079 int PSHUFLMask[4] = {-1, -1, -1, -1};
8080 int PSHUFHMask[4] = {-1, -1, -1, -1};
8081 int PSHUFDMask[4] = {-1, -1, -1, -1};
8083 // First fix the masks for all the inputs that are staying in their
8084 // original halves. This will then dictate the targets of the cross-half
8086 auto fixInPlaceInputs =
8087 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8088 MutableArrayRef<int> SourceHalfMask,
8089 MutableArrayRef<int> HalfMask, int HalfOffset) {
8090 if (InPlaceInputs.empty())
8092 if (InPlaceInputs.size() == 1) {
8093 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8094 InPlaceInputs[0] - HalfOffset;
8095 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8098 if (IncomingInputs.empty()) {
8099 // Just fix all of the in place inputs.
8100 for (int Input : InPlaceInputs) {
8101 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8102 PSHUFDMask[Input / 2] = Input / 2;
8107 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8108 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8109 InPlaceInputs[0] - HalfOffset;
8110 // Put the second input next to the first so that they are packed into
8111 // a dword. We find the adjacent index by toggling the low bit.
8112 int AdjIndex = InPlaceInputs[0] ^ 1;
8113 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8114 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8115 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8117 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8118 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8120 // Now gather the cross-half inputs and place them into a free dword of
8121 // their target half.
8122 // FIXME: This operation could almost certainly be simplified dramatically to
8123 // look more like the 3-1 fixing operation.
8124 auto moveInputsToRightHalf = [&PSHUFDMask](
8125 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8126 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8127 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8129 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8130 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8132 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8134 int LowWord = Word & ~1;
8135 int HighWord = Word | 1;
8136 return isWordClobbered(SourceHalfMask, LowWord) ||
8137 isWordClobbered(SourceHalfMask, HighWord);
8140 if (IncomingInputs.empty())
8143 if (ExistingInputs.empty()) {
8144 // Map any dwords with inputs from them into the right half.
8145 for (int Input : IncomingInputs) {
8146 // If the source half mask maps over the inputs, turn those into
8147 // swaps and use the swapped lane.
8148 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8149 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8150 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8151 Input - SourceOffset;
8152 // We have to swap the uses in our half mask in one sweep.
8153 for (int &M : HalfMask)
8154 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8156 else if (M == Input)
8157 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8159 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8160 Input - SourceOffset &&
8161 "Previous placement doesn't match!");
8163 // Note that this correctly re-maps both when we do a swap and when
8164 // we observe the other side of the swap above. We rely on that to
8165 // avoid swapping the members of the input list directly.
8166 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8169 // Map the input's dword into the correct half.
8170 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8171 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8173 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8175 "Previous placement doesn't match!");
8178 // And just directly shift any other-half mask elements to be same-half
8179 // as we will have mirrored the dword containing the element into the
8180 // same position within that half.
8181 for (int &M : HalfMask)
8182 if (M >= SourceOffset && M < SourceOffset + 4) {
8183 M = M - SourceOffset + DestOffset;
8184 assert(M >= 0 && "This should never wrap below zero!");
8189 // Ensure we have the input in a viable dword of its current half. This
8190 // is particularly tricky because the original position may be clobbered
8191 // by inputs being moved and *staying* in that half.
8192 if (IncomingInputs.size() == 1) {
8193 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8194 int InputFixed = std::find(std::begin(SourceHalfMask),
8195 std::end(SourceHalfMask), -1) -
8196 std::begin(SourceHalfMask) + SourceOffset;
8197 SourceHalfMask[InputFixed - SourceOffset] =
8198 IncomingInputs[0] - SourceOffset;
8199 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8201 IncomingInputs[0] = InputFixed;
8203 } else if (IncomingInputs.size() == 2) {
8204 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8205 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8206 // We have two non-adjacent or clobbered inputs we need to extract from
8207 // the source half. To do this, we need to map them into some adjacent
8208 // dword slot in the source mask.
8209 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8210 IncomingInputs[1] - SourceOffset};
8212 // If there is a free slot in the source half mask adjacent to one of
8213 // the inputs, place the other input in it. We use (Index XOR 1) to
8214 // compute an adjacent index.
8215 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8216 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8217 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8218 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8219 InputsFixed[1] = InputsFixed[0] ^ 1;
8220 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8221 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8222 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8223 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8224 InputsFixed[0] = InputsFixed[1] ^ 1;
8225 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8226 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8227 // The two inputs are in the same DWord but it is clobbered and the
8228 // adjacent DWord isn't used at all. Move both inputs to the free
8230 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8231 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8232 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8233 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8235 // The only way we hit this point is if there is no clobbering
8236 // (because there are no off-half inputs to this half) and there is no
8237 // free slot adjacent to one of the inputs. In this case, we have to
8238 // swap an input with a non-input.
8239 for (int i = 0; i < 4; ++i)
8240 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8241 "We can't handle any clobbers here!");
8242 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8243 "Cannot have adjacent inputs here!");
8245 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8246 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8248 // We also have to update the final source mask in this case because
8249 // it may need to undo the above swap.
8250 for (int &M : FinalSourceHalfMask)
8251 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8252 M = InputsFixed[1] + SourceOffset;
8253 else if (M == InputsFixed[1] + SourceOffset)
8254 M = (InputsFixed[0] ^ 1) + SourceOffset;
8256 InputsFixed[1] = InputsFixed[0] ^ 1;
8259 // Point everything at the fixed inputs.
8260 for (int &M : HalfMask)
8261 if (M == IncomingInputs[0])
8262 M = InputsFixed[0] + SourceOffset;
8263 else if (M == IncomingInputs[1])
8264 M = InputsFixed[1] + SourceOffset;
8266 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8267 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8270 llvm_unreachable("Unhandled input size!");
8273 // Now hoist the DWord down to the right half.
8274 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8275 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8276 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8277 for (int &M : HalfMask)
8278 for (int Input : IncomingInputs)
8280 M = FreeDWord * 2 + Input % 2;
8282 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8283 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8284 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8285 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8287 // Now enact all the shuffles we've computed to move the inputs into their
8289 if (!isNoopShuffleMask(PSHUFLMask))
8290 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8291 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8292 if (!isNoopShuffleMask(PSHUFHMask))
8293 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8294 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8295 if (!isNoopShuffleMask(PSHUFDMask))
8296 V = DAG.getNode(ISD::BITCAST, DL, VT,
8297 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8298 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8299 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8302 // At this point, each half should contain all its inputs, and we can then
8303 // just shuffle them into their final position.
8304 assert(std::count_if(LoMask.begin(), LoMask.end(),
8305 [](int M) { return M >= 4; }) == 0 &&
8306 "Failed to lift all the high half inputs to the low mask!");
8307 assert(std::count_if(HiMask.begin(), HiMask.end(),
8308 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8309 "Failed to lift all the low half inputs to the high mask!");
8311 // Do a half shuffle for the low mask.
8312 if (!isNoopShuffleMask(LoMask))
8313 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8314 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8316 // Do a half shuffle with the high mask after shifting its values down.
8317 for (int &M : HiMask)
8320 if (!isNoopShuffleMask(HiMask))
8321 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8322 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8327 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8328 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8329 SDValue V2, ArrayRef<int> Mask,
8330 SelectionDAG &DAG, bool &V1InUse,
8332 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8338 int Size = Mask.size();
8339 int Scale = 16 / Size;
8340 for (int i = 0; i < 16; ++i) {
8341 if (Mask[i / Scale] == -1) {
8342 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8344 const int ZeroMask = 0x80;
8345 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8347 int V2Idx = Mask[i / Scale] < Size
8349 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8350 if (Zeroable[i / Scale])
8351 V1Idx = V2Idx = ZeroMask;
8352 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8353 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8354 V1InUse |= (ZeroMask != V1Idx);
8355 V2InUse |= (ZeroMask != V2Idx);
8360 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8361 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8362 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8364 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8365 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8366 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8368 // If we need shuffled inputs from both, blend the two.
8370 if (V1InUse && V2InUse)
8371 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8373 V = V1InUse ? V1 : V2;
8375 // Cast the result back to the correct type.
8376 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8379 /// \brief Generic lowering of 8-lane i16 shuffles.
8381 /// This handles both single-input shuffles and combined shuffle/blends with
8382 /// two inputs. The single input shuffles are immediately delegated to
8383 /// a dedicated lowering routine.
8385 /// The blends are lowered in one of three fundamental ways. If there are few
8386 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8387 /// of the input is significantly cheaper when lowered as an interleaving of
8388 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8389 /// halves of the inputs separately (making them have relatively few inputs)
8390 /// and then concatenate them.
8391 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8392 const X86Subtarget *Subtarget,
8393 SelectionDAG &DAG) {
8395 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8396 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8397 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8398 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8399 ArrayRef<int> OrigMask = SVOp->getMask();
8400 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8401 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8402 MutableArrayRef<int> Mask(MaskStorage);
8404 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8406 // Whenever we can lower this as a zext, that instruction is strictly faster
8407 // than any alternative.
8408 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8409 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8412 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8414 auto isV2 = [](int M) { return M >= 8; };
8416 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8418 if (NumV2Inputs == 0) {
8419 // Check for being able to broadcast a single element.
8420 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8421 Mask, Subtarget, DAG))
8424 // Try to use shift instructions.
8426 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8429 // Use dedicated unpack instructions for masks that match their pattern.
8430 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8431 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8432 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8433 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8435 // Try to use byte rotation instructions.
8436 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8437 Mask, Subtarget, DAG))
8440 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8444 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8445 "All single-input shuffles should be canonicalized to be V1-input "
8448 // Try to use shift instructions.
8450 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8453 // There are special ways we can lower some single-element blends.
8454 if (NumV2Inputs == 1)
8455 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8456 Mask, Subtarget, DAG))
8459 // We have different paths for blend lowering, but they all must use the
8460 // *exact* same predicate.
8461 bool IsBlendSupported = Subtarget->hasSSE41();
8462 if (IsBlendSupported)
8463 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8467 if (SDValue Masked =
8468 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8471 // Use dedicated unpack instructions for masks that match their pattern.
8472 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8473 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8474 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8475 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8477 // Try to use byte rotation instructions.
8478 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8479 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8482 if (SDValue BitBlend =
8483 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8486 if (SDValue Unpack =
8487 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8490 // If we can't directly blend but can use PSHUFB, that will be better as it
8491 // can both shuffle and set up the inefficient blend.
8492 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8493 bool V1InUse, V2InUse;
8494 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8498 // We can always bit-blend if we have to so the fallback strategy is to
8499 // decompose into single-input permutes and blends.
8500 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8504 /// \brief Check whether a compaction lowering can be done by dropping even
8505 /// elements and compute how many times even elements must be dropped.
8507 /// This handles shuffles which take every Nth element where N is a power of
8508 /// two. Example shuffle masks:
8510 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8511 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8512 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8513 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8514 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8515 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8517 /// Any of these lanes can of course be undef.
8519 /// This routine only supports N <= 3.
8520 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8523 /// \returns N above, or the number of times even elements must be dropped if
8524 /// there is such a number. Otherwise returns zero.
8525 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8526 // Figure out whether we're looping over two inputs or just one.
8527 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8529 // The modulus for the shuffle vector entries is based on whether this is
8530 // a single input or not.
8531 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8532 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8533 "We should only be called with masks with a power-of-2 size!");
8535 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8537 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8538 // and 2^3 simultaneously. This is because we may have ambiguity with
8539 // partially undef inputs.
8540 bool ViableForN[3] = {true, true, true};
8542 for (int i = 0, e = Mask.size(); i < e; ++i) {
8543 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8548 bool IsAnyViable = false;
8549 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8550 if (ViableForN[j]) {
8553 // The shuffle mask must be equal to (i * 2^N) % M.
8554 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8557 ViableForN[j] = false;
8559 // Early exit if we exhaust the possible powers of two.
8564 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8568 // Return 0 as there is no viable power of two.
8572 /// \brief Generic lowering of v16i8 shuffles.
8574 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8575 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8576 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8577 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8579 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8580 const X86Subtarget *Subtarget,
8581 SelectionDAG &DAG) {
8583 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8584 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8585 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8586 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8587 ArrayRef<int> Mask = SVOp->getMask();
8588 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8590 // Try to use shift instructions.
8592 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8595 // Try to use byte rotation instructions.
8596 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8597 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8600 // Try to use a zext lowering.
8601 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8602 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8606 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8608 // For single-input shuffles, there are some nicer lowering tricks we can use.
8609 if (NumV2Elements == 0) {
8610 // Check for being able to broadcast a single element.
8611 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8612 Mask, Subtarget, DAG))
8615 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8616 // Notably, this handles splat and partial-splat shuffles more efficiently.
8617 // However, it only makes sense if the pre-duplication shuffle simplifies
8618 // things significantly. Currently, this means we need to be able to
8619 // express the pre-duplication shuffle as an i16 shuffle.
8621 // FIXME: We should check for other patterns which can be widened into an
8622 // i16 shuffle as well.
8623 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8624 for (int i = 0; i < 16; i += 2)
8625 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8630 auto tryToWidenViaDuplication = [&]() -> SDValue {
8631 if (!canWidenViaDuplication(Mask))
8633 SmallVector<int, 4> LoInputs;
8634 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8635 [](int M) { return M >= 0 && M < 8; });
8636 std::sort(LoInputs.begin(), LoInputs.end());
8637 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8639 SmallVector<int, 4> HiInputs;
8640 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8641 [](int M) { return M >= 8; });
8642 std::sort(HiInputs.begin(), HiInputs.end());
8643 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8646 bool TargetLo = LoInputs.size() >= HiInputs.size();
8647 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8648 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8650 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8651 SmallDenseMap<int, int, 8> LaneMap;
8652 for (int I : InPlaceInputs) {
8653 PreDupI16Shuffle[I/2] = I/2;
8656 int j = TargetLo ? 0 : 4, je = j + 4;
8657 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8658 // Check if j is already a shuffle of this input. This happens when
8659 // there are two adjacent bytes after we move the low one.
8660 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8661 // If we haven't yet mapped the input, search for a slot into which
8663 while (j < je && PreDupI16Shuffle[j] != -1)
8667 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8670 // Map this input with the i16 shuffle.
8671 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8674 // Update the lane map based on the mapping we ended up with.
8675 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8678 ISD::BITCAST, DL, MVT::v16i8,
8679 DAG.getVectorShuffle(MVT::v8i16, DL,
8680 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8681 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8683 // Unpack the bytes to form the i16s that will be shuffled into place.
8684 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8685 MVT::v16i8, V1, V1);
8687 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8688 for (int i = 0; i < 16; ++i)
8689 if (Mask[i] != -1) {
8690 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8691 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8692 if (PostDupI16Shuffle[i / 2] == -1)
8693 PostDupI16Shuffle[i / 2] = MappedMask;
8695 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8696 "Conflicting entrties in the original shuffle!");
8699 ISD::BITCAST, DL, MVT::v16i8,
8700 DAG.getVectorShuffle(MVT::v8i16, DL,
8701 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8702 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8704 if (SDValue V = tryToWidenViaDuplication())
8708 // Use dedicated unpack instructions for masks that match their pattern.
8709 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8710 0, 16, 1, 17, 2, 18, 3, 19,
8712 4, 20, 5, 21, 6, 22, 7, 23}))
8713 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8714 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8715 8, 24, 9, 25, 10, 26, 11, 27,
8717 12, 28, 13, 29, 14, 30, 15, 31}))
8718 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8720 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8721 // with PSHUFB. It is important to do this before we attempt to generate any
8722 // blends but after all of the single-input lowerings. If the single input
8723 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8724 // want to preserve that and we can DAG combine any longer sequences into
8725 // a PSHUFB in the end. But once we start blending from multiple inputs,
8726 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8727 // and there are *very* few patterns that would actually be faster than the
8728 // PSHUFB approach because of its ability to zero lanes.
8730 // FIXME: The only exceptions to the above are blends which are exact
8731 // interleavings with direct instructions supporting them. We currently don't
8732 // handle those well here.
8733 if (Subtarget->hasSSSE3()) {
8734 bool V1InUse = false;
8735 bool V2InUse = false;
8737 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8738 DAG, V1InUse, V2InUse);
8740 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8741 // do so. This avoids using them to handle blends-with-zero which is
8742 // important as a single pshufb is significantly faster for that.
8743 if (V1InUse && V2InUse) {
8744 if (Subtarget->hasSSE41())
8745 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8746 Mask, Subtarget, DAG))
8749 // We can use an unpack to do the blending rather than an or in some
8750 // cases. Even though the or may be (very minorly) more efficient, we
8751 // preference this lowering because there are common cases where part of
8752 // the complexity of the shuffles goes away when we do the final blend as
8754 // FIXME: It might be worth trying to detect if the unpack-feeding
8755 // shuffles will both be pshufb, in which case we shouldn't bother with
8757 if (SDValue Unpack =
8758 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8765 // There are special ways we can lower some single-element blends.
8766 if (NumV2Elements == 1)
8767 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8768 Mask, Subtarget, DAG))
8771 if (SDValue BitBlend =
8772 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8775 // Check whether a compaction lowering can be done. This handles shuffles
8776 // which take every Nth element for some even N. See the helper function for
8779 // We special case these as they can be particularly efficiently handled with
8780 // the PACKUSB instruction on x86 and they show up in common patterns of
8781 // rearranging bytes to truncate wide elements.
8782 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8783 // NumEvenDrops is the power of two stride of the elements. Another way of
8784 // thinking about it is that we need to drop the even elements this many
8785 // times to get the original input.
8786 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8788 // First we need to zero all the dropped bytes.
8789 assert(NumEvenDrops <= 3 &&
8790 "No support for dropping even elements more than 3 times.");
8791 // We use the mask type to pick which bytes are preserved based on how many
8792 // elements are dropped.
8793 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8794 SDValue ByteClearMask =
8795 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8796 DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8797 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8799 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8801 // Now pack things back together.
8802 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8803 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8804 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8805 for (int i = 1; i < NumEvenDrops; ++i) {
8806 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8807 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8813 // Handle multi-input cases by blending single-input shuffles.
8814 if (NumV2Elements > 0)
8815 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8818 // The fallback path for single-input shuffles widens this into two v8i16
8819 // vectors with unpacks, shuffles those, and then pulls them back together
8823 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8824 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8825 for (int i = 0; i < 16; ++i)
8827 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8829 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8831 SDValue VLoHalf, VHiHalf;
8832 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8833 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8835 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8836 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8837 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8838 [](int M) { return M >= 0 && M % 2 == 1; })) {
8839 // Use a mask to drop the high bytes.
8840 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8841 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8842 DAG.getConstant(0x00FF, DL, MVT::v8i16));
8844 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8845 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8847 // Squash the masks to point directly into VLoHalf.
8848 for (int &M : LoBlendMask)
8851 for (int &M : HiBlendMask)
8855 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8856 // VHiHalf so that we can blend them as i16s.
8857 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8858 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8859 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8860 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8863 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8864 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8866 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8869 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8871 /// This routine breaks down the specific type of 128-bit shuffle and
8872 /// dispatches to the lowering routines accordingly.
8873 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8874 MVT VT, const X86Subtarget *Subtarget,
8875 SelectionDAG &DAG) {
8876 switch (VT.SimpleTy) {
8878 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8880 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8882 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8884 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8886 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8888 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8891 llvm_unreachable("Unimplemented!");
8895 /// \brief Helper function to test whether a shuffle mask could be
8896 /// simplified by widening the elements being shuffled.
8898 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8899 /// leaves it in an unspecified state.
8901 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8902 /// shuffle masks. The latter have the special property of a '-2' representing
8903 /// a zero-ed lane of a vector.
8904 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8905 SmallVectorImpl<int> &WidenedMask) {
8906 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8907 // If both elements are undef, its trivial.
8908 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8909 WidenedMask.push_back(SM_SentinelUndef);
8913 // Check for an undef mask and a mask value properly aligned to fit with
8914 // a pair of values. If we find such a case, use the non-undef mask's value.
8915 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8916 WidenedMask.push_back(Mask[i + 1] / 2);
8919 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8920 WidenedMask.push_back(Mask[i] / 2);
8924 // When zeroing, we need to spread the zeroing across both lanes to widen.
8925 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8926 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8927 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8928 WidenedMask.push_back(SM_SentinelZero);
8934 // Finally check if the two mask values are adjacent and aligned with
8936 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8937 WidenedMask.push_back(Mask[i] / 2);
8941 // Otherwise we can't safely widen the elements used in this shuffle.
8944 assert(WidenedMask.size() == Mask.size() / 2 &&
8945 "Incorrect size of mask after widening the elements!");
8950 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8952 /// This routine just extracts two subvectors, shuffles them independently, and
8953 /// then concatenates them back together. This should work effectively with all
8954 /// AVX vector shuffle types.
8955 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8956 SDValue V2, ArrayRef<int> Mask,
8957 SelectionDAG &DAG) {
8958 assert(VT.getSizeInBits() >= 256 &&
8959 "Only for 256-bit or wider vector shuffles!");
8960 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8961 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8963 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8964 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8966 int NumElements = VT.getVectorNumElements();
8967 int SplitNumElements = NumElements / 2;
8968 MVT ScalarVT = VT.getScalarType();
8969 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8971 // Rather than splitting build-vectors, just build two narrower build
8972 // vectors. This helps shuffling with splats and zeros.
8973 auto SplitVector = [&](SDValue V) {
8974 while (V.getOpcode() == ISD::BITCAST)
8975 V = V->getOperand(0);
8977 MVT OrigVT = V.getSimpleValueType();
8978 int OrigNumElements = OrigVT.getVectorNumElements();
8979 int OrigSplitNumElements = OrigNumElements / 2;
8980 MVT OrigScalarVT = OrigVT.getScalarType();
8981 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8985 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8987 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8988 DAG.getIntPtrConstant(0, DL));
8989 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8990 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
8993 SmallVector<SDValue, 16> LoOps, HiOps;
8994 for (int i = 0; i < OrigSplitNumElements; ++i) {
8995 LoOps.push_back(BV->getOperand(i));
8996 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8998 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8999 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9001 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9002 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9005 SDValue LoV1, HiV1, LoV2, HiV2;
9006 std::tie(LoV1, HiV1) = SplitVector(V1);
9007 std::tie(LoV2, HiV2) = SplitVector(V2);
9009 // Now create two 4-way blends of these half-width vectors.
9010 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9011 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9012 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9013 for (int i = 0; i < SplitNumElements; ++i) {
9014 int M = HalfMask[i];
9015 if (M >= NumElements) {
9016 if (M >= NumElements + SplitNumElements)
9020 V2BlendMask.push_back(M - NumElements);
9021 V1BlendMask.push_back(-1);
9022 BlendMask.push_back(SplitNumElements + i);
9023 } else if (M >= 0) {
9024 if (M >= SplitNumElements)
9028 V2BlendMask.push_back(-1);
9029 V1BlendMask.push_back(M);
9030 BlendMask.push_back(i);
9032 V2BlendMask.push_back(-1);
9033 V1BlendMask.push_back(-1);
9034 BlendMask.push_back(-1);
9038 // Because the lowering happens after all combining takes place, we need to
9039 // manually combine these blend masks as much as possible so that we create
9040 // a minimal number of high-level vector shuffle nodes.
9042 // First try just blending the halves of V1 or V2.
9043 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9044 return DAG.getUNDEF(SplitVT);
9045 if (!UseLoV2 && !UseHiV2)
9046 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9047 if (!UseLoV1 && !UseHiV1)
9048 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9050 SDValue V1Blend, V2Blend;
9051 if (UseLoV1 && UseHiV1) {
9053 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9055 // We only use half of V1 so map the usage down into the final blend mask.
9056 V1Blend = UseLoV1 ? LoV1 : HiV1;
9057 for (int i = 0; i < SplitNumElements; ++i)
9058 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9059 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9061 if (UseLoV2 && UseHiV2) {
9063 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9065 // We only use half of V2 so map the usage down into the final blend mask.
9066 V2Blend = UseLoV2 ? LoV2 : HiV2;
9067 for (int i = 0; i < SplitNumElements; ++i)
9068 if (BlendMask[i] >= SplitNumElements)
9069 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9071 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9073 SDValue Lo = HalfBlend(LoMask);
9074 SDValue Hi = HalfBlend(HiMask);
9075 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9078 /// \brief Either split a vector in halves or decompose the shuffles and the
9081 /// This is provided as a good fallback for many lowerings of non-single-input
9082 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9083 /// between splitting the shuffle into 128-bit components and stitching those
9084 /// back together vs. extracting the single-input shuffles and blending those
9086 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9087 SDValue V2, ArrayRef<int> Mask,
9088 SelectionDAG &DAG) {
9089 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9090 "lower single-input shuffles as it "
9091 "could then recurse on itself.");
9092 int Size = Mask.size();
9094 // If this can be modeled as a broadcast of two elements followed by a blend,
9095 // prefer that lowering. This is especially important because broadcasts can
9096 // often fold with memory operands.
9097 auto DoBothBroadcast = [&] {
9098 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9101 if (V2BroadcastIdx == -1)
9102 V2BroadcastIdx = M - Size;
9103 else if (M - Size != V2BroadcastIdx)
9105 } else if (M >= 0) {
9106 if (V1BroadcastIdx == -1)
9108 else if (M != V1BroadcastIdx)
9113 if (DoBothBroadcast())
9114 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9117 // If the inputs all stem from a single 128-bit lane of each input, then we
9118 // split them rather than blending because the split will decompose to
9119 // unusually few instructions.
9120 int LaneCount = VT.getSizeInBits() / 128;
9121 int LaneSize = Size / LaneCount;
9122 SmallBitVector LaneInputs[2];
9123 LaneInputs[0].resize(LaneCount, false);
9124 LaneInputs[1].resize(LaneCount, false);
9125 for (int i = 0; i < Size; ++i)
9127 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9128 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9129 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9131 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9132 // that the decomposed single-input shuffles don't end up here.
9133 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9136 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9137 /// a permutation and blend of those lanes.
9139 /// This essentially blends the out-of-lane inputs to each lane into the lane
9140 /// from a permuted copy of the vector. This lowering strategy results in four
9141 /// instructions in the worst case for a single-input cross lane shuffle which
9142 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9143 /// of. Special cases for each particular shuffle pattern should be handled
9144 /// prior to trying this lowering.
9145 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9146 SDValue V1, SDValue V2,
9148 SelectionDAG &DAG) {
9149 // FIXME: This should probably be generalized for 512-bit vectors as well.
9150 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9151 int LaneSize = Mask.size() / 2;
9153 // If there are only inputs from one 128-bit lane, splitting will in fact be
9154 // less expensive. The flags track whether the given lane contains an element
9155 // that crosses to another lane.
9156 bool LaneCrossing[2] = {false, false};
9157 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9158 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9159 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9160 if (!LaneCrossing[0] || !LaneCrossing[1])
9161 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9163 if (isSingleInputShuffleMask(Mask)) {
9164 SmallVector<int, 32> FlippedBlendMask;
9165 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9166 FlippedBlendMask.push_back(
9167 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9169 : Mask[i] % LaneSize +
9170 (i / LaneSize) * LaneSize + Size));
9172 // Flip the vector, and blend the results which should now be in-lane. The
9173 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9174 // 5 for the high source. The value 3 selects the high half of source 2 and
9175 // the value 2 selects the low half of source 2. We only use source 2 to
9176 // allow folding it into a memory operand.
9177 unsigned PERMMask = 3 | 2 << 4;
9178 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9179 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9180 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9183 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9184 // will be handled by the above logic and a blend of the results, much like
9185 // other patterns in AVX.
9186 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9189 /// \brief Handle lowering 2-lane 128-bit shuffles.
9190 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9191 SDValue V2, ArrayRef<int> Mask,
9192 const X86Subtarget *Subtarget,
9193 SelectionDAG &DAG) {
9194 // TODO: If minimizing size and one of the inputs is a zero vector and the
9195 // the zero vector has only one use, we could use a VPERM2X128 to save the
9196 // instruction bytes needed to explicitly generate the zero vector.
9198 // Blends are faster and handle all the non-lane-crossing cases.
9199 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9203 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9204 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9206 // If either input operand is a zero vector, use VPERM2X128 because its mask
9207 // allows us to replace the zero input with an implicit zero.
9208 if (!IsV1Zero && !IsV2Zero) {
9209 // Check for patterns which can be matched with a single insert of a 128-bit
9211 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9212 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9213 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9214 VT.getVectorNumElements() / 2);
9215 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9216 DAG.getIntPtrConstant(0, DL));
9217 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9218 OnlyUsesV1 ? V1 : V2,
9219 DAG.getIntPtrConstant(0, DL));
9220 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9224 // Otherwise form a 128-bit permutation. After accounting for undefs,
9225 // convert the 64-bit shuffle mask selection values into 128-bit
9226 // selection bits by dividing the indexes by 2 and shifting into positions
9227 // defined by a vperm2*128 instruction's immediate control byte.
9229 // The immediate permute control byte looks like this:
9230 // [1:0] - select 128 bits from sources for low half of destination
9232 // [3] - zero low half of destination
9233 // [5:4] - select 128 bits from sources for high half of destination
9235 // [7] - zero high half of destination
9237 int MaskLO = Mask[0];
9238 if (MaskLO == SM_SentinelUndef)
9239 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9241 int MaskHI = Mask[2];
9242 if (MaskHI == SM_SentinelUndef)
9243 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9245 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9247 // If either input is a zero vector, replace it with an undef input.
9248 // Shuffle mask values < 4 are selecting elements of V1.
9249 // Shuffle mask values >= 4 are selecting elements of V2.
9250 // Adjust each half of the permute mask by clearing the half that was
9251 // selecting the zero vector and setting the zero mask bit.
9253 V1 = DAG.getUNDEF(VT);
9255 PermMask = (PermMask & 0xf0) | 0x08;
9257 PermMask = (PermMask & 0x0f) | 0x80;
9260 V2 = DAG.getUNDEF(VT);
9262 PermMask = (PermMask & 0xf0) | 0x08;
9264 PermMask = (PermMask & 0x0f) | 0x80;
9267 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9268 DAG.getConstant(PermMask, DL, MVT::i8));
9271 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9272 /// shuffling each lane.
9274 /// This will only succeed when the result of fixing the 128-bit lanes results
9275 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9276 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9277 /// the lane crosses early and then use simpler shuffles within each lane.
9279 /// FIXME: It might be worthwhile at some point to support this without
9280 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9281 /// in x86 only floating point has interesting non-repeating shuffles, and even
9282 /// those are still *marginally* more expensive.
9283 static SDValue lowerVectorShuffleByMerging128BitLanes(
9284 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9285 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9286 assert(!isSingleInputShuffleMask(Mask) &&
9287 "This is only useful with multiple inputs.");
9289 int Size = Mask.size();
9290 int LaneSize = 128 / VT.getScalarSizeInBits();
9291 int NumLanes = Size / LaneSize;
9292 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9294 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9295 // check whether the in-128-bit lane shuffles share a repeating pattern.
9296 SmallVector<int, 4> Lanes;
9297 Lanes.resize(NumLanes, -1);
9298 SmallVector<int, 4> InLaneMask;
9299 InLaneMask.resize(LaneSize, -1);
9300 for (int i = 0; i < Size; ++i) {
9304 int j = i / LaneSize;
9307 // First entry we've seen for this lane.
9308 Lanes[j] = Mask[i] / LaneSize;
9309 } else if (Lanes[j] != Mask[i] / LaneSize) {
9310 // This doesn't match the lane selected previously!
9314 // Check that within each lane we have a consistent shuffle mask.
9315 int k = i % LaneSize;
9316 if (InLaneMask[k] < 0) {
9317 InLaneMask[k] = Mask[i] % LaneSize;
9318 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9319 // This doesn't fit a repeating in-lane mask.
9324 // First shuffle the lanes into place.
9325 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9326 VT.getSizeInBits() / 64);
9327 SmallVector<int, 8> LaneMask;
9328 LaneMask.resize(NumLanes * 2, -1);
9329 for (int i = 0; i < NumLanes; ++i)
9330 if (Lanes[i] >= 0) {
9331 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9332 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9335 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9336 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9337 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9339 // Cast it back to the type we actually want.
9340 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9342 // Now do a simple shuffle that isn't lane crossing.
9343 SmallVector<int, 8> NewMask;
9344 NewMask.resize(Size, -1);
9345 for (int i = 0; i < Size; ++i)
9347 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9348 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9349 "Must not introduce lane crosses at this point!");
9351 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9354 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9357 /// This returns true if the elements from a particular input are already in the
9358 /// slot required by the given mask and require no permutation.
9359 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9360 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9361 int Size = Mask.size();
9362 for (int i = 0; i < Size; ++i)
9363 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9369 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9371 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9372 /// isn't available.
9373 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9374 const X86Subtarget *Subtarget,
9375 SelectionDAG &DAG) {
9377 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9378 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9379 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9380 ArrayRef<int> Mask = SVOp->getMask();
9381 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9383 SmallVector<int, 4> WidenedMask;
9384 if (canWidenShuffleElements(Mask, WidenedMask))
9385 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9388 if (isSingleInputShuffleMask(Mask)) {
9389 // Check for being able to broadcast a single element.
9390 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9391 Mask, Subtarget, DAG))
9394 // Use low duplicate instructions for masks that match their pattern.
9395 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9396 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9398 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9399 // Non-half-crossing single input shuffles can be lowerid with an
9400 // interleaved permutation.
9401 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9402 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9403 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9404 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9407 // With AVX2 we have direct support for this permutation.
9408 if (Subtarget->hasAVX2())
9409 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9410 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9412 // Otherwise, fall back.
9413 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9417 // X86 has dedicated unpack instructions that can handle specific blend
9418 // operations: UNPCKH and UNPCKL.
9419 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9420 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9421 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9422 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9423 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9424 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9425 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9426 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9428 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9432 // Check if the blend happens to exactly fit that of SHUFPD.
9433 if ((Mask[0] == -1 || Mask[0] < 2) &&
9434 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9435 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9436 (Mask[3] == -1 || Mask[3] >= 6)) {
9437 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9438 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9439 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9440 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9442 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9443 (Mask[1] == -1 || Mask[1] < 2) &&
9444 (Mask[2] == -1 || Mask[2] >= 6) &&
9445 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9446 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9447 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9448 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9449 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9452 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9453 // shuffle. However, if we have AVX2 and either inputs are already in place,
9454 // we will be able to shuffle even across lanes the other input in a single
9455 // instruction so skip this pattern.
9456 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9457 isShuffleMaskInputInPlace(1, Mask))))
9458 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9459 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9462 // If we have AVX2 then we always want to lower with a blend because an v4 we
9463 // can fully permute the elements.
9464 if (Subtarget->hasAVX2())
9465 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9468 // Otherwise fall back on generic lowering.
9469 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9472 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9474 /// This routine is only called when we have AVX2 and thus a reasonable
9475 /// instruction set for v4i64 shuffling..
9476 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9477 const X86Subtarget *Subtarget,
9478 SelectionDAG &DAG) {
9480 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9481 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9482 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9483 ArrayRef<int> Mask = SVOp->getMask();
9484 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9485 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9487 SmallVector<int, 4> WidenedMask;
9488 if (canWidenShuffleElements(Mask, WidenedMask))
9489 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9492 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9496 // Check for being able to broadcast a single element.
9497 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9498 Mask, Subtarget, DAG))
9501 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9502 // use lower latency instructions that will operate on both 128-bit lanes.
9503 SmallVector<int, 2> RepeatedMask;
9504 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9505 if (isSingleInputShuffleMask(Mask)) {
9506 int PSHUFDMask[] = {-1, -1, -1, -1};
9507 for (int i = 0; i < 2; ++i)
9508 if (RepeatedMask[i] >= 0) {
9509 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9510 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9513 ISD::BITCAST, DL, MVT::v4i64,
9514 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9515 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9516 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9520 // AVX2 provides a direct instruction for permuting a single input across
9522 if (isSingleInputShuffleMask(Mask))
9523 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9524 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9526 // Try to use shift instructions.
9528 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9531 // Use dedicated unpack instructions for masks that match their pattern.
9532 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9533 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9534 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9535 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9536 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9537 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9538 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9539 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9541 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9542 // shuffle. However, if we have AVX2 and either inputs are already in place,
9543 // we will be able to shuffle even across lanes the other input in a single
9544 // instruction so skip this pattern.
9545 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9546 isShuffleMaskInputInPlace(1, Mask))))
9547 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9548 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9551 // Otherwise fall back on generic blend lowering.
9552 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9556 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9558 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9559 /// isn't available.
9560 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9561 const X86Subtarget *Subtarget,
9562 SelectionDAG &DAG) {
9564 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9565 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9566 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9567 ArrayRef<int> Mask = SVOp->getMask();
9568 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9570 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9574 // Check for being able to broadcast a single element.
9575 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9576 Mask, Subtarget, DAG))
9579 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9580 // options to efficiently lower the shuffle.
9581 SmallVector<int, 4> RepeatedMask;
9582 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9583 assert(RepeatedMask.size() == 4 &&
9584 "Repeated masks must be half the mask width!");
9586 // Use even/odd duplicate instructions for masks that match their pattern.
9587 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9588 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9589 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9590 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9592 if (isSingleInputShuffleMask(Mask))
9593 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9594 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9596 // Use dedicated unpack instructions for masks that match their pattern.
9597 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9598 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9599 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9600 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9601 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9602 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9603 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9604 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9606 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9607 // have already handled any direct blends. We also need to squash the
9608 // repeated mask into a simulated v4f32 mask.
9609 for (int i = 0; i < 4; ++i)
9610 if (RepeatedMask[i] >= 8)
9611 RepeatedMask[i] -= 4;
9612 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9615 // If we have a single input shuffle with different shuffle patterns in the
9616 // two 128-bit lanes use the variable mask to VPERMILPS.
9617 if (isSingleInputShuffleMask(Mask)) {
9618 SDValue VPermMask[8];
9619 for (int i = 0; i < 8; ++i)
9620 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9621 : DAG.getConstant(Mask[i], DL, MVT::i32);
9622 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9624 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9625 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9627 if (Subtarget->hasAVX2())
9628 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9629 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9630 DAG.getNode(ISD::BUILD_VECTOR, DL,
9631 MVT::v8i32, VPermMask)),
9634 // Otherwise, fall back.
9635 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9639 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9641 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9642 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9645 // If we have AVX2 then we always want to lower with a blend because at v8 we
9646 // can fully permute the elements.
9647 if (Subtarget->hasAVX2())
9648 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9651 // Otherwise fall back on generic lowering.
9652 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9655 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9657 /// This routine is only called when we have AVX2 and thus a reasonable
9658 /// instruction set for v8i32 shuffling..
9659 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9660 const X86Subtarget *Subtarget,
9661 SelectionDAG &DAG) {
9663 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9664 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9665 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9666 ArrayRef<int> Mask = SVOp->getMask();
9667 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9668 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9670 // Whenever we can lower this as a zext, that instruction is strictly faster
9671 // than any alternative. It also allows us to fold memory operands into the
9672 // shuffle in many cases.
9673 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9674 Mask, Subtarget, DAG))
9677 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9681 // Check for being able to broadcast a single element.
9682 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9683 Mask, Subtarget, DAG))
9686 // If the shuffle mask is repeated in each 128-bit lane we can use more
9687 // efficient instructions that mirror the shuffles across the two 128-bit
9689 SmallVector<int, 4> RepeatedMask;
9690 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9691 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9692 if (isSingleInputShuffleMask(Mask))
9693 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9694 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9696 // Use dedicated unpack instructions for masks that match their pattern.
9697 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9698 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9699 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9700 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9701 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9702 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9703 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9704 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9707 // Try to use shift instructions.
9709 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9712 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9713 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9716 // If the shuffle patterns aren't repeated but it is a single input, directly
9717 // generate a cross-lane VPERMD instruction.
9718 if (isSingleInputShuffleMask(Mask)) {
9719 SDValue VPermMask[8];
9720 for (int i = 0; i < 8; ++i)
9721 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9722 : DAG.getConstant(Mask[i], DL, MVT::i32);
9724 X86ISD::VPERMV, DL, MVT::v8i32,
9725 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9728 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9730 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9731 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9734 // Otherwise fall back on generic blend lowering.
9735 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9739 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9741 /// This routine is only called when we have AVX2 and thus a reasonable
9742 /// instruction set for v16i16 shuffling..
9743 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9744 const X86Subtarget *Subtarget,
9745 SelectionDAG &DAG) {
9747 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9748 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9749 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9750 ArrayRef<int> Mask = SVOp->getMask();
9751 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9752 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9754 // Whenever we can lower this as a zext, that instruction is strictly faster
9755 // than any alternative. It also allows us to fold memory operands into the
9756 // shuffle in many cases.
9757 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9758 Mask, Subtarget, DAG))
9761 // Check for being able to broadcast a single element.
9762 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9763 Mask, Subtarget, DAG))
9766 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9770 // Use dedicated unpack instructions for masks that match their pattern.
9771 if (isShuffleEquivalent(V1, V2, Mask,
9772 {// First 128-bit lane:
9773 0, 16, 1, 17, 2, 18, 3, 19,
9774 // Second 128-bit lane:
9775 8, 24, 9, 25, 10, 26, 11, 27}))
9776 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9777 if (isShuffleEquivalent(V1, V2, Mask,
9778 {// First 128-bit lane:
9779 4, 20, 5, 21, 6, 22, 7, 23,
9780 // Second 128-bit lane:
9781 12, 28, 13, 29, 14, 30, 15, 31}))
9782 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9784 // Try to use shift instructions.
9786 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9789 // Try to use byte rotation instructions.
9790 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9791 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9794 if (isSingleInputShuffleMask(Mask)) {
9795 // There are no generalized cross-lane shuffle operations available on i16
9797 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9798 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9801 SmallVector<int, 8> RepeatedMask;
9802 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9803 // As this is a single-input shuffle, the repeated mask should be
9804 // a strictly valid v8i16 mask that we can pass through to the v8i16
9805 // lowering to handle even the v16 case.
9806 return lowerV8I16GeneralSingleInputVectorShuffle(
9807 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9810 SDValue PSHUFBMask[32];
9811 for (int i = 0; i < 16; ++i) {
9812 if (Mask[i] == -1) {
9813 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9817 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9818 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9819 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9820 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9823 ISD::BITCAST, DL, MVT::v16i16,
9825 X86ISD::PSHUFB, DL, MVT::v32i8,
9826 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9827 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9830 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9832 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9833 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9836 // Otherwise fall back on generic lowering.
9837 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9840 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9842 /// This routine is only called when we have AVX2 and thus a reasonable
9843 /// instruction set for v32i8 shuffling..
9844 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9845 const X86Subtarget *Subtarget,
9846 SelectionDAG &DAG) {
9848 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9849 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9850 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9851 ArrayRef<int> Mask = SVOp->getMask();
9852 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9853 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9855 // Whenever we can lower this as a zext, that instruction is strictly faster
9856 // than any alternative. It also allows us to fold memory operands into the
9857 // shuffle in many cases.
9858 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9859 Mask, Subtarget, DAG))
9862 // Check for being able to broadcast a single element.
9863 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9864 Mask, Subtarget, DAG))
9867 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9871 // Use dedicated unpack instructions for masks that match their pattern.
9872 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9874 if (isShuffleEquivalent(
9876 {// First 128-bit lane:
9877 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9878 // Second 128-bit lane:
9879 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9880 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9881 if (isShuffleEquivalent(
9883 {// First 128-bit lane:
9884 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9885 // Second 128-bit lane:
9886 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9887 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9889 // Try to use shift instructions.
9891 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9894 // Try to use byte rotation instructions.
9895 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9896 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9899 if (isSingleInputShuffleMask(Mask)) {
9900 // There are no generalized cross-lane shuffle operations available on i8
9902 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9903 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9906 SDValue PSHUFBMask[32];
9907 for (int i = 0; i < 32; ++i)
9910 ? DAG.getUNDEF(MVT::i8)
9911 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9915 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9916 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9919 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9921 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9922 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9925 // Otherwise fall back on generic lowering.
9926 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9929 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9931 /// This routine either breaks down the specific type of a 256-bit x86 vector
9932 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9933 /// together based on the available instructions.
9934 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9935 MVT VT, const X86Subtarget *Subtarget,
9936 SelectionDAG &DAG) {
9938 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9939 ArrayRef<int> Mask = SVOp->getMask();
9941 // If we have a single input to the zero element, insert that into V1 if we
9942 // can do so cheaply.
9943 int NumElts = VT.getVectorNumElements();
9944 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9945 return M >= NumElts;
9948 if (NumV2Elements == 1 && Mask[0] >= NumElts)
9949 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9950 DL, VT, V1, V2, Mask, Subtarget, DAG))
9953 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9954 // check for those subtargets here and avoid much of the subtarget querying in
9955 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9956 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9957 // floating point types there eventually, just immediately cast everything to
9958 // a float and operate entirely in that domain.
9959 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9960 int ElementBits = VT.getScalarSizeInBits();
9961 if (ElementBits < 32)
9962 // No floating point type available, decompose into 128-bit vectors.
9963 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9965 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9966 VT.getVectorNumElements());
9967 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9968 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9969 return DAG.getNode(ISD::BITCAST, DL, VT,
9970 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9973 switch (VT.SimpleTy) {
9975 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9977 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9979 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9981 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9983 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9985 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9988 llvm_unreachable("Not a valid 256-bit x86 vector type!");
9992 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9993 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9994 const X86Subtarget *Subtarget,
9995 SelectionDAG &DAG) {
9997 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9998 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9999 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10000 ArrayRef<int> Mask = SVOp->getMask();
10001 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10003 // X86 has dedicated unpack instructions that can handle specific blend
10004 // operations: UNPCKH and UNPCKL.
10005 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10006 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10007 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10008 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10010 // FIXME: Implement direct support for this type!
10011 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10014 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10015 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10016 const X86Subtarget *Subtarget,
10017 SelectionDAG &DAG) {
10019 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10020 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10021 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10022 ArrayRef<int> Mask = SVOp->getMask();
10023 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10025 // Use dedicated unpack instructions for masks that match their pattern.
10026 if (isShuffleEquivalent(V1, V2, Mask,
10027 {// First 128-bit lane.
10028 0, 16, 1, 17, 4, 20, 5, 21,
10029 // Second 128-bit lane.
10030 8, 24, 9, 25, 12, 28, 13, 29}))
10031 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10032 if (isShuffleEquivalent(V1, V2, Mask,
10033 {// First 128-bit lane.
10034 2, 18, 3, 19, 6, 22, 7, 23,
10035 // Second 128-bit lane.
10036 10, 26, 11, 27, 14, 30, 15, 31}))
10037 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10039 // FIXME: Implement direct support for this type!
10040 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10043 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10044 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10045 const X86Subtarget *Subtarget,
10046 SelectionDAG &DAG) {
10048 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10049 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10050 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10051 ArrayRef<int> Mask = SVOp->getMask();
10052 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10054 // X86 has dedicated unpack instructions that can handle specific blend
10055 // operations: UNPCKH and UNPCKL.
10056 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10057 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10058 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10059 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10061 // FIXME: Implement direct support for this type!
10062 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10065 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10066 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10067 const X86Subtarget *Subtarget,
10068 SelectionDAG &DAG) {
10070 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10071 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10072 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10073 ArrayRef<int> Mask = SVOp->getMask();
10074 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10076 // Use dedicated unpack instructions for masks that match their pattern.
10077 if (isShuffleEquivalent(V1, V2, Mask,
10078 {// First 128-bit lane.
10079 0, 16, 1, 17, 4, 20, 5, 21,
10080 // Second 128-bit lane.
10081 8, 24, 9, 25, 12, 28, 13, 29}))
10082 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10083 if (isShuffleEquivalent(V1, V2, Mask,
10084 {// First 128-bit lane.
10085 2, 18, 3, 19, 6, 22, 7, 23,
10086 // Second 128-bit lane.
10087 10, 26, 11, 27, 14, 30, 15, 31}))
10088 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10090 // FIXME: Implement direct support for this type!
10091 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10094 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10095 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10096 const X86Subtarget *Subtarget,
10097 SelectionDAG &DAG) {
10099 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10100 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10101 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10102 ArrayRef<int> Mask = SVOp->getMask();
10103 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10104 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10106 // FIXME: Implement direct support for this type!
10107 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10110 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10111 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10112 const X86Subtarget *Subtarget,
10113 SelectionDAG &DAG) {
10115 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10116 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10117 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10118 ArrayRef<int> Mask = SVOp->getMask();
10119 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10120 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10122 // FIXME: Implement direct support for this type!
10123 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10126 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10128 /// This routine either breaks down the specific type of a 512-bit x86 vector
10129 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10130 /// together based on the available instructions.
10131 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10132 MVT VT, const X86Subtarget *Subtarget,
10133 SelectionDAG &DAG) {
10135 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10136 ArrayRef<int> Mask = SVOp->getMask();
10137 assert(Subtarget->hasAVX512() &&
10138 "Cannot lower 512-bit vectors w/ basic ISA!");
10140 // Check for being able to broadcast a single element.
10141 if (SDValue Broadcast =
10142 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10145 // Dispatch to each element type for lowering. If we don't have supprot for
10146 // specific element type shuffles at 512 bits, immediately split them and
10147 // lower them. Each lowering routine of a given type is allowed to assume that
10148 // the requisite ISA extensions for that element type are available.
10149 switch (VT.SimpleTy) {
10151 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10153 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10155 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10157 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10159 if (Subtarget->hasBWI())
10160 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10163 if (Subtarget->hasBWI())
10164 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10168 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10171 // Otherwise fall back on splitting.
10172 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10175 /// \brief Top-level lowering for x86 vector shuffles.
10177 /// This handles decomposition, canonicalization, and lowering of all x86
10178 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10179 /// above in helper routines. The canonicalization attempts to widen shuffles
10180 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10181 /// s.t. only one of the two inputs needs to be tested, etc.
10182 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10183 SelectionDAG &DAG) {
10184 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10185 ArrayRef<int> Mask = SVOp->getMask();
10186 SDValue V1 = Op.getOperand(0);
10187 SDValue V2 = Op.getOperand(1);
10188 MVT VT = Op.getSimpleValueType();
10189 int NumElements = VT.getVectorNumElements();
10192 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10194 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10195 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10196 if (V1IsUndef && V2IsUndef)
10197 return DAG.getUNDEF(VT);
10199 // When we create a shuffle node we put the UNDEF node to second operand,
10200 // but in some cases the first operand may be transformed to UNDEF.
10201 // In this case we should just commute the node.
10203 return DAG.getCommutedVectorShuffle(*SVOp);
10205 // Check for non-undef masks pointing at an undef vector and make the masks
10206 // undef as well. This makes it easier to match the shuffle based solely on
10210 if (M >= NumElements) {
10211 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10212 for (int &M : NewMask)
10213 if (M >= NumElements)
10215 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10218 // We actually see shuffles that are entirely re-arrangements of a set of
10219 // zero inputs. This mostly happens while decomposing complex shuffles into
10220 // simple ones. Directly lower these as a buildvector of zeros.
10221 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10222 if (Zeroable.all())
10223 return getZeroVector(VT, Subtarget, DAG, dl);
10225 // Try to collapse shuffles into using a vector type with fewer elements but
10226 // wider element types. We cap this to not form integers or floating point
10227 // elements wider than 64 bits, but it might be interesting to form i128
10228 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10229 SmallVector<int, 16> WidenedMask;
10230 if (VT.getScalarSizeInBits() < 64 &&
10231 canWidenShuffleElements(Mask, WidenedMask)) {
10232 MVT NewEltVT = VT.isFloatingPoint()
10233 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10234 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10235 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10236 // Make sure that the new vector type is legal. For example, v2f64 isn't
10238 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10239 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10240 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10241 return DAG.getNode(ISD::BITCAST, dl, VT,
10242 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10246 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10247 for (int M : SVOp->getMask())
10249 ++NumUndefElements;
10250 else if (M < NumElements)
10255 // Commute the shuffle as needed such that more elements come from V1 than
10256 // V2. This allows us to match the shuffle pattern strictly on how many
10257 // elements come from V1 without handling the symmetric cases.
10258 if (NumV2Elements > NumV1Elements)
10259 return DAG.getCommutedVectorShuffle(*SVOp);
10261 // When the number of V1 and V2 elements are the same, try to minimize the
10262 // number of uses of V2 in the low half of the vector. When that is tied,
10263 // ensure that the sum of indices for V1 is equal to or lower than the sum
10264 // indices for V2. When those are equal, try to ensure that the number of odd
10265 // indices for V1 is lower than the number of odd indices for V2.
10266 if (NumV1Elements == NumV2Elements) {
10267 int LowV1Elements = 0, LowV2Elements = 0;
10268 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10269 if (M >= NumElements)
10273 if (LowV2Elements > LowV1Elements) {
10274 return DAG.getCommutedVectorShuffle(*SVOp);
10275 } else if (LowV2Elements == LowV1Elements) {
10276 int SumV1Indices = 0, SumV2Indices = 0;
10277 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10278 if (SVOp->getMask()[i] >= NumElements)
10280 else if (SVOp->getMask()[i] >= 0)
10282 if (SumV2Indices < SumV1Indices) {
10283 return DAG.getCommutedVectorShuffle(*SVOp);
10284 } else if (SumV2Indices == SumV1Indices) {
10285 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10286 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10287 if (SVOp->getMask()[i] >= NumElements)
10288 NumV2OddIndices += i % 2;
10289 else if (SVOp->getMask()[i] >= 0)
10290 NumV1OddIndices += i % 2;
10291 if (NumV2OddIndices < NumV1OddIndices)
10292 return DAG.getCommutedVectorShuffle(*SVOp);
10297 // For each vector width, delegate to a specialized lowering routine.
10298 if (VT.getSizeInBits() == 128)
10299 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10301 if (VT.getSizeInBits() == 256)
10302 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10304 // Force AVX-512 vectors to be scalarized for now.
10305 // FIXME: Implement AVX-512 support!
10306 if (VT.getSizeInBits() == 512)
10307 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10309 llvm_unreachable("Unimplemented!");
10312 // This function assumes its argument is a BUILD_VECTOR of constants or
10313 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10315 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10316 unsigned &MaskValue) {
10318 unsigned NumElems = BuildVector->getNumOperands();
10319 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10320 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10321 unsigned NumElemsInLane = NumElems / NumLanes;
10323 // Blend for v16i16 should be symetric for the both lanes.
10324 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10325 SDValue EltCond = BuildVector->getOperand(i);
10326 SDValue SndLaneEltCond =
10327 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10329 int Lane1Cond = -1, Lane2Cond = -1;
10330 if (isa<ConstantSDNode>(EltCond))
10331 Lane1Cond = !isZero(EltCond);
10332 if (isa<ConstantSDNode>(SndLaneEltCond))
10333 Lane2Cond = !isZero(SndLaneEltCond);
10335 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10336 // Lane1Cond != 0, means we want the first argument.
10337 // Lane1Cond == 0, means we want the second argument.
10338 // The encoding of this argument is 0 for the first argument, 1
10339 // for the second. Therefore, invert the condition.
10340 MaskValue |= !Lane1Cond << i;
10341 else if (Lane1Cond < 0)
10342 MaskValue |= !Lane2Cond << i;
10349 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10350 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10351 const X86Subtarget *Subtarget,
10352 SelectionDAG &DAG) {
10353 SDValue Cond = Op.getOperand(0);
10354 SDValue LHS = Op.getOperand(1);
10355 SDValue RHS = Op.getOperand(2);
10357 MVT VT = Op.getSimpleValueType();
10359 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10361 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10363 // Only non-legal VSELECTs reach this lowering, convert those into generic
10364 // shuffles and re-use the shuffle lowering path for blends.
10365 SmallVector<int, 32> Mask;
10366 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10367 SDValue CondElt = CondBV->getOperand(i);
10369 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10371 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10374 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10375 // A vselect where all conditions and data are constants can be optimized into
10376 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10377 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10378 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10379 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10382 // Try to lower this to a blend-style vector shuffle. This can handle all
10383 // constant condition cases.
10384 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10387 // Variable blends are only legal from SSE4.1 onward.
10388 if (!Subtarget->hasSSE41())
10391 // Only some types will be legal on some subtargets. If we can emit a legal
10392 // VSELECT-matching blend, return Op, and but if we need to expand, return
10394 switch (Op.getSimpleValueType().SimpleTy) {
10396 // Most of the vector types have blends past SSE4.1.
10400 // The byte blends for AVX vectors were introduced only in AVX2.
10401 if (Subtarget->hasAVX2())
10408 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10409 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10412 // FIXME: We should custom lower this by fixing the condition and using i8
10418 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10419 MVT VT = Op.getSimpleValueType();
10422 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10425 if (VT.getSizeInBits() == 8) {
10426 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10427 Op.getOperand(0), Op.getOperand(1));
10428 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10429 DAG.getValueType(VT));
10430 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10433 if (VT.getSizeInBits() == 16) {
10434 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10435 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10437 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10438 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10439 DAG.getNode(ISD::BITCAST, dl,
10442 Op.getOperand(1)));
10443 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10444 Op.getOperand(0), Op.getOperand(1));
10445 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10446 DAG.getValueType(VT));
10447 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10450 if (VT == MVT::f32) {
10451 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10452 // the result back to FR32 register. It's only worth matching if the
10453 // result has a single use which is a store or a bitcast to i32. And in
10454 // the case of a store, it's not worth it if the index is a constant 0,
10455 // because a MOVSSmr can be used instead, which is smaller and faster.
10456 if (!Op.hasOneUse())
10458 SDNode *User = *Op.getNode()->use_begin();
10459 if ((User->getOpcode() != ISD::STORE ||
10460 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10461 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10462 (User->getOpcode() != ISD::BITCAST ||
10463 User->getValueType(0) != MVT::i32))
10465 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10466 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10469 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10472 if (VT == MVT::i32 || VT == MVT::i64) {
10473 // ExtractPS/pextrq works with constant index.
10474 if (isa<ConstantSDNode>(Op.getOperand(1)))
10480 /// Extract one bit from mask vector, like v16i1 or v8i1.
10481 /// AVX-512 feature.
10483 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10484 SDValue Vec = Op.getOperand(0);
10486 MVT VecVT = Vec.getSimpleValueType();
10487 SDValue Idx = Op.getOperand(1);
10488 MVT EltVT = Op.getSimpleValueType();
10490 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10491 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10492 "Unexpected vector type in ExtractBitFromMaskVector");
10494 // variable index can't be handled in mask registers,
10495 // extend vector to VR512
10496 if (!isa<ConstantSDNode>(Idx)) {
10497 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10498 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10499 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10500 ExtVT.getVectorElementType(), Ext, Idx);
10501 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10504 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10505 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10506 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10507 rc = getRegClassFor(MVT::v16i1);
10508 unsigned MaxSift = rc->getSize()*8 - 1;
10509 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10510 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10511 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10512 DAG.getConstant(MaxSift, dl, MVT::i8));
10513 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10514 DAG.getIntPtrConstant(0, dl));
10518 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10519 SelectionDAG &DAG) const {
10521 SDValue Vec = Op.getOperand(0);
10522 MVT VecVT = Vec.getSimpleValueType();
10523 SDValue Idx = Op.getOperand(1);
10525 if (Op.getSimpleValueType() == MVT::i1)
10526 return ExtractBitFromMaskVector(Op, DAG);
10528 if (!isa<ConstantSDNode>(Idx)) {
10529 if (VecVT.is512BitVector() ||
10530 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10531 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10534 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10535 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10536 MaskEltVT.getSizeInBits());
10538 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10539 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10540 getZeroVector(MaskVT, Subtarget, DAG, dl),
10541 Idx, DAG.getConstant(0, dl, getPointerTy()));
10542 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10543 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10544 Perm, DAG.getConstant(0, dl, getPointerTy()));
10549 // If this is a 256-bit vector result, first extract the 128-bit vector and
10550 // then extract the element from the 128-bit vector.
10551 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10553 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10554 // Get the 128-bit vector.
10555 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10556 MVT EltVT = VecVT.getVectorElementType();
10558 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10560 //if (IdxVal >= NumElems/2)
10561 // IdxVal -= NumElems/2;
10562 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10563 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10564 DAG.getConstant(IdxVal, dl, MVT::i32));
10567 assert(VecVT.is128BitVector() && "Unexpected vector length");
10569 if (Subtarget->hasSSE41()) {
10570 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10575 MVT VT = Op.getSimpleValueType();
10576 // TODO: handle v16i8.
10577 if (VT.getSizeInBits() == 16) {
10578 SDValue Vec = Op.getOperand(0);
10579 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10581 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10582 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10583 DAG.getNode(ISD::BITCAST, dl,
10585 Op.getOperand(1)));
10586 // Transform it so it match pextrw which produces a 32-bit result.
10587 MVT EltVT = MVT::i32;
10588 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10589 Op.getOperand(0), Op.getOperand(1));
10590 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10591 DAG.getValueType(VT));
10592 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10595 if (VT.getSizeInBits() == 32) {
10596 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10600 // SHUFPS the element to the lowest double word, then movss.
10601 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10602 MVT VVT = Op.getOperand(0).getSimpleValueType();
10603 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10604 DAG.getUNDEF(VVT), Mask);
10605 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10606 DAG.getIntPtrConstant(0, dl));
10609 if (VT.getSizeInBits() == 64) {
10610 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10611 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10612 // to match extract_elt for f64.
10613 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10617 // UNPCKHPD the element to the lowest double word, then movsd.
10618 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10619 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10620 int Mask[2] = { 1, -1 };
10621 MVT VVT = Op.getOperand(0).getSimpleValueType();
10622 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10623 DAG.getUNDEF(VVT), Mask);
10624 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10625 DAG.getIntPtrConstant(0, dl));
10631 /// Insert one bit to mask vector, like v16i1 or v8i1.
10632 /// AVX-512 feature.
10634 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10636 SDValue Vec = Op.getOperand(0);
10637 SDValue Elt = Op.getOperand(1);
10638 SDValue Idx = Op.getOperand(2);
10639 MVT VecVT = Vec.getSimpleValueType();
10641 if (!isa<ConstantSDNode>(Idx)) {
10642 // Non constant index. Extend source and destination,
10643 // insert element and then truncate the result.
10644 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10645 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10646 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10647 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10648 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10649 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10652 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10653 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10654 if (Vec.getOpcode() == ISD::UNDEF)
10655 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10656 DAG.getConstant(IdxVal, dl, MVT::i8));
10657 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10658 unsigned MaxSift = rc->getSize()*8 - 1;
10659 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10660 DAG.getConstant(MaxSift, dl, MVT::i8));
10661 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10662 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10663 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10666 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10667 SelectionDAG &DAG) const {
10668 MVT VT = Op.getSimpleValueType();
10669 MVT EltVT = VT.getVectorElementType();
10671 if (EltVT == MVT::i1)
10672 return InsertBitToMaskVector(Op, DAG);
10675 SDValue N0 = Op.getOperand(0);
10676 SDValue N1 = Op.getOperand(1);
10677 SDValue N2 = Op.getOperand(2);
10678 if (!isa<ConstantSDNode>(N2))
10680 auto *N2C = cast<ConstantSDNode>(N2);
10681 unsigned IdxVal = N2C->getZExtValue();
10683 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10684 // into that, and then insert the subvector back into the result.
10685 if (VT.is256BitVector() || VT.is512BitVector()) {
10686 // With a 256-bit vector, we can insert into the zero element efficiently
10687 // using a blend if we have AVX or AVX2 and the right data type.
10688 if (VT.is256BitVector() && IdxVal == 0) {
10689 // TODO: It is worthwhile to cast integer to floating point and back
10690 // and incur a domain crossing penalty if that's what we'll end up
10691 // doing anyway after extracting to a 128-bit vector.
10692 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10693 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10694 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10695 N2 = DAG.getIntPtrConstant(1, dl);
10696 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10700 // Get the desired 128-bit vector chunk.
10701 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10703 // Insert the element into the desired chunk.
10704 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10705 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10707 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10708 DAG.getConstant(IdxIn128, dl, MVT::i32));
10710 // Insert the changed part back into the bigger vector
10711 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10713 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10715 if (Subtarget->hasSSE41()) {
10716 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10718 if (VT == MVT::v8i16) {
10719 Opc = X86ISD::PINSRW;
10721 assert(VT == MVT::v16i8);
10722 Opc = X86ISD::PINSRB;
10725 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10727 if (N1.getValueType() != MVT::i32)
10728 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10729 if (N2.getValueType() != MVT::i32)
10730 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10731 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10734 if (EltVT == MVT::f32) {
10735 // Bits [7:6] of the constant are the source select. This will always be
10736 // zero here. The DAG Combiner may combine an extract_elt index into
10737 // these bits. For example (insert (extract, 3), 2) could be matched by
10738 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10739 // Bits [5:4] of the constant are the destination select. This is the
10740 // value of the incoming immediate.
10741 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10742 // combine either bitwise AND or insert of float 0.0 to set these bits.
10744 const Function *F = DAG.getMachineFunction().getFunction();
10745 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10746 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10747 // If this is an insertion of 32-bits into the low 32-bits of
10748 // a vector, we prefer to generate a blend with immediate rather
10749 // than an insertps. Blends are simpler operations in hardware and so
10750 // will always have equal or better performance than insertps.
10751 // But if optimizing for size and there's a load folding opportunity,
10752 // generate insertps because blendps does not have a 32-bit memory
10754 N2 = DAG.getIntPtrConstant(1, dl);
10755 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10756 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10758 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10759 // Create this as a scalar to vector..
10760 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10761 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10764 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10765 // PINSR* works with constant index.
10770 if (EltVT == MVT::i8)
10773 if (EltVT.getSizeInBits() == 16) {
10774 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10775 // as its second argument.
10776 if (N1.getValueType() != MVT::i32)
10777 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10778 if (N2.getValueType() != MVT::i32)
10779 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10780 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10785 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10787 MVT OpVT = Op.getSimpleValueType();
10789 // If this is a 256-bit vector result, first insert into a 128-bit
10790 // vector and then insert into the 256-bit vector.
10791 if (!OpVT.is128BitVector()) {
10792 // Insert into a 128-bit vector.
10793 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10794 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10795 OpVT.getVectorNumElements() / SizeFactor);
10797 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10799 // Insert the 128-bit vector.
10800 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10803 if (OpVT == MVT::v1i64 &&
10804 Op.getOperand(0).getValueType() == MVT::i64)
10805 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10807 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10808 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10809 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10810 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10813 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10814 // a simple subregister reference or explicit instructions to grab
10815 // upper bits of a vector.
10816 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10817 SelectionDAG &DAG) {
10819 SDValue In = Op.getOperand(0);
10820 SDValue Idx = Op.getOperand(1);
10821 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10822 MVT ResVT = Op.getSimpleValueType();
10823 MVT InVT = In.getSimpleValueType();
10825 if (Subtarget->hasFp256()) {
10826 if (ResVT.is128BitVector() &&
10827 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10828 isa<ConstantSDNode>(Idx)) {
10829 return Extract128BitVector(In, IdxVal, DAG, dl);
10831 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10832 isa<ConstantSDNode>(Idx)) {
10833 return Extract256BitVector(In, IdxVal, DAG, dl);
10839 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10840 // simple superregister reference or explicit instructions to insert
10841 // the upper bits of a vector.
10842 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10843 SelectionDAG &DAG) {
10844 if (!Subtarget->hasAVX())
10848 SDValue Vec = Op.getOperand(0);
10849 SDValue SubVec = Op.getOperand(1);
10850 SDValue Idx = Op.getOperand(2);
10852 if (!isa<ConstantSDNode>(Idx))
10855 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10856 MVT OpVT = Op.getSimpleValueType();
10857 MVT SubVecVT = SubVec.getSimpleValueType();
10859 // Fold two 16-byte subvector loads into one 32-byte load:
10860 // (insert_subvector (insert_subvector undef, (load addr), 0),
10861 // (load addr + 16), Elts/2)
10863 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10864 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10865 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10866 !Subtarget->isUnalignedMem32Slow()) {
10867 SDValue SubVec2 = Vec.getOperand(1);
10868 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10869 if (Idx2->getZExtValue() == 0) {
10870 SDValue Ops[] = { SubVec2, SubVec };
10871 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10878 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10879 SubVecVT.is128BitVector())
10880 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10882 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10883 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10885 if (OpVT.getVectorElementType() == MVT::i1) {
10886 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10888 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10889 SDValue Undef = DAG.getUNDEF(OpVT);
10890 unsigned NumElems = OpVT.getVectorNumElements();
10891 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10893 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10894 // Zero upper bits of the Vec
10895 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10896 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10898 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10900 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10901 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10904 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10906 // Zero upper bits of the Vec2
10907 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10908 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10909 // Zero lower bits of the Vec
10910 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10911 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10912 // Merge them together
10913 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10919 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10920 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10921 // one of the above mentioned nodes. It has to be wrapped because otherwise
10922 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10923 // be used to form addressing mode. These wrapped nodes will be selected
10926 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10927 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10929 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10930 // global base reg.
10931 unsigned char OpFlag = 0;
10932 unsigned WrapperKind = X86ISD::Wrapper;
10933 CodeModel::Model M = DAG.getTarget().getCodeModel();
10935 if (Subtarget->isPICStyleRIPRel() &&
10936 (M == CodeModel::Small || M == CodeModel::Kernel))
10937 WrapperKind = X86ISD::WrapperRIP;
10938 else if (Subtarget->isPICStyleGOT())
10939 OpFlag = X86II::MO_GOTOFF;
10940 else if (Subtarget->isPICStyleStubPIC())
10941 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10943 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10944 CP->getAlignment(),
10945 CP->getOffset(), OpFlag);
10947 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10948 // With PIC, the address is actually $g + Offset.
10950 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10951 DAG.getNode(X86ISD::GlobalBaseReg,
10952 SDLoc(), getPointerTy()),
10959 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10960 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10962 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10963 // global base reg.
10964 unsigned char OpFlag = 0;
10965 unsigned WrapperKind = X86ISD::Wrapper;
10966 CodeModel::Model M = DAG.getTarget().getCodeModel();
10968 if (Subtarget->isPICStyleRIPRel() &&
10969 (M == CodeModel::Small || M == CodeModel::Kernel))
10970 WrapperKind = X86ISD::WrapperRIP;
10971 else if (Subtarget->isPICStyleGOT())
10972 OpFlag = X86II::MO_GOTOFF;
10973 else if (Subtarget->isPICStyleStubPIC())
10974 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10976 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10979 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10981 // With PIC, the address is actually $g + Offset.
10983 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10984 DAG.getNode(X86ISD::GlobalBaseReg,
10985 SDLoc(), getPointerTy()),
10992 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10993 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10995 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10996 // global base reg.
10997 unsigned char OpFlag = 0;
10998 unsigned WrapperKind = X86ISD::Wrapper;
10999 CodeModel::Model M = DAG.getTarget().getCodeModel();
11001 if (Subtarget->isPICStyleRIPRel() &&
11002 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11003 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11004 OpFlag = X86II::MO_GOTPCREL;
11005 WrapperKind = X86ISD::WrapperRIP;
11006 } else if (Subtarget->isPICStyleGOT()) {
11007 OpFlag = X86II::MO_GOT;
11008 } else if (Subtarget->isPICStyleStubPIC()) {
11009 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11010 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11011 OpFlag = X86II::MO_DARWIN_NONLAZY;
11014 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11017 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11019 // With PIC, the address is actually $g + Offset.
11020 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11021 !Subtarget->is64Bit()) {
11022 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11023 DAG.getNode(X86ISD::GlobalBaseReg,
11024 SDLoc(), getPointerTy()),
11028 // For symbols that require a load from a stub to get the address, emit the
11030 if (isGlobalStubReference(OpFlag))
11031 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11032 MachinePointerInfo::getGOT(), false, false, false, 0);
11038 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11039 // Create the TargetBlockAddressAddress node.
11040 unsigned char OpFlags =
11041 Subtarget->ClassifyBlockAddressReference();
11042 CodeModel::Model M = DAG.getTarget().getCodeModel();
11043 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11044 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11046 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11049 if (Subtarget->isPICStyleRIPRel() &&
11050 (M == CodeModel::Small || M == CodeModel::Kernel))
11051 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11053 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11055 // With PIC, the address is actually $g + Offset.
11056 if (isGlobalRelativeToPICBase(OpFlags)) {
11057 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11058 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11066 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11067 int64_t Offset, SelectionDAG &DAG) const {
11068 // Create the TargetGlobalAddress node, folding in the constant
11069 // offset if it is legal.
11070 unsigned char OpFlags =
11071 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11072 CodeModel::Model M = DAG.getTarget().getCodeModel();
11074 if (OpFlags == X86II::MO_NO_FLAG &&
11075 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11076 // A direct static reference to a global.
11077 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11080 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11083 if (Subtarget->isPICStyleRIPRel() &&
11084 (M == CodeModel::Small || M == CodeModel::Kernel))
11085 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11087 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11089 // With PIC, the address is actually $g + Offset.
11090 if (isGlobalRelativeToPICBase(OpFlags)) {
11091 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11092 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11096 // For globals that require a load from a stub to get the address, emit the
11098 if (isGlobalStubReference(OpFlags))
11099 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11100 MachinePointerInfo::getGOT(), false, false, false, 0);
11102 // If there was a non-zero offset that we didn't fold, create an explicit
11103 // addition for it.
11105 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11106 DAG.getConstant(Offset, dl, getPointerTy()));
11112 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11113 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11114 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11115 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11119 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11120 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11121 unsigned char OperandFlags, bool LocalDynamic = false) {
11122 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11123 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11125 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11126 GA->getValueType(0),
11130 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11134 SDValue Ops[] = { Chain, TGA, *InFlag };
11135 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11137 SDValue Ops[] = { Chain, TGA };
11138 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11141 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11142 MFI->setAdjustsStack(true);
11143 MFI->setHasCalls(true);
11145 SDValue Flag = Chain.getValue(1);
11146 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11149 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11151 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11154 SDLoc dl(GA); // ? function entry point might be better
11155 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11156 DAG.getNode(X86ISD::GlobalBaseReg,
11157 SDLoc(), PtrVT), InFlag);
11158 InFlag = Chain.getValue(1);
11160 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11163 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11165 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11167 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11168 X86::RAX, X86II::MO_TLSGD);
11171 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11177 // Get the start address of the TLS block for this module.
11178 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11179 .getInfo<X86MachineFunctionInfo>();
11180 MFI->incNumLocalDynamicTLSAccesses();
11184 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11185 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11188 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11189 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11190 InFlag = Chain.getValue(1);
11191 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11192 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11195 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11199 unsigned char OperandFlags = X86II::MO_DTPOFF;
11200 unsigned WrapperKind = X86ISD::Wrapper;
11201 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11202 GA->getValueType(0),
11203 GA->getOffset(), OperandFlags);
11204 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11206 // Add x@dtpoff with the base.
11207 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11210 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11211 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11212 const EVT PtrVT, TLSModel::Model model,
11213 bool is64Bit, bool isPIC) {
11216 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11217 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11218 is64Bit ? 257 : 256));
11220 SDValue ThreadPointer =
11221 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11222 MachinePointerInfo(Ptr), false, false, false, 0);
11224 unsigned char OperandFlags = 0;
11225 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11227 unsigned WrapperKind = X86ISD::Wrapper;
11228 if (model == TLSModel::LocalExec) {
11229 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11230 } else if (model == TLSModel::InitialExec) {
11232 OperandFlags = X86II::MO_GOTTPOFF;
11233 WrapperKind = X86ISD::WrapperRIP;
11235 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11238 llvm_unreachable("Unexpected model");
11241 // emit "addl x@ntpoff,%eax" (local exec)
11242 // or "addl x@indntpoff,%eax" (initial exec)
11243 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11245 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11246 GA->getOffset(), OperandFlags);
11247 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11249 if (model == TLSModel::InitialExec) {
11250 if (isPIC && !is64Bit) {
11251 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11252 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11256 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11257 MachinePointerInfo::getGOT(), false, false, false, 0);
11260 // The address of the thread local variable is the add of the thread
11261 // pointer with the offset of the variable.
11262 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11266 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11268 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11269 const GlobalValue *GV = GA->getGlobal();
11271 if (Subtarget->isTargetELF()) {
11272 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11275 case TLSModel::GeneralDynamic:
11276 if (Subtarget->is64Bit())
11277 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11278 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11279 case TLSModel::LocalDynamic:
11280 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11281 Subtarget->is64Bit());
11282 case TLSModel::InitialExec:
11283 case TLSModel::LocalExec:
11284 return LowerToTLSExecModel(
11285 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11286 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11288 llvm_unreachable("Unknown TLS model.");
11291 if (Subtarget->isTargetDarwin()) {
11292 // Darwin only has one model of TLS. Lower to that.
11293 unsigned char OpFlag = 0;
11294 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11295 X86ISD::WrapperRIP : X86ISD::Wrapper;
11297 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11298 // global base reg.
11299 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11300 !Subtarget->is64Bit();
11302 OpFlag = X86II::MO_TLVP_PIC_BASE;
11304 OpFlag = X86II::MO_TLVP;
11306 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11307 GA->getValueType(0),
11308 GA->getOffset(), OpFlag);
11309 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11311 // With PIC32, the address is actually $g + Offset.
11313 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11314 DAG.getNode(X86ISD::GlobalBaseReg,
11315 SDLoc(), getPointerTy()),
11318 // Lowering the machine isd will make sure everything is in the right
11320 SDValue Chain = DAG.getEntryNode();
11321 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11322 SDValue Args[] = { Chain, Offset };
11323 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11325 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11326 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11327 MFI->setAdjustsStack(true);
11329 // And our return value (tls address) is in the standard call return value
11331 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11332 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11333 Chain.getValue(1));
11336 if (Subtarget->isTargetKnownWindowsMSVC() ||
11337 Subtarget->isTargetWindowsGNU()) {
11338 // Just use the implicit TLS architecture
11339 // Need to generate someting similar to:
11340 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11342 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11343 // mov rcx, qword [rdx+rcx*8]
11344 // mov eax, .tls$:tlsvar
11345 // [rax+rcx] contains the address
11346 // Windows 64bit: gs:0x58
11347 // Windows 32bit: fs:__tls_array
11350 SDValue Chain = DAG.getEntryNode();
11352 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11353 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11354 // use its literal value of 0x2C.
11355 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11356 ? Type::getInt8PtrTy(*DAG.getContext(),
11358 : Type::getInt32PtrTy(*DAG.getContext(),
11362 Subtarget->is64Bit()
11363 ? DAG.getIntPtrConstant(0x58, dl)
11364 : (Subtarget->isTargetWindowsGNU()
11365 ? DAG.getIntPtrConstant(0x2C, dl)
11366 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11368 SDValue ThreadPointer =
11369 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11370 MachinePointerInfo(Ptr), false, false, false, 0);
11372 // Load the _tls_index variable
11373 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11374 if (Subtarget->is64Bit())
11375 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11376 IDX, MachinePointerInfo(), MVT::i32,
11377 false, false, false, 0);
11379 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11380 false, false, false, 0);
11382 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11384 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11386 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11387 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11388 false, false, false, 0);
11390 // Get the offset of start of .tls section
11391 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11392 GA->getValueType(0),
11393 GA->getOffset(), X86II::MO_SECREL);
11394 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11396 // The address of the thread local variable is the add of the thread
11397 // pointer with the offset of the variable.
11398 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11401 llvm_unreachable("TLS not implemented for this target.");
11404 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11405 /// and take a 2 x i32 value to shift plus a shift amount.
11406 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11407 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11408 MVT VT = Op.getSimpleValueType();
11409 unsigned VTBits = VT.getSizeInBits();
11411 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11412 SDValue ShOpLo = Op.getOperand(0);
11413 SDValue ShOpHi = Op.getOperand(1);
11414 SDValue ShAmt = Op.getOperand(2);
11415 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11416 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11418 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11419 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11420 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11421 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11422 : DAG.getConstant(0, dl, VT);
11424 SDValue Tmp2, Tmp3;
11425 if (Op.getOpcode() == ISD::SHL_PARTS) {
11426 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11427 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11429 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11430 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11433 // If the shift amount is larger or equal than the width of a part we can't
11434 // rely on the results of shld/shrd. Insert a test and select the appropriate
11435 // values for large shift amounts.
11436 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11437 DAG.getConstant(VTBits, dl, MVT::i8));
11438 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11439 AndNode, DAG.getConstant(0, dl, MVT::i8));
11442 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11443 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11444 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11446 if (Op.getOpcode() == ISD::SHL_PARTS) {
11447 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11448 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11450 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11451 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11454 SDValue Ops[2] = { Lo, Hi };
11455 return DAG.getMergeValues(Ops, dl);
11458 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11459 SelectionDAG &DAG) const {
11460 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11463 if (SrcVT.isVector()) {
11464 if (SrcVT.getVectorElementType() == MVT::i1) {
11465 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11466 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11467 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11468 Op.getOperand(0)));
11473 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11474 "Unknown SINT_TO_FP to lower!");
11476 // These are really Legal; return the operand so the caller accepts it as
11478 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11480 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11481 Subtarget->is64Bit()) {
11485 unsigned Size = SrcVT.getSizeInBits()/8;
11486 MachineFunction &MF = DAG.getMachineFunction();
11487 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11488 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11489 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11491 MachinePointerInfo::getFixedStack(SSFI),
11493 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11496 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11498 SelectionDAG &DAG) const {
11502 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11504 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11506 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11508 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11510 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11511 MachineMemOperand *MMO;
11513 int SSFI = FI->getIndex();
11515 DAG.getMachineFunction()
11516 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11517 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11519 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11520 StackSlot = StackSlot.getOperand(1);
11522 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11523 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11525 Tys, Ops, SrcVT, MMO);
11528 Chain = Result.getValue(1);
11529 SDValue InFlag = Result.getValue(2);
11531 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11532 // shouldn't be necessary except that RFP cannot be live across
11533 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11534 MachineFunction &MF = DAG.getMachineFunction();
11535 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11536 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11537 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11538 Tys = DAG.getVTList(MVT::Other);
11540 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11542 MachineMemOperand *MMO =
11543 DAG.getMachineFunction()
11544 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11545 MachineMemOperand::MOStore, SSFISize, SSFISize);
11547 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11548 Ops, Op.getValueType(), MMO);
11549 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11550 MachinePointerInfo::getFixedStack(SSFI),
11551 false, false, false, 0);
11557 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11558 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11559 SelectionDAG &DAG) const {
11560 // This algorithm is not obvious. Here it is what we're trying to output:
11563 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11564 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11566 haddpd %xmm0, %xmm0
11568 pshufd $0x4e, %xmm0, %xmm1
11574 LLVMContext *Context = DAG.getContext();
11576 // Build some magic constants.
11577 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11578 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11579 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11581 SmallVector<Constant*,2> CV1;
11583 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11584 APInt(64, 0x4330000000000000ULL))));
11586 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11587 APInt(64, 0x4530000000000000ULL))));
11588 Constant *C1 = ConstantVector::get(CV1);
11589 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11591 // Load the 64-bit value into an XMM register.
11592 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11594 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11595 MachinePointerInfo::getConstantPool(),
11596 false, false, false, 16);
11597 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11598 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11601 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11602 MachinePointerInfo::getConstantPool(),
11603 false, false, false, 16);
11604 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11605 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11608 if (Subtarget->hasSSE3()) {
11609 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11610 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11612 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11613 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11615 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11616 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11620 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11621 DAG.getIntPtrConstant(0, dl));
11624 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11625 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11626 SelectionDAG &DAG) const {
11628 // FP constant to bias correct the final result.
11629 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11632 // Load the 32-bit value into an XMM register.
11633 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11636 // Zero out the upper parts of the register.
11637 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11639 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11640 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11641 DAG.getIntPtrConstant(0, dl));
11643 // Or the load with the bias.
11644 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11645 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11646 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11647 MVT::v2f64, Load)),
11648 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11649 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11650 MVT::v2f64, Bias)));
11651 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11652 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11653 DAG.getIntPtrConstant(0, dl));
11655 // Subtract the bias.
11656 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11658 // Handle final rounding.
11659 EVT DestVT = Op.getValueType();
11661 if (DestVT.bitsLT(MVT::f64))
11662 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11663 DAG.getIntPtrConstant(0, dl));
11664 if (DestVT.bitsGT(MVT::f64))
11665 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11667 // Handle final rounding.
11671 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11672 const X86Subtarget &Subtarget) {
11673 // The algorithm is the following:
11674 // #ifdef __SSE4_1__
11675 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11676 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11677 // (uint4) 0x53000000, 0xaa);
11679 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11680 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11682 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11683 // return (float4) lo + fhi;
11686 SDValue V = Op->getOperand(0);
11687 EVT VecIntVT = V.getValueType();
11688 bool Is128 = VecIntVT == MVT::v4i32;
11689 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11690 // If we convert to something else than the supported type, e.g., to v4f64,
11692 if (VecFloatVT != Op->getValueType(0))
11695 unsigned NumElts = VecIntVT.getVectorNumElements();
11696 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11697 "Unsupported custom type");
11698 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11700 // In the #idef/#else code, we have in common:
11701 // - The vector of constants:
11707 // Create the splat vector for 0x4b000000.
11708 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11709 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11710 CstLow, CstLow, CstLow, CstLow};
11711 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11712 makeArrayRef(&CstLowArray[0], NumElts));
11713 // Create the splat vector for 0x53000000.
11714 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11715 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11716 CstHigh, CstHigh, CstHigh, CstHigh};
11717 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11718 makeArrayRef(&CstHighArray[0], NumElts));
11720 // Create the right shift.
11721 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11722 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11723 CstShift, CstShift, CstShift, CstShift};
11724 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11725 makeArrayRef(&CstShiftArray[0], NumElts));
11726 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11729 if (Subtarget.hasSSE41()) {
11730 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11731 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11732 SDValue VecCstLowBitcast =
11733 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11734 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11735 // Low will be bitcasted right away, so do not bother bitcasting back to its
11737 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11738 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11739 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11740 // (uint4) 0x53000000, 0xaa);
11741 SDValue VecCstHighBitcast =
11742 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11743 SDValue VecShiftBitcast =
11744 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11745 // High will be bitcasted right away, so do not bother bitcasting back to
11746 // its original type.
11747 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11748 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11750 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11751 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11752 CstMask, CstMask, CstMask);
11753 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11754 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11755 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11757 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11758 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11761 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11762 SDValue CstFAdd = DAG.getConstantFP(
11763 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11764 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11765 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11766 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11767 makeArrayRef(&CstFAddArray[0], NumElts));
11769 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11770 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11772 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11773 // return (float4) lo + fhi;
11774 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11775 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11778 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11779 SelectionDAG &DAG) const {
11780 SDValue N0 = Op.getOperand(0);
11781 MVT SVT = N0.getSimpleValueType();
11784 switch (SVT.SimpleTy) {
11786 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11791 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11792 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11793 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11797 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11800 if (Subtarget->hasAVX512())
11801 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11802 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11804 llvm_unreachable(nullptr);
11807 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11808 SelectionDAG &DAG) const {
11809 SDValue N0 = Op.getOperand(0);
11812 if (Op.getValueType().isVector())
11813 return lowerUINT_TO_FP_vec(Op, DAG);
11815 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11816 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11817 // the optimization here.
11818 if (DAG.SignBitIsZero(N0))
11819 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11821 MVT SrcVT = N0.getSimpleValueType();
11822 MVT DstVT = Op.getSimpleValueType();
11823 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11824 return LowerUINT_TO_FP_i64(Op, DAG);
11825 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11826 return LowerUINT_TO_FP_i32(Op, DAG);
11827 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11830 // Make a 64-bit buffer, and use it to build an FILD.
11831 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11832 if (SrcVT == MVT::i32) {
11833 SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11834 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11835 getPointerTy(), StackSlot, WordOff);
11836 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11837 StackSlot, MachinePointerInfo(),
11839 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11840 OffsetSlot, MachinePointerInfo(),
11842 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11846 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11847 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11848 StackSlot, MachinePointerInfo(),
11850 // For i64 source, we need to add the appropriate power of 2 if the input
11851 // was negative. This is the same as the optimization in
11852 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11853 // we must be careful to do the computation in x87 extended precision, not
11854 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11855 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11856 MachineMemOperand *MMO =
11857 DAG.getMachineFunction()
11858 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11859 MachineMemOperand::MOLoad, 8, 8);
11861 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11862 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11863 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11866 APInt FF(32, 0x5F800000ULL);
11868 // Check whether the sign bit is set.
11869 SDValue SignSet = DAG.getSetCC(dl,
11870 getSetCCResultType(*DAG.getContext(), MVT::i64),
11872 DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11874 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11875 SDValue FudgePtr = DAG.getConstantPool(
11876 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11879 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11880 SDValue Zero = DAG.getIntPtrConstant(0, dl);
11881 SDValue Four = DAG.getIntPtrConstant(4, dl);
11882 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11884 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11886 // Load the value out, extending it from f32 to f80.
11887 // FIXME: Avoid the extend by constructing the right constant pool?
11888 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11889 FudgePtr, MachinePointerInfo::getConstantPool(),
11890 MVT::f32, false, false, false, 4);
11891 // Extend everything to 80 bits to force it to be done on x87.
11892 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11893 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11894 DAG.getIntPtrConstant(0, dl));
11897 std::pair<SDValue,SDValue>
11898 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11899 bool IsSigned, bool IsReplace) const {
11902 EVT DstTy = Op.getValueType();
11904 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11905 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11909 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11910 DstTy.getSimpleVT() >= MVT::i16 &&
11911 "Unknown FP_TO_INT to lower!");
11913 // These are really Legal.
11914 if (DstTy == MVT::i32 &&
11915 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11916 return std::make_pair(SDValue(), SDValue());
11917 if (Subtarget->is64Bit() &&
11918 DstTy == MVT::i64 &&
11919 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11920 return std::make_pair(SDValue(), SDValue());
11922 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11923 // stack slot, or into the FTOL runtime function.
11924 MachineFunction &MF = DAG.getMachineFunction();
11925 unsigned MemSize = DstTy.getSizeInBits()/8;
11926 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11927 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11930 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11931 Opc = X86ISD::WIN_FTOL;
11933 switch (DstTy.getSimpleVT().SimpleTy) {
11934 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11935 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11936 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11937 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11940 SDValue Chain = DAG.getEntryNode();
11941 SDValue Value = Op.getOperand(0);
11942 EVT TheVT = Op.getOperand(0).getValueType();
11943 // FIXME This causes a redundant load/store if the SSE-class value is already
11944 // in memory, such as if it is on the callstack.
11945 if (isScalarFPTypeInSSEReg(TheVT)) {
11946 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11947 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11948 MachinePointerInfo::getFixedStack(SSFI),
11950 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11952 Chain, StackSlot, DAG.getValueType(TheVT)
11955 MachineMemOperand *MMO =
11956 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11957 MachineMemOperand::MOLoad, MemSize, MemSize);
11958 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11959 Chain = Value.getValue(1);
11960 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11961 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11964 MachineMemOperand *MMO =
11965 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11966 MachineMemOperand::MOStore, MemSize, MemSize);
11968 if (Opc != X86ISD::WIN_FTOL) {
11969 // Build the FP_TO_INT*_IN_MEM
11970 SDValue Ops[] = { Chain, Value, StackSlot };
11971 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11973 return std::make_pair(FIST, StackSlot);
11975 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11976 DAG.getVTList(MVT::Other, MVT::Glue),
11978 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11979 MVT::i32, ftol.getValue(1));
11980 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11981 MVT::i32, eax.getValue(2));
11982 SDValue Ops[] = { eax, edx };
11983 SDValue pair = IsReplace
11984 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11985 : DAG.getMergeValues(Ops, DL);
11986 return std::make_pair(pair, SDValue());
11990 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11991 const X86Subtarget *Subtarget) {
11992 MVT VT = Op->getSimpleValueType(0);
11993 SDValue In = Op->getOperand(0);
11994 MVT InVT = In.getSimpleValueType();
11997 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
11998 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12000 // Optimize vectors in AVX mode:
12003 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12004 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12005 // Concat upper and lower parts.
12008 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12009 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12010 // Concat upper and lower parts.
12013 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12014 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12015 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12018 if (Subtarget->hasInt256())
12019 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12021 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12022 SDValue Undef = DAG.getUNDEF(InVT);
12023 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12024 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12025 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12027 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12028 VT.getVectorNumElements()/2);
12030 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12031 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12033 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12036 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12037 SelectionDAG &DAG) {
12038 MVT VT = Op->getSimpleValueType(0);
12039 SDValue In = Op->getOperand(0);
12040 MVT InVT = In.getSimpleValueType();
12042 unsigned int NumElts = VT.getVectorNumElements();
12043 if (NumElts != 8 && NumElts != 16)
12046 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12047 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12049 assert(InVT.getVectorElementType() == MVT::i1);
12050 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12052 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12054 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12056 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12057 if (VT.is512BitVector())
12059 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12062 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12063 SelectionDAG &DAG) {
12064 if (Subtarget->hasFp256()) {
12065 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12073 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12074 SelectionDAG &DAG) {
12076 MVT VT = Op.getSimpleValueType();
12077 SDValue In = Op.getOperand(0);
12078 MVT SVT = In.getSimpleValueType();
12080 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12081 return LowerZERO_EXTEND_AVX512(Op, DAG);
12083 if (Subtarget->hasFp256()) {
12084 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12089 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12090 VT.getVectorNumElements() != SVT.getVectorNumElements());
12094 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12096 MVT VT = Op.getSimpleValueType();
12097 SDValue In = Op.getOperand(0);
12098 MVT InVT = In.getSimpleValueType();
12100 if (VT == MVT::i1) {
12101 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12102 "Invalid scalar TRUNCATE operation");
12103 if (InVT.getSizeInBits() >= 32)
12105 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12106 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12108 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12109 "Invalid TRUNCATE operation");
12111 // move vector to mask - truncate solution for SKX
12112 if (VT.getVectorElementType() == MVT::i1) {
12113 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12114 Subtarget->hasBWI())
12115 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12116 if ((InVT.is256BitVector() || InVT.is128BitVector())
12117 && InVT.getScalarSizeInBits() <= 16 &&
12118 Subtarget->hasBWI() && Subtarget->hasVLX())
12119 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12120 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12121 Subtarget->hasDQI())
12122 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12123 if ((InVT.is256BitVector() || InVT.is128BitVector())
12124 && InVT.getScalarSizeInBits() >= 32 &&
12125 Subtarget->hasDQI() && Subtarget->hasVLX())
12126 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12128 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12129 if (VT.getVectorElementType().getSizeInBits() >=8)
12130 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12132 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12133 unsigned NumElts = InVT.getVectorNumElements();
12134 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12135 if (InVT.getSizeInBits() < 512) {
12136 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12137 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12142 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12143 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12144 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12147 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12148 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12149 if (Subtarget->hasInt256()) {
12150 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12151 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12152 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12154 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12155 DAG.getIntPtrConstant(0, DL));
12158 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12159 DAG.getIntPtrConstant(0, DL));
12160 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12161 DAG.getIntPtrConstant(2, DL));
12162 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12163 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12164 static const int ShufMask[] = {0, 2, 4, 6};
12165 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12168 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12169 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12170 if (Subtarget->hasInt256()) {
12171 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12173 SmallVector<SDValue,32> pshufbMask;
12174 for (unsigned i = 0; i < 2; ++i) {
12175 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12176 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12177 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12178 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12179 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12180 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12181 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12182 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12183 for (unsigned j = 0; j < 8; ++j)
12184 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12186 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12187 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12188 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12190 static const int ShufMask[] = {0, 2, -1, -1};
12191 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12193 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12194 DAG.getIntPtrConstant(0, DL));
12195 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12198 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12199 DAG.getIntPtrConstant(0, DL));
12201 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12202 DAG.getIntPtrConstant(4, DL));
12204 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12205 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12207 // The PSHUFB mask:
12208 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12209 -1, -1, -1, -1, -1, -1, -1, -1};
12211 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12212 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12213 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12215 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12216 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12218 // The MOVLHPS Mask:
12219 static const int ShufMask2[] = {0, 1, 4, 5};
12220 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12221 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12224 // Handle truncation of V256 to V128 using shuffles.
12225 if (!VT.is128BitVector() || !InVT.is256BitVector())
12228 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12230 unsigned NumElems = VT.getVectorNumElements();
12231 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12233 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12234 // Prepare truncation shuffle mask
12235 for (unsigned i = 0; i != NumElems; ++i)
12236 MaskVec[i] = i * 2;
12237 SDValue V = DAG.getVectorShuffle(NVT, DL,
12238 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12239 DAG.getUNDEF(NVT), &MaskVec[0]);
12240 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12241 DAG.getIntPtrConstant(0, DL));
12244 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12245 SelectionDAG &DAG) const {
12246 assert(!Op.getSimpleValueType().isVector());
12248 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12249 /*IsSigned=*/ true, /*IsReplace=*/ false);
12250 SDValue FIST = Vals.first, StackSlot = Vals.second;
12251 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12252 if (!FIST.getNode()) return Op;
12254 if (StackSlot.getNode())
12255 // Load the result.
12256 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12257 FIST, StackSlot, MachinePointerInfo(),
12258 false, false, false, 0);
12260 // The node is the result.
12264 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12265 SelectionDAG &DAG) const {
12266 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12267 /*IsSigned=*/ false, /*IsReplace=*/ false);
12268 SDValue FIST = Vals.first, StackSlot = Vals.second;
12269 assert(FIST.getNode() && "Unexpected failure");
12271 if (StackSlot.getNode())
12272 // Load the result.
12273 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12274 FIST, StackSlot, MachinePointerInfo(),
12275 false, false, false, 0);
12277 // The node is the result.
12281 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12283 MVT VT = Op.getSimpleValueType();
12284 SDValue In = Op.getOperand(0);
12285 MVT SVT = In.getSimpleValueType();
12287 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12289 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12290 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12291 In, DAG.getUNDEF(SVT)));
12294 /// The only differences between FABS and FNEG are the mask and the logic op.
12295 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12296 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12297 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12298 "Wrong opcode for lowering FABS or FNEG.");
12300 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12302 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12303 // into an FNABS. We'll lower the FABS after that if it is still in use.
12305 for (SDNode *User : Op->uses())
12306 if (User->getOpcode() == ISD::FNEG)
12309 SDValue Op0 = Op.getOperand(0);
12310 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12313 MVT VT = Op.getSimpleValueType();
12314 // Assume scalar op for initialization; update for vector if needed.
12315 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12316 // generate a 16-byte vector constant and logic op even for the scalar case.
12317 // Using a 16-byte mask allows folding the load of the mask with
12318 // the logic op, so it can save (~4 bytes) on code size.
12320 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12321 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12322 // decide if we should generate a 16-byte constant mask when we only need 4 or
12323 // 8 bytes for the scalar case.
12324 if (VT.isVector()) {
12325 EltVT = VT.getVectorElementType();
12326 NumElts = VT.getVectorNumElements();
12329 unsigned EltBits = EltVT.getSizeInBits();
12330 LLVMContext *Context = DAG.getContext();
12331 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12333 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12334 Constant *C = ConstantInt::get(*Context, MaskElt);
12335 C = ConstantVector::getSplat(NumElts, C);
12336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12337 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12338 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12339 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12340 MachinePointerInfo::getConstantPool(),
12341 false, false, false, Alignment);
12343 if (VT.isVector()) {
12344 // For a vector, cast operands to a vector type, perform the logic op,
12345 // and cast the result back to the original value type.
12346 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12347 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12348 SDValue Operand = IsFNABS ?
12349 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12350 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12351 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12352 return DAG.getNode(ISD::BITCAST, dl, VT,
12353 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12356 // If not vector, then scalar.
12357 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12358 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12359 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12362 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12364 LLVMContext *Context = DAG.getContext();
12365 SDValue Op0 = Op.getOperand(0);
12366 SDValue Op1 = Op.getOperand(1);
12368 MVT VT = Op.getSimpleValueType();
12369 MVT SrcVT = Op1.getSimpleValueType();
12371 // If second operand is smaller, extend it first.
12372 if (SrcVT.bitsLT(VT)) {
12373 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12376 // And if it is bigger, shrink it first.
12377 if (SrcVT.bitsGT(VT)) {
12378 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12382 // At this point the operands and the result should have the same
12383 // type, and that won't be f80 since that is not custom lowered.
12385 const fltSemantics &Sem =
12386 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12387 const unsigned SizeInBits = VT.getSizeInBits();
12389 SmallVector<Constant *, 4> CV(
12390 VT == MVT::f64 ? 2 : 4,
12391 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12393 // First, clear all bits but the sign bit from the second operand (sign).
12394 CV[0] = ConstantFP::get(*Context,
12395 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12396 Constant *C = ConstantVector::get(CV);
12397 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12398 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12399 MachinePointerInfo::getConstantPool(),
12400 false, false, false, 16);
12401 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12403 // Next, clear the sign bit from the first operand (magnitude).
12404 // If it's a constant, we can clear it here.
12405 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12406 APFloat APF = Op0CN->getValueAPF();
12407 // If the magnitude is a positive zero, the sign bit alone is enough.
12408 if (APF.isPosZero())
12411 CV[0] = ConstantFP::get(*Context, APF);
12413 CV[0] = ConstantFP::get(
12415 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12417 C = ConstantVector::get(CV);
12418 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12419 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12420 MachinePointerInfo::getConstantPool(),
12421 false, false, false, 16);
12422 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12423 if (!isa<ConstantFPSDNode>(Op0))
12424 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12426 // OR the magnitude value with the sign bit.
12427 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12430 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12431 SDValue N0 = Op.getOperand(0);
12433 MVT VT = Op.getSimpleValueType();
12435 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12436 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12437 DAG.getConstant(1, dl, VT));
12438 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12441 // Check whether an OR'd tree is PTEST-able.
12442 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12443 SelectionDAG &DAG) {
12444 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12446 if (!Subtarget->hasSSE41())
12449 if (!Op->hasOneUse())
12452 SDNode *N = Op.getNode();
12455 SmallVector<SDValue, 8> Opnds;
12456 DenseMap<SDValue, unsigned> VecInMap;
12457 SmallVector<SDValue, 8> VecIns;
12458 EVT VT = MVT::Other;
12460 // Recognize a special case where a vector is casted into wide integer to
12462 Opnds.push_back(N->getOperand(0));
12463 Opnds.push_back(N->getOperand(1));
12465 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12466 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12467 // BFS traverse all OR'd operands.
12468 if (I->getOpcode() == ISD::OR) {
12469 Opnds.push_back(I->getOperand(0));
12470 Opnds.push_back(I->getOperand(1));
12471 // Re-evaluate the number of nodes to be traversed.
12472 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12476 // Quit if a non-EXTRACT_VECTOR_ELT
12477 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12480 // Quit if without a constant index.
12481 SDValue Idx = I->getOperand(1);
12482 if (!isa<ConstantSDNode>(Idx))
12485 SDValue ExtractedFromVec = I->getOperand(0);
12486 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12487 if (M == VecInMap.end()) {
12488 VT = ExtractedFromVec.getValueType();
12489 // Quit if not 128/256-bit vector.
12490 if (!VT.is128BitVector() && !VT.is256BitVector())
12492 // Quit if not the same type.
12493 if (VecInMap.begin() != VecInMap.end() &&
12494 VT != VecInMap.begin()->first.getValueType())
12496 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12497 VecIns.push_back(ExtractedFromVec);
12499 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12502 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12503 "Not extracted from 128-/256-bit vector.");
12505 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12507 for (DenseMap<SDValue, unsigned>::const_iterator
12508 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12509 // Quit if not all elements are used.
12510 if (I->second != FullMask)
12514 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12516 // Cast all vectors into TestVT for PTEST.
12517 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12518 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12520 // If more than one full vectors are evaluated, OR them first before PTEST.
12521 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12522 // Each iteration will OR 2 nodes and append the result until there is only
12523 // 1 node left, i.e. the final OR'd value of all vectors.
12524 SDValue LHS = VecIns[Slot];
12525 SDValue RHS = VecIns[Slot + 1];
12526 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12529 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12530 VecIns.back(), VecIns.back());
12533 /// \brief return true if \c Op has a use that doesn't just read flags.
12534 static bool hasNonFlagsUse(SDValue Op) {
12535 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12537 SDNode *User = *UI;
12538 unsigned UOpNo = UI.getOperandNo();
12539 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12540 // Look pass truncate.
12541 UOpNo = User->use_begin().getOperandNo();
12542 User = *User->use_begin();
12545 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12546 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12552 /// Emit nodes that will be selected as "test Op0,Op0", or something
12554 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12555 SelectionDAG &DAG) const {
12556 if (Op.getValueType() == MVT::i1) {
12557 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12558 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12559 DAG.getConstant(0, dl, MVT::i8));
12561 // CF and OF aren't always set the way we want. Determine which
12562 // of these we need.
12563 bool NeedCF = false;
12564 bool NeedOF = false;
12567 case X86::COND_A: case X86::COND_AE:
12568 case X86::COND_B: case X86::COND_BE:
12571 case X86::COND_G: case X86::COND_GE:
12572 case X86::COND_L: case X86::COND_LE:
12573 case X86::COND_O: case X86::COND_NO: {
12574 // Check if we really need to set the
12575 // Overflow flag. If NoSignedWrap is present
12576 // that is not actually needed.
12577 switch (Op->getOpcode()) {
12582 const BinaryWithFlagsSDNode *BinNode =
12583 cast<BinaryWithFlagsSDNode>(Op.getNode());
12584 if (BinNode->Flags.hasNoSignedWrap())
12594 // See if we can use the EFLAGS value from the operand instead of
12595 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12596 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12597 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12598 // Emit a CMP with 0, which is the TEST pattern.
12599 //if (Op.getValueType() == MVT::i1)
12600 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12601 // DAG.getConstant(0, MVT::i1));
12602 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12603 DAG.getConstant(0, dl, Op.getValueType()));
12605 unsigned Opcode = 0;
12606 unsigned NumOperands = 0;
12608 // Truncate operations may prevent the merge of the SETCC instruction
12609 // and the arithmetic instruction before it. Attempt to truncate the operands
12610 // of the arithmetic instruction and use a reduced bit-width instruction.
12611 bool NeedTruncation = false;
12612 SDValue ArithOp = Op;
12613 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12614 SDValue Arith = Op->getOperand(0);
12615 // Both the trunc and the arithmetic op need to have one user each.
12616 if (Arith->hasOneUse())
12617 switch (Arith.getOpcode()) {
12624 NeedTruncation = true;
12630 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12631 // which may be the result of a CAST. We use the variable 'Op', which is the
12632 // non-casted variable when we check for possible users.
12633 switch (ArithOp.getOpcode()) {
12635 // Due to an isel shortcoming, be conservative if this add is likely to be
12636 // selected as part of a load-modify-store instruction. When the root node
12637 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12638 // uses of other nodes in the match, such as the ADD in this case. This
12639 // leads to the ADD being left around and reselected, with the result being
12640 // two adds in the output. Alas, even if none our users are stores, that
12641 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12642 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12643 // climbing the DAG back to the root, and it doesn't seem to be worth the
12645 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12646 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12647 if (UI->getOpcode() != ISD::CopyToReg &&
12648 UI->getOpcode() != ISD::SETCC &&
12649 UI->getOpcode() != ISD::STORE)
12652 if (ConstantSDNode *C =
12653 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12654 // An add of one will be selected as an INC.
12655 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12656 Opcode = X86ISD::INC;
12661 // An add of negative one (subtract of one) will be selected as a DEC.
12662 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12663 Opcode = X86ISD::DEC;
12669 // Otherwise use a regular EFLAGS-setting add.
12670 Opcode = X86ISD::ADD;
12675 // If we have a constant logical shift that's only used in a comparison
12676 // against zero turn it into an equivalent AND. This allows turning it into
12677 // a TEST instruction later.
12678 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12679 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12680 EVT VT = Op.getValueType();
12681 unsigned BitWidth = VT.getSizeInBits();
12682 unsigned ShAmt = Op->getConstantOperandVal(1);
12683 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12685 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12686 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12687 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12688 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12690 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12691 DAG.getConstant(Mask, dl, VT));
12692 DAG.ReplaceAllUsesWith(Op, New);
12698 // If the primary and result isn't used, don't bother using X86ISD::AND,
12699 // because a TEST instruction will be better.
12700 if (!hasNonFlagsUse(Op))
12706 // Due to the ISEL shortcoming noted above, be conservative if this op is
12707 // likely to be selected as part of a load-modify-store instruction.
12708 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12709 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12710 if (UI->getOpcode() == ISD::STORE)
12713 // Otherwise use a regular EFLAGS-setting instruction.
12714 switch (ArithOp.getOpcode()) {
12715 default: llvm_unreachable("unexpected operator!");
12716 case ISD::SUB: Opcode = X86ISD::SUB; break;
12717 case ISD::XOR: Opcode = X86ISD::XOR; break;
12718 case ISD::AND: Opcode = X86ISD::AND; break;
12720 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12721 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12722 if (EFLAGS.getNode())
12725 Opcode = X86ISD::OR;
12739 return SDValue(Op.getNode(), 1);
12745 // If we found that truncation is beneficial, perform the truncation and
12747 if (NeedTruncation) {
12748 EVT VT = Op.getValueType();
12749 SDValue WideVal = Op->getOperand(0);
12750 EVT WideVT = WideVal.getValueType();
12751 unsigned ConvertedOp = 0;
12752 // Use a target machine opcode to prevent further DAGCombine
12753 // optimizations that may separate the arithmetic operations
12754 // from the setcc node.
12755 switch (WideVal.getOpcode()) {
12757 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12758 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12759 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12760 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12761 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12765 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12766 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12767 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12768 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12769 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12775 // Emit a CMP with 0, which is the TEST pattern.
12776 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12777 DAG.getConstant(0, dl, Op.getValueType()));
12779 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12780 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12782 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12783 DAG.ReplaceAllUsesWith(Op, New);
12784 return SDValue(New.getNode(), 1);
12787 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12789 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12790 SDLoc dl, SelectionDAG &DAG) const {
12791 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12792 if (C->getAPIntValue() == 0)
12793 return EmitTest(Op0, X86CC, dl, DAG);
12795 if (Op0.getValueType() == MVT::i1)
12796 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12799 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12800 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12801 // Do the comparison at i32 if it's smaller, besides the Atom case.
12802 // This avoids subregister aliasing issues. Keep the smaller reference
12803 // if we're optimizing for size, however, as that'll allow better folding
12804 // of memory operations.
12805 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12806 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12807 Attribute::MinSize) &&
12808 !Subtarget->isAtom()) {
12809 unsigned ExtendOp =
12810 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12811 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12812 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12814 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12815 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12816 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12818 return SDValue(Sub.getNode(), 1);
12820 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12823 /// Convert a comparison if required by the subtarget.
12824 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12825 SelectionDAG &DAG) const {
12826 // If the subtarget does not support the FUCOMI instruction, floating-point
12827 // comparisons have to be converted.
12828 if (Subtarget->hasCMov() ||
12829 Cmp.getOpcode() != X86ISD::CMP ||
12830 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12831 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12834 // The instruction selector will select an FUCOM instruction instead of
12835 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12836 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12837 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12839 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12840 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12841 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12842 DAG.getConstant(8, dl, MVT::i8));
12843 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12844 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12847 /// The minimum architected relative accuracy is 2^-12. We need one
12848 /// Newton-Raphson step to have a good float result (24 bits of precision).
12849 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12850 DAGCombinerInfo &DCI,
12851 unsigned &RefinementSteps,
12852 bool &UseOneConstNR) const {
12853 // FIXME: We should use instruction latency models to calculate the cost of
12854 // each potential sequence, but this is very hard to do reliably because
12855 // at least Intel's Core* chips have variable timing based on the number of
12856 // significant digits in the divisor and/or sqrt operand.
12857 if (!Subtarget->useSqrtEst())
12860 EVT VT = Op.getValueType();
12862 // SSE1 has rsqrtss and rsqrtps.
12863 // TODO: Add support for AVX512 (v16f32).
12864 // It is likely not profitable to do this for f64 because a double-precision
12865 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12866 // instructions: convert to single, rsqrtss, convert back to double, refine
12867 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12868 // along with FMA, this could be a throughput win.
12869 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12870 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12871 RefinementSteps = 1;
12872 UseOneConstNR = false;
12873 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12878 /// The minimum architected relative accuracy is 2^-12. We need one
12879 /// Newton-Raphson step to have a good float result (24 bits of precision).
12880 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12881 DAGCombinerInfo &DCI,
12882 unsigned &RefinementSteps) const {
12883 // FIXME: We should use instruction latency models to calculate the cost of
12884 // each potential sequence, but this is very hard to do reliably because
12885 // at least Intel's Core* chips have variable timing based on the number of
12886 // significant digits in the divisor.
12887 if (!Subtarget->useReciprocalEst())
12890 EVT VT = Op.getValueType();
12892 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12893 // TODO: Add support for AVX512 (v16f32).
12894 // It is likely not profitable to do this for f64 because a double-precision
12895 // reciprocal estimate with refinement on x86 prior to FMA requires
12896 // 15 instructions: convert to single, rcpss, convert back to double, refine
12897 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12898 // along with FMA, this could be a throughput win.
12899 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12900 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12901 RefinementSteps = ReciprocalEstimateRefinementSteps;
12902 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12907 /// If we have at least two divisions that use the same divisor, convert to
12908 /// multplication by a reciprocal. This may need to be adjusted for a given
12909 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12910 /// This is because we still need one division to calculate the reciprocal and
12911 /// then we need two multiplies by that reciprocal as replacements for the
12912 /// original divisions.
12913 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12914 return NumUsers > 1;
12917 static bool isAllOnes(SDValue V) {
12918 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12919 return C && C->isAllOnesValue();
12922 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12923 /// if it's possible.
12924 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12925 SDLoc dl, SelectionDAG &DAG) const {
12926 SDValue Op0 = And.getOperand(0);
12927 SDValue Op1 = And.getOperand(1);
12928 if (Op0.getOpcode() == ISD::TRUNCATE)
12929 Op0 = Op0.getOperand(0);
12930 if (Op1.getOpcode() == ISD::TRUNCATE)
12931 Op1 = Op1.getOperand(0);
12934 if (Op1.getOpcode() == ISD::SHL)
12935 std::swap(Op0, Op1);
12936 if (Op0.getOpcode() == ISD::SHL) {
12937 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12938 if (And00C->getZExtValue() == 1) {
12939 // If we looked past a truncate, check that it's only truncating away
12941 unsigned BitWidth = Op0.getValueSizeInBits();
12942 unsigned AndBitWidth = And.getValueSizeInBits();
12943 if (BitWidth > AndBitWidth) {
12945 DAG.computeKnownBits(Op0, Zeros, Ones);
12946 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12950 RHS = Op0.getOperand(1);
12952 } else if (Op1.getOpcode() == ISD::Constant) {
12953 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12954 uint64_t AndRHSVal = AndRHS->getZExtValue();
12955 SDValue AndLHS = Op0;
12957 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12958 LHS = AndLHS.getOperand(0);
12959 RHS = AndLHS.getOperand(1);
12962 // Use BT if the immediate can't be encoded in a TEST instruction.
12963 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12965 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12969 if (LHS.getNode()) {
12970 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12971 // instruction. Since the shift amount is in-range-or-undefined, we know
12972 // that doing a bittest on the i32 value is ok. We extend to i32 because
12973 // the encoding for the i16 version is larger than the i32 version.
12974 // Also promote i16 to i32 for performance / code size reason.
12975 if (LHS.getValueType() == MVT::i8 ||
12976 LHS.getValueType() == MVT::i16)
12977 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12979 // If the operand types disagree, extend the shift amount to match. Since
12980 // BT ignores high bits (like shifts) we can use anyextend.
12981 if (LHS.getValueType() != RHS.getValueType())
12982 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12984 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12985 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12986 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12987 DAG.getConstant(Cond, dl, MVT::i8), BT);
12993 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12995 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13000 // SSE Condition code mapping:
13009 switch (SetCCOpcode) {
13010 default: llvm_unreachable("Unexpected SETCC condition");
13012 case ISD::SETEQ: SSECC = 0; break;
13014 case ISD::SETGT: Swap = true; // Fallthrough
13016 case ISD::SETOLT: SSECC = 1; break;
13018 case ISD::SETGE: Swap = true; // Fallthrough
13020 case ISD::SETOLE: SSECC = 2; break;
13021 case ISD::SETUO: SSECC = 3; break;
13023 case ISD::SETNE: SSECC = 4; break;
13024 case ISD::SETULE: Swap = true; // Fallthrough
13025 case ISD::SETUGE: SSECC = 5; break;
13026 case ISD::SETULT: Swap = true; // Fallthrough
13027 case ISD::SETUGT: SSECC = 6; break;
13028 case ISD::SETO: SSECC = 7; break;
13030 case ISD::SETONE: SSECC = 8; break;
13033 std::swap(Op0, Op1);
13038 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13039 // ones, and then concatenate the result back.
13040 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13041 MVT VT = Op.getSimpleValueType();
13043 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13044 "Unsupported value type for operation");
13046 unsigned NumElems = VT.getVectorNumElements();
13048 SDValue CC = Op.getOperand(2);
13050 // Extract the LHS vectors
13051 SDValue LHS = Op.getOperand(0);
13052 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13053 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13055 // Extract the RHS vectors
13056 SDValue RHS = Op.getOperand(1);
13057 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13058 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13060 // Issue the operation on the smaller types and concatenate the result back
13061 MVT EltVT = VT.getVectorElementType();
13062 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13063 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13064 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13065 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13068 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13069 SDValue Op0 = Op.getOperand(0);
13070 SDValue Op1 = Op.getOperand(1);
13071 SDValue CC = Op.getOperand(2);
13072 MVT VT = Op.getSimpleValueType();
13075 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13076 "Unexpected type for boolean compare operation");
13077 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13078 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13079 DAG.getConstant(-1, dl, VT));
13080 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13081 DAG.getConstant(-1, dl, VT));
13082 switch (SetCCOpcode) {
13083 default: llvm_unreachable("Unexpected SETCC condition");
13085 // (x != y) -> ~(x ^ y)
13086 return DAG.getNode(ISD::XOR, dl, VT,
13087 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13088 DAG.getConstant(-1, dl, VT));
13090 // (x == y) -> (x ^ y)
13091 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13094 // (x > y) -> (x & ~y)
13095 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13098 // (x < y) -> (~x & y)
13099 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13102 // (x <= y) -> (~x | y)
13103 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13106 // (x >=y) -> (x | ~y)
13107 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13111 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13112 const X86Subtarget *Subtarget) {
13113 SDValue Op0 = Op.getOperand(0);
13114 SDValue Op1 = Op.getOperand(1);
13115 SDValue CC = Op.getOperand(2);
13116 MVT VT = Op.getSimpleValueType();
13119 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13120 Op.getValueType().getScalarType() == MVT::i1 &&
13121 "Cannot set masked compare for this operation");
13123 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13125 bool Unsigned = false;
13128 switch (SetCCOpcode) {
13129 default: llvm_unreachable("Unexpected SETCC condition");
13130 case ISD::SETNE: SSECC = 4; break;
13131 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13132 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13133 case ISD::SETLT: Swap = true; //fall-through
13134 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13135 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13136 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13137 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13138 case ISD::SETULE: Unsigned = true; //fall-through
13139 case ISD::SETLE: SSECC = 2; break;
13143 std::swap(Op0, Op1);
13145 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13146 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13147 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13148 DAG.getConstant(SSECC, dl, MVT::i8));
13151 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13152 /// operand \p Op1. If non-trivial (for example because it's not constant)
13153 /// return an empty value.
13154 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13156 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13160 MVT VT = Op1.getSimpleValueType();
13161 MVT EVT = VT.getVectorElementType();
13162 unsigned n = VT.getVectorNumElements();
13163 SmallVector<SDValue, 8> ULTOp1;
13165 for (unsigned i = 0; i < n; ++i) {
13166 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13167 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13170 // Avoid underflow.
13171 APInt Val = Elt->getAPIntValue();
13175 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13178 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13181 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13182 SelectionDAG &DAG) {
13183 SDValue Op0 = Op.getOperand(0);
13184 SDValue Op1 = Op.getOperand(1);
13185 SDValue CC = Op.getOperand(2);
13186 MVT VT = Op.getSimpleValueType();
13187 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13188 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13193 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13194 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13197 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13198 unsigned Opc = X86ISD::CMPP;
13199 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13200 assert(VT.getVectorNumElements() <= 16);
13201 Opc = X86ISD::CMPM;
13203 // In the two special cases we can't handle, emit two comparisons.
13206 unsigned CombineOpc;
13207 if (SetCCOpcode == ISD::SETUEQ) {
13208 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13210 assert(SetCCOpcode == ISD::SETONE);
13211 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13214 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13215 DAG.getConstant(CC0, dl, MVT::i8));
13216 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13217 DAG.getConstant(CC1, dl, MVT::i8));
13218 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13220 // Handle all other FP comparisons here.
13221 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13222 DAG.getConstant(SSECC, dl, MVT::i8));
13225 // Break 256-bit integer vector compare into smaller ones.
13226 if (VT.is256BitVector() && !Subtarget->hasInt256())
13227 return Lower256IntVSETCC(Op, DAG);
13229 EVT OpVT = Op1.getValueType();
13230 if (OpVT.getVectorElementType() == MVT::i1)
13231 return LowerBoolVSETCC_AVX512(Op, DAG);
13233 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13234 if (Subtarget->hasAVX512()) {
13235 if (Op1.getValueType().is512BitVector() ||
13236 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13237 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13238 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13240 // In AVX-512 architecture setcc returns mask with i1 elements,
13241 // But there is no compare instruction for i8 and i16 elements in KNL.
13242 // We are not talking about 512-bit operands in this case, these
13243 // types are illegal.
13245 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13246 OpVT.getVectorElementType().getSizeInBits() >= 8))
13247 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13248 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13251 // We are handling one of the integer comparisons here. Since SSE only has
13252 // GT and EQ comparisons for integer, swapping operands and multiple
13253 // operations may be required for some comparisons.
13255 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13256 bool Subus = false;
13258 switch (SetCCOpcode) {
13259 default: llvm_unreachable("Unexpected SETCC condition");
13260 case ISD::SETNE: Invert = true;
13261 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13262 case ISD::SETLT: Swap = true;
13263 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13264 case ISD::SETGE: Swap = true;
13265 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13266 Invert = true; break;
13267 case ISD::SETULT: Swap = true;
13268 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13269 FlipSigns = true; break;
13270 case ISD::SETUGE: Swap = true;
13271 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13272 FlipSigns = true; Invert = true; break;
13275 // Special case: Use min/max operations for SETULE/SETUGE
13276 MVT VET = VT.getVectorElementType();
13278 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13279 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13282 switch (SetCCOpcode) {
13284 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13285 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13288 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13291 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13292 if (!MinMax && hasSubus) {
13293 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13295 // t = psubus Op0, Op1
13296 // pcmpeq t, <0..0>
13297 switch (SetCCOpcode) {
13299 case ISD::SETULT: {
13300 // If the comparison is against a constant we can turn this into a
13301 // setule. With psubus, setule does not require a swap. This is
13302 // beneficial because the constant in the register is no longer
13303 // destructed as the destination so it can be hoisted out of a loop.
13304 // Only do this pre-AVX since vpcmp* is no longer destructive.
13305 if (Subtarget->hasAVX())
13307 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13308 if (ULEOp1.getNode()) {
13310 Subus = true; Invert = false; Swap = false;
13314 // Psubus is better than flip-sign because it requires no inversion.
13315 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13316 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13320 Opc = X86ISD::SUBUS;
13326 std::swap(Op0, Op1);
13328 // Check that the operation in question is available (most are plain SSE2,
13329 // but PCMPGTQ and PCMPEQQ have different requirements).
13330 if (VT == MVT::v2i64) {
13331 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13332 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13334 // First cast everything to the right type.
13335 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13336 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13338 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13339 // bits of the inputs before performing those operations. The lower
13340 // compare is always unsigned.
13343 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13345 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13346 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13347 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13348 Sign, Zero, Sign, Zero);
13350 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13351 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13353 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13354 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13355 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13357 // Create masks for only the low parts/high parts of the 64 bit integers.
13358 static const int MaskHi[] = { 1, 1, 3, 3 };
13359 static const int MaskLo[] = { 0, 0, 2, 2 };
13360 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13361 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13362 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13364 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13365 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13368 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13370 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13373 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13374 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13375 // pcmpeqd + pshufd + pand.
13376 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13378 // First cast everything to the right type.
13379 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13380 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13383 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13385 // Make sure the lower and upper halves are both all-ones.
13386 static const int Mask[] = { 1, 0, 3, 2 };
13387 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13388 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13391 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13393 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13397 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13398 // bits of the inputs before performing those operations.
13400 EVT EltVT = VT.getVectorElementType();
13401 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13403 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13404 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13407 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13409 // If the logical-not of the result is required, perform that now.
13411 Result = DAG.getNOT(dl, Result, VT);
13414 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13417 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13418 getZeroVector(VT, Subtarget, DAG, dl));
13423 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13425 MVT VT = Op.getSimpleValueType();
13427 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13429 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13430 && "SetCC type must be 8-bit or 1-bit integer");
13431 SDValue Op0 = Op.getOperand(0);
13432 SDValue Op1 = Op.getOperand(1);
13434 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13436 // Optimize to BT if possible.
13437 // Lower (X & (1 << N)) == 0 to BT(X, N).
13438 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13439 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13440 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13441 Op1.getOpcode() == ISD::Constant &&
13442 cast<ConstantSDNode>(Op1)->isNullValue() &&
13443 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13444 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13445 if (NewSetCC.getNode()) {
13447 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13452 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13454 if (Op1.getOpcode() == ISD::Constant &&
13455 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13456 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13457 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13459 // If the input is a setcc, then reuse the input setcc or use a new one with
13460 // the inverted condition.
13461 if (Op0.getOpcode() == X86ISD::SETCC) {
13462 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13463 bool Invert = (CC == ISD::SETNE) ^
13464 cast<ConstantSDNode>(Op1)->isNullValue();
13468 CCode = X86::GetOppositeBranchCondition(CCode);
13469 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13470 DAG.getConstant(CCode, dl, MVT::i8),
13471 Op0.getOperand(1));
13473 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13477 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13478 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13479 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13481 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13482 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13485 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13486 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13487 if (X86CC == X86::COND_INVALID)
13490 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13491 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13492 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13493 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13495 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13499 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13500 static bool isX86LogicalCmp(SDValue Op) {
13501 unsigned Opc = Op.getNode()->getOpcode();
13502 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13503 Opc == X86ISD::SAHF)
13505 if (Op.getResNo() == 1 &&
13506 (Opc == X86ISD::ADD ||
13507 Opc == X86ISD::SUB ||
13508 Opc == X86ISD::ADC ||
13509 Opc == X86ISD::SBB ||
13510 Opc == X86ISD::SMUL ||
13511 Opc == X86ISD::UMUL ||
13512 Opc == X86ISD::INC ||
13513 Opc == X86ISD::DEC ||
13514 Opc == X86ISD::OR ||
13515 Opc == X86ISD::XOR ||
13516 Opc == X86ISD::AND))
13519 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13525 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13526 if (V.getOpcode() != ISD::TRUNCATE)
13529 SDValue VOp0 = V.getOperand(0);
13530 unsigned InBits = VOp0.getValueSizeInBits();
13531 unsigned Bits = V.getValueSizeInBits();
13532 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13535 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13536 bool addTest = true;
13537 SDValue Cond = Op.getOperand(0);
13538 SDValue Op1 = Op.getOperand(1);
13539 SDValue Op2 = Op.getOperand(2);
13541 EVT VT = Op1.getValueType();
13544 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13545 // are available or VBLENDV if AVX is available.
13546 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13547 if (Cond.getOpcode() == ISD::SETCC &&
13548 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13549 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13550 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13551 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13552 int SSECC = translateX86FSETCC(
13553 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13556 if (Subtarget->hasAVX512()) {
13557 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13558 DAG.getConstant(SSECC, DL, MVT::i8));
13559 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13562 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13563 DAG.getConstant(SSECC, DL, MVT::i8));
13565 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13566 // of 3 logic instructions for size savings and potentially speed.
13567 // Unfortunately, there is no scalar form of VBLENDV.
13569 // If either operand is a constant, don't try this. We can expect to
13570 // optimize away at least one of the logic instructions later in that
13571 // case, so that sequence would be faster than a variable blend.
13573 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13574 // uses XMM0 as the selection register. That may need just as many
13575 // instructions as the AND/ANDN/OR sequence due to register moves, so
13578 if (Subtarget->hasAVX() &&
13579 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13581 // Convert to vectors, do a VSELECT, and convert back to scalar.
13582 // All of the conversions should be optimized away.
13584 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13585 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13586 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13587 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13589 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13590 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13592 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13594 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13595 VSel, DAG.getIntPtrConstant(0, DL));
13597 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13598 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13599 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13603 if (Cond.getOpcode() == ISD::SETCC) {
13604 SDValue NewCond = LowerSETCC(Cond, DAG);
13605 if (NewCond.getNode())
13609 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13610 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13611 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13612 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13613 if (Cond.getOpcode() == X86ISD::SETCC &&
13614 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13615 isZero(Cond.getOperand(1).getOperand(1))) {
13616 SDValue Cmp = Cond.getOperand(1);
13618 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13620 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13621 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13622 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13624 SDValue CmpOp0 = Cmp.getOperand(0);
13625 // Apply further optimizations for special cases
13626 // (select (x != 0), -1, 0) -> neg & sbb
13627 // (select (x == 0), 0, -1) -> neg & sbb
13628 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13629 if (YC->isNullValue() &&
13630 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13631 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13632 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13633 DAG.getConstant(0, DL,
13634 CmpOp0.getValueType()),
13636 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13637 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13638 SDValue(Neg.getNode(), 1));
13642 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13643 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13644 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13646 SDValue Res = // Res = 0 or -1.
13647 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13648 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13650 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13651 Res = DAG.getNOT(DL, Res, Res.getValueType());
13653 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13654 if (!N2C || !N2C->isNullValue())
13655 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13660 // Look past (and (setcc_carry (cmp ...)), 1).
13661 if (Cond.getOpcode() == ISD::AND &&
13662 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13663 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13664 if (C && C->getAPIntValue() == 1)
13665 Cond = Cond.getOperand(0);
13668 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13669 // setting operand in place of the X86ISD::SETCC.
13670 unsigned CondOpcode = Cond.getOpcode();
13671 if (CondOpcode == X86ISD::SETCC ||
13672 CondOpcode == X86ISD::SETCC_CARRY) {
13673 CC = Cond.getOperand(0);
13675 SDValue Cmp = Cond.getOperand(1);
13676 unsigned Opc = Cmp.getOpcode();
13677 MVT VT = Op.getSimpleValueType();
13679 bool IllegalFPCMov = false;
13680 if (VT.isFloatingPoint() && !VT.isVector() &&
13681 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13682 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13684 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13685 Opc == X86ISD::BT) { // FIXME
13689 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13690 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13691 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13692 Cond.getOperand(0).getValueType() != MVT::i8)) {
13693 SDValue LHS = Cond.getOperand(0);
13694 SDValue RHS = Cond.getOperand(1);
13695 unsigned X86Opcode;
13698 switch (CondOpcode) {
13699 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13700 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13701 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13702 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13703 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13704 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13705 default: llvm_unreachable("unexpected overflowing operator");
13707 if (CondOpcode == ISD::UMULO)
13708 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13711 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13713 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13715 if (CondOpcode == ISD::UMULO)
13716 Cond = X86Op.getValue(2);
13718 Cond = X86Op.getValue(1);
13720 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13725 // Look pass the truncate if the high bits are known zero.
13726 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13727 Cond = Cond.getOperand(0);
13729 // We know the result of AND is compared against zero. Try to match
13731 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13732 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13733 if (NewSetCC.getNode()) {
13734 CC = NewSetCC.getOperand(0);
13735 Cond = NewSetCC.getOperand(1);
13742 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13743 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13746 // a < b ? -1 : 0 -> RES = ~setcc_carry
13747 // a < b ? 0 : -1 -> RES = setcc_carry
13748 // a >= b ? -1 : 0 -> RES = setcc_carry
13749 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13750 if (Cond.getOpcode() == X86ISD::SUB) {
13751 Cond = ConvertCmpIfNecessary(Cond, DAG);
13752 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13754 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13755 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13756 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13757 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13759 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13760 return DAG.getNOT(DL, Res, Res.getValueType());
13765 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13766 // widen the cmov and push the truncate through. This avoids introducing a new
13767 // branch during isel and doesn't add any extensions.
13768 if (Op.getValueType() == MVT::i8 &&
13769 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13770 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13771 if (T1.getValueType() == T2.getValueType() &&
13772 // Blacklist CopyFromReg to avoid partial register stalls.
13773 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13774 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13775 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13776 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13780 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13781 // condition is true.
13782 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13783 SDValue Ops[] = { Op2, Op1, CC, Cond };
13784 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13787 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13788 SelectionDAG &DAG) {
13789 MVT VT = Op->getSimpleValueType(0);
13790 SDValue In = Op->getOperand(0);
13791 MVT InVT = In.getSimpleValueType();
13792 MVT VTElt = VT.getVectorElementType();
13793 MVT InVTElt = InVT.getVectorElementType();
13797 if ((InVTElt == MVT::i1) &&
13798 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13799 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13801 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13802 VTElt.getSizeInBits() <= 16)) ||
13804 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13805 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13807 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13808 VTElt.getSizeInBits() >= 32))))
13809 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13811 unsigned int NumElts = VT.getVectorNumElements();
13813 if (NumElts != 8 && NumElts != 16)
13816 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13817 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13818 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13819 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13822 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13823 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13825 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13828 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13830 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13831 if (VT.is512BitVector())
13833 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13836 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13837 SelectionDAG &DAG) {
13838 MVT VT = Op->getSimpleValueType(0);
13839 SDValue In = Op->getOperand(0);
13840 MVT InVT = In.getSimpleValueType();
13843 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13844 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13846 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13847 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13848 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13851 if (Subtarget->hasInt256())
13852 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13854 // Optimize vectors in AVX mode
13855 // Sign extend v8i16 to v8i32 and
13858 // Divide input vector into two parts
13859 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13860 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13861 // concat the vectors to original VT
13863 unsigned NumElems = InVT.getVectorNumElements();
13864 SDValue Undef = DAG.getUNDEF(InVT);
13866 SmallVector<int,8> ShufMask1(NumElems, -1);
13867 for (unsigned i = 0; i != NumElems/2; ++i)
13870 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13872 SmallVector<int,8> ShufMask2(NumElems, -1);
13873 for (unsigned i = 0; i != NumElems/2; ++i)
13874 ShufMask2[i] = i + NumElems/2;
13876 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13878 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13879 VT.getVectorNumElements()/2);
13881 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13882 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13884 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13887 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13888 // may emit an illegal shuffle but the expansion is still better than scalar
13889 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13890 // we'll emit a shuffle and a arithmetic shift.
13891 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13892 // TODO: It is possible to support ZExt by zeroing the undef values during
13893 // the shuffle phase or after the shuffle.
13894 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13895 SelectionDAG &DAG) {
13896 MVT RegVT = Op.getSimpleValueType();
13897 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13898 assert(RegVT.isInteger() &&
13899 "We only custom lower integer vector sext loads.");
13901 // Nothing useful we can do without SSE2 shuffles.
13902 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13904 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13906 EVT MemVT = Ld->getMemoryVT();
13907 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13908 unsigned RegSz = RegVT.getSizeInBits();
13910 ISD::LoadExtType Ext = Ld->getExtensionType();
13912 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13913 && "Only anyext and sext are currently implemented.");
13914 assert(MemVT != RegVT && "Cannot extend to the same type");
13915 assert(MemVT.isVector() && "Must load a vector from memory");
13917 unsigned NumElems = RegVT.getVectorNumElements();
13918 unsigned MemSz = MemVT.getSizeInBits();
13919 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13921 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13922 // The only way in which we have a legal 256-bit vector result but not the
13923 // integer 256-bit operations needed to directly lower a sextload is if we
13924 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13925 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13926 // correctly legalized. We do this late to allow the canonical form of
13927 // sextload to persist throughout the rest of the DAG combiner -- it wants
13928 // to fold together any extensions it can, and so will fuse a sign_extend
13929 // of an sextload into a sextload targeting a wider value.
13931 if (MemSz == 128) {
13932 // Just switch this to a normal load.
13933 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13934 "it must be a legal 128-bit vector "
13936 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13937 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13938 Ld->isInvariant(), Ld->getAlignment());
13940 assert(MemSz < 128 &&
13941 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13942 // Do an sext load to a 128-bit vector type. We want to use the same
13943 // number of elements, but elements half as wide. This will end up being
13944 // recursively lowered by this routine, but will succeed as we definitely
13945 // have all the necessary features if we're using AVX1.
13947 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13948 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13950 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13951 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13952 Ld->isNonTemporal(), Ld->isInvariant(),
13953 Ld->getAlignment());
13956 // Replace chain users with the new chain.
13957 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13958 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13960 // Finally, do a normal sign-extend to the desired register.
13961 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13964 // All sizes must be a power of two.
13965 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13966 "Non-power-of-two elements are not custom lowered!");
13968 // Attempt to load the original value using scalar loads.
13969 // Find the largest scalar type that divides the total loaded size.
13970 MVT SclrLoadTy = MVT::i8;
13971 for (MVT Tp : MVT::integer_valuetypes()) {
13972 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13977 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13978 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13980 SclrLoadTy = MVT::f64;
13982 // Calculate the number of scalar loads that we need to perform
13983 // in order to load our vector from memory.
13984 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13986 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13987 "Can only lower sext loads with a single scalar load!");
13989 unsigned loadRegZize = RegSz;
13990 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13993 // Represent our vector as a sequence of elements which are the
13994 // largest scalar that we can load.
13995 EVT LoadUnitVecVT = EVT::getVectorVT(
13996 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13998 // Represent the data using the same element type that is stored in
13999 // memory. In practice, we ''widen'' MemVT.
14001 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14002 loadRegZize / MemVT.getScalarType().getSizeInBits());
14004 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14005 "Invalid vector type");
14007 // We can't shuffle using an illegal type.
14008 assert(TLI.isTypeLegal(WideVecVT) &&
14009 "We only lower types that form legal widened vector types");
14011 SmallVector<SDValue, 8> Chains;
14012 SDValue Ptr = Ld->getBasePtr();
14013 SDValue Increment =
14014 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14015 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14017 for (unsigned i = 0; i < NumLoads; ++i) {
14018 // Perform a single load.
14019 SDValue ScalarLoad =
14020 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14021 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14022 Ld->getAlignment());
14023 Chains.push_back(ScalarLoad.getValue(1));
14024 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14025 // another round of DAGCombining.
14027 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14029 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14030 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14032 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14035 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14037 // Bitcast the loaded value to a vector of the original element type, in
14038 // the size of the target vector type.
14039 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14040 unsigned SizeRatio = RegSz / MemSz;
14042 if (Ext == ISD::SEXTLOAD) {
14043 // If we have SSE4.1, we can directly emit a VSEXT node.
14044 if (Subtarget->hasSSE41()) {
14045 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14046 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14050 // Otherwise we'll shuffle the small elements in the high bits of the
14051 // larger type and perform an arithmetic shift. If the shift is not legal
14052 // it's better to scalarize.
14053 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14054 "We can't implement a sext load without an arithmetic right shift!");
14056 // Redistribute the loaded elements into the different locations.
14057 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14058 for (unsigned i = 0; i != NumElems; ++i)
14059 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14061 SDValue Shuff = DAG.getVectorShuffle(
14062 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14064 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14066 // Build the arithmetic shift.
14067 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14068 MemVT.getVectorElementType().getSizeInBits();
14070 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14071 DAG.getConstant(Amt, dl, RegVT));
14073 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14077 // Redistribute the loaded elements into the different locations.
14078 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14079 for (unsigned i = 0; i != NumElems; ++i)
14080 ShuffleVec[i * SizeRatio] = i;
14082 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14083 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14085 // Bitcast to the requested type.
14086 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14087 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14091 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14092 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14093 // from the AND / OR.
14094 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14095 Opc = Op.getOpcode();
14096 if (Opc != ISD::OR && Opc != ISD::AND)
14098 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14099 Op.getOperand(0).hasOneUse() &&
14100 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14101 Op.getOperand(1).hasOneUse());
14104 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14105 // 1 and that the SETCC node has a single use.
14106 static bool isXor1OfSetCC(SDValue Op) {
14107 if (Op.getOpcode() != ISD::XOR)
14109 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14110 if (N1C && N1C->getAPIntValue() == 1) {
14111 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14112 Op.getOperand(0).hasOneUse();
14117 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14118 bool addTest = true;
14119 SDValue Chain = Op.getOperand(0);
14120 SDValue Cond = Op.getOperand(1);
14121 SDValue Dest = Op.getOperand(2);
14124 bool Inverted = false;
14126 if (Cond.getOpcode() == ISD::SETCC) {
14127 // Check for setcc([su]{add,sub,mul}o == 0).
14128 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14129 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14130 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14131 Cond.getOperand(0).getResNo() == 1 &&
14132 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14133 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14134 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14135 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14136 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14137 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14139 Cond = Cond.getOperand(0);
14141 SDValue NewCond = LowerSETCC(Cond, DAG);
14142 if (NewCond.getNode())
14147 // FIXME: LowerXALUO doesn't handle these!!
14148 else if (Cond.getOpcode() == X86ISD::ADD ||
14149 Cond.getOpcode() == X86ISD::SUB ||
14150 Cond.getOpcode() == X86ISD::SMUL ||
14151 Cond.getOpcode() == X86ISD::UMUL)
14152 Cond = LowerXALUO(Cond, DAG);
14155 // Look pass (and (setcc_carry (cmp ...)), 1).
14156 if (Cond.getOpcode() == ISD::AND &&
14157 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14158 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14159 if (C && C->getAPIntValue() == 1)
14160 Cond = Cond.getOperand(0);
14163 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14164 // setting operand in place of the X86ISD::SETCC.
14165 unsigned CondOpcode = Cond.getOpcode();
14166 if (CondOpcode == X86ISD::SETCC ||
14167 CondOpcode == X86ISD::SETCC_CARRY) {
14168 CC = Cond.getOperand(0);
14170 SDValue Cmp = Cond.getOperand(1);
14171 unsigned Opc = Cmp.getOpcode();
14172 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14173 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14177 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14181 // These can only come from an arithmetic instruction with overflow,
14182 // e.g. SADDO, UADDO.
14183 Cond = Cond.getNode()->getOperand(1);
14189 CondOpcode = Cond.getOpcode();
14190 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14191 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14192 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14193 Cond.getOperand(0).getValueType() != MVT::i8)) {
14194 SDValue LHS = Cond.getOperand(0);
14195 SDValue RHS = Cond.getOperand(1);
14196 unsigned X86Opcode;
14199 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14200 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14202 switch (CondOpcode) {
14203 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14207 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14210 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14211 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14213 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14215 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14218 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14219 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14220 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14221 default: llvm_unreachable("unexpected overflowing operator");
14224 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14225 if (CondOpcode == ISD::UMULO)
14226 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14229 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14231 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14233 if (CondOpcode == ISD::UMULO)
14234 Cond = X86Op.getValue(2);
14236 Cond = X86Op.getValue(1);
14238 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14242 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14243 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14244 if (CondOpc == ISD::OR) {
14245 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14246 // two branches instead of an explicit OR instruction with a
14248 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14249 isX86LogicalCmp(Cmp)) {
14250 CC = Cond.getOperand(0).getOperand(0);
14251 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14252 Chain, Dest, CC, Cmp);
14253 CC = Cond.getOperand(1).getOperand(0);
14257 } else { // ISD::AND
14258 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14259 // two branches instead of an explicit AND instruction with a
14260 // separate test. However, we only do this if this block doesn't
14261 // have a fall-through edge, because this requires an explicit
14262 // jmp when the condition is false.
14263 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14264 isX86LogicalCmp(Cmp) &&
14265 Op.getNode()->hasOneUse()) {
14266 X86::CondCode CCode =
14267 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14268 CCode = X86::GetOppositeBranchCondition(CCode);
14269 CC = DAG.getConstant(CCode, dl, MVT::i8);
14270 SDNode *User = *Op.getNode()->use_begin();
14271 // Look for an unconditional branch following this conditional branch.
14272 // We need this because we need to reverse the successors in order
14273 // to implement FCMP_OEQ.
14274 if (User->getOpcode() == ISD::BR) {
14275 SDValue FalseBB = User->getOperand(1);
14277 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14278 assert(NewBR == User);
14282 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14283 Chain, Dest, CC, Cmp);
14284 X86::CondCode CCode =
14285 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14286 CCode = X86::GetOppositeBranchCondition(CCode);
14287 CC = DAG.getConstant(CCode, dl, MVT::i8);
14293 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14294 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14295 // It should be transformed during dag combiner except when the condition
14296 // is set by a arithmetics with overflow node.
14297 X86::CondCode CCode =
14298 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14299 CCode = X86::GetOppositeBranchCondition(CCode);
14300 CC = DAG.getConstant(CCode, dl, MVT::i8);
14301 Cond = Cond.getOperand(0).getOperand(1);
14303 } else if (Cond.getOpcode() == ISD::SETCC &&
14304 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14305 // For FCMP_OEQ, we can emit
14306 // two branches instead of an explicit AND instruction with a
14307 // separate test. However, we only do this if this block doesn't
14308 // have a fall-through edge, because this requires an explicit
14309 // jmp when the condition is false.
14310 if (Op.getNode()->hasOneUse()) {
14311 SDNode *User = *Op.getNode()->use_begin();
14312 // Look for an unconditional branch following this conditional branch.
14313 // We need this because we need to reverse the successors in order
14314 // to implement FCMP_OEQ.
14315 if (User->getOpcode() == ISD::BR) {
14316 SDValue FalseBB = User->getOperand(1);
14318 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14319 assert(NewBR == User);
14323 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14324 Cond.getOperand(0), Cond.getOperand(1));
14325 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14326 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14327 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14328 Chain, Dest, CC, Cmp);
14329 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14334 } else if (Cond.getOpcode() == ISD::SETCC &&
14335 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14336 // For FCMP_UNE, we can emit
14337 // two branches instead of an explicit AND instruction with a
14338 // separate test. However, we only do this if this block doesn't
14339 // have a fall-through edge, because this requires an explicit
14340 // jmp when the condition is false.
14341 if (Op.getNode()->hasOneUse()) {
14342 SDNode *User = *Op.getNode()->use_begin();
14343 // Look for an unconditional branch following this conditional branch.
14344 // We need this because we need to reverse the successors in order
14345 // to implement FCMP_UNE.
14346 if (User->getOpcode() == ISD::BR) {
14347 SDValue FalseBB = User->getOperand(1);
14349 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14350 assert(NewBR == User);
14353 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14354 Cond.getOperand(0), Cond.getOperand(1));
14355 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14356 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14357 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14358 Chain, Dest, CC, Cmp);
14359 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14369 // Look pass the truncate if the high bits are known zero.
14370 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14371 Cond = Cond.getOperand(0);
14373 // We know the result of AND is compared against zero. Try to match
14375 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14376 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14377 if (NewSetCC.getNode()) {
14378 CC = NewSetCC.getOperand(0);
14379 Cond = NewSetCC.getOperand(1);
14386 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14387 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14388 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14390 Cond = ConvertCmpIfNecessary(Cond, DAG);
14391 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14392 Chain, Dest, CC, Cond);
14395 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14396 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14397 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14398 // that the guard pages used by the OS virtual memory manager are allocated in
14399 // correct sequence.
14401 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14402 SelectionDAG &DAG) const {
14403 MachineFunction &MF = DAG.getMachineFunction();
14404 bool SplitStack = MF.shouldSplitStack();
14405 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14411 SDNode* Node = Op.getNode();
14413 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14414 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14415 " not tell us which reg is the stack pointer!");
14416 EVT VT = Node->getValueType(0);
14417 SDValue Tmp1 = SDValue(Node, 0);
14418 SDValue Tmp2 = SDValue(Node, 1);
14419 SDValue Tmp3 = Node->getOperand(2);
14420 SDValue Chain = Tmp1.getOperand(0);
14422 // Chain the dynamic stack allocation so that it doesn't modify the stack
14423 // pointer when other instructions are using the stack.
14424 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14427 SDValue Size = Tmp2.getOperand(1);
14428 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14429 Chain = SP.getValue(1);
14430 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14431 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14432 unsigned StackAlign = TFI.getStackAlignment();
14433 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14434 if (Align > StackAlign)
14435 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14436 DAG.getConstant(-(uint64_t)Align, dl, VT));
14437 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14439 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14440 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14443 SDValue Ops[2] = { Tmp1, Tmp2 };
14444 return DAG.getMergeValues(Ops, dl);
14448 SDValue Chain = Op.getOperand(0);
14449 SDValue Size = Op.getOperand(1);
14450 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14451 EVT VT = Op.getNode()->getValueType(0);
14453 bool Is64Bit = Subtarget->is64Bit();
14454 EVT SPTy = getPointerTy();
14457 MachineRegisterInfo &MRI = MF.getRegInfo();
14460 // The 64 bit implementation of segmented stacks needs to clobber both r10
14461 // r11. This makes it impossible to use it along with nested parameters.
14462 const Function *F = MF.getFunction();
14464 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14466 if (I->hasNestAttr())
14467 report_fatal_error("Cannot use segmented stacks with functions that "
14468 "have nested arguments.");
14471 const TargetRegisterClass *AddrRegClass =
14472 getRegClassFor(getPointerTy());
14473 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14474 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14475 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14476 DAG.getRegister(Vreg, SPTy));
14477 SDValue Ops1[2] = { Value, Chain };
14478 return DAG.getMergeValues(Ops1, dl);
14481 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14483 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14484 Flag = Chain.getValue(1);
14485 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14487 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14489 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14490 unsigned SPReg = RegInfo->getStackRegister();
14491 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14492 Chain = SP.getValue(1);
14495 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14496 DAG.getConstant(-(uint64_t)Align, dl, VT));
14497 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14500 SDValue Ops1[2] = { SP, Chain };
14501 return DAG.getMergeValues(Ops1, dl);
14505 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14506 MachineFunction &MF = DAG.getMachineFunction();
14507 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14509 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14512 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14513 // vastart just stores the address of the VarArgsFrameIndex slot into the
14514 // memory location argument.
14515 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14517 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14518 MachinePointerInfo(SV), false, false, 0);
14522 // gp_offset (0 - 6 * 8)
14523 // fp_offset (48 - 48 + 8 * 16)
14524 // overflow_arg_area (point to parameters coming in memory).
14526 SmallVector<SDValue, 8> MemOps;
14527 SDValue FIN = Op.getOperand(1);
14529 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14530 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14532 FIN, MachinePointerInfo(SV), false, false, 0);
14533 MemOps.push_back(Store);
14536 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14537 FIN, DAG.getIntPtrConstant(4, DL));
14538 Store = DAG.getStore(Op.getOperand(0), DL,
14539 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14541 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14542 MemOps.push_back(Store);
14544 // Store ptr to overflow_arg_area
14545 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14546 FIN, DAG.getIntPtrConstant(4, DL));
14547 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14549 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14550 MachinePointerInfo(SV, 8),
14552 MemOps.push_back(Store);
14554 // Store ptr to reg_save_area.
14555 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14556 FIN, DAG.getIntPtrConstant(8, DL));
14557 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14559 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14560 MachinePointerInfo(SV, 16), false, false, 0);
14561 MemOps.push_back(Store);
14562 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14565 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14566 assert(Subtarget->is64Bit() &&
14567 "LowerVAARG only handles 64-bit va_arg!");
14568 assert((Subtarget->isTargetLinux() ||
14569 Subtarget->isTargetDarwin()) &&
14570 "Unhandled target in LowerVAARG");
14571 assert(Op.getNode()->getNumOperands() == 4);
14572 SDValue Chain = Op.getOperand(0);
14573 SDValue SrcPtr = Op.getOperand(1);
14574 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14575 unsigned Align = Op.getConstantOperandVal(3);
14578 EVT ArgVT = Op.getNode()->getValueType(0);
14579 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14580 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14583 // Decide which area this value should be read from.
14584 // TODO: Implement the AMD64 ABI in its entirety. This simple
14585 // selection mechanism works only for the basic types.
14586 if (ArgVT == MVT::f80) {
14587 llvm_unreachable("va_arg for f80 not yet implemented");
14588 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14589 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14590 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14591 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14593 llvm_unreachable("Unhandled argument type in LowerVAARG");
14596 if (ArgMode == 2) {
14597 // Sanity Check: Make sure using fp_offset makes sense.
14598 assert(!DAG.getTarget().Options.UseSoftFloat &&
14599 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14600 Attribute::NoImplicitFloat)) &&
14601 Subtarget->hasSSE1());
14604 // Insert VAARG_64 node into the DAG
14605 // VAARG_64 returns two values: Variable Argument Address, Chain
14606 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14607 DAG.getConstant(ArgMode, dl, MVT::i8),
14608 DAG.getConstant(Align, dl, MVT::i32)};
14609 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14610 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14611 VTs, InstOps, MVT::i64,
14612 MachinePointerInfo(SV),
14614 /*Volatile=*/false,
14616 /*WriteMem=*/true);
14617 Chain = VAARG.getValue(1);
14619 // Load the next argument and return it
14620 return DAG.getLoad(ArgVT, dl,
14623 MachinePointerInfo(),
14624 false, false, false, 0);
14627 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14628 SelectionDAG &DAG) {
14629 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14630 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14631 SDValue Chain = Op.getOperand(0);
14632 SDValue DstPtr = Op.getOperand(1);
14633 SDValue SrcPtr = Op.getOperand(2);
14634 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14635 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14638 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14639 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14641 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14644 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14645 // amount is a constant. Takes immediate version of shift as input.
14646 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14647 SDValue SrcOp, uint64_t ShiftAmt,
14648 SelectionDAG &DAG) {
14649 MVT ElementType = VT.getVectorElementType();
14651 // Fold this packed shift into its first operand if ShiftAmt is 0.
14655 // Check for ShiftAmt >= element width
14656 if (ShiftAmt >= ElementType.getSizeInBits()) {
14657 if (Opc == X86ISD::VSRAI)
14658 ShiftAmt = ElementType.getSizeInBits() - 1;
14660 return DAG.getConstant(0, dl, VT);
14663 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14664 && "Unknown target vector shift-by-constant node");
14666 // Fold this packed vector shift into a build vector if SrcOp is a
14667 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14668 if (VT == SrcOp.getSimpleValueType() &&
14669 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14670 SmallVector<SDValue, 8> Elts;
14671 unsigned NumElts = SrcOp->getNumOperands();
14672 ConstantSDNode *ND;
14675 default: llvm_unreachable(nullptr);
14676 case X86ISD::VSHLI:
14677 for (unsigned i=0; i!=NumElts; ++i) {
14678 SDValue CurrentOp = SrcOp->getOperand(i);
14679 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14680 Elts.push_back(CurrentOp);
14683 ND = cast<ConstantSDNode>(CurrentOp);
14684 const APInt &C = ND->getAPIntValue();
14685 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14688 case X86ISD::VSRLI:
14689 for (unsigned i=0; i!=NumElts; ++i) {
14690 SDValue CurrentOp = SrcOp->getOperand(i);
14691 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14692 Elts.push_back(CurrentOp);
14695 ND = cast<ConstantSDNode>(CurrentOp);
14696 const APInt &C = ND->getAPIntValue();
14697 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14700 case X86ISD::VSRAI:
14701 for (unsigned i=0; i!=NumElts; ++i) {
14702 SDValue CurrentOp = SrcOp->getOperand(i);
14703 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14704 Elts.push_back(CurrentOp);
14707 ND = cast<ConstantSDNode>(CurrentOp);
14708 const APInt &C = ND->getAPIntValue();
14709 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14714 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14717 return DAG.getNode(Opc, dl, VT, SrcOp,
14718 DAG.getConstant(ShiftAmt, dl, MVT::i8));
14721 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14722 // may or may not be a constant. Takes immediate version of shift as input.
14723 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14724 SDValue SrcOp, SDValue ShAmt,
14725 SelectionDAG &DAG) {
14726 MVT SVT = ShAmt.getSimpleValueType();
14727 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14729 // Catch shift-by-constant.
14730 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14731 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14732 CShAmt->getZExtValue(), DAG);
14734 // Change opcode to non-immediate version
14736 default: llvm_unreachable("Unknown target vector shift node");
14737 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14738 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14739 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14742 const X86Subtarget &Subtarget =
14743 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14744 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14745 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14746 // Let the shuffle legalizer expand this shift amount node.
14747 SDValue Op0 = ShAmt.getOperand(0);
14748 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14749 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14751 // Need to build a vector containing shift amount.
14752 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14753 SmallVector<SDValue, 4> ShOps;
14754 ShOps.push_back(ShAmt);
14755 if (SVT == MVT::i32) {
14756 ShOps.push_back(DAG.getConstant(0, dl, SVT));
14757 ShOps.push_back(DAG.getUNDEF(SVT));
14759 ShOps.push_back(DAG.getUNDEF(SVT));
14761 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14762 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14765 // The return type has to be a 128-bit type with the same element
14766 // type as the input type.
14767 MVT EltVT = VT.getVectorElementType();
14768 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14770 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14771 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14774 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14775 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14776 /// necessary casting for \p Mask when lowering masking intrinsics.
14777 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14778 SDValue PreservedSrc,
14779 const X86Subtarget *Subtarget,
14780 SelectionDAG &DAG) {
14781 EVT VT = Op.getValueType();
14782 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14783 MVT::i1, VT.getVectorNumElements());
14784 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14785 Mask.getValueType().getSizeInBits());
14788 assert(MaskVT.isSimple() && "invalid mask type");
14790 if (isAllOnes(Mask))
14793 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14794 // are extracted by EXTRACT_SUBVECTOR.
14795 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14796 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14797 DAG.getIntPtrConstant(0, dl));
14799 switch (Op.getOpcode()) {
14801 case X86ISD::PCMPEQM:
14802 case X86ISD::PCMPGTM:
14804 case X86ISD::CMPMU:
14805 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14807 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14808 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14809 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14812 /// \brief Creates an SDNode for a predicated scalar operation.
14813 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14814 /// The mask is comming as MVT::i8 and it should be truncated
14815 /// to MVT::i1 while lowering masking intrinsics.
14816 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14817 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14818 /// a scalar instruction.
14819 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14820 SDValue PreservedSrc,
14821 const X86Subtarget *Subtarget,
14822 SelectionDAG &DAG) {
14823 if (isAllOnes(Mask))
14826 EVT VT = Op.getValueType();
14828 // The mask should be of type MVT::i1
14829 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14831 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14832 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14833 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14836 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14837 SelectionDAG &DAG) {
14839 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14840 EVT VT = Op.getValueType();
14841 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14843 switch(IntrData->Type) {
14844 case INTR_TYPE_1OP:
14845 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14846 case INTR_TYPE_2OP:
14847 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14849 case INTR_TYPE_3OP:
14850 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14851 Op.getOperand(2), Op.getOperand(3));
14852 case INTR_TYPE_1OP_MASK_RM: {
14853 SDValue Src = Op.getOperand(1);
14854 SDValue Src0 = Op.getOperand(2);
14855 SDValue Mask = Op.getOperand(3);
14856 SDValue RoundingMode = Op.getOperand(4);
14857 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14859 Mask, Src0, Subtarget, DAG);
14861 case INTR_TYPE_SCALAR_MASK_RM: {
14862 SDValue Src1 = Op.getOperand(1);
14863 SDValue Src2 = Op.getOperand(2);
14864 SDValue Src0 = Op.getOperand(3);
14865 SDValue Mask = Op.getOperand(4);
14866 // There are 2 kinds of intrinsics in this group:
14867 // (1) With supress-all-exceptions (sae) - 6 operands
14868 // (2) With rounding mode and sae - 7 operands.
14869 if (Op.getNumOperands() == 6) {
14870 SDValue Sae = Op.getOperand(5);
14871 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14873 Mask, Src0, Subtarget, DAG);
14875 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14876 SDValue RoundingMode = Op.getOperand(5);
14877 SDValue Sae = Op.getOperand(6);
14878 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14879 RoundingMode, Sae),
14880 Mask, Src0, Subtarget, DAG);
14882 case INTR_TYPE_2OP_MASK: {
14883 SDValue Src1 = Op.getOperand(1);
14884 SDValue Src2 = Op.getOperand(2);
14885 SDValue PassThru = Op.getOperand(3);
14886 SDValue Mask = Op.getOperand(4);
14887 // We specify 2 possible opcodes for intrinsics with rounding modes.
14888 // First, we check if the intrinsic may have non-default rounding mode,
14889 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14890 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14891 if (IntrWithRoundingModeOpcode != 0) {
14892 SDValue Rnd = Op.getOperand(5);
14893 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14894 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14895 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14896 dl, Op.getValueType(),
14898 Mask, PassThru, Subtarget, DAG);
14901 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14903 Mask, PassThru, Subtarget, DAG);
14905 case FMA_OP_MASK: {
14906 SDValue Src1 = Op.getOperand(1);
14907 SDValue Src2 = Op.getOperand(2);
14908 SDValue Src3 = Op.getOperand(3);
14909 SDValue Mask = Op.getOperand(4);
14910 // We specify 2 possible opcodes for intrinsics with rounding modes.
14911 // First, we check if the intrinsic may have non-default rounding mode,
14912 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14913 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14914 if (IntrWithRoundingModeOpcode != 0) {
14915 SDValue Rnd = Op.getOperand(5);
14916 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14917 X86::STATIC_ROUNDING::CUR_DIRECTION)
14918 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14919 dl, Op.getValueType(),
14920 Src1, Src2, Src3, Rnd),
14921 Mask, Src1, Subtarget, DAG);
14923 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14924 dl, Op.getValueType(),
14926 Mask, Src1, Subtarget, DAG);
14929 case CMP_MASK_CC: {
14930 // Comparison intrinsics with masks.
14931 // Example of transformation:
14932 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14933 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14935 // (v8i1 (insert_subvector undef,
14936 // (v2i1 (and (PCMPEQM %a, %b),
14937 // (extract_subvector
14938 // (v8i1 (bitcast %mask)), 0))), 0))))
14939 EVT VT = Op.getOperand(1).getValueType();
14940 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14941 VT.getVectorNumElements());
14942 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14943 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14944 Mask.getValueType().getSizeInBits());
14946 if (IntrData->Type == CMP_MASK_CC) {
14947 SDValue CC = Op.getOperand(3);
14948 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14949 // We specify 2 possible opcodes for intrinsics with rounding modes.
14950 // First, we check if the intrinsic may have non-default rounding mode,
14951 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14952 if (IntrData->Opc1 != 0) {
14953 SDValue Rnd = Op.getOperand(5);
14954 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14955 X86::STATIC_ROUNDING::CUR_DIRECTION)
14956 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14957 Op.getOperand(2), CC, Rnd);
14959 //default rounding mode
14961 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14962 Op.getOperand(2), CC);
14965 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14966 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14969 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14970 DAG.getTargetConstant(0, dl,
14973 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14974 DAG.getUNDEF(BitcastVT), CmpMask,
14975 DAG.getIntPtrConstant(0, dl));
14976 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14978 case COMI: { // Comparison intrinsics
14979 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14980 SDValue LHS = Op.getOperand(1);
14981 SDValue RHS = Op.getOperand(2);
14982 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
14983 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14984 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14985 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14986 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
14987 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14990 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14991 Op.getOperand(1), Op.getOperand(2), DAG);
14993 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14994 Op.getSimpleValueType(),
14996 Op.getOperand(2), DAG),
14997 Op.getOperand(4), Op.getOperand(3), Subtarget,
14999 case COMPRESS_EXPAND_IN_REG: {
15000 SDValue Mask = Op.getOperand(3);
15001 SDValue DataToCompress = Op.getOperand(1);
15002 SDValue PassThru = Op.getOperand(2);
15003 if (isAllOnes(Mask)) // return data as is
15004 return Op.getOperand(1);
15005 EVT VT = Op.getValueType();
15006 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15007 VT.getVectorNumElements());
15008 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15009 Mask.getValueType().getSizeInBits());
15011 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15012 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15013 DAG.getIntPtrConstant(0, dl));
15015 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15019 SDValue Mask = Op.getOperand(3);
15020 EVT VT = Op.getValueType();
15021 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15022 VT.getVectorNumElements());
15023 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15024 Mask.getValueType().getSizeInBits());
15026 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15027 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15028 DAG.getIntPtrConstant(0, dl));
15029 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15038 default: return SDValue(); // Don't custom lower most intrinsics.
15040 case Intrinsic::x86_avx2_permd:
15041 case Intrinsic::x86_avx2_permps:
15042 // Operands intentionally swapped. Mask is last operand to intrinsic,
15043 // but second operand for node/instruction.
15044 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15045 Op.getOperand(2), Op.getOperand(1));
15047 case Intrinsic::x86_avx512_mask_valign_q_512:
15048 case Intrinsic::x86_avx512_mask_valign_d_512:
15049 // Vector source operands are swapped.
15050 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15051 Op.getValueType(), Op.getOperand(2),
15054 Op.getOperand(5), Op.getOperand(4),
15057 // ptest and testp intrinsics. The intrinsic these come from are designed to
15058 // return an integer value, not just an instruction so lower it to the ptest
15059 // or testp pattern and a setcc for the result.
15060 case Intrinsic::x86_sse41_ptestz:
15061 case Intrinsic::x86_sse41_ptestc:
15062 case Intrinsic::x86_sse41_ptestnzc:
15063 case Intrinsic::x86_avx_ptestz_256:
15064 case Intrinsic::x86_avx_ptestc_256:
15065 case Intrinsic::x86_avx_ptestnzc_256:
15066 case Intrinsic::x86_avx_vtestz_ps:
15067 case Intrinsic::x86_avx_vtestc_ps:
15068 case Intrinsic::x86_avx_vtestnzc_ps:
15069 case Intrinsic::x86_avx_vtestz_pd:
15070 case Intrinsic::x86_avx_vtestc_pd:
15071 case Intrinsic::x86_avx_vtestnzc_pd:
15072 case Intrinsic::x86_avx_vtestz_ps_256:
15073 case Intrinsic::x86_avx_vtestc_ps_256:
15074 case Intrinsic::x86_avx_vtestnzc_ps_256:
15075 case Intrinsic::x86_avx_vtestz_pd_256:
15076 case Intrinsic::x86_avx_vtestc_pd_256:
15077 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15078 bool IsTestPacked = false;
15081 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15082 case Intrinsic::x86_avx_vtestz_ps:
15083 case Intrinsic::x86_avx_vtestz_pd:
15084 case Intrinsic::x86_avx_vtestz_ps_256:
15085 case Intrinsic::x86_avx_vtestz_pd_256:
15086 IsTestPacked = true; // Fallthrough
15087 case Intrinsic::x86_sse41_ptestz:
15088 case Intrinsic::x86_avx_ptestz_256:
15090 X86CC = X86::COND_E;
15092 case Intrinsic::x86_avx_vtestc_ps:
15093 case Intrinsic::x86_avx_vtestc_pd:
15094 case Intrinsic::x86_avx_vtestc_ps_256:
15095 case Intrinsic::x86_avx_vtestc_pd_256:
15096 IsTestPacked = true; // Fallthrough
15097 case Intrinsic::x86_sse41_ptestc:
15098 case Intrinsic::x86_avx_ptestc_256:
15100 X86CC = X86::COND_B;
15102 case Intrinsic::x86_avx_vtestnzc_ps:
15103 case Intrinsic::x86_avx_vtestnzc_pd:
15104 case Intrinsic::x86_avx_vtestnzc_ps_256:
15105 case Intrinsic::x86_avx_vtestnzc_pd_256:
15106 IsTestPacked = true; // Fallthrough
15107 case Intrinsic::x86_sse41_ptestnzc:
15108 case Intrinsic::x86_avx_ptestnzc_256:
15110 X86CC = X86::COND_A;
15114 SDValue LHS = Op.getOperand(1);
15115 SDValue RHS = Op.getOperand(2);
15116 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15117 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15118 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15119 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15120 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15122 case Intrinsic::x86_avx512_kortestz_w:
15123 case Intrinsic::x86_avx512_kortestc_w: {
15124 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15125 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15126 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15127 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15128 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15129 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15130 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15133 case Intrinsic::x86_sse42_pcmpistria128:
15134 case Intrinsic::x86_sse42_pcmpestria128:
15135 case Intrinsic::x86_sse42_pcmpistric128:
15136 case Intrinsic::x86_sse42_pcmpestric128:
15137 case Intrinsic::x86_sse42_pcmpistrio128:
15138 case Intrinsic::x86_sse42_pcmpestrio128:
15139 case Intrinsic::x86_sse42_pcmpistris128:
15140 case Intrinsic::x86_sse42_pcmpestris128:
15141 case Intrinsic::x86_sse42_pcmpistriz128:
15142 case Intrinsic::x86_sse42_pcmpestriz128: {
15146 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15147 case Intrinsic::x86_sse42_pcmpistria128:
15148 Opcode = X86ISD::PCMPISTRI;
15149 X86CC = X86::COND_A;
15151 case Intrinsic::x86_sse42_pcmpestria128:
15152 Opcode = X86ISD::PCMPESTRI;
15153 X86CC = X86::COND_A;
15155 case Intrinsic::x86_sse42_pcmpistric128:
15156 Opcode = X86ISD::PCMPISTRI;
15157 X86CC = X86::COND_B;
15159 case Intrinsic::x86_sse42_pcmpestric128:
15160 Opcode = X86ISD::PCMPESTRI;
15161 X86CC = X86::COND_B;
15163 case Intrinsic::x86_sse42_pcmpistrio128:
15164 Opcode = X86ISD::PCMPISTRI;
15165 X86CC = X86::COND_O;
15167 case Intrinsic::x86_sse42_pcmpestrio128:
15168 Opcode = X86ISD::PCMPESTRI;
15169 X86CC = X86::COND_O;
15171 case Intrinsic::x86_sse42_pcmpistris128:
15172 Opcode = X86ISD::PCMPISTRI;
15173 X86CC = X86::COND_S;
15175 case Intrinsic::x86_sse42_pcmpestris128:
15176 Opcode = X86ISD::PCMPESTRI;
15177 X86CC = X86::COND_S;
15179 case Intrinsic::x86_sse42_pcmpistriz128:
15180 Opcode = X86ISD::PCMPISTRI;
15181 X86CC = X86::COND_E;
15183 case Intrinsic::x86_sse42_pcmpestriz128:
15184 Opcode = X86ISD::PCMPESTRI;
15185 X86CC = X86::COND_E;
15188 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15189 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15190 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15191 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15192 DAG.getConstant(X86CC, dl, MVT::i8),
15193 SDValue(PCMP.getNode(), 1));
15194 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15197 case Intrinsic::x86_sse42_pcmpistri128:
15198 case Intrinsic::x86_sse42_pcmpestri128: {
15200 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15201 Opcode = X86ISD::PCMPISTRI;
15203 Opcode = X86ISD::PCMPESTRI;
15205 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15206 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15207 return DAG.getNode(Opcode, dl, VTs, NewOps);
15212 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15213 SDValue Src, SDValue Mask, SDValue Base,
15214 SDValue Index, SDValue ScaleOp, SDValue Chain,
15215 const X86Subtarget * Subtarget) {
15217 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15218 assert(C && "Invalid scale type");
15219 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15220 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15221 Index.getSimpleValueType().getVectorNumElements());
15223 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15225 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15227 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15228 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15229 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15230 SDValue Segment = DAG.getRegister(0, MVT::i32);
15231 if (Src.getOpcode() == ISD::UNDEF)
15232 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15233 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15234 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15235 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15236 return DAG.getMergeValues(RetOps, dl);
15239 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15240 SDValue Src, SDValue Mask, SDValue Base,
15241 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15243 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15244 assert(C && "Invalid scale type");
15245 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15246 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15247 SDValue Segment = DAG.getRegister(0, MVT::i32);
15248 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15249 Index.getSimpleValueType().getVectorNumElements());
15251 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15253 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15255 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15256 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15257 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15258 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15259 return SDValue(Res, 1);
15262 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15263 SDValue Mask, SDValue Base, SDValue Index,
15264 SDValue ScaleOp, SDValue Chain) {
15266 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15267 assert(C && "Invalid scale type");
15268 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15269 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15270 SDValue Segment = DAG.getRegister(0, MVT::i32);
15272 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15274 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15276 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15278 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15279 //SDVTList VTs = DAG.getVTList(MVT::Other);
15280 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15281 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15282 return SDValue(Res, 0);
15285 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15286 // read performance monitor counters (x86_rdpmc).
15287 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15288 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15289 SmallVectorImpl<SDValue> &Results) {
15290 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15291 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15294 // The ECX register is used to select the index of the performance counter
15296 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15298 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15300 // Reads the content of a 64-bit performance counter and returns it in the
15301 // registers EDX:EAX.
15302 if (Subtarget->is64Bit()) {
15303 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15304 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15307 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15308 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15311 Chain = HI.getValue(1);
15313 if (Subtarget->is64Bit()) {
15314 // The EAX register is loaded with the low-order 32 bits. The EDX register
15315 // is loaded with the supported high-order bits of the counter.
15316 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15317 DAG.getConstant(32, DL, MVT::i8));
15318 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15319 Results.push_back(Chain);
15323 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15324 SDValue Ops[] = { LO, HI };
15325 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15326 Results.push_back(Pair);
15327 Results.push_back(Chain);
15330 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15331 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15332 // also used to custom lower READCYCLECOUNTER nodes.
15333 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15334 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15335 SmallVectorImpl<SDValue> &Results) {
15336 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15337 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15340 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15341 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15342 // and the EAX register is loaded with the low-order 32 bits.
15343 if (Subtarget->is64Bit()) {
15344 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15345 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15348 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15349 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15352 SDValue Chain = HI.getValue(1);
15354 if (Opcode == X86ISD::RDTSCP_DAG) {
15355 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15357 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15358 // the ECX register. Add 'ecx' explicitly to the chain.
15359 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15361 // Explicitly store the content of ECX at the location passed in input
15362 // to the 'rdtscp' intrinsic.
15363 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15364 MachinePointerInfo(), false, false, 0);
15367 if (Subtarget->is64Bit()) {
15368 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15369 // the EAX register is loaded with the low-order 32 bits.
15370 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15371 DAG.getConstant(32, DL, MVT::i8));
15372 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15373 Results.push_back(Chain);
15377 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15378 SDValue Ops[] = { LO, HI };
15379 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15380 Results.push_back(Pair);
15381 Results.push_back(Chain);
15384 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15385 SelectionDAG &DAG) {
15386 SmallVector<SDValue, 2> Results;
15388 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15390 return DAG.getMergeValues(Results, DL);
15394 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15395 SelectionDAG &DAG) {
15396 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15398 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15403 switch(IntrData->Type) {
15405 llvm_unreachable("Unknown Intrinsic Type");
15409 // Emit the node with the right value type.
15410 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15411 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15413 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15414 // Otherwise return the value from Rand, which is always 0, casted to i32.
15415 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15416 DAG.getConstant(1, dl, Op->getValueType(1)),
15417 DAG.getConstant(X86::COND_B, dl, MVT::i32),
15418 SDValue(Result.getNode(), 1) };
15419 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15420 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15423 // Return { result, isValid, chain }.
15424 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15425 SDValue(Result.getNode(), 2));
15428 //gather(v1, mask, index, base, scale);
15429 SDValue Chain = Op.getOperand(0);
15430 SDValue Src = Op.getOperand(2);
15431 SDValue Base = Op.getOperand(3);
15432 SDValue Index = Op.getOperand(4);
15433 SDValue Mask = Op.getOperand(5);
15434 SDValue Scale = Op.getOperand(6);
15435 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15439 //scatter(base, mask, index, v1, scale);
15440 SDValue Chain = Op.getOperand(0);
15441 SDValue Base = Op.getOperand(2);
15442 SDValue Mask = Op.getOperand(3);
15443 SDValue Index = Op.getOperand(4);
15444 SDValue Src = Op.getOperand(5);
15445 SDValue Scale = Op.getOperand(6);
15446 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15450 SDValue Hint = Op.getOperand(6);
15451 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15452 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15453 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15454 SDValue Chain = Op.getOperand(0);
15455 SDValue Mask = Op.getOperand(2);
15456 SDValue Index = Op.getOperand(3);
15457 SDValue Base = Op.getOperand(4);
15458 SDValue Scale = Op.getOperand(5);
15459 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15461 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15463 SmallVector<SDValue, 2> Results;
15464 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15466 return DAG.getMergeValues(Results, dl);
15468 // Read Performance Monitoring Counters.
15470 SmallVector<SDValue, 2> Results;
15471 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15472 return DAG.getMergeValues(Results, dl);
15474 // XTEST intrinsics.
15476 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15477 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15478 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15479 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15481 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15482 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15483 Ret, SDValue(InTrans.getNode(), 1));
15487 SmallVector<SDValue, 2> Results;
15488 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15489 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15490 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15491 DAG.getConstant(-1, dl, MVT::i8));
15492 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15493 Op.getOperand(4), GenCF.getValue(1));
15494 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15495 Op.getOperand(5), MachinePointerInfo(),
15497 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15498 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15500 Results.push_back(SetCC);
15501 Results.push_back(Store);
15502 return DAG.getMergeValues(Results, dl);
15504 case COMPRESS_TO_MEM: {
15506 SDValue Mask = Op.getOperand(4);
15507 SDValue DataToCompress = Op.getOperand(3);
15508 SDValue Addr = Op.getOperand(2);
15509 SDValue Chain = Op.getOperand(0);
15511 if (isAllOnes(Mask)) // return just a store
15512 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15513 MachinePointerInfo(), false, false, 0);
15515 EVT VT = DataToCompress.getValueType();
15516 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15517 VT.getVectorNumElements());
15518 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15519 Mask.getValueType().getSizeInBits());
15520 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15521 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15522 DAG.getIntPtrConstant(0, dl));
15524 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15525 DataToCompress, DAG.getUNDEF(VT));
15526 return DAG.getStore(Chain, dl, Compressed, Addr,
15527 MachinePointerInfo(), false, false, 0);
15529 case EXPAND_FROM_MEM: {
15531 SDValue Mask = Op.getOperand(4);
15532 SDValue PathThru = Op.getOperand(3);
15533 SDValue Addr = Op.getOperand(2);
15534 SDValue Chain = Op.getOperand(0);
15535 EVT VT = Op.getValueType();
15537 if (isAllOnes(Mask)) // return just a load
15538 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15540 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15541 VT.getVectorNumElements());
15542 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15543 Mask.getValueType().getSizeInBits());
15544 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15545 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15546 DAG.getIntPtrConstant(0, dl));
15548 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15549 false, false, false, 0);
15551 SDValue Results[] = {
15552 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15554 return DAG.getMergeValues(Results, dl);
15559 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15560 SelectionDAG &DAG) const {
15561 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15562 MFI->setReturnAddressIsTaken(true);
15564 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15567 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15569 EVT PtrVT = getPointerTy();
15572 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15573 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15574 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15575 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15576 DAG.getNode(ISD::ADD, dl, PtrVT,
15577 FrameAddr, Offset),
15578 MachinePointerInfo(), false, false, false, 0);
15581 // Just load the return address.
15582 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15583 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15584 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15587 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15588 MachineFunction &MF = DAG.getMachineFunction();
15589 MachineFrameInfo *MFI = MF.getFrameInfo();
15590 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15591 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15592 EVT VT = Op.getValueType();
15594 MFI->setFrameAddressIsTaken(true);
15596 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15597 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15598 // is not possible to crawl up the stack without looking at the unwind codes
15600 int FrameAddrIndex = FuncInfo->getFAIndex();
15601 if (!FrameAddrIndex) {
15602 // Set up a frame object for the return address.
15603 unsigned SlotSize = RegInfo->getSlotSize();
15604 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15605 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15606 FuncInfo->setFAIndex(FrameAddrIndex);
15608 return DAG.getFrameIndex(FrameAddrIndex, VT);
15611 unsigned FrameReg =
15612 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15613 SDLoc dl(Op); // FIXME probably not meaningful
15614 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15615 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15616 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15617 "Invalid Frame Register!");
15618 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15620 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15621 MachinePointerInfo(),
15622 false, false, false, 0);
15626 // FIXME? Maybe this could be a TableGen attribute on some registers and
15627 // this table could be generated automatically from RegInfo.
15628 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15630 unsigned Reg = StringSwitch<unsigned>(RegName)
15631 .Case("esp", X86::ESP)
15632 .Case("rsp", X86::RSP)
15636 report_fatal_error("Invalid register name global variable");
15639 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15640 SelectionDAG &DAG) const {
15641 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15642 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15645 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15646 SDValue Chain = Op.getOperand(0);
15647 SDValue Offset = Op.getOperand(1);
15648 SDValue Handler = Op.getOperand(2);
15651 EVT PtrVT = getPointerTy();
15652 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15653 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15654 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15655 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15656 "Invalid Frame Register!");
15657 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15658 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15660 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15661 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15663 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15664 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15666 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15668 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15669 DAG.getRegister(StoreAddrReg, PtrVT));
15672 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15673 SelectionDAG &DAG) const {
15675 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15676 DAG.getVTList(MVT::i32, MVT::Other),
15677 Op.getOperand(0), Op.getOperand(1));
15680 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15681 SelectionDAG &DAG) const {
15683 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15684 Op.getOperand(0), Op.getOperand(1));
15687 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15688 return Op.getOperand(0);
15691 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15692 SelectionDAG &DAG) const {
15693 SDValue Root = Op.getOperand(0);
15694 SDValue Trmp = Op.getOperand(1); // trampoline
15695 SDValue FPtr = Op.getOperand(2); // nested function
15696 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15699 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15700 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15702 if (Subtarget->is64Bit()) {
15703 SDValue OutChains[6];
15705 // Large code-model.
15706 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15707 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15709 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15710 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15712 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15714 // Load the pointer to the nested function into R11.
15715 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15716 SDValue Addr = Trmp;
15717 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15718 Addr, MachinePointerInfo(TrmpAddr),
15721 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15722 DAG.getConstant(2, dl, MVT::i64));
15723 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15724 MachinePointerInfo(TrmpAddr, 2),
15727 // Load the 'nest' parameter value into R10.
15728 // R10 is specified in X86CallingConv.td
15729 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15730 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15731 DAG.getConstant(10, dl, MVT::i64));
15732 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15733 Addr, MachinePointerInfo(TrmpAddr, 10),
15736 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15737 DAG.getConstant(12, dl, MVT::i64));
15738 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15739 MachinePointerInfo(TrmpAddr, 12),
15742 // Jump to the nested function.
15743 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15744 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15745 DAG.getConstant(20, dl, MVT::i64));
15746 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15747 Addr, MachinePointerInfo(TrmpAddr, 20),
15750 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15751 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15752 DAG.getConstant(22, dl, MVT::i64));
15753 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15754 Addr, MachinePointerInfo(TrmpAddr, 22),
15757 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15759 const Function *Func =
15760 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15761 CallingConv::ID CC = Func->getCallingConv();
15766 llvm_unreachable("Unsupported calling convention");
15767 case CallingConv::C:
15768 case CallingConv::X86_StdCall: {
15769 // Pass 'nest' parameter in ECX.
15770 // Must be kept in sync with X86CallingConv.td
15771 NestReg = X86::ECX;
15773 // Check that ECX wasn't needed by an 'inreg' parameter.
15774 FunctionType *FTy = Func->getFunctionType();
15775 const AttributeSet &Attrs = Func->getAttributes();
15777 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15778 unsigned InRegCount = 0;
15781 for (FunctionType::param_iterator I = FTy->param_begin(),
15782 E = FTy->param_end(); I != E; ++I, ++Idx)
15783 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15784 // FIXME: should only count parameters that are lowered to integers.
15785 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15787 if (InRegCount > 2) {
15788 report_fatal_error("Nest register in use - reduce number of inreg"
15794 case CallingConv::X86_FastCall:
15795 case CallingConv::X86_ThisCall:
15796 case CallingConv::Fast:
15797 // Pass 'nest' parameter in EAX.
15798 // Must be kept in sync with X86CallingConv.td
15799 NestReg = X86::EAX;
15803 SDValue OutChains[4];
15804 SDValue Addr, Disp;
15806 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15807 DAG.getConstant(10, dl, MVT::i32));
15808 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15810 // This is storing the opcode for MOV32ri.
15811 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15812 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15813 OutChains[0] = DAG.getStore(Root, dl,
15814 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15815 Trmp, MachinePointerInfo(TrmpAddr),
15818 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15819 DAG.getConstant(1, dl, MVT::i32));
15820 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15821 MachinePointerInfo(TrmpAddr, 1),
15824 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15825 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15826 DAG.getConstant(5, dl, MVT::i32));
15827 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15828 Addr, MachinePointerInfo(TrmpAddr, 5),
15831 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15832 DAG.getConstant(6, dl, MVT::i32));
15833 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15834 MachinePointerInfo(TrmpAddr, 6),
15837 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15841 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15842 SelectionDAG &DAG) const {
15844 The rounding mode is in bits 11:10 of FPSR, and has the following
15846 00 Round to nearest
15851 FLT_ROUNDS, on the other hand, expects the following:
15858 To perform the conversion, we do:
15859 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15862 MachineFunction &MF = DAG.getMachineFunction();
15863 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15864 unsigned StackAlignment = TFI.getStackAlignment();
15865 MVT VT = Op.getSimpleValueType();
15868 // Save FP Control Word to stack slot
15869 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15870 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15872 MachineMemOperand *MMO =
15873 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15874 MachineMemOperand::MOStore, 2, 2);
15876 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15877 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15878 DAG.getVTList(MVT::Other),
15879 Ops, MVT::i16, MMO);
15881 // Load FP Control Word from stack slot
15882 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15883 MachinePointerInfo(), false, false, false, 0);
15885 // Transform as necessary
15887 DAG.getNode(ISD::SRL, DL, MVT::i16,
15888 DAG.getNode(ISD::AND, DL, MVT::i16,
15889 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15890 DAG.getConstant(11, DL, MVT::i8));
15892 DAG.getNode(ISD::SRL, DL, MVT::i16,
15893 DAG.getNode(ISD::AND, DL, MVT::i16,
15894 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15895 DAG.getConstant(9, DL, MVT::i8));
15898 DAG.getNode(ISD::AND, DL, MVT::i16,
15899 DAG.getNode(ISD::ADD, DL, MVT::i16,
15900 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15901 DAG.getConstant(1, DL, MVT::i16)),
15902 DAG.getConstant(3, DL, MVT::i16));
15904 return DAG.getNode((VT.getSizeInBits() < 16 ?
15905 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15908 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15909 MVT VT = Op.getSimpleValueType();
15911 unsigned NumBits = VT.getSizeInBits();
15914 Op = Op.getOperand(0);
15915 if (VT == MVT::i8) {
15916 // Zero extend to i32 since there is not an i8 bsr.
15918 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15921 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15922 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15923 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15925 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15928 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15929 DAG.getConstant(X86::COND_E, dl, MVT::i8),
15932 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15934 // Finally xor with NumBits-1.
15935 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15936 DAG.getConstant(NumBits - 1, dl, OpVT));
15939 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15943 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15944 MVT VT = Op.getSimpleValueType();
15946 unsigned NumBits = VT.getSizeInBits();
15949 Op = Op.getOperand(0);
15950 if (VT == MVT::i8) {
15951 // Zero extend to i32 since there is not an i8 bsr.
15953 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15956 // Issue a bsr (scan bits in reverse).
15957 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15958 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15960 // And xor with NumBits-1.
15961 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15962 DAG.getConstant(NumBits - 1, dl, OpVT));
15965 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15969 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15970 MVT VT = Op.getSimpleValueType();
15971 unsigned NumBits = VT.getSizeInBits();
15973 Op = Op.getOperand(0);
15975 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15976 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15977 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15979 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15982 DAG.getConstant(NumBits, dl, VT),
15983 DAG.getConstant(X86::COND_E, dl, MVT::i8),
15986 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15989 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15990 // ones, and then concatenate the result back.
15991 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15992 MVT VT = Op.getSimpleValueType();
15994 assert(VT.is256BitVector() && VT.isInteger() &&
15995 "Unsupported value type for operation");
15997 unsigned NumElems = VT.getVectorNumElements();
16000 // Extract the LHS vectors
16001 SDValue LHS = Op.getOperand(0);
16002 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16003 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16005 // Extract the RHS vectors
16006 SDValue RHS = Op.getOperand(1);
16007 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16008 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16010 MVT EltVT = VT.getVectorElementType();
16011 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16013 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16014 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16015 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16018 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16019 assert(Op.getSimpleValueType().is256BitVector() &&
16020 Op.getSimpleValueType().isInteger() &&
16021 "Only handle AVX 256-bit vector integer operation");
16022 return Lower256IntArith(Op, DAG);
16025 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16026 assert(Op.getSimpleValueType().is256BitVector() &&
16027 Op.getSimpleValueType().isInteger() &&
16028 "Only handle AVX 256-bit vector integer operation");
16029 return Lower256IntArith(Op, DAG);
16032 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16033 SelectionDAG &DAG) {
16035 MVT VT = Op.getSimpleValueType();
16037 // Decompose 256-bit ops into smaller 128-bit ops.
16038 if (VT.is256BitVector() && !Subtarget->hasInt256())
16039 return Lower256IntArith(Op, DAG);
16041 SDValue A = Op.getOperand(0);
16042 SDValue B = Op.getOperand(1);
16044 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16045 // pairs, multiply and truncate.
16046 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16047 if (Subtarget->hasInt256()) {
16048 if (VT == MVT::v32i8) {
16049 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16050 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16051 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16052 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16053 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16054 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16055 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16056 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16057 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16058 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16061 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16062 return DAG.getNode(
16063 ISD::TRUNCATE, dl, VT,
16064 DAG.getNode(ISD::MUL, dl, ExVT,
16065 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16066 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16069 assert(VT == MVT::v16i8 &&
16070 "Pre-AVX2 support only supports v16i8 multiplication");
16071 MVT ExVT = MVT::v8i16;
16073 // Extract the lo parts and sign extend to i16
16075 if (Subtarget->hasSSE41()) {
16076 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16077 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16079 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16080 -1, 4, -1, 5, -1, 6, -1, 7};
16081 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16082 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16083 ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16084 BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16085 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16086 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16089 // Extract the hi parts and sign extend to i16
16091 if (Subtarget->hasSSE41()) {
16092 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16093 -1, -1, -1, -1, -1, -1, -1, -1};
16094 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16095 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16096 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16097 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16099 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16100 -1, 12, -1, 13, -1, 14, -1, 15};
16101 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16102 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16103 AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16104 BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16105 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16106 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16109 // Multiply, mask the lower 8bits of the lo/hi results and pack
16110 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16111 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16112 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16113 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16114 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16117 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16118 if (VT == MVT::v4i32) {
16119 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16120 "Should not custom lower when pmuldq is available!");
16122 // Extract the odd parts.
16123 static const int UnpackMask[] = { 1, -1, 3, -1 };
16124 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16125 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16127 // Multiply the even parts.
16128 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16129 // Now multiply odd parts.
16130 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16132 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16133 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16135 // Merge the two vectors back together with a shuffle. This expands into 2
16137 static const int ShufMask[] = { 0, 4, 2, 6 };
16138 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16141 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16142 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16144 // Ahi = psrlqi(a, 32);
16145 // Bhi = psrlqi(b, 32);
16147 // AloBlo = pmuludq(a, b);
16148 // AloBhi = pmuludq(a, Bhi);
16149 // AhiBlo = pmuludq(Ahi, b);
16151 // AloBhi = psllqi(AloBhi, 32);
16152 // AhiBlo = psllqi(AhiBlo, 32);
16153 // return AloBlo + AloBhi + AhiBlo;
16155 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16156 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16158 // Bit cast to 32-bit vectors for MULUDQ
16159 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16160 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16161 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16162 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16163 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16164 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16166 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16167 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16168 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16170 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16171 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16173 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16174 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16177 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16178 assert(Subtarget->isTargetWin64() && "Unexpected target");
16179 EVT VT = Op.getValueType();
16180 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16181 "Unexpected return type for lowering");
16185 switch (Op->getOpcode()) {
16186 default: llvm_unreachable("Unexpected request for libcall!");
16187 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16188 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16189 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16190 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16191 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16192 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16196 SDValue InChain = DAG.getEntryNode();
16198 TargetLowering::ArgListTy Args;
16199 TargetLowering::ArgListEntry Entry;
16200 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16201 EVT ArgVT = Op->getOperand(i).getValueType();
16202 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16203 "Unexpected argument type for lowering");
16204 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16205 Entry.Node = StackPtr;
16206 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16208 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16209 Entry.Ty = PointerType::get(ArgTy,0);
16210 Entry.isSExt = false;
16211 Entry.isZExt = false;
16212 Args.push_back(Entry);
16215 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16218 TargetLowering::CallLoweringInfo CLI(DAG);
16219 CLI.setDebugLoc(dl).setChain(InChain)
16220 .setCallee(getLibcallCallingConv(LC),
16221 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16222 Callee, std::move(Args), 0)
16223 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16225 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16226 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16229 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16230 SelectionDAG &DAG) {
16231 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16232 EVT VT = Op0.getValueType();
16235 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16236 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16238 // PMULxD operations multiply each even value (starting at 0) of LHS with
16239 // the related value of RHS and produce a widen result.
16240 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16241 // => <2 x i64> <ae|cg>
16243 // In other word, to have all the results, we need to perform two PMULxD:
16244 // 1. one with the even values.
16245 // 2. one with the odd values.
16246 // To achieve #2, with need to place the odd values at an even position.
16248 // Place the odd value at an even position (basically, shift all values 1
16249 // step to the left):
16250 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16251 // <a|b|c|d> => <b|undef|d|undef>
16252 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16253 // <e|f|g|h> => <f|undef|h|undef>
16254 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16256 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16258 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16259 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16261 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16262 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16263 // => <2 x i64> <ae|cg>
16264 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16265 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16266 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16267 // => <2 x i64> <bf|dh>
16268 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16269 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16271 // Shuffle it back into the right order.
16272 SDValue Highs, Lows;
16273 if (VT == MVT::v8i32) {
16274 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16275 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16276 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16277 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16279 const int HighMask[] = {1, 5, 3, 7};
16280 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16281 const int LowMask[] = {0, 4, 2, 6};
16282 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16285 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16286 // unsigned multiply.
16287 if (IsSigned && !Subtarget->hasSSE41()) {
16289 DAG.getConstant(31, dl,
16290 DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16291 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16292 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16293 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16294 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16296 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16297 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16300 // The first result of MUL_LOHI is actually the low value, followed by the
16302 SDValue Ops[] = {Lows, Highs};
16303 return DAG.getMergeValues(Ops, dl);
16306 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16307 const X86Subtarget *Subtarget) {
16308 MVT VT = Op.getSimpleValueType();
16310 SDValue R = Op.getOperand(0);
16311 SDValue Amt = Op.getOperand(1);
16313 // Optimize shl/srl/sra with constant shift amount.
16314 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16315 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16316 uint64_t ShiftAmt = ShiftConst->getZExtValue();
16318 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16319 (Subtarget->hasInt256() &&
16320 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16321 (Subtarget->hasAVX512() &&
16322 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16323 if (Op.getOpcode() == ISD::SHL)
16324 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16326 if (Op.getOpcode() == ISD::SRL)
16327 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16329 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16330 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16334 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16335 unsigned NumElts = VT.getVectorNumElements();
16336 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16338 if (Op.getOpcode() == ISD::SHL) {
16339 // Make a large shift.
16340 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16342 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16343 // Zero out the rightmost bits.
16344 SmallVector<SDValue, 32> V(
16345 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16346 return DAG.getNode(ISD::AND, dl, VT, SHL,
16347 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16349 if (Op.getOpcode() == ISD::SRL) {
16350 // Make a large shift.
16351 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16353 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16354 // Zero out the leftmost bits.
16355 SmallVector<SDValue, 32> V(
16356 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16357 return DAG.getNode(ISD::AND, dl, VT, SRL,
16358 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16360 if (Op.getOpcode() == ISD::SRA) {
16361 if (ShiftAmt == 7) {
16362 // R s>> 7 === R s< 0
16363 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16364 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16367 // R s>> a === ((R u>> a) ^ m) - m
16368 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16369 SmallVector<SDValue, 32> V(NumElts,
16370 DAG.getConstant(128 >> ShiftAmt, dl,
16372 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16373 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16374 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16377 llvm_unreachable("Unknown shift opcode.");
16382 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16383 if (!Subtarget->is64Bit() &&
16384 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16385 Amt.getOpcode() == ISD::BITCAST &&
16386 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16387 Amt = Amt.getOperand(0);
16388 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16389 VT.getVectorNumElements();
16390 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16391 uint64_t ShiftAmt = 0;
16392 for (unsigned i = 0; i != Ratio; ++i) {
16393 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16397 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16399 // Check remaining shift amounts.
16400 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16401 uint64_t ShAmt = 0;
16402 for (unsigned j = 0; j != Ratio; ++j) {
16403 ConstantSDNode *C =
16404 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16408 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16410 if (ShAmt != ShiftAmt)
16413 switch (Op.getOpcode()) {
16415 llvm_unreachable("Unknown shift opcode!");
16417 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16420 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16423 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16431 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16432 const X86Subtarget* Subtarget) {
16433 MVT VT = Op.getSimpleValueType();
16435 SDValue R = Op.getOperand(0);
16436 SDValue Amt = Op.getOperand(1);
16438 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16439 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16440 (Subtarget->hasInt256() &&
16441 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16442 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16443 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16445 EVT EltVT = VT.getVectorElementType();
16447 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16448 // Check if this build_vector node is doing a splat.
16449 // If so, then set BaseShAmt equal to the splat value.
16450 BaseShAmt = BV->getSplatValue();
16451 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16452 BaseShAmt = SDValue();
16454 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16455 Amt = Amt.getOperand(0);
16457 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16458 if (SVN && SVN->isSplat()) {
16459 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16460 SDValue InVec = Amt.getOperand(0);
16461 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16462 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16463 "Unexpected shuffle index found!");
16464 BaseShAmt = InVec.getOperand(SplatIdx);
16465 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16466 if (ConstantSDNode *C =
16467 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16468 if (C->getZExtValue() == SplatIdx)
16469 BaseShAmt = InVec.getOperand(1);
16474 // Avoid introducing an extract element from a shuffle.
16475 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16476 DAG.getIntPtrConstant(SplatIdx, dl));
16480 if (BaseShAmt.getNode()) {
16481 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16482 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16483 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16484 else if (EltVT.bitsLT(MVT::i32))
16485 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16487 switch (Op.getOpcode()) {
16489 llvm_unreachable("Unknown shift opcode!");
16491 switch (VT.SimpleTy) {
16492 default: return SDValue();
16501 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16504 switch (VT.SimpleTy) {
16505 default: return SDValue();
16512 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16515 switch (VT.SimpleTy) {
16516 default: return SDValue();
16525 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16531 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16532 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
16533 Amt.getOpcode() == ISD::BITCAST &&
16534 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16535 Amt = Amt.getOperand(0);
16536 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16537 VT.getVectorNumElements();
16538 std::vector<SDValue> Vals(Ratio);
16539 for (unsigned i = 0; i != Ratio; ++i)
16540 Vals[i] = Amt.getOperand(i);
16541 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16542 for (unsigned j = 0; j != Ratio; ++j)
16543 if (Vals[j] != Amt.getOperand(i + j))
16546 switch (Op.getOpcode()) {
16548 llvm_unreachable("Unknown shift opcode!");
16550 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16552 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16554 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16561 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16562 SelectionDAG &DAG) {
16563 MVT VT = Op.getSimpleValueType();
16565 SDValue R = Op.getOperand(0);
16566 SDValue Amt = Op.getOperand(1);
16568 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16569 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16571 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16574 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16577 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16580 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16581 if (Subtarget->hasInt256()) {
16582 if (Op.getOpcode() == ISD::SRL &&
16583 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16584 VT == MVT::v4i64 || VT == MVT::v8i32))
16586 if (Op.getOpcode() == ISD::SHL &&
16587 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16588 VT == MVT::v4i64 || VT == MVT::v8i32))
16590 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16594 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16595 // shifts per-lane and then shuffle the partial results back together.
16596 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16597 // Splat the shift amounts so the scalar shifts above will catch it.
16598 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16599 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16600 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16601 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16602 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16605 // If possible, lower this packed shift into a vector multiply instead of
16606 // expanding it into a sequence of scalar shifts.
16607 // Do this only if the vector shift count is a constant build_vector.
16608 if (Op.getOpcode() == ISD::SHL &&
16609 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16610 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16611 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16612 SmallVector<SDValue, 8> Elts;
16613 EVT SVT = VT.getScalarType();
16614 unsigned SVTBits = SVT.getSizeInBits();
16615 const APInt &One = APInt(SVTBits, 1);
16616 unsigned NumElems = VT.getVectorNumElements();
16618 for (unsigned i=0; i !=NumElems; ++i) {
16619 SDValue Op = Amt->getOperand(i);
16620 if (Op->getOpcode() == ISD::UNDEF) {
16621 Elts.push_back(Op);
16625 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16626 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16627 uint64_t ShAmt = C.getZExtValue();
16628 if (ShAmt >= SVTBits) {
16629 Elts.push_back(DAG.getUNDEF(SVT));
16632 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16634 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16635 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16638 // Lower SHL with variable shift amount.
16639 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16640 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16642 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16643 DAG.getConstant(0x3f800000U, dl, VT));
16644 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16645 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16646 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16649 // If possible, lower this shift as a sequence of two shifts by
16650 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16652 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16654 // Could be rewritten as:
16655 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16657 // The advantage is that the two shifts from the example would be
16658 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16659 // the vector shift into four scalar shifts plus four pairs of vector
16661 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16662 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16663 unsigned TargetOpcode = X86ISD::MOVSS;
16664 bool CanBeSimplified;
16665 // The splat value for the first packed shift (the 'X' from the example).
16666 SDValue Amt1 = Amt->getOperand(0);
16667 // The splat value for the second packed shift (the 'Y' from the example).
16668 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16669 Amt->getOperand(2);
16671 // See if it is possible to replace this node with a sequence of
16672 // two shifts followed by a MOVSS/MOVSD
16673 if (VT == MVT::v4i32) {
16674 // Check if it is legal to use a MOVSS.
16675 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16676 Amt2 == Amt->getOperand(3);
16677 if (!CanBeSimplified) {
16678 // Otherwise, check if we can still simplify this node using a MOVSD.
16679 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16680 Amt->getOperand(2) == Amt->getOperand(3);
16681 TargetOpcode = X86ISD::MOVSD;
16682 Amt2 = Amt->getOperand(2);
16685 // Do similar checks for the case where the machine value type
16687 CanBeSimplified = Amt1 == Amt->getOperand(1);
16688 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16689 CanBeSimplified = Amt2 == Amt->getOperand(i);
16691 if (!CanBeSimplified) {
16692 TargetOpcode = X86ISD::MOVSD;
16693 CanBeSimplified = true;
16694 Amt2 = Amt->getOperand(4);
16695 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16696 CanBeSimplified = Amt1 == Amt->getOperand(i);
16697 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16698 CanBeSimplified = Amt2 == Amt->getOperand(j);
16702 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16703 isa<ConstantSDNode>(Amt2)) {
16704 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16705 EVT CastVT = MVT::v4i32;
16707 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16708 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16710 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16711 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16712 if (TargetOpcode == X86ISD::MOVSD)
16713 CastVT = MVT::v2i64;
16714 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16715 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16716 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16718 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16722 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16723 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16724 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16726 SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16727 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16728 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16730 // r = VSELECT(r, shl(r, 4), a);
16731 SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16732 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16735 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16736 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16737 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16739 // r = VSELECT(r, shl(r, 2), a);
16740 M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16741 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16744 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16745 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16746 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16748 // return VSELECT(r, r+r, a);
16749 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16750 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16754 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16755 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16756 // solution better.
16757 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16758 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16760 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16761 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16762 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16763 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16764 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16767 // Decompose 256-bit shifts into smaller 128-bit shifts.
16768 if (VT.is256BitVector()) {
16769 unsigned NumElems = VT.getVectorNumElements();
16770 MVT EltVT = VT.getVectorElementType();
16771 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16773 // Extract the two vectors
16774 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16775 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16777 // Recreate the shift amount vectors
16778 SDValue Amt1, Amt2;
16779 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16780 // Constant shift amount
16781 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16782 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16783 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16785 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16786 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16788 // Variable shift amount
16789 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16790 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16793 // Issue new vector shifts for the smaller types
16794 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16795 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16797 // Concatenate the result back
16798 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16804 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16805 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16806 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16807 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16808 // has only one use.
16809 SDNode *N = Op.getNode();
16810 SDValue LHS = N->getOperand(0);
16811 SDValue RHS = N->getOperand(1);
16812 unsigned BaseOp = 0;
16815 switch (Op.getOpcode()) {
16816 default: llvm_unreachable("Unknown ovf instruction!");
16818 // A subtract of one will be selected as a INC. Note that INC doesn't
16819 // set CF, so we can't do this for UADDO.
16820 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16822 BaseOp = X86ISD::INC;
16823 Cond = X86::COND_O;
16826 BaseOp = X86ISD::ADD;
16827 Cond = X86::COND_O;
16830 BaseOp = X86ISD::ADD;
16831 Cond = X86::COND_B;
16834 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16835 // set CF, so we can't do this for USUBO.
16836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16838 BaseOp = X86ISD::DEC;
16839 Cond = X86::COND_O;
16842 BaseOp = X86ISD::SUB;
16843 Cond = X86::COND_O;
16846 BaseOp = X86ISD::SUB;
16847 Cond = X86::COND_B;
16850 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16851 Cond = X86::COND_O;
16853 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16854 if (N->getValueType(0) == MVT::i8) {
16855 BaseOp = X86ISD::UMUL8;
16856 Cond = X86::COND_O;
16859 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16861 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16864 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16865 DAG.getConstant(X86::COND_O, DL, MVT::i32),
16866 SDValue(Sum.getNode(), 2));
16868 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16872 // Also sets EFLAGS.
16873 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16874 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16877 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16878 DAG.getConstant(Cond, DL, MVT::i32),
16879 SDValue(Sum.getNode(), 1));
16881 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16884 /// Returns true if the operand type is exactly twice the native width, and
16885 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16886 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16887 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16888 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16889 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16892 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16893 else if (OpWidth == 128)
16894 return Subtarget->hasCmpxchg16b();
16899 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16900 return needsCmpXchgNb(SI->getValueOperand()->getType());
16903 // Note: this turns large loads into lock cmpxchg8b/16b.
16904 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16905 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16906 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16907 return needsCmpXchgNb(PTy->getElementType());
16910 TargetLoweringBase::AtomicRMWExpansionKind
16911 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16912 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16913 const Type *MemType = AI->getType();
16915 // If the operand is too big, we must see if cmpxchg8/16b is available
16916 // and default to library calls otherwise.
16917 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16918 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16919 : AtomicRMWExpansionKind::None;
16922 AtomicRMWInst::BinOp Op = AI->getOperation();
16925 llvm_unreachable("Unknown atomic operation");
16926 case AtomicRMWInst::Xchg:
16927 case AtomicRMWInst::Add:
16928 case AtomicRMWInst::Sub:
16929 // It's better to use xadd, xsub or xchg for these in all cases.
16930 return AtomicRMWExpansionKind::None;
16931 case AtomicRMWInst::Or:
16932 case AtomicRMWInst::And:
16933 case AtomicRMWInst::Xor:
16934 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16935 // prefix to a normal instruction for these operations.
16936 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16937 : AtomicRMWExpansionKind::None;
16938 case AtomicRMWInst::Nand:
16939 case AtomicRMWInst::Max:
16940 case AtomicRMWInst::Min:
16941 case AtomicRMWInst::UMax:
16942 case AtomicRMWInst::UMin:
16943 // These always require a non-trivial set of data operations on x86. We must
16944 // use a cmpxchg loop.
16945 return AtomicRMWExpansionKind::CmpXChg;
16949 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16950 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16951 // no-sse2). There isn't any reason to disable it if the target processor
16953 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16957 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16958 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16959 const Type *MemType = AI->getType();
16960 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16961 // there is no benefit in turning such RMWs into loads, and it is actually
16962 // harmful as it introduces a mfence.
16963 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16966 auto Builder = IRBuilder<>(AI);
16967 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16968 auto SynchScope = AI->getSynchScope();
16969 // We must restrict the ordering to avoid generating loads with Release or
16970 // ReleaseAcquire orderings.
16971 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16972 auto Ptr = AI->getPointerOperand();
16974 // Before the load we need a fence. Here is an example lifted from
16975 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16978 // x.store(1, relaxed);
16979 // r1 = y.fetch_add(0, release);
16981 // y.fetch_add(42, acquire);
16982 // r2 = x.load(relaxed);
16983 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16984 // lowered to just a load without a fence. A mfence flushes the store buffer,
16985 // making the optimization clearly correct.
16986 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16987 // otherwise, we might be able to be more agressive on relaxed idempotent
16988 // rmw. In practice, they do not look useful, so we don't try to be
16989 // especially clever.
16990 if (SynchScope == SingleThread) {
16991 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16992 // the IR level, so we must wrap it in an intrinsic.
16994 } else if (hasMFENCE(*Subtarget)) {
16995 Function *MFence = llvm::Intrinsic::getDeclaration(M,
16996 Intrinsic::x86_sse2_mfence);
16997 Builder.CreateCall(MFence);
16999 // FIXME: it might make sense to use a locked operation here but on a
17000 // different cache-line to prevent cache-line bouncing. In practice it
17001 // is probably a small win, and x86 processors without mfence are rare
17002 // enough that we do not bother.
17006 // Finally we can emit the atomic load.
17007 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17008 AI->getType()->getPrimitiveSizeInBits());
17009 Loaded->setAtomic(Order, SynchScope);
17010 AI->replaceAllUsesWith(Loaded);
17011 AI->eraseFromParent();
17015 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17016 SelectionDAG &DAG) {
17018 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17019 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17020 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17021 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17023 // The only fence that needs an instruction is a sequentially-consistent
17024 // cross-thread fence.
17025 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17026 if (hasMFENCE(*Subtarget))
17027 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17029 SDValue Chain = Op.getOperand(0);
17030 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17032 DAG.getRegister(X86::ESP, MVT::i32), // Base
17033 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
17034 DAG.getRegister(0, MVT::i32), // Index
17035 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
17036 DAG.getRegister(0, MVT::i32), // Segment.
17040 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17041 return SDValue(Res, 0);
17044 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17045 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17048 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17049 SelectionDAG &DAG) {
17050 MVT T = Op.getSimpleValueType();
17054 switch(T.SimpleTy) {
17055 default: llvm_unreachable("Invalid value type!");
17056 case MVT::i8: Reg = X86::AL; size = 1; break;
17057 case MVT::i16: Reg = X86::AX; size = 2; break;
17058 case MVT::i32: Reg = X86::EAX; size = 4; break;
17060 assert(Subtarget->is64Bit() && "Node not type legal!");
17061 Reg = X86::RAX; size = 8;
17064 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17065 Op.getOperand(2), SDValue());
17066 SDValue Ops[] = { cpIn.getValue(0),
17069 DAG.getTargetConstant(size, DL, MVT::i8),
17070 cpIn.getValue(1) };
17071 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17072 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17073 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17077 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17078 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17079 MVT::i32, cpOut.getValue(2));
17080 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17081 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17084 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17085 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17086 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17090 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17091 SelectionDAG &DAG) {
17092 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17093 MVT DstVT = Op.getSimpleValueType();
17095 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17096 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17097 if (DstVT != MVT::f64)
17098 // This conversion needs to be expanded.
17101 SDValue InVec = Op->getOperand(0);
17103 unsigned NumElts = SrcVT.getVectorNumElements();
17104 EVT SVT = SrcVT.getVectorElementType();
17106 // Widen the vector in input in the case of MVT::v2i32.
17107 // Example: from MVT::v2i32 to MVT::v4i32.
17108 SmallVector<SDValue, 16> Elts;
17109 for (unsigned i = 0, e = NumElts; i != e; ++i)
17110 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17111 DAG.getIntPtrConstant(i, dl)));
17113 // Explicitly mark the extra elements as Undef.
17114 Elts.append(NumElts, DAG.getUNDEF(SVT));
17116 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17117 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17118 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17119 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17120 DAG.getIntPtrConstant(0, dl));
17123 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17124 Subtarget->hasMMX() && "Unexpected custom BITCAST");
17125 assert((DstVT == MVT::i64 ||
17126 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17127 "Unexpected custom BITCAST");
17128 // i64 <=> MMX conversions are Legal.
17129 if (SrcVT==MVT::i64 && DstVT.isVector())
17131 if (DstVT==MVT::i64 && SrcVT.isVector())
17133 // MMX <=> MMX conversions are Legal.
17134 if (SrcVT.isVector() && DstVT.isVector())
17136 // All other conversions need to be expanded.
17140 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17141 SelectionDAG &DAG) {
17142 SDNode *Node = Op.getNode();
17145 Op = Op.getOperand(0);
17146 EVT VT = Op.getValueType();
17147 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17148 "CTPOP lowering only implemented for 128/256-bit wide vector types");
17150 unsigned NumElts = VT.getVectorNumElements();
17151 EVT EltVT = VT.getVectorElementType();
17152 unsigned Len = EltVT.getSizeInBits();
17154 // This is the vectorized version of the "best" algorithm from
17155 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17156 // with a minor tweak to use a series of adds + shifts instead of vector
17157 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17159 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17160 // v8i32 => Always profitable
17162 // FIXME: There a couple of possible improvements:
17164 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17165 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17167 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17168 "CTPOP not implemented for this vector element type.");
17170 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17171 // extra legalization.
17172 bool NeedsBitcast = EltVT == MVT::i32;
17173 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17175 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17177 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17179 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17182 // v = v - ((v >> 1) & 0x55555555...)
17183 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17184 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17185 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17187 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17189 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17190 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17192 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17194 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17195 if (VT != And.getValueType())
17196 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17197 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17199 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17200 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17201 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17202 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17203 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17205 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17206 if (NeedsBitcast) {
17207 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17208 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17209 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17212 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17213 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17214 if (VT != AndRHS.getValueType()) {
17215 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17216 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17218 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17220 // v = (v + (v >> 4)) & 0x0F0F0F0F...
17221 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17222 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17223 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17224 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17226 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17227 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17228 if (NeedsBitcast) {
17229 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17230 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17232 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17233 if (VT != And.getValueType())
17234 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17236 // The algorithm mentioned above uses:
17237 // v = (v * 0x01010101...) >> (Len - 8)
17239 // Change it to use vector adds + vector shifts which yield faster results on
17240 // Haswell than using vector integer multiplication.
17242 // For i32 elements:
17243 // v = v + (v >> 8)
17244 // v = v + (v >> 16)
17246 // For i64 elements:
17247 // v = v + (v >> 8)
17248 // v = v + (v >> 16)
17249 // v = v + (v >> 32)
17252 SmallVector<SDValue, 8> Csts;
17253 for (unsigned i = 8; i <= Len/2; i *= 2) {
17254 Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17255 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17256 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17257 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17261 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17262 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17264 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17265 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17266 if (NeedsBitcast) {
17267 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17268 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17270 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17271 if (VT != And.getValueType())
17272 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17277 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17278 SDNode *Node = Op.getNode();
17280 EVT T = Node->getValueType(0);
17281 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17282 DAG.getConstant(0, dl, T), Node->getOperand(2));
17283 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17284 cast<AtomicSDNode>(Node)->getMemoryVT(),
17285 Node->getOperand(0),
17286 Node->getOperand(1), negOp,
17287 cast<AtomicSDNode>(Node)->getMemOperand(),
17288 cast<AtomicSDNode>(Node)->getOrdering(),
17289 cast<AtomicSDNode>(Node)->getSynchScope());
17292 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17293 SDNode *Node = Op.getNode();
17295 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17297 // Convert seq_cst store -> xchg
17298 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17299 // FIXME: On 32-bit, store -> fist or movq would be more efficient
17300 // (The only way to get a 16-byte store is cmpxchg16b)
17301 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17302 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17303 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17304 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17305 cast<AtomicSDNode>(Node)->getMemoryVT(),
17306 Node->getOperand(0),
17307 Node->getOperand(1), Node->getOperand(2),
17308 cast<AtomicSDNode>(Node)->getMemOperand(),
17309 cast<AtomicSDNode>(Node)->getOrdering(),
17310 cast<AtomicSDNode>(Node)->getSynchScope());
17311 return Swap.getValue(1);
17313 // Other atomic stores have a simple pattern.
17317 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17318 EVT VT = Op.getNode()->getSimpleValueType(0);
17320 // Let legalize expand this if it isn't a legal type yet.
17321 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17324 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17327 bool ExtraOp = false;
17328 switch (Op.getOpcode()) {
17329 default: llvm_unreachable("Invalid code");
17330 case ISD::ADDC: Opc = X86ISD::ADD; break;
17331 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17332 case ISD::SUBC: Opc = X86ISD::SUB; break;
17333 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17337 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17339 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17340 Op.getOperand(1), Op.getOperand(2));
17343 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17344 SelectionDAG &DAG) {
17345 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17347 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17348 // which returns the values as { float, float } (in XMM0) or
17349 // { double, double } (which is returned in XMM0, XMM1).
17351 SDValue Arg = Op.getOperand(0);
17352 EVT ArgVT = Arg.getValueType();
17353 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17355 TargetLowering::ArgListTy Args;
17356 TargetLowering::ArgListEntry Entry;
17360 Entry.isSExt = false;
17361 Entry.isZExt = false;
17362 Args.push_back(Entry);
17364 bool isF64 = ArgVT == MVT::f64;
17365 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17366 // the small struct {f32, f32} is returned in (eax, edx). For f64,
17367 // the results are returned via SRet in memory.
17368 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
17369 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17370 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17372 Type *RetTy = isF64
17373 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17374 : (Type*)VectorType::get(ArgTy, 4);
17376 TargetLowering::CallLoweringInfo CLI(DAG);
17377 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17378 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17380 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17383 // Returned in xmm0 and xmm1.
17384 return CallResult.first;
17386 // Returned in bits 0:31 and 32:64 xmm0.
17387 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17388 CallResult.first, DAG.getIntPtrConstant(0, dl));
17389 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17390 CallResult.first, DAG.getIntPtrConstant(1, dl));
17391 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17392 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17395 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17396 SelectionDAG &DAG) {
17397 assert(Subtarget->hasAVX512() &&
17398 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17400 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17401 EVT VT = N->getValue().getValueType();
17402 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17405 // X86 scatter kills mask register, so its type should be added to
17406 // the list of return values
17407 if (N->getNumValues() == 1) {
17408 SDValue Index = N->getIndex();
17409 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17410 !Index.getValueType().is512BitVector())
17411 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17413 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17414 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17415 N->getOperand(3), Index };
17417 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17418 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17419 return SDValue(NewScatter.getNode(), 0);
17424 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17425 SelectionDAG &DAG) {
17426 assert(Subtarget->hasAVX512() &&
17427 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17429 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17430 EVT VT = Op.getValueType();
17431 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17434 SDValue Index = N->getIndex();
17435 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17436 !Index.getValueType().is512BitVector()) {
17437 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17438 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17439 N->getOperand(3), Index };
17440 DAG.UpdateNodeOperands(N, Ops);
17445 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17446 SelectionDAG &DAG) const {
17447 // TODO: Eventually, the lowering of these nodes should be informed by or
17448 // deferred to the GC strategy for the function in which they appear. For
17449 // now, however, they must be lowered to something. Since they are logically
17450 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17451 // require special handling for these nodes), lower them as literal NOOPs for
17453 SmallVector<SDValue, 2> Ops;
17455 Ops.push_back(Op.getOperand(0));
17456 if (Op->getGluedNode())
17457 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17460 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17461 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17466 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17467 SelectionDAG &DAG) const {
17468 // TODO: Eventually, the lowering of these nodes should be informed by or
17469 // deferred to the GC strategy for the function in which they appear. For
17470 // now, however, they must be lowered to something. Since they are logically
17471 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17472 // require special handling for these nodes), lower them as literal NOOPs for
17474 SmallVector<SDValue, 2> Ops;
17476 Ops.push_back(Op.getOperand(0));
17477 if (Op->getGluedNode())
17478 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17481 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17482 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17487 /// LowerOperation - Provide custom lowering hooks for some operations.
17489 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17490 switch (Op.getOpcode()) {
17491 default: llvm_unreachable("Should not custom lower this!");
17492 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17493 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17494 return LowerCMP_SWAP(Op, Subtarget, DAG);
17495 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
17496 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17497 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17498 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17499 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17500 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
17501 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17502 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17503 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17504 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17505 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17506 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17507 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17508 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17509 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17510 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17511 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17512 case ISD::SHL_PARTS:
17513 case ISD::SRA_PARTS:
17514 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17515 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17516 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17517 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17518 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17519 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17520 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17521 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17522 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17523 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17524 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17526 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17527 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17528 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17529 case ISD::SETCC: return LowerSETCC(Op, DAG);
17530 case ISD::SELECT: return LowerSELECT(Op, DAG);
17531 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17532 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17533 case ISD::VASTART: return LowerVASTART(Op, DAG);
17534 case ISD::VAARG: return LowerVAARG(Op, DAG);
17535 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17536 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17537 case ISD::INTRINSIC_VOID:
17538 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17539 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17540 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17541 case ISD::FRAME_TO_ARGS_OFFSET:
17542 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17543 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17544 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17545 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17546 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17547 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17548 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17549 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17550 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17551 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17552 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17553 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17554 case ISD::UMUL_LOHI:
17555 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17558 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17564 case ISD::UMULO: return LowerXALUO(Op, DAG);
17565 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17566 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17570 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17571 case ISD::ADD: return LowerADD(Op, DAG);
17572 case ISD::SUB: return LowerSUB(Op, DAG);
17573 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17574 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
17575 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
17576 case ISD::GC_TRANSITION_START:
17577 return LowerGC_TRANSITION_START(Op, DAG);
17578 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
17582 /// ReplaceNodeResults - Replace a node with an illegal result type
17583 /// with a new node built out of custom code.
17584 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17585 SmallVectorImpl<SDValue>&Results,
17586 SelectionDAG &DAG) const {
17588 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17589 switch (N->getOpcode()) {
17591 llvm_unreachable("Do not know how to custom type legalize this operation!");
17592 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17593 case X86ISD::FMINC:
17595 case X86ISD::FMAXC:
17596 case X86ISD::FMAX: {
17597 EVT VT = N->getValueType(0);
17598 if (VT != MVT::v2f32)
17599 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17600 SDValue UNDEF = DAG.getUNDEF(VT);
17601 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17602 N->getOperand(0), UNDEF);
17603 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17604 N->getOperand(1), UNDEF);
17605 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17608 case ISD::SIGN_EXTEND_INREG:
17613 // We don't want to expand or promote these.
17620 case ISD::UDIVREM: {
17621 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17622 Results.push_back(V);
17625 case ISD::FP_TO_SINT:
17626 case ISD::FP_TO_UINT: {
17627 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17629 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17632 std::pair<SDValue,SDValue> Vals =
17633 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17634 SDValue FIST = Vals.first, StackSlot = Vals.second;
17635 if (FIST.getNode()) {
17636 EVT VT = N->getValueType(0);
17637 // Return a load from the stack slot.
17638 if (StackSlot.getNode())
17639 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17640 MachinePointerInfo(),
17641 false, false, false, 0));
17643 Results.push_back(FIST);
17647 case ISD::UINT_TO_FP: {
17648 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17649 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17650 N->getValueType(0) != MVT::v2f32)
17652 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17654 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17656 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17657 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17658 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17659 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17660 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17661 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17664 case ISD::FP_ROUND: {
17665 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17667 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17668 Results.push_back(V);
17671 case ISD::INTRINSIC_W_CHAIN: {
17672 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17674 default : llvm_unreachable("Do not know how to custom type "
17675 "legalize this intrinsic operation!");
17676 case Intrinsic::x86_rdtsc:
17677 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17679 case Intrinsic::x86_rdtscp:
17680 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17682 case Intrinsic::x86_rdpmc:
17683 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17686 case ISD::READCYCLECOUNTER: {
17687 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17690 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17691 EVT T = N->getValueType(0);
17692 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17693 bool Regs64bit = T == MVT::i128;
17694 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17695 SDValue cpInL, cpInH;
17696 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17697 DAG.getConstant(0, dl, HalfT));
17698 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17699 DAG.getConstant(1, dl, HalfT));
17700 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17701 Regs64bit ? X86::RAX : X86::EAX,
17703 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17704 Regs64bit ? X86::RDX : X86::EDX,
17705 cpInH, cpInL.getValue(1));
17706 SDValue swapInL, swapInH;
17707 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17708 DAG.getConstant(0, dl, HalfT));
17709 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17710 DAG.getConstant(1, dl, HalfT));
17711 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17712 Regs64bit ? X86::RBX : X86::EBX,
17713 swapInL, cpInH.getValue(1));
17714 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17715 Regs64bit ? X86::RCX : X86::ECX,
17716 swapInH, swapInL.getValue(1));
17717 SDValue Ops[] = { swapInH.getValue(0),
17719 swapInH.getValue(1) };
17720 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17721 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17722 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17723 X86ISD::LCMPXCHG8_DAG;
17724 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17725 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17726 Regs64bit ? X86::RAX : X86::EAX,
17727 HalfT, Result.getValue(1));
17728 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17729 Regs64bit ? X86::RDX : X86::EDX,
17730 HalfT, cpOutL.getValue(2));
17731 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17733 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17734 MVT::i32, cpOutH.getValue(2));
17736 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17737 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17738 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17740 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17741 Results.push_back(Success);
17742 Results.push_back(EFLAGS.getValue(1));
17745 case ISD::ATOMIC_SWAP:
17746 case ISD::ATOMIC_LOAD_ADD:
17747 case ISD::ATOMIC_LOAD_SUB:
17748 case ISD::ATOMIC_LOAD_AND:
17749 case ISD::ATOMIC_LOAD_OR:
17750 case ISD::ATOMIC_LOAD_XOR:
17751 case ISD::ATOMIC_LOAD_NAND:
17752 case ISD::ATOMIC_LOAD_MIN:
17753 case ISD::ATOMIC_LOAD_MAX:
17754 case ISD::ATOMIC_LOAD_UMIN:
17755 case ISD::ATOMIC_LOAD_UMAX:
17756 case ISD::ATOMIC_LOAD: {
17757 // Delegate to generic TypeLegalization. Situations we can really handle
17758 // should have already been dealt with by AtomicExpandPass.cpp.
17761 case ISD::BITCAST: {
17762 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17763 EVT DstVT = N->getValueType(0);
17764 EVT SrcVT = N->getOperand(0)->getValueType(0);
17766 if (SrcVT != MVT::f64 ||
17767 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17770 unsigned NumElts = DstVT.getVectorNumElements();
17771 EVT SVT = DstVT.getVectorElementType();
17772 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17773 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17774 MVT::v2f64, N->getOperand(0));
17775 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17777 if (ExperimentalVectorWideningLegalization) {
17778 // If we are legalizing vectors by widening, we already have the desired
17779 // legal vector type, just return it.
17780 Results.push_back(ToVecInt);
17784 SmallVector<SDValue, 8> Elts;
17785 for (unsigned i = 0, e = NumElts; i != e; ++i)
17786 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17787 ToVecInt, DAG.getIntPtrConstant(i, dl)));
17789 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17794 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17795 switch ((X86ISD::NodeType)Opcode) {
17796 case X86ISD::FIRST_NUMBER: break;
17797 case X86ISD::BSF: return "X86ISD::BSF";
17798 case X86ISD::BSR: return "X86ISD::BSR";
17799 case X86ISD::SHLD: return "X86ISD::SHLD";
17800 case X86ISD::SHRD: return "X86ISD::SHRD";
17801 case X86ISD::FAND: return "X86ISD::FAND";
17802 case X86ISD::FANDN: return "X86ISD::FANDN";
17803 case X86ISD::FOR: return "X86ISD::FOR";
17804 case X86ISD::FXOR: return "X86ISD::FXOR";
17805 case X86ISD::FSRL: return "X86ISD::FSRL";
17806 case X86ISD::FILD: return "X86ISD::FILD";
17807 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17808 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17809 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17810 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17811 case X86ISD::FLD: return "X86ISD::FLD";
17812 case X86ISD::FST: return "X86ISD::FST";
17813 case X86ISD::CALL: return "X86ISD::CALL";
17814 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17815 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17816 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17817 case X86ISD::BT: return "X86ISD::BT";
17818 case X86ISD::CMP: return "X86ISD::CMP";
17819 case X86ISD::COMI: return "X86ISD::COMI";
17820 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17821 case X86ISD::CMPM: return "X86ISD::CMPM";
17822 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17823 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
17824 case X86ISD::SETCC: return "X86ISD::SETCC";
17825 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17826 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17827 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
17828 case X86ISD::CMOV: return "X86ISD::CMOV";
17829 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17830 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17831 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17832 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17833 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17834 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17835 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17836 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
17837 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
17838 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
17839 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17840 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17841 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17842 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17843 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17844 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
17845 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17846 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17847 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17848 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17849 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17850 case X86ISD::ADDUS: return "X86ISD::ADDUS";
17851 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17852 case X86ISD::HADD: return "X86ISD::HADD";
17853 case X86ISD::HSUB: return "X86ISD::HSUB";
17854 case X86ISD::FHADD: return "X86ISD::FHADD";
17855 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17856 case X86ISD::UMAX: return "X86ISD::UMAX";
17857 case X86ISD::UMIN: return "X86ISD::UMIN";
17858 case X86ISD::SMAX: return "X86ISD::SMAX";
17859 case X86ISD::SMIN: return "X86ISD::SMIN";
17860 case X86ISD::FMAX: return "X86ISD::FMAX";
17861 case X86ISD::FMIN: return "X86ISD::FMIN";
17862 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17863 case X86ISD::FMINC: return "X86ISD::FMINC";
17864 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17865 case X86ISD::FRCP: return "X86ISD::FRCP";
17866 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17867 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17868 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17869 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17870 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17871 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17872 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17873 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17874 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17875 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17876 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17877 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17878 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17879 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17880 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17881 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17882 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17883 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17884 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17885 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17886 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17887 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17888 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17889 case X86ISD::VSHL: return "X86ISD::VSHL";
17890 case X86ISD::VSRL: return "X86ISD::VSRL";
17891 case X86ISD::VSRA: return "X86ISD::VSRA";
17892 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17893 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17894 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17895 case X86ISD::CMPP: return "X86ISD::CMPP";
17896 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17897 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17898 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17899 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17900 case X86ISD::ADD: return "X86ISD::ADD";
17901 case X86ISD::SUB: return "X86ISD::SUB";
17902 case X86ISD::ADC: return "X86ISD::ADC";
17903 case X86ISD::SBB: return "X86ISD::SBB";
17904 case X86ISD::SMUL: return "X86ISD::SMUL";
17905 case X86ISD::UMUL: return "X86ISD::UMUL";
17906 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17907 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17908 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17909 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17910 case X86ISD::INC: return "X86ISD::INC";
17911 case X86ISD::DEC: return "X86ISD::DEC";
17912 case X86ISD::OR: return "X86ISD::OR";
17913 case X86ISD::XOR: return "X86ISD::XOR";
17914 case X86ISD::AND: return "X86ISD::AND";
17915 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17916 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17917 case X86ISD::PTEST: return "X86ISD::PTEST";
17918 case X86ISD::TESTP: return "X86ISD::TESTP";
17919 case X86ISD::TESTM: return "X86ISD::TESTM";
17920 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17921 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17922 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17923 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17924 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17925 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17926 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17927 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17928 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17929 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17930 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17931 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17932 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17933 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17934 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17935 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17936 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17937 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17938 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17939 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17940 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17941 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17942 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17943 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17944 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
17945 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17946 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17947 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17948 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17949 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17950 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17951 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17952 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17953 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17954 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17955 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17956 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17957 case X86ISD::MFENCE: return "X86ISD::MFENCE";
17958 case X86ISD::SFENCE: return "X86ISD::SFENCE";
17959 case X86ISD::LFENCE: return "X86ISD::LFENCE";
17960 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17961 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17962 case X86ISD::SAHF: return "X86ISD::SAHF";
17963 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17964 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17965 case X86ISD::FMADD: return "X86ISD::FMADD";
17966 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17967 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17968 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17969 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17970 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17971 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
17972 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
17973 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
17974 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
17975 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
17976 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
17977 case X86ISD::RNDSCALE: return "X86ISD::RNDSCALE";
17978 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17979 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17980 case X86ISD::XTEST: return "X86ISD::XTEST";
17981 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
17982 case X86ISD::EXPAND: return "X86ISD::EXPAND";
17983 case X86ISD::SELECT: return "X86ISD::SELECT";
17984 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
17985 case X86ISD::RCP28: return "X86ISD::RCP28";
17986 case X86ISD::EXP2: return "X86ISD::EXP2";
17987 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
17988 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
17989 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
17990 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
17991 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
17992 case X86ISD::ADDS: return "X86ISD::ADDS";
17993 case X86ISD::SUBS: return "X86ISD::SUBS";
17998 // isLegalAddressingMode - Return true if the addressing mode represented
17999 // by AM is legal for this target, for a load/store of the specified type.
18000 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18002 // X86 supports extremely general addressing modes.
18003 CodeModel::Model M = getTargetMachine().getCodeModel();
18004 Reloc::Model R = getTargetMachine().getRelocationModel();
18006 // X86 allows a sign-extended 32-bit immediate field as a displacement.
18007 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18012 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18014 // If a reference to this global requires an extra load, we can't fold it.
18015 if (isGlobalStubReference(GVFlags))
18018 // If BaseGV requires a register for the PIC base, we cannot also have a
18019 // BaseReg specified.
18020 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18023 // If lower 4G is not available, then we must use rip-relative addressing.
18024 if ((M != CodeModel::Small || R != Reloc::Static) &&
18025 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18029 switch (AM.Scale) {
18035 // These scales always work.
18040 // These scales are formed with basereg+scalereg. Only accept if there is
18045 default: // Other stuff never works.
18052 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18053 unsigned Bits = Ty->getScalarSizeInBits();
18055 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18056 // particularly cheaper than those without.
18060 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18061 // variable shifts just as cheap as scalar ones.
18062 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18065 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18066 // fully general vector.
18070 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18071 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18073 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18074 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18075 return NumBits1 > NumBits2;
18078 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18079 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18082 if (!isTypeLegal(EVT::getEVT(Ty1)))
18085 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18087 // Assuming the caller doesn't have a zeroext or signext return parameter,
18088 // truncation all the way down to i1 is valid.
18092 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18093 return isInt<32>(Imm);
18096 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18097 // Can also use sub to handle negated immediates.
18098 return isInt<32>(Imm);
18101 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18102 if (!VT1.isInteger() || !VT2.isInteger())
18104 unsigned NumBits1 = VT1.getSizeInBits();
18105 unsigned NumBits2 = VT2.getSizeInBits();
18106 return NumBits1 > NumBits2;
18109 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18110 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18111 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18114 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18115 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18116 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18119 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18120 EVT VT1 = Val.getValueType();
18121 if (isZExtFree(VT1, VT2))
18124 if (Val.getOpcode() != ISD::LOAD)
18127 if (!VT1.isSimple() || !VT1.isInteger() ||
18128 !VT2.isSimple() || !VT2.isInteger())
18131 switch (VT1.getSimpleVT().SimpleTy) {
18136 // X86 has 8, 16, and 32-bit zero-extending loads.
18143 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18146 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18147 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18150 VT = VT.getScalarType();
18152 if (!VT.isSimple())
18155 switch (VT.getSimpleVT().SimpleTy) {
18166 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18167 // i16 instructions are longer (0x66 prefix) and potentially slower.
18168 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18171 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18172 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18173 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18174 /// are assumed to be legal.
18176 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18178 if (!VT.isSimple())
18181 // Not for i1 vectors
18182 if (VT.getScalarType() == MVT::i1)
18185 // Very little shuffling can be done for 64-bit vectors right now.
18186 if (VT.getSizeInBits() == 64)
18189 // We only care that the types being shuffled are legal. The lowering can
18190 // handle any possible shuffle mask that results.
18191 return isTypeLegal(VT.getSimpleVT());
18195 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18197 // Just delegate to the generic legality, clear masks aren't special.
18198 return isShuffleMaskLegal(Mask, VT);
18201 //===----------------------------------------------------------------------===//
18202 // X86 Scheduler Hooks
18203 //===----------------------------------------------------------------------===//
18205 /// Utility function to emit xbegin specifying the start of an RTM region.
18206 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18207 const TargetInstrInfo *TII) {
18208 DebugLoc DL = MI->getDebugLoc();
18210 const BasicBlock *BB = MBB->getBasicBlock();
18211 MachineFunction::iterator I = MBB;
18214 // For the v = xbegin(), we generate
18225 MachineBasicBlock *thisMBB = MBB;
18226 MachineFunction *MF = MBB->getParent();
18227 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18228 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18229 MF->insert(I, mainMBB);
18230 MF->insert(I, sinkMBB);
18232 // Transfer the remainder of BB and its successor edges to sinkMBB.
18233 sinkMBB->splice(sinkMBB->begin(), MBB,
18234 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18235 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18239 // # fallthrough to mainMBB
18240 // # abortion to sinkMBB
18241 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18242 thisMBB->addSuccessor(mainMBB);
18243 thisMBB->addSuccessor(sinkMBB);
18247 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18248 mainMBB->addSuccessor(sinkMBB);
18251 // EAX is live into the sinkMBB
18252 sinkMBB->addLiveIn(X86::EAX);
18253 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18254 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18257 MI->eraseFromParent();
18261 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18262 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18263 // in the .td file.
18264 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18265 const TargetInstrInfo *TII) {
18267 switch (MI->getOpcode()) {
18268 default: llvm_unreachable("illegal opcode!");
18269 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
18270 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18271 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
18272 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18273 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
18274 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18275 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
18276 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18279 DebugLoc dl = MI->getDebugLoc();
18280 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18282 unsigned NumArgs = MI->getNumOperands();
18283 for (unsigned i = 1; i < NumArgs; ++i) {
18284 MachineOperand &Op = MI->getOperand(i);
18285 if (!(Op.isReg() && Op.isImplicit()))
18286 MIB.addOperand(Op);
18288 if (MI->hasOneMemOperand())
18289 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18291 BuildMI(*BB, MI, dl,
18292 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18293 .addReg(X86::XMM0);
18295 MI->eraseFromParent();
18299 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18300 // defs in an instruction pattern
18301 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18302 const TargetInstrInfo *TII) {
18304 switch (MI->getOpcode()) {
18305 default: llvm_unreachable("illegal opcode!");
18306 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
18307 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18308 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
18309 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18310 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
18311 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18312 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
18313 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18316 DebugLoc dl = MI->getDebugLoc();
18317 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18319 unsigned NumArgs = MI->getNumOperands(); // remove the results
18320 for (unsigned i = 1; i < NumArgs; ++i) {
18321 MachineOperand &Op = MI->getOperand(i);
18322 if (!(Op.isReg() && Op.isImplicit()))
18323 MIB.addOperand(Op);
18325 if (MI->hasOneMemOperand())
18326 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18328 BuildMI(*BB, MI, dl,
18329 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18332 MI->eraseFromParent();
18336 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18337 const X86Subtarget *Subtarget) {
18338 DebugLoc dl = MI->getDebugLoc();
18339 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18340 // Address into RAX/EAX, other two args into ECX, EDX.
18341 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18342 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18343 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18344 for (int i = 0; i < X86::AddrNumOperands; ++i)
18345 MIB.addOperand(MI->getOperand(i));
18347 unsigned ValOps = X86::AddrNumOperands;
18348 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18349 .addReg(MI->getOperand(ValOps).getReg());
18350 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18351 .addReg(MI->getOperand(ValOps+1).getReg());
18353 // The instruction doesn't actually take any operands though.
18354 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18356 MI->eraseFromParent(); // The pseudo is gone now.
18360 MachineBasicBlock *
18361 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18362 MachineBasicBlock *MBB) const {
18363 // Emit va_arg instruction on X86-64.
18365 // Operands to this pseudo-instruction:
18366 // 0 ) Output : destination address (reg)
18367 // 1-5) Input : va_list address (addr, i64mem)
18368 // 6 ) ArgSize : Size (in bytes) of vararg type
18369 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18370 // 8 ) Align : Alignment of type
18371 // 9 ) EFLAGS (implicit-def)
18373 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18374 static_assert(X86::AddrNumOperands == 5,
18375 "VAARG_64 assumes 5 address operands");
18377 unsigned DestReg = MI->getOperand(0).getReg();
18378 MachineOperand &Base = MI->getOperand(1);
18379 MachineOperand &Scale = MI->getOperand(2);
18380 MachineOperand &Index = MI->getOperand(3);
18381 MachineOperand &Disp = MI->getOperand(4);
18382 MachineOperand &Segment = MI->getOperand(5);
18383 unsigned ArgSize = MI->getOperand(6).getImm();
18384 unsigned ArgMode = MI->getOperand(7).getImm();
18385 unsigned Align = MI->getOperand(8).getImm();
18387 // Memory Reference
18388 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18389 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18390 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18392 // Machine Information
18393 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18394 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18395 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18396 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18397 DebugLoc DL = MI->getDebugLoc();
18399 // struct va_list {
18402 // i64 overflow_area (address)
18403 // i64 reg_save_area (address)
18405 // sizeof(va_list) = 24
18406 // alignment(va_list) = 8
18408 unsigned TotalNumIntRegs = 6;
18409 unsigned TotalNumXMMRegs = 8;
18410 bool UseGPOffset = (ArgMode == 1);
18411 bool UseFPOffset = (ArgMode == 2);
18412 unsigned MaxOffset = TotalNumIntRegs * 8 +
18413 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18415 /* Align ArgSize to a multiple of 8 */
18416 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18417 bool NeedsAlign = (Align > 8);
18419 MachineBasicBlock *thisMBB = MBB;
18420 MachineBasicBlock *overflowMBB;
18421 MachineBasicBlock *offsetMBB;
18422 MachineBasicBlock *endMBB;
18424 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
18425 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
18426 unsigned OffsetReg = 0;
18428 if (!UseGPOffset && !UseFPOffset) {
18429 // If we only pull from the overflow region, we don't create a branch.
18430 // We don't need to alter control flow.
18431 OffsetDestReg = 0; // unused
18432 OverflowDestReg = DestReg;
18434 offsetMBB = nullptr;
18435 overflowMBB = thisMBB;
18438 // First emit code to check if gp_offset (or fp_offset) is below the bound.
18439 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18440 // If not, pull from overflow_area. (branch to overflowMBB)
18445 // offsetMBB overflowMBB
18450 // Registers for the PHI in endMBB
18451 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18452 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18454 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18455 MachineFunction *MF = MBB->getParent();
18456 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18457 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18458 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18460 MachineFunction::iterator MBBIter = MBB;
18463 // Insert the new basic blocks
18464 MF->insert(MBBIter, offsetMBB);
18465 MF->insert(MBBIter, overflowMBB);
18466 MF->insert(MBBIter, endMBB);
18468 // Transfer the remainder of MBB and its successor edges to endMBB.
18469 endMBB->splice(endMBB->begin(), thisMBB,
18470 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18471 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18473 // Make offsetMBB and overflowMBB successors of thisMBB
18474 thisMBB->addSuccessor(offsetMBB);
18475 thisMBB->addSuccessor(overflowMBB);
18477 // endMBB is a successor of both offsetMBB and overflowMBB
18478 offsetMBB->addSuccessor(endMBB);
18479 overflowMBB->addSuccessor(endMBB);
18481 // Load the offset value into a register
18482 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18483 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18487 .addDisp(Disp, UseFPOffset ? 4 : 0)
18488 .addOperand(Segment)
18489 .setMemRefs(MMOBegin, MMOEnd);
18491 // Check if there is enough room left to pull this argument.
18492 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18494 .addImm(MaxOffset + 8 - ArgSizeA8);
18496 // Branch to "overflowMBB" if offset >= max
18497 // Fall through to "offsetMBB" otherwise
18498 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18499 .addMBB(overflowMBB);
18502 // In offsetMBB, emit code to use the reg_save_area.
18504 assert(OffsetReg != 0);
18506 // Read the reg_save_area address.
18507 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18508 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18513 .addOperand(Segment)
18514 .setMemRefs(MMOBegin, MMOEnd);
18516 // Zero-extend the offset
18517 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18518 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18521 .addImm(X86::sub_32bit);
18523 // Add the offset to the reg_save_area to get the final address.
18524 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18525 .addReg(OffsetReg64)
18526 .addReg(RegSaveReg);
18528 // Compute the offset for the next argument
18529 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18530 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18532 .addImm(UseFPOffset ? 16 : 8);
18534 // Store it back into the va_list.
18535 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18539 .addDisp(Disp, UseFPOffset ? 4 : 0)
18540 .addOperand(Segment)
18541 .addReg(NextOffsetReg)
18542 .setMemRefs(MMOBegin, MMOEnd);
18545 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18550 // Emit code to use overflow area
18553 // Load the overflow_area address into a register.
18554 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18555 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18560 .addOperand(Segment)
18561 .setMemRefs(MMOBegin, MMOEnd);
18563 // If we need to align it, do so. Otherwise, just copy the address
18564 // to OverflowDestReg.
18566 // Align the overflow address
18567 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18568 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18570 // aligned_addr = (addr + (align-1)) & ~(align-1)
18571 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18572 .addReg(OverflowAddrReg)
18575 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18577 .addImm(~(uint64_t)(Align-1));
18579 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18580 .addReg(OverflowAddrReg);
18583 // Compute the next overflow address after this argument.
18584 // (the overflow address should be kept 8-byte aligned)
18585 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18586 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18587 .addReg(OverflowDestReg)
18588 .addImm(ArgSizeA8);
18590 // Store the new overflow address.
18591 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18596 .addOperand(Segment)
18597 .addReg(NextAddrReg)
18598 .setMemRefs(MMOBegin, MMOEnd);
18600 // If we branched, emit the PHI to the front of endMBB.
18602 BuildMI(*endMBB, endMBB->begin(), DL,
18603 TII->get(X86::PHI), DestReg)
18604 .addReg(OffsetDestReg).addMBB(offsetMBB)
18605 .addReg(OverflowDestReg).addMBB(overflowMBB);
18608 // Erase the pseudo instruction
18609 MI->eraseFromParent();
18614 MachineBasicBlock *
18615 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18617 MachineBasicBlock *MBB) const {
18618 // Emit code to save XMM registers to the stack. The ABI says that the
18619 // number of registers to save is given in %al, so it's theoretically
18620 // possible to do an indirect jump trick to avoid saving all of them,
18621 // however this code takes a simpler approach and just executes all
18622 // of the stores if %al is non-zero. It's less code, and it's probably
18623 // easier on the hardware branch predictor, and stores aren't all that
18624 // expensive anyway.
18626 // Create the new basic blocks. One block contains all the XMM stores,
18627 // and one block is the final destination regardless of whether any
18628 // stores were performed.
18629 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18630 MachineFunction *F = MBB->getParent();
18631 MachineFunction::iterator MBBIter = MBB;
18633 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18634 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18635 F->insert(MBBIter, XMMSaveMBB);
18636 F->insert(MBBIter, EndMBB);
18638 // Transfer the remainder of MBB and its successor edges to EndMBB.
18639 EndMBB->splice(EndMBB->begin(), MBB,
18640 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18641 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18643 // The original block will now fall through to the XMM save block.
18644 MBB->addSuccessor(XMMSaveMBB);
18645 // The XMMSaveMBB will fall through to the end block.
18646 XMMSaveMBB->addSuccessor(EndMBB);
18648 // Now add the instructions.
18649 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18650 DebugLoc DL = MI->getDebugLoc();
18652 unsigned CountReg = MI->getOperand(0).getReg();
18653 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18654 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18656 if (!Subtarget->isTargetWin64()) {
18657 // If %al is 0, branch around the XMM save block.
18658 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18659 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18660 MBB->addSuccessor(EndMBB);
18663 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18664 // that was just emitted, but clearly shouldn't be "saved".
18665 assert((MI->getNumOperands() <= 3 ||
18666 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18667 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18668 && "Expected last argument to be EFLAGS");
18669 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18670 // In the XMM save block, save all the XMM argument registers.
18671 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18672 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18673 MachineMemOperand *MMO =
18674 F->getMachineMemOperand(
18675 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18676 MachineMemOperand::MOStore,
18677 /*Size=*/16, /*Align=*/16);
18678 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18679 .addFrameIndex(RegSaveFrameIndex)
18680 .addImm(/*Scale=*/1)
18681 .addReg(/*IndexReg=*/0)
18682 .addImm(/*Disp=*/Offset)
18683 .addReg(/*Segment=*/0)
18684 .addReg(MI->getOperand(i).getReg())
18685 .addMemOperand(MMO);
18688 MI->eraseFromParent(); // The pseudo instruction is gone now.
18693 // The EFLAGS operand of SelectItr might be missing a kill marker
18694 // because there were multiple uses of EFLAGS, and ISel didn't know
18695 // which to mark. Figure out whether SelectItr should have had a
18696 // kill marker, and set it if it should. Returns the correct kill
18698 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18699 MachineBasicBlock* BB,
18700 const TargetRegisterInfo* TRI) {
18701 // Scan forward through BB for a use/def of EFLAGS.
18702 MachineBasicBlock::iterator miI(std::next(SelectItr));
18703 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18704 const MachineInstr& mi = *miI;
18705 if (mi.readsRegister(X86::EFLAGS))
18707 if (mi.definesRegister(X86::EFLAGS))
18708 break; // Should have kill-flag - update below.
18711 // If we hit the end of the block, check whether EFLAGS is live into a
18713 if (miI == BB->end()) {
18714 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18715 sEnd = BB->succ_end();
18716 sItr != sEnd; ++sItr) {
18717 MachineBasicBlock* succ = *sItr;
18718 if (succ->isLiveIn(X86::EFLAGS))
18723 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18724 // out. SelectMI should have a kill flag on EFLAGS.
18725 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18729 MachineBasicBlock *
18730 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18731 MachineBasicBlock *BB) const {
18732 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18733 DebugLoc DL = MI->getDebugLoc();
18735 // To "insert" a SELECT_CC instruction, we actually have to insert the
18736 // diamond control-flow pattern. The incoming instruction knows the
18737 // destination vreg to set, the condition code register to branch on, the
18738 // true/false values to select between, and a branch opcode to use.
18739 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18740 MachineFunction::iterator It = BB;
18746 // cmpTY ccX, r1, r2
18748 // fallthrough --> copy0MBB
18749 MachineBasicBlock *thisMBB = BB;
18750 MachineFunction *F = BB->getParent();
18752 // We also lower double CMOVs:
18753 // (CMOV (CMOV F, T, cc1), T, cc2)
18754 // to two successives branches. For that, we look for another CMOV as the
18755 // following instruction.
18757 // Without this, we would add a PHI between the two jumps, which ends up
18758 // creating a few copies all around. For instance, for
18760 // (sitofp (zext (fcmp une)))
18762 // we would generate:
18764 // ucomiss %xmm1, %xmm0
18765 // movss <1.0f>, %xmm0
18766 // movaps %xmm0, %xmm1
18768 // xorps %xmm1, %xmm1
18771 // movaps %xmm1, %xmm0
18775 // because this custom-inserter would have generated:
18787 // A: X = ...; Y = ...
18789 // C: Z = PHI [X, A], [Y, B]
18791 // E: PHI [X, C], [Z, D]
18793 // If we lower both CMOVs in a single step, we can instead generate:
18805 // A: X = ...; Y = ...
18807 // E: PHI [X, A], [X, C], [Y, D]
18809 // Which, in our sitofp/fcmp example, gives us something like:
18811 // ucomiss %xmm1, %xmm0
18812 // movss <1.0f>, %xmm0
18815 // xorps %xmm0, %xmm0
18819 MachineInstr *NextCMOV = nullptr;
18820 MachineBasicBlock::iterator NextMIIt =
18821 std::next(MachineBasicBlock::iterator(MI));
18822 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18823 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18824 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18825 NextCMOV = &*NextMIIt;
18827 MachineBasicBlock *jcc1MBB = nullptr;
18829 // If we have a double CMOV, we lower it to two successive branches to
18830 // the same block. EFLAGS is used by both, so mark it as live in the second.
18832 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18833 F->insert(It, jcc1MBB);
18834 jcc1MBB->addLiveIn(X86::EFLAGS);
18837 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18838 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18839 F->insert(It, copy0MBB);
18840 F->insert(It, sinkMBB);
18842 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18843 // live into the sink and copy blocks.
18844 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18846 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18847 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18848 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18849 copy0MBB->addLiveIn(X86::EFLAGS);
18850 sinkMBB->addLiveIn(X86::EFLAGS);
18853 // Transfer the remainder of BB and its successor edges to sinkMBB.
18854 sinkMBB->splice(sinkMBB->begin(), BB,
18855 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18856 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18858 // Add the true and fallthrough blocks as its successors.
18860 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18861 BB->addSuccessor(jcc1MBB);
18863 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18864 // jump to the sinkMBB.
18865 jcc1MBB->addSuccessor(copy0MBB);
18866 jcc1MBB->addSuccessor(sinkMBB);
18868 BB->addSuccessor(copy0MBB);
18871 // The true block target of the first (or only) branch is always sinkMBB.
18872 BB->addSuccessor(sinkMBB);
18874 // Create the conditional branch instruction.
18876 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18877 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18880 unsigned Opc2 = X86::GetCondBranchFromCond(
18881 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18882 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18886 // %FalseValue = ...
18887 // # fallthrough to sinkMBB
18888 copy0MBB->addSuccessor(sinkMBB);
18891 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18893 MachineInstrBuilder MIB =
18894 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18895 MI->getOperand(0).getReg())
18896 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18897 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18899 // If we have a double CMOV, the second Jcc provides the same incoming
18900 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18902 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18903 // Copy the PHI result to the register defined by the second CMOV.
18904 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18905 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18906 .addReg(MI->getOperand(0).getReg());
18907 NextCMOV->eraseFromParent();
18910 MI->eraseFromParent(); // The pseudo instruction is gone now.
18914 MachineBasicBlock *
18915 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18916 MachineBasicBlock *BB) const {
18917 MachineFunction *MF = BB->getParent();
18918 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18919 DebugLoc DL = MI->getDebugLoc();
18920 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18922 assert(MF->shouldSplitStack());
18924 const bool Is64Bit = Subtarget->is64Bit();
18925 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18927 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18928 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18931 // ... [Till the alloca]
18932 // If stacklet is not large enough, jump to mallocMBB
18935 // Allocate by subtracting from RSP
18936 // Jump to continueMBB
18939 // Allocate by call to runtime
18943 // [rest of original BB]
18946 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18947 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18948 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18950 MachineRegisterInfo &MRI = MF->getRegInfo();
18951 const TargetRegisterClass *AddrRegClass =
18952 getRegClassFor(getPointerTy());
18954 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18955 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18956 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18957 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18958 sizeVReg = MI->getOperand(1).getReg(),
18959 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18961 MachineFunction::iterator MBBIter = BB;
18964 MF->insert(MBBIter, bumpMBB);
18965 MF->insert(MBBIter, mallocMBB);
18966 MF->insert(MBBIter, continueMBB);
18968 continueMBB->splice(continueMBB->begin(), BB,
18969 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18970 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18972 // Add code to the main basic block to check if the stack limit has been hit,
18973 // and if so, jump to mallocMBB otherwise to bumpMBB.
18974 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18975 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18976 .addReg(tmpSPVReg).addReg(sizeVReg);
18977 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18978 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18979 .addReg(SPLimitVReg);
18980 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18982 // bumpMBB simply decreases the stack pointer, since we know the current
18983 // stacklet has enough space.
18984 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18985 .addReg(SPLimitVReg);
18986 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18987 .addReg(SPLimitVReg);
18988 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18990 // Calls into a routine in libgcc to allocate more space from the heap.
18991 const uint32_t *RegMask =
18992 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18994 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18996 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18997 .addExternalSymbol("__morestack_allocate_stack_space")
18998 .addRegMask(RegMask)
18999 .addReg(X86::RDI, RegState::Implicit)
19000 .addReg(X86::RAX, RegState::ImplicitDefine);
19001 } else if (Is64Bit) {
19002 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19004 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19005 .addExternalSymbol("__morestack_allocate_stack_space")
19006 .addRegMask(RegMask)
19007 .addReg(X86::EDI, RegState::Implicit)
19008 .addReg(X86::EAX, RegState::ImplicitDefine);
19010 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19012 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19013 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19014 .addExternalSymbol("__morestack_allocate_stack_space")
19015 .addRegMask(RegMask)
19016 .addReg(X86::EAX, RegState::ImplicitDefine);
19020 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19023 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19024 .addReg(IsLP64 ? X86::RAX : X86::EAX);
19025 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19027 // Set up the CFG correctly.
19028 BB->addSuccessor(bumpMBB);
19029 BB->addSuccessor(mallocMBB);
19030 mallocMBB->addSuccessor(continueMBB);
19031 bumpMBB->addSuccessor(continueMBB);
19033 // Take care of the PHI nodes.
19034 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19035 MI->getOperand(0).getReg())
19036 .addReg(mallocPtrVReg).addMBB(mallocMBB)
19037 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19039 // Delete the original pseudo instruction.
19040 MI->eraseFromParent();
19043 return continueMBB;
19046 MachineBasicBlock *
19047 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19048 MachineBasicBlock *BB) const {
19049 DebugLoc DL = MI->getDebugLoc();
19051 assert(!Subtarget->isTargetMachO());
19053 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19055 MI->eraseFromParent(); // The pseudo instruction is gone now.
19059 MachineBasicBlock *
19060 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19061 MachineBasicBlock *BB) const {
19062 // This is pretty easy. We're taking the value that we received from
19063 // our load from the relocation, sticking it in either RDI (x86-64)
19064 // or EAX and doing an indirect call. The return value will then
19065 // be in the normal return register.
19066 MachineFunction *F = BB->getParent();
19067 const X86InstrInfo *TII = Subtarget->getInstrInfo();
19068 DebugLoc DL = MI->getDebugLoc();
19070 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19071 assert(MI->getOperand(3).isGlobal() && "This should be a global");
19073 // Get a register mask for the lowered call.
19074 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19075 // proper register mask.
19076 const uint32_t *RegMask =
19077 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19078 if (Subtarget->is64Bit()) {
19079 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19080 TII->get(X86::MOV64rm), X86::RDI)
19082 .addImm(0).addReg(0)
19083 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19084 MI->getOperand(3).getTargetFlags())
19086 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19087 addDirectMem(MIB, X86::RDI);
19088 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19089 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19090 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19091 TII->get(X86::MOV32rm), X86::EAX)
19093 .addImm(0).addReg(0)
19094 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19095 MI->getOperand(3).getTargetFlags())
19097 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19098 addDirectMem(MIB, X86::EAX);
19099 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19101 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19102 TII->get(X86::MOV32rm), X86::EAX)
19103 .addReg(TII->getGlobalBaseReg(F))
19104 .addImm(0).addReg(0)
19105 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19106 MI->getOperand(3).getTargetFlags())
19108 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19109 addDirectMem(MIB, X86::EAX);
19110 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19113 MI->eraseFromParent(); // The pseudo instruction is gone now.
19117 MachineBasicBlock *
19118 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19119 MachineBasicBlock *MBB) const {
19120 DebugLoc DL = MI->getDebugLoc();
19121 MachineFunction *MF = MBB->getParent();
19122 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19123 MachineRegisterInfo &MRI = MF->getRegInfo();
19125 const BasicBlock *BB = MBB->getBasicBlock();
19126 MachineFunction::iterator I = MBB;
19129 // Memory Reference
19130 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19131 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19134 unsigned MemOpndSlot = 0;
19136 unsigned CurOp = 0;
19138 DstReg = MI->getOperand(CurOp++).getReg();
19139 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19140 assert(RC->hasType(MVT::i32) && "Invalid destination!");
19141 unsigned mainDstReg = MRI.createVirtualRegister(RC);
19142 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19144 MemOpndSlot = CurOp;
19146 MVT PVT = getPointerTy();
19147 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19148 "Invalid Pointer Size!");
19150 // For v = setjmp(buf), we generate
19153 // buf[LabelOffset] = restoreMBB
19154 // SjLjSetup restoreMBB
19160 // v = phi(main, restore)
19163 // if base pointer being used, load it from frame
19166 MachineBasicBlock *thisMBB = MBB;
19167 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19168 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19169 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19170 MF->insert(I, mainMBB);
19171 MF->insert(I, sinkMBB);
19172 MF->push_back(restoreMBB);
19174 MachineInstrBuilder MIB;
19176 // Transfer the remainder of BB and its successor edges to sinkMBB.
19177 sinkMBB->splice(sinkMBB->begin(), MBB,
19178 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19179 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19182 unsigned PtrStoreOpc = 0;
19183 unsigned LabelReg = 0;
19184 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19185 Reloc::Model RM = MF->getTarget().getRelocationModel();
19186 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19187 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19189 // Prepare IP either in reg or imm.
19190 if (!UseImmLabel) {
19191 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19192 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19193 LabelReg = MRI.createVirtualRegister(PtrRC);
19194 if (Subtarget->is64Bit()) {
19195 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19199 .addMBB(restoreMBB)
19202 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19203 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19204 .addReg(XII->getGlobalBaseReg(MF))
19207 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19211 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19213 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19214 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19215 if (i == X86::AddrDisp)
19216 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19218 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19221 MIB.addReg(LabelReg);
19223 MIB.addMBB(restoreMBB);
19224 MIB.setMemRefs(MMOBegin, MMOEnd);
19226 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19227 .addMBB(restoreMBB);
19229 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19230 MIB.addRegMask(RegInfo->getNoPreservedMask());
19231 thisMBB->addSuccessor(mainMBB);
19232 thisMBB->addSuccessor(restoreMBB);
19236 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19237 mainMBB->addSuccessor(sinkMBB);
19240 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19241 TII->get(X86::PHI), DstReg)
19242 .addReg(mainDstReg).addMBB(mainMBB)
19243 .addReg(restoreDstReg).addMBB(restoreMBB);
19246 if (RegInfo->hasBasePointer(*MF)) {
19247 const bool Uses64BitFramePtr =
19248 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19249 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19250 X86FI->setRestoreBasePointer(MF);
19251 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19252 unsigned BasePtr = RegInfo->getBaseRegister();
19253 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19254 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19255 FramePtr, true, X86FI->getRestoreBasePointerOffset())
19256 .setMIFlag(MachineInstr::FrameSetup);
19258 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19259 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19260 restoreMBB->addSuccessor(sinkMBB);
19262 MI->eraseFromParent();
19266 MachineBasicBlock *
19267 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19268 MachineBasicBlock *MBB) const {
19269 DebugLoc DL = MI->getDebugLoc();
19270 MachineFunction *MF = MBB->getParent();
19271 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19272 MachineRegisterInfo &MRI = MF->getRegInfo();
19274 // Memory Reference
19275 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19276 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19278 MVT PVT = getPointerTy();
19279 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19280 "Invalid Pointer Size!");
19282 const TargetRegisterClass *RC =
19283 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19284 unsigned Tmp = MRI.createVirtualRegister(RC);
19285 // Since FP is only updated here but NOT referenced, it's treated as GPR.
19286 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19287 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19288 unsigned SP = RegInfo->getStackRegister();
19290 MachineInstrBuilder MIB;
19292 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19293 const int64_t SPOffset = 2 * PVT.getStoreSize();
19295 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19296 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19299 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19300 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19301 MIB.addOperand(MI->getOperand(i));
19302 MIB.setMemRefs(MMOBegin, MMOEnd);
19304 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19305 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19306 if (i == X86::AddrDisp)
19307 MIB.addDisp(MI->getOperand(i), LabelOffset);
19309 MIB.addOperand(MI->getOperand(i));
19311 MIB.setMemRefs(MMOBegin, MMOEnd);
19313 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19314 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19315 if (i == X86::AddrDisp)
19316 MIB.addDisp(MI->getOperand(i), SPOffset);
19318 MIB.addOperand(MI->getOperand(i));
19320 MIB.setMemRefs(MMOBegin, MMOEnd);
19322 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19324 MI->eraseFromParent();
19328 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19329 // accumulator loops. Writing back to the accumulator allows the coalescer
19330 // to remove extra copies in the loop.
19331 MachineBasicBlock *
19332 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19333 MachineBasicBlock *MBB) const {
19334 MachineOperand &AddendOp = MI->getOperand(3);
19336 // Bail out early if the addend isn't a register - we can't switch these.
19337 if (!AddendOp.isReg())
19340 MachineFunction &MF = *MBB->getParent();
19341 MachineRegisterInfo &MRI = MF.getRegInfo();
19343 // Check whether the addend is defined by a PHI:
19344 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19345 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19346 if (!AddendDef.isPHI())
19349 // Look for the following pattern:
19351 // %addend = phi [%entry, 0], [%loop, %result]
19353 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19357 // %addend = phi [%entry, 0], [%loop, %result]
19359 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19361 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19362 assert(AddendDef.getOperand(i).isReg());
19363 MachineOperand PHISrcOp = AddendDef.getOperand(i);
19364 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19365 if (&PHISrcInst == MI) {
19366 // Found a matching instruction.
19367 unsigned NewFMAOpc = 0;
19368 switch (MI->getOpcode()) {
19369 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19370 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19371 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19372 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19373 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19374 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19375 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19376 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19377 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19378 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19379 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19380 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19381 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19382 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19383 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19384 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19385 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19386 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19387 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19388 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19390 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19391 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19392 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19393 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19394 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19395 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19396 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19397 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19398 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19399 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19400 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19401 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19402 default: llvm_unreachable("Unrecognized FMA variant.");
19405 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19406 MachineInstrBuilder MIB =
19407 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19408 .addOperand(MI->getOperand(0))
19409 .addOperand(MI->getOperand(3))
19410 .addOperand(MI->getOperand(2))
19411 .addOperand(MI->getOperand(1));
19412 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19413 MI->eraseFromParent();
19420 MachineBasicBlock *
19421 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19422 MachineBasicBlock *BB) const {
19423 switch (MI->getOpcode()) {
19424 default: llvm_unreachable("Unexpected instr type to insert");
19425 case X86::TAILJMPd64:
19426 case X86::TAILJMPr64:
19427 case X86::TAILJMPm64:
19428 case X86::TAILJMPd64_REX:
19429 case X86::TAILJMPr64_REX:
19430 case X86::TAILJMPm64_REX:
19431 llvm_unreachable("TAILJMP64 would not be touched here.");
19432 case X86::TCRETURNdi64:
19433 case X86::TCRETURNri64:
19434 case X86::TCRETURNmi64:
19436 case X86::WIN_ALLOCA:
19437 return EmitLoweredWinAlloca(MI, BB);
19438 case X86::SEG_ALLOCA_32:
19439 case X86::SEG_ALLOCA_64:
19440 return EmitLoweredSegAlloca(MI, BB);
19441 case X86::TLSCall_32:
19442 case X86::TLSCall_64:
19443 return EmitLoweredTLSCall(MI, BB);
19444 case X86::CMOV_GR8:
19445 case X86::CMOV_FR32:
19446 case X86::CMOV_FR64:
19447 case X86::CMOV_V4F32:
19448 case X86::CMOV_V2F64:
19449 case X86::CMOV_V2I64:
19450 case X86::CMOV_V8F32:
19451 case X86::CMOV_V4F64:
19452 case X86::CMOV_V4I64:
19453 case X86::CMOV_V16F32:
19454 case X86::CMOV_V8F64:
19455 case X86::CMOV_V8I64:
19456 case X86::CMOV_GR16:
19457 case X86::CMOV_GR32:
19458 case X86::CMOV_RFP32:
19459 case X86::CMOV_RFP64:
19460 case X86::CMOV_RFP80:
19461 return EmitLoweredSelect(MI, BB);
19463 case X86::FP32_TO_INT16_IN_MEM:
19464 case X86::FP32_TO_INT32_IN_MEM:
19465 case X86::FP32_TO_INT64_IN_MEM:
19466 case X86::FP64_TO_INT16_IN_MEM:
19467 case X86::FP64_TO_INT32_IN_MEM:
19468 case X86::FP64_TO_INT64_IN_MEM:
19469 case X86::FP80_TO_INT16_IN_MEM:
19470 case X86::FP80_TO_INT32_IN_MEM:
19471 case X86::FP80_TO_INT64_IN_MEM: {
19472 MachineFunction *F = BB->getParent();
19473 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19474 DebugLoc DL = MI->getDebugLoc();
19476 // Change the floating point control register to use "round towards zero"
19477 // mode when truncating to an integer value.
19478 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19479 addFrameReference(BuildMI(*BB, MI, DL,
19480 TII->get(X86::FNSTCW16m)), CWFrameIdx);
19482 // Load the old value of the high byte of the control word...
19484 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19485 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19488 // Set the high part to be round to zero...
19489 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19492 // Reload the modified control word now...
19493 addFrameReference(BuildMI(*BB, MI, DL,
19494 TII->get(X86::FLDCW16m)), CWFrameIdx);
19496 // Restore the memory image of control word to original value
19497 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19500 // Get the X86 opcode to use.
19502 switch (MI->getOpcode()) {
19503 default: llvm_unreachable("illegal opcode!");
19504 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19505 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19506 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19507 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19508 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19509 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19510 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19511 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19512 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19516 MachineOperand &Op = MI->getOperand(0);
19518 AM.BaseType = X86AddressMode::RegBase;
19519 AM.Base.Reg = Op.getReg();
19521 AM.BaseType = X86AddressMode::FrameIndexBase;
19522 AM.Base.FrameIndex = Op.getIndex();
19524 Op = MI->getOperand(1);
19526 AM.Scale = Op.getImm();
19527 Op = MI->getOperand(2);
19529 AM.IndexReg = Op.getImm();
19530 Op = MI->getOperand(3);
19531 if (Op.isGlobal()) {
19532 AM.GV = Op.getGlobal();
19534 AM.Disp = Op.getImm();
19536 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19537 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19539 // Reload the original control word now.
19540 addFrameReference(BuildMI(*BB, MI, DL,
19541 TII->get(X86::FLDCW16m)), CWFrameIdx);
19543 MI->eraseFromParent(); // The pseudo instruction is gone now.
19546 // String/text processing lowering.
19547 case X86::PCMPISTRM128REG:
19548 case X86::VPCMPISTRM128REG:
19549 case X86::PCMPISTRM128MEM:
19550 case X86::VPCMPISTRM128MEM:
19551 case X86::PCMPESTRM128REG:
19552 case X86::VPCMPESTRM128REG:
19553 case X86::PCMPESTRM128MEM:
19554 case X86::VPCMPESTRM128MEM:
19555 assert(Subtarget->hasSSE42() &&
19556 "Target must have SSE4.2 or AVX features enabled");
19557 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19559 // String/text processing lowering.
19560 case X86::PCMPISTRIREG:
19561 case X86::VPCMPISTRIREG:
19562 case X86::PCMPISTRIMEM:
19563 case X86::VPCMPISTRIMEM:
19564 case X86::PCMPESTRIREG:
19565 case X86::VPCMPESTRIREG:
19566 case X86::PCMPESTRIMEM:
19567 case X86::VPCMPESTRIMEM:
19568 assert(Subtarget->hasSSE42() &&
19569 "Target must have SSE4.2 or AVX features enabled");
19570 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19572 // Thread synchronization.
19574 return EmitMonitor(MI, BB, Subtarget);
19578 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19580 case X86::VASTART_SAVE_XMM_REGS:
19581 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19583 case X86::VAARG_64:
19584 return EmitVAARG64WithCustomInserter(MI, BB);
19586 case X86::EH_SjLj_SetJmp32:
19587 case X86::EH_SjLj_SetJmp64:
19588 return emitEHSjLjSetJmp(MI, BB);
19590 case X86::EH_SjLj_LongJmp32:
19591 case X86::EH_SjLj_LongJmp64:
19592 return emitEHSjLjLongJmp(MI, BB);
19594 case TargetOpcode::STATEPOINT:
19595 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19596 // this point in the process. We diverge later.
19597 return emitPatchPoint(MI, BB);
19599 case TargetOpcode::STACKMAP:
19600 case TargetOpcode::PATCHPOINT:
19601 return emitPatchPoint(MI, BB);
19603 case X86::VFMADDPDr213r:
19604 case X86::VFMADDPSr213r:
19605 case X86::VFMADDSDr213r:
19606 case X86::VFMADDSSr213r:
19607 case X86::VFMSUBPDr213r:
19608 case X86::VFMSUBPSr213r:
19609 case X86::VFMSUBSDr213r:
19610 case X86::VFMSUBSSr213r:
19611 case X86::VFNMADDPDr213r:
19612 case X86::VFNMADDPSr213r:
19613 case X86::VFNMADDSDr213r:
19614 case X86::VFNMADDSSr213r:
19615 case X86::VFNMSUBPDr213r:
19616 case X86::VFNMSUBPSr213r:
19617 case X86::VFNMSUBSDr213r:
19618 case X86::VFNMSUBSSr213r:
19619 case X86::VFMADDSUBPDr213r:
19620 case X86::VFMADDSUBPSr213r:
19621 case X86::VFMSUBADDPDr213r:
19622 case X86::VFMSUBADDPSr213r:
19623 case X86::VFMADDPDr213rY:
19624 case X86::VFMADDPSr213rY:
19625 case X86::VFMSUBPDr213rY:
19626 case X86::VFMSUBPSr213rY:
19627 case X86::VFNMADDPDr213rY:
19628 case X86::VFNMADDPSr213rY:
19629 case X86::VFNMSUBPDr213rY:
19630 case X86::VFNMSUBPSr213rY:
19631 case X86::VFMADDSUBPDr213rY:
19632 case X86::VFMADDSUBPSr213rY:
19633 case X86::VFMSUBADDPDr213rY:
19634 case X86::VFMSUBADDPSr213rY:
19635 return emitFMA3Instr(MI, BB);
19639 //===----------------------------------------------------------------------===//
19640 // X86 Optimization Hooks
19641 //===----------------------------------------------------------------------===//
19643 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19646 const SelectionDAG &DAG,
19647 unsigned Depth) const {
19648 unsigned BitWidth = KnownZero.getBitWidth();
19649 unsigned Opc = Op.getOpcode();
19650 assert((Opc >= ISD::BUILTIN_OP_END ||
19651 Opc == ISD::INTRINSIC_WO_CHAIN ||
19652 Opc == ISD::INTRINSIC_W_CHAIN ||
19653 Opc == ISD::INTRINSIC_VOID) &&
19654 "Should use MaskedValueIsZero if you don't know whether Op"
19655 " is a target node!");
19657 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19671 // These nodes' second result is a boolean.
19672 if (Op.getResNo() == 0)
19675 case X86ISD::SETCC:
19676 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19678 case ISD::INTRINSIC_WO_CHAIN: {
19679 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19680 unsigned NumLoBits = 0;
19683 case Intrinsic::x86_sse_movmsk_ps:
19684 case Intrinsic::x86_avx_movmsk_ps_256:
19685 case Intrinsic::x86_sse2_movmsk_pd:
19686 case Intrinsic::x86_avx_movmsk_pd_256:
19687 case Intrinsic::x86_mmx_pmovmskb:
19688 case Intrinsic::x86_sse2_pmovmskb_128:
19689 case Intrinsic::x86_avx2_pmovmskb: {
19690 // High bits of movmskp{s|d}, pmovmskb are known zero.
19692 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19693 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19694 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19695 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19696 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19697 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19698 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19699 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19701 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19710 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19712 const SelectionDAG &,
19713 unsigned Depth) const {
19714 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19715 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19716 return Op.getValueType().getScalarType().getSizeInBits();
19722 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19723 /// node is a GlobalAddress + offset.
19724 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19725 const GlobalValue* &GA,
19726 int64_t &Offset) const {
19727 if (N->getOpcode() == X86ISD::Wrapper) {
19728 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19729 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19730 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19734 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19737 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19738 /// same as extracting the high 128-bit part of 256-bit vector and then
19739 /// inserting the result into the low part of a new 256-bit vector
19740 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19741 EVT VT = SVOp->getValueType(0);
19742 unsigned NumElems = VT.getVectorNumElements();
19744 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19745 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19746 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19747 SVOp->getMaskElt(j) >= 0)
19753 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19754 /// same as extracting the low 128-bit part of 256-bit vector and then
19755 /// inserting the result into the high part of a new 256-bit vector
19756 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19757 EVT VT = SVOp->getValueType(0);
19758 unsigned NumElems = VT.getVectorNumElements();
19760 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19761 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19762 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19763 SVOp->getMaskElt(j) >= 0)
19769 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19770 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19771 TargetLowering::DAGCombinerInfo &DCI,
19772 const X86Subtarget* Subtarget) {
19774 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19775 SDValue V1 = SVOp->getOperand(0);
19776 SDValue V2 = SVOp->getOperand(1);
19777 EVT VT = SVOp->getValueType(0);
19778 unsigned NumElems = VT.getVectorNumElements();
19780 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19781 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19785 // V UNDEF BUILD_VECTOR UNDEF
19787 // CONCAT_VECTOR CONCAT_VECTOR
19790 // RESULT: V + zero extended
19792 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19793 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19794 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19797 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19800 // To match the shuffle mask, the first half of the mask should
19801 // be exactly the first vector, and all the rest a splat with the
19802 // first element of the second one.
19803 for (unsigned i = 0; i != NumElems/2; ++i)
19804 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19805 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19808 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19809 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19810 if (Ld->hasNUsesOfValue(1, 0)) {
19811 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19812 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19814 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19816 Ld->getPointerInfo(),
19817 Ld->getAlignment(),
19818 false/*isVolatile*/, true/*ReadMem*/,
19819 false/*WriteMem*/);
19821 // Make sure the newly-created LOAD is in the same position as Ld in
19822 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19823 // and update uses of Ld's output chain to use the TokenFactor.
19824 if (Ld->hasAnyUseOfValue(1)) {
19825 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19826 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19827 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19828 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19829 SDValue(ResNode.getNode(), 1));
19832 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19836 // Emit a zeroed vector and insert the desired subvector on its
19838 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19839 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19840 return DCI.CombineTo(N, InsV);
19843 //===--------------------------------------------------------------------===//
19844 // Combine some shuffles into subvector extracts and inserts:
19847 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19848 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19849 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19850 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19851 return DCI.CombineTo(N, InsV);
19854 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19855 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19856 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19857 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19858 return DCI.CombineTo(N, InsV);
19864 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19867 /// This is the leaf of the recursive combinine below. When we have found some
19868 /// chain of single-use x86 shuffle instructions and accumulated the combined
19869 /// shuffle mask represented by them, this will try to pattern match that mask
19870 /// into either a single instruction if there is a special purpose instruction
19871 /// for this operation, or into a PSHUFB instruction which is a fully general
19872 /// instruction but should only be used to replace chains over a certain depth.
19873 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19874 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19875 TargetLowering::DAGCombinerInfo &DCI,
19876 const X86Subtarget *Subtarget) {
19877 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19879 // Find the operand that enters the chain. Note that multiple uses are OK
19880 // here, we're not going to remove the operand we find.
19881 SDValue Input = Op.getOperand(0);
19882 while (Input.getOpcode() == ISD::BITCAST)
19883 Input = Input.getOperand(0);
19885 MVT VT = Input.getSimpleValueType();
19886 MVT RootVT = Root.getSimpleValueType();
19889 // Just remove no-op shuffle masks.
19890 if (Mask.size() == 1) {
19891 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19896 // Use the float domain if the operand type is a floating point type.
19897 bool FloatDomain = VT.isFloatingPoint();
19899 // For floating point shuffles, we don't have free copies in the shuffle
19900 // instructions or the ability to load as part of the instruction, so
19901 // canonicalize their shuffles to UNPCK or MOV variants.
19903 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19904 // vectors because it can have a load folded into it that UNPCK cannot. This
19905 // doesn't preclude something switching to the shorter encoding post-RA.
19907 // FIXME: Should teach these routines about AVX vector widths.
19908 if (FloatDomain && VT.getSizeInBits() == 128) {
19909 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19910 bool Lo = Mask.equals({0, 0});
19913 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19914 // is no slower than UNPCKLPD but has the option to fold the input operand
19915 // into even an unaligned memory load.
19916 if (Lo && Subtarget->hasSSE3()) {
19917 Shuffle = X86ISD::MOVDDUP;
19918 ShuffleVT = MVT::v2f64;
19920 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19921 // than the UNPCK variants.
19922 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19923 ShuffleVT = MVT::v4f32;
19925 if (Depth == 1 && Root->getOpcode() == Shuffle)
19926 return false; // Nothing to do!
19927 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19928 DCI.AddToWorklist(Op.getNode());
19929 if (Shuffle == X86ISD::MOVDDUP)
19930 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19932 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19933 DCI.AddToWorklist(Op.getNode());
19934 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19938 if (Subtarget->hasSSE3() &&
19939 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19940 bool Lo = Mask.equals({0, 0, 2, 2});
19941 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19942 MVT ShuffleVT = MVT::v4f32;
19943 if (Depth == 1 && Root->getOpcode() == Shuffle)
19944 return false; // Nothing to do!
19945 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19946 DCI.AddToWorklist(Op.getNode());
19947 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19948 DCI.AddToWorklist(Op.getNode());
19949 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19953 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19954 bool Lo = Mask.equals({0, 0, 1, 1});
19955 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19956 MVT ShuffleVT = MVT::v4f32;
19957 if (Depth == 1 && Root->getOpcode() == Shuffle)
19958 return false; // Nothing to do!
19959 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19960 DCI.AddToWorklist(Op.getNode());
19961 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19962 DCI.AddToWorklist(Op.getNode());
19963 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19969 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19970 // variants as none of these have single-instruction variants that are
19971 // superior to the UNPCK formulation.
19972 if (!FloatDomain && VT.getSizeInBits() == 128 &&
19973 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19974 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19975 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19977 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19978 bool Lo = Mask[0] == 0;
19979 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19980 if (Depth == 1 && Root->getOpcode() == Shuffle)
19981 return false; // Nothing to do!
19983 switch (Mask.size()) {
19985 ShuffleVT = MVT::v8i16;
19988 ShuffleVT = MVT::v16i8;
19991 llvm_unreachable("Impossible mask size!");
19993 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19994 DCI.AddToWorklist(Op.getNode());
19995 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19996 DCI.AddToWorklist(Op.getNode());
19997 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20002 // Don't try to re-form single instruction chains under any circumstances now
20003 // that we've done encoding canonicalization for them.
20007 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20008 // can replace them with a single PSHUFB instruction profitably. Intel's
20009 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20010 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20011 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20012 SmallVector<SDValue, 16> PSHUFBMask;
20013 int NumBytes = VT.getSizeInBits() / 8;
20014 int Ratio = NumBytes / Mask.size();
20015 for (int i = 0; i < NumBytes; ++i) {
20016 if (Mask[i / Ratio] == SM_SentinelUndef) {
20017 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20020 int M = Mask[i / Ratio] != SM_SentinelZero
20021 ? Ratio * Mask[i / Ratio] + i % Ratio
20023 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20025 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20026 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20027 DCI.AddToWorklist(Op.getNode());
20028 SDValue PSHUFBMaskOp =
20029 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20030 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20031 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20032 DCI.AddToWorklist(Op.getNode());
20033 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20038 // Failed to find any combines.
20042 /// \brief Fully generic combining of x86 shuffle instructions.
20044 /// This should be the last combine run over the x86 shuffle instructions. Once
20045 /// they have been fully optimized, this will recursively consider all chains
20046 /// of single-use shuffle instructions, build a generic model of the cumulative
20047 /// shuffle operation, and check for simpler instructions which implement this
20048 /// operation. We use this primarily for two purposes:
20050 /// 1) Collapse generic shuffles to specialized single instructions when
20051 /// equivalent. In most cases, this is just an encoding size win, but
20052 /// sometimes we will collapse multiple generic shuffles into a single
20053 /// special-purpose shuffle.
20054 /// 2) Look for sequences of shuffle instructions with 3 or more total
20055 /// instructions, and replace them with the slightly more expensive SSSE3
20056 /// PSHUFB instruction if available. We do this as the last combining step
20057 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
20058 /// a suitable short sequence of other instructions. The PHUFB will either
20059 /// use a register or have to read from memory and so is slightly (but only
20060 /// slightly) more expensive than the other shuffle instructions.
20062 /// Because this is inherently a quadratic operation (for each shuffle in
20063 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20064 /// This should never be an issue in practice as the shuffle lowering doesn't
20065 /// produce sequences of more than 8 instructions.
20067 /// FIXME: We will currently miss some cases where the redundant shuffling
20068 /// would simplify under the threshold for PSHUFB formation because of
20069 /// combine-ordering. To fix this, we should do the redundant instruction
20070 /// combining in this recursive walk.
20071 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20072 ArrayRef<int> RootMask,
20073 int Depth, bool HasPSHUFB,
20075 TargetLowering::DAGCombinerInfo &DCI,
20076 const X86Subtarget *Subtarget) {
20077 // Bound the depth of our recursive combine because this is ultimately
20078 // quadratic in nature.
20082 // Directly rip through bitcasts to find the underlying operand.
20083 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20084 Op = Op.getOperand(0);
20086 MVT VT = Op.getSimpleValueType();
20087 if (!VT.isVector())
20088 return false; // Bail if we hit a non-vector.
20090 assert(Root.getSimpleValueType().isVector() &&
20091 "Shuffles operate on vector types!");
20092 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20093 "Can only combine shuffles of the same vector register size.");
20095 if (!isTargetShuffle(Op.getOpcode()))
20097 SmallVector<int, 16> OpMask;
20099 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20100 // We only can combine unary shuffles which we can decode the mask for.
20101 if (!HaveMask || !IsUnary)
20104 assert(VT.getVectorNumElements() == OpMask.size() &&
20105 "Different mask size from vector size!");
20106 assert(((RootMask.size() > OpMask.size() &&
20107 RootMask.size() % OpMask.size() == 0) ||
20108 (OpMask.size() > RootMask.size() &&
20109 OpMask.size() % RootMask.size() == 0) ||
20110 OpMask.size() == RootMask.size()) &&
20111 "The smaller number of elements must divide the larger.");
20112 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20113 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20114 assert(((RootRatio == 1 && OpRatio == 1) ||
20115 (RootRatio == 1) != (OpRatio == 1)) &&
20116 "Must not have a ratio for both incoming and op masks!");
20118 SmallVector<int, 16> Mask;
20119 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20121 // Merge this shuffle operation's mask into our accumulated mask. Note that
20122 // this shuffle's mask will be the first applied to the input, followed by the
20123 // root mask to get us all the way to the root value arrangement. The reason
20124 // for this order is that we are recursing up the operation chain.
20125 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20126 int RootIdx = i / RootRatio;
20127 if (RootMask[RootIdx] < 0) {
20128 // This is a zero or undef lane, we're done.
20129 Mask.push_back(RootMask[RootIdx]);
20133 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20134 int OpIdx = RootMaskedIdx / OpRatio;
20135 if (OpMask[OpIdx] < 0) {
20136 // The incoming lanes are zero or undef, it doesn't matter which ones we
20138 Mask.push_back(OpMask[OpIdx]);
20142 // Ok, we have non-zero lanes, map them through.
20143 Mask.push_back(OpMask[OpIdx] * OpRatio +
20144 RootMaskedIdx % OpRatio);
20147 // See if we can recurse into the operand to combine more things.
20148 switch (Op.getOpcode()) {
20149 case X86ISD::PSHUFB:
20151 case X86ISD::PSHUFD:
20152 case X86ISD::PSHUFHW:
20153 case X86ISD::PSHUFLW:
20154 if (Op.getOperand(0).hasOneUse() &&
20155 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20156 HasPSHUFB, DAG, DCI, Subtarget))
20160 case X86ISD::UNPCKL:
20161 case X86ISD::UNPCKH:
20162 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20163 // We can't check for single use, we have to check that this shuffle is the only user.
20164 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20165 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20166 HasPSHUFB, DAG, DCI, Subtarget))
20171 // Minor canonicalization of the accumulated shuffle mask to make it easier
20172 // to match below. All this does is detect masks with squential pairs of
20173 // elements, and shrink them to the half-width mask. It does this in a loop
20174 // so it will reduce the size of the mask to the minimal width mask which
20175 // performs an equivalent shuffle.
20176 SmallVector<int, 16> WidenedMask;
20177 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20178 Mask = std::move(WidenedMask);
20179 WidenedMask.clear();
20182 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20186 /// \brief Get the PSHUF-style mask from PSHUF node.
20188 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20189 /// PSHUF-style masks that can be reused with such instructions.
20190 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20191 MVT VT = N.getSimpleValueType();
20192 SmallVector<int, 4> Mask;
20194 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20198 // If we have more than 128-bits, only the low 128-bits of shuffle mask
20199 // matter. Check that the upper masks are repeats and remove them.
20200 if (VT.getSizeInBits() > 128) {
20201 int LaneElts = 128 / VT.getScalarSizeInBits();
20203 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20204 for (int j = 0; j < LaneElts; ++j)
20205 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20206 "Mask doesn't repeat in high 128-bit lanes!");
20208 Mask.resize(LaneElts);
20211 switch (N.getOpcode()) {
20212 case X86ISD::PSHUFD:
20214 case X86ISD::PSHUFLW:
20217 case X86ISD::PSHUFHW:
20218 Mask.erase(Mask.begin(), Mask.begin() + 4);
20219 for (int &M : Mask)
20223 llvm_unreachable("No valid shuffle instruction found!");
20227 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20229 /// We walk up the chain and look for a combinable shuffle, skipping over
20230 /// shuffles that we could hoist this shuffle's transformation past without
20231 /// altering anything.
20233 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20235 TargetLowering::DAGCombinerInfo &DCI) {
20236 assert(N.getOpcode() == X86ISD::PSHUFD &&
20237 "Called with something other than an x86 128-bit half shuffle!");
20240 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20241 // of the shuffles in the chain so that we can form a fresh chain to replace
20243 SmallVector<SDValue, 8> Chain;
20244 SDValue V = N.getOperand(0);
20245 for (; V.hasOneUse(); V = V.getOperand(0)) {
20246 switch (V.getOpcode()) {
20248 return SDValue(); // Nothing combined!
20251 // Skip bitcasts as we always know the type for the target specific
20255 case X86ISD::PSHUFD:
20256 // Found another dword shuffle.
20259 case X86ISD::PSHUFLW:
20260 // Check that the low words (being shuffled) are the identity in the
20261 // dword shuffle, and the high words are self-contained.
20262 if (Mask[0] != 0 || Mask[1] != 1 ||
20263 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20266 Chain.push_back(V);
20269 case X86ISD::PSHUFHW:
20270 // Check that the high words (being shuffled) are the identity in the
20271 // dword shuffle, and the low words are self-contained.
20272 if (Mask[2] != 2 || Mask[3] != 3 ||
20273 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20276 Chain.push_back(V);
20279 case X86ISD::UNPCKL:
20280 case X86ISD::UNPCKH:
20281 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20282 // shuffle into a preceding word shuffle.
20283 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20284 V.getSimpleValueType().getScalarType() != MVT::i16)
20287 // Search for a half-shuffle which we can combine with.
20288 unsigned CombineOp =
20289 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20290 if (V.getOperand(0) != V.getOperand(1) ||
20291 !V->isOnlyUserOf(V.getOperand(0).getNode()))
20293 Chain.push_back(V);
20294 V = V.getOperand(0);
20296 switch (V.getOpcode()) {
20298 return SDValue(); // Nothing to combine.
20300 case X86ISD::PSHUFLW:
20301 case X86ISD::PSHUFHW:
20302 if (V.getOpcode() == CombineOp)
20305 Chain.push_back(V);
20309 V = V.getOperand(0);
20313 } while (V.hasOneUse());
20316 // Break out of the loop if we break out of the switch.
20320 if (!V.hasOneUse())
20321 // We fell out of the loop without finding a viable combining instruction.
20324 // Merge this node's mask and our incoming mask.
20325 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20326 for (int &M : Mask)
20328 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20329 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20331 // Rebuild the chain around this new shuffle.
20332 while (!Chain.empty()) {
20333 SDValue W = Chain.pop_back_val();
20335 if (V.getValueType() != W.getOperand(0).getValueType())
20336 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20338 switch (W.getOpcode()) {
20340 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20342 case X86ISD::UNPCKL:
20343 case X86ISD::UNPCKH:
20344 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20347 case X86ISD::PSHUFD:
20348 case X86ISD::PSHUFLW:
20349 case X86ISD::PSHUFHW:
20350 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20354 if (V.getValueType() != N.getValueType())
20355 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20357 // Return the new chain to replace N.
20361 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20363 /// We walk up the chain, skipping shuffles of the other half and looking
20364 /// through shuffles which switch halves trying to find a shuffle of the same
20365 /// pair of dwords.
20366 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20368 TargetLowering::DAGCombinerInfo &DCI) {
20370 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20371 "Called with something other than an x86 128-bit half shuffle!");
20373 unsigned CombineOpcode = N.getOpcode();
20375 // Walk up a single-use chain looking for a combinable shuffle.
20376 SDValue V = N.getOperand(0);
20377 for (; V.hasOneUse(); V = V.getOperand(0)) {
20378 switch (V.getOpcode()) {
20380 return false; // Nothing combined!
20383 // Skip bitcasts as we always know the type for the target specific
20387 case X86ISD::PSHUFLW:
20388 case X86ISD::PSHUFHW:
20389 if (V.getOpcode() == CombineOpcode)
20392 // Other-half shuffles are no-ops.
20395 // Break out of the loop if we break out of the switch.
20399 if (!V.hasOneUse())
20400 // We fell out of the loop without finding a viable combining instruction.
20403 // Combine away the bottom node as its shuffle will be accumulated into
20404 // a preceding shuffle.
20405 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20407 // Record the old value.
20410 // Merge this node's mask and our incoming mask (adjusted to account for all
20411 // the pshufd instructions encountered).
20412 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20413 for (int &M : Mask)
20415 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20416 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20418 // Check that the shuffles didn't cancel each other out. If not, we need to
20419 // combine to the new one.
20421 // Replace the combinable shuffle with the combined one, updating all users
20422 // so that we re-evaluate the chain here.
20423 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20428 /// \brief Try to combine x86 target specific shuffles.
20429 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20430 TargetLowering::DAGCombinerInfo &DCI,
20431 const X86Subtarget *Subtarget) {
20433 MVT VT = N.getSimpleValueType();
20434 SmallVector<int, 4> Mask;
20436 switch (N.getOpcode()) {
20437 case X86ISD::PSHUFD:
20438 case X86ISD::PSHUFLW:
20439 case X86ISD::PSHUFHW:
20440 Mask = getPSHUFShuffleMask(N);
20441 assert(Mask.size() == 4);
20447 // Nuke no-op shuffles that show up after combining.
20448 if (isNoopShuffleMask(Mask))
20449 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20451 // Look for simplifications involving one or two shuffle instructions.
20452 SDValue V = N.getOperand(0);
20453 switch (N.getOpcode()) {
20456 case X86ISD::PSHUFLW:
20457 case X86ISD::PSHUFHW:
20458 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20460 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20461 return SDValue(); // We combined away this shuffle, so we're done.
20463 // See if this reduces to a PSHUFD which is no more expensive and can
20464 // combine with more operations. Note that it has to at least flip the
20465 // dwords as otherwise it would have been removed as a no-op.
20466 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20467 int DMask[] = {0, 1, 2, 3};
20468 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20469 DMask[DOffset + 0] = DOffset + 1;
20470 DMask[DOffset + 1] = DOffset + 0;
20471 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20472 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20473 DCI.AddToWorklist(V.getNode());
20474 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20475 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20476 DCI.AddToWorklist(V.getNode());
20477 return DAG.getNode(ISD::BITCAST, DL, VT, V);
20480 // Look for shuffle patterns which can be implemented as a single unpack.
20481 // FIXME: This doesn't handle the location of the PSHUFD generically, and
20482 // only works when we have a PSHUFD followed by two half-shuffles.
20483 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20484 (V.getOpcode() == X86ISD::PSHUFLW ||
20485 V.getOpcode() == X86ISD::PSHUFHW) &&
20486 V.getOpcode() != N.getOpcode() &&
20488 SDValue D = V.getOperand(0);
20489 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20490 D = D.getOperand(0);
20491 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20492 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20493 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20494 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20495 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20497 for (int i = 0; i < 4; ++i) {
20498 WordMask[i + NOffset] = Mask[i] + NOffset;
20499 WordMask[i + VOffset] = VMask[i] + VOffset;
20501 // Map the word mask through the DWord mask.
20503 for (int i = 0; i < 8; ++i)
20504 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20505 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20506 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20507 // We can replace all three shuffles with an unpack.
20508 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20509 DCI.AddToWorklist(V.getNode());
20510 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20519 case X86ISD::PSHUFD:
20520 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20529 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20531 /// We combine this directly on the abstract vector shuffle nodes so it is
20532 /// easier to generically match. We also insert dummy vector shuffle nodes for
20533 /// the operands which explicitly discard the lanes which are unused by this
20534 /// operation to try to flow through the rest of the combiner the fact that
20535 /// they're unused.
20536 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20538 EVT VT = N->getValueType(0);
20540 // We only handle target-independent shuffles.
20541 // FIXME: It would be easy and harmless to use the target shuffle mask
20542 // extraction tool to support more.
20543 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20546 auto *SVN = cast<ShuffleVectorSDNode>(N);
20547 ArrayRef<int> Mask = SVN->getMask();
20548 SDValue V1 = N->getOperand(0);
20549 SDValue V2 = N->getOperand(1);
20551 // We require the first shuffle operand to be the SUB node, and the second to
20552 // be the ADD node.
20553 // FIXME: We should support the commuted patterns.
20554 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20557 // If there are other uses of these operations we can't fold them.
20558 if (!V1->hasOneUse() || !V2->hasOneUse())
20561 // Ensure that both operations have the same operands. Note that we can
20562 // commute the FADD operands.
20563 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20564 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20565 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20568 // We're looking for blends between FADD and FSUB nodes. We insist on these
20569 // nodes being lined up in a specific expected pattern.
20570 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20571 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20572 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20575 // Only specific types are legal at this point, assert so we notice if and
20576 // when these change.
20577 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20578 VT == MVT::v4f64) &&
20579 "Unknown vector type encountered!");
20581 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20584 /// PerformShuffleCombine - Performs several different shuffle combines.
20585 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20586 TargetLowering::DAGCombinerInfo &DCI,
20587 const X86Subtarget *Subtarget) {
20589 SDValue N0 = N->getOperand(0);
20590 SDValue N1 = N->getOperand(1);
20591 EVT VT = N->getValueType(0);
20593 // Don't create instructions with illegal types after legalize types has run.
20594 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20595 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20598 // If we have legalized the vector types, look for blends of FADD and FSUB
20599 // nodes that we can fuse into an ADDSUB node.
20600 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20601 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20604 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20605 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20606 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20607 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20609 // During Type Legalization, when promoting illegal vector types,
20610 // the backend might introduce new shuffle dag nodes and bitcasts.
20612 // This code performs the following transformation:
20613 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20614 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20616 // We do this only if both the bitcast and the BINOP dag nodes have
20617 // one use. Also, perform this transformation only if the new binary
20618 // operation is legal. This is to avoid introducing dag nodes that
20619 // potentially need to be further expanded (or custom lowered) into a
20620 // less optimal sequence of dag nodes.
20621 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20622 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20623 N0.getOpcode() == ISD::BITCAST) {
20624 SDValue BC0 = N0.getOperand(0);
20625 EVT SVT = BC0.getValueType();
20626 unsigned Opcode = BC0.getOpcode();
20627 unsigned NumElts = VT.getVectorNumElements();
20629 if (BC0.hasOneUse() && SVT.isVector() &&
20630 SVT.getVectorNumElements() * 2 == NumElts &&
20631 TLI.isOperationLegal(Opcode, VT)) {
20632 bool CanFold = false;
20644 unsigned SVTNumElts = SVT.getVectorNumElements();
20645 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20646 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20647 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20648 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20649 CanFold = SVOp->getMaskElt(i) < 0;
20652 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20653 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20654 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20655 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20660 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20661 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20662 // consecutive, non-overlapping, and in the right order.
20663 SmallVector<SDValue, 16> Elts;
20664 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20665 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20667 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20671 if (isTargetShuffle(N->getOpcode())) {
20673 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20674 if (Shuffle.getNode())
20677 // Try recursively combining arbitrary sequences of x86 shuffle
20678 // instructions into higher-order shuffles. We do this after combining
20679 // specific PSHUF instruction sequences into their minimal form so that we
20680 // can evaluate how many specialized shuffle instructions are involved in
20681 // a particular chain.
20682 SmallVector<int, 1> NonceMask; // Just a placeholder.
20683 NonceMask.push_back(0);
20684 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20685 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20687 return SDValue(); // This routine will use CombineTo to replace N.
20693 /// PerformTruncateCombine - Converts truncate operation to
20694 /// a sequence of vector shuffle operations.
20695 /// It is possible when we truncate 256-bit vector to 128-bit vector
20696 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20697 TargetLowering::DAGCombinerInfo &DCI,
20698 const X86Subtarget *Subtarget) {
20702 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20703 /// specific shuffle of a load can be folded into a single element load.
20704 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20705 /// shuffles have been custom lowered so we need to handle those here.
20706 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20707 TargetLowering::DAGCombinerInfo &DCI) {
20708 if (DCI.isBeforeLegalizeOps())
20711 SDValue InVec = N->getOperand(0);
20712 SDValue EltNo = N->getOperand(1);
20714 if (!isa<ConstantSDNode>(EltNo))
20717 EVT OriginalVT = InVec.getValueType();
20719 if (InVec.getOpcode() == ISD::BITCAST) {
20720 // Don't duplicate a load with other uses.
20721 if (!InVec.hasOneUse())
20723 EVT BCVT = InVec.getOperand(0).getValueType();
20724 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20726 InVec = InVec.getOperand(0);
20729 EVT CurrentVT = InVec.getValueType();
20731 if (!isTargetShuffle(InVec.getOpcode()))
20734 // Don't duplicate a load with other uses.
20735 if (!InVec.hasOneUse())
20738 SmallVector<int, 16> ShuffleMask;
20740 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20741 ShuffleMask, UnaryShuffle))
20744 // Select the input vector, guarding against out of range extract vector.
20745 unsigned NumElems = CurrentVT.getVectorNumElements();
20746 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20747 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20748 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20749 : InVec.getOperand(1);
20751 // If inputs to shuffle are the same for both ops, then allow 2 uses
20752 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20753 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20755 if (LdNode.getOpcode() == ISD::BITCAST) {
20756 // Don't duplicate a load with other uses.
20757 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20760 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20761 LdNode = LdNode.getOperand(0);
20764 if (!ISD::isNormalLoad(LdNode.getNode()))
20767 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20769 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20772 EVT EltVT = N->getValueType(0);
20773 // If there's a bitcast before the shuffle, check if the load type and
20774 // alignment is valid.
20775 unsigned Align = LN0->getAlignment();
20776 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20777 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20778 EltVT.getTypeForEVT(*DAG.getContext()));
20780 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20783 // All checks match so transform back to vector_shuffle so that DAG combiner
20784 // can finish the job
20787 // Create shuffle node taking into account the case that its a unary shuffle
20788 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20789 : InVec.getOperand(1);
20790 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20791 InVec.getOperand(0), Shuffle,
20793 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20794 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20798 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20799 /// special and don't usually play with other vector types, it's better to
20800 /// handle them early to be sure we emit efficient code by avoiding
20801 /// store-load conversions.
20802 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20803 if (N->getValueType(0) != MVT::x86mmx ||
20804 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20805 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20808 SDValue V = N->getOperand(0);
20809 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20810 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20811 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20812 N->getValueType(0), V.getOperand(0));
20817 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20818 /// generation and convert it from being a bunch of shuffles and extracts
20819 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20820 /// storing the value and loading scalars back, while for x64 we should
20821 /// use 64-bit extracts and shifts.
20822 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20823 TargetLowering::DAGCombinerInfo &DCI) {
20824 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20825 if (NewOp.getNode())
20828 SDValue InputVector = N->getOperand(0);
20830 // Detect mmx to i32 conversion through a v2i32 elt extract.
20831 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20832 N->getValueType(0) == MVT::i32 &&
20833 InputVector.getValueType() == MVT::v2i32) {
20835 // The bitcast source is a direct mmx result.
20836 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20837 if (MMXSrc.getValueType() == MVT::x86mmx)
20838 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20839 N->getValueType(0),
20840 InputVector.getNode()->getOperand(0));
20842 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20843 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20844 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20845 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20846 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20847 MMXSrcOp.getValueType() == MVT::v1i64 &&
20848 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20849 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20850 N->getValueType(0),
20851 MMXSrcOp.getOperand(0));
20854 // Only operate on vectors of 4 elements, where the alternative shuffling
20855 // gets to be more expensive.
20856 if (InputVector.getValueType() != MVT::v4i32)
20859 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20860 // single use which is a sign-extend or zero-extend, and all elements are
20862 SmallVector<SDNode *, 4> Uses;
20863 unsigned ExtractedElements = 0;
20864 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20865 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20866 if (UI.getUse().getResNo() != InputVector.getResNo())
20869 SDNode *Extract = *UI;
20870 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20873 if (Extract->getValueType(0) != MVT::i32)
20875 if (!Extract->hasOneUse())
20877 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20878 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20880 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20883 // Record which element was extracted.
20884 ExtractedElements |=
20885 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20887 Uses.push_back(Extract);
20890 // If not all the elements were used, this may not be worthwhile.
20891 if (ExtractedElements != 15)
20894 // Ok, we've now decided to do the transformation.
20895 // If 64-bit shifts are legal, use the extract-shift sequence,
20896 // otherwise bounce the vector off the cache.
20897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20899 SDLoc dl(InputVector);
20901 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20902 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20903 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20904 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20905 DAG.getConstant(0, dl, VecIdxTy));
20906 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20907 DAG.getConstant(1, dl, VecIdxTy));
20909 SDValue ShAmt = DAG.getConstant(32, dl,
20910 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20911 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20912 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20913 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20914 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20915 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20916 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20918 // Store the value to a temporary stack slot.
20919 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20920 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20921 MachinePointerInfo(), false, false, 0);
20923 EVT ElementType = InputVector.getValueType().getVectorElementType();
20924 unsigned EltSize = ElementType.getSizeInBits() / 8;
20926 // Replace each use (extract) with a load of the appropriate element.
20927 for (unsigned i = 0; i < 4; ++i) {
20928 uint64_t Offset = EltSize * i;
20929 SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20931 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20932 StackPtr, OffsetVal);
20934 // Load the scalar.
20935 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20936 ScalarAddr, MachinePointerInfo(),
20937 false, false, false, 0);
20942 // Replace the extracts
20943 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20944 UE = Uses.end(); UI != UE; ++UI) {
20945 SDNode *Extract = *UI;
20947 SDValue Idx = Extract->getOperand(1);
20948 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20949 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20952 // The replacement was made in place; don't return anything.
20956 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20957 static std::pair<unsigned, bool>
20958 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20959 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20960 if (!VT.isVector())
20961 return std::make_pair(0, false);
20963 bool NeedSplit = false;
20964 switch (VT.getSimpleVT().SimpleTy) {
20965 default: return std::make_pair(0, false);
20968 if (!Subtarget->hasVLX())
20969 return std::make_pair(0, false);
20973 if (!Subtarget->hasBWI())
20974 return std::make_pair(0, false);
20978 if (!Subtarget->hasAVX512())
20979 return std::make_pair(0, false);
20984 if (!Subtarget->hasAVX2())
20986 if (!Subtarget->hasAVX())
20987 return std::make_pair(0, false);
20992 if (!Subtarget->hasSSE2())
20993 return std::make_pair(0, false);
20996 // SSE2 has only a small subset of the operations.
20997 bool hasUnsigned = Subtarget->hasSSE41() ||
20998 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20999 bool hasSigned = Subtarget->hasSSE41() ||
21000 (Subtarget->hasSSE2() && VT == MVT::v8i16);
21002 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21005 // Check for x CC y ? x : y.
21006 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21007 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21012 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21015 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21018 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21021 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21023 // Check for x CC y ? y : x -- a min/max with reversed arms.
21024 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21025 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21030 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21033 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21036 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21039 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21043 return std::make_pair(Opc, NeedSplit);
21047 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21048 const X86Subtarget *Subtarget) {
21050 SDValue Cond = N->getOperand(0);
21051 SDValue LHS = N->getOperand(1);
21052 SDValue RHS = N->getOperand(2);
21054 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21055 SDValue CondSrc = Cond->getOperand(0);
21056 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21057 Cond = CondSrc->getOperand(0);
21060 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21063 // A vselect where all conditions and data are constants can be optimized into
21064 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21065 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21066 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21069 unsigned MaskValue = 0;
21070 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21073 MVT VT = N->getSimpleValueType(0);
21074 unsigned NumElems = VT.getVectorNumElements();
21075 SmallVector<int, 8> ShuffleMask(NumElems, -1);
21076 for (unsigned i = 0; i < NumElems; ++i) {
21077 // Be sure we emit undef where we can.
21078 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21079 ShuffleMask[i] = -1;
21081 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21084 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21085 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21087 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21090 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21092 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21093 TargetLowering::DAGCombinerInfo &DCI,
21094 const X86Subtarget *Subtarget) {
21096 SDValue Cond = N->getOperand(0);
21097 // Get the LHS/RHS of the select.
21098 SDValue LHS = N->getOperand(1);
21099 SDValue RHS = N->getOperand(2);
21100 EVT VT = LHS.getValueType();
21101 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21103 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21104 // instructions match the semantics of the common C idiom x<y?x:y but not
21105 // x<=y?x:y, because of how they handle negative zero (which can be
21106 // ignored in unsafe-math mode).
21107 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21108 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21109 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21110 (Subtarget->hasSSE2() ||
21111 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21112 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21114 unsigned Opcode = 0;
21115 // Check for x CC y ? x : y.
21116 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21117 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21121 // Converting this to a min would handle NaNs incorrectly, and swapping
21122 // the operands would cause it to handle comparisons between positive
21123 // and negative zero incorrectly.
21124 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21125 if (!DAG.getTarget().Options.UnsafeFPMath &&
21126 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21128 std::swap(LHS, RHS);
21130 Opcode = X86ISD::FMIN;
21133 // Converting this to a min would handle comparisons between positive
21134 // and negative zero incorrectly.
21135 if (!DAG.getTarget().Options.UnsafeFPMath &&
21136 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21138 Opcode = X86ISD::FMIN;
21141 // Converting this to a min would handle both negative zeros and NaNs
21142 // incorrectly, but we can swap the operands to fix both.
21143 std::swap(LHS, RHS);
21147 Opcode = X86ISD::FMIN;
21151 // Converting this to a max would handle comparisons between positive
21152 // and negative zero incorrectly.
21153 if (!DAG.getTarget().Options.UnsafeFPMath &&
21154 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21156 Opcode = X86ISD::FMAX;
21159 // Converting this to a max would handle NaNs incorrectly, and swapping
21160 // the operands would cause it to handle comparisons between positive
21161 // and negative zero incorrectly.
21162 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21163 if (!DAG.getTarget().Options.UnsafeFPMath &&
21164 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21166 std::swap(LHS, RHS);
21168 Opcode = X86ISD::FMAX;
21171 // Converting this to a max would handle both negative zeros and NaNs
21172 // incorrectly, but we can swap the operands to fix both.
21173 std::swap(LHS, RHS);
21177 Opcode = X86ISD::FMAX;
21180 // Check for x CC y ? y : x -- a min/max with reversed arms.
21181 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21182 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21186 // Converting this to a min would handle comparisons between positive
21187 // and negative zero incorrectly, and swapping the operands would
21188 // cause it to handle NaNs incorrectly.
21189 if (!DAG.getTarget().Options.UnsafeFPMath &&
21190 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21191 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21193 std::swap(LHS, RHS);
21195 Opcode = X86ISD::FMIN;
21198 // Converting this to a min would handle NaNs incorrectly.
21199 if (!DAG.getTarget().Options.UnsafeFPMath &&
21200 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21202 Opcode = X86ISD::FMIN;
21205 // Converting this to a min would handle both negative zeros and NaNs
21206 // incorrectly, but we can swap the operands to fix both.
21207 std::swap(LHS, RHS);
21211 Opcode = X86ISD::FMIN;
21215 // Converting this to a max would handle NaNs incorrectly.
21216 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21218 Opcode = X86ISD::FMAX;
21221 // Converting this to a max would handle comparisons between positive
21222 // and negative zero incorrectly, and swapping the operands would
21223 // cause it to handle NaNs incorrectly.
21224 if (!DAG.getTarget().Options.UnsafeFPMath &&
21225 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21226 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21228 std::swap(LHS, RHS);
21230 Opcode = X86ISD::FMAX;
21233 // Converting this to a max would handle both negative zeros and NaNs
21234 // incorrectly, but we can swap the operands to fix both.
21235 std::swap(LHS, RHS);
21239 Opcode = X86ISD::FMAX;
21245 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21248 EVT CondVT = Cond.getValueType();
21249 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21250 CondVT.getVectorElementType() == MVT::i1) {
21251 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21252 // lowering on KNL. In this case we convert it to
21253 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21254 // The same situation for all 128 and 256-bit vectors of i8 and i16.
21255 // Since SKX these selects have a proper lowering.
21256 EVT OpVT = LHS.getValueType();
21257 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21258 (OpVT.getVectorElementType() == MVT::i8 ||
21259 OpVT.getVectorElementType() == MVT::i16) &&
21260 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21261 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21262 DCI.AddToWorklist(Cond.getNode());
21263 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21266 // If this is a select between two integer constants, try to do some
21268 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21269 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21270 // Don't do this for crazy integer types.
21271 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21272 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21273 // so that TrueC (the true value) is larger than FalseC.
21274 bool NeedsCondInvert = false;
21276 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21277 // Efficiently invertible.
21278 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
21279 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
21280 isa<ConstantSDNode>(Cond.getOperand(1))))) {
21281 NeedsCondInvert = true;
21282 std::swap(TrueC, FalseC);
21285 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
21286 if (FalseC->getAPIntValue() == 0 &&
21287 TrueC->getAPIntValue().isPowerOf2()) {
21288 if (NeedsCondInvert) // Invert the condition if needed.
21289 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21290 DAG.getConstant(1, DL, Cond.getValueType()));
21292 // Zero extend the condition if needed.
21293 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21295 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21296 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21297 DAG.getConstant(ShAmt, DL, MVT::i8));
21300 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21301 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21302 if (NeedsCondInvert) // Invert the condition if needed.
21303 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21304 DAG.getConstant(1, DL, Cond.getValueType()));
21306 // Zero extend the condition if needed.
21307 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21308 FalseC->getValueType(0), Cond);
21309 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21310 SDValue(FalseC, 0));
21313 // Optimize cases that will turn into an LEA instruction. This requires
21314 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21315 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21316 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21317 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21319 bool isFastMultiplier = false;
21321 switch ((unsigned char)Diff) {
21323 case 1: // result = add base, cond
21324 case 2: // result = lea base( , cond*2)
21325 case 3: // result = lea base(cond, cond*2)
21326 case 4: // result = lea base( , cond*4)
21327 case 5: // result = lea base(cond, cond*4)
21328 case 8: // result = lea base( , cond*8)
21329 case 9: // result = lea base(cond, cond*8)
21330 isFastMultiplier = true;
21335 if (isFastMultiplier) {
21336 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21337 if (NeedsCondInvert) // Invert the condition if needed.
21338 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21339 DAG.getConstant(1, DL, Cond.getValueType()));
21341 // Zero extend the condition if needed.
21342 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21344 // Scale the condition by the difference.
21346 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21347 DAG.getConstant(Diff, DL,
21348 Cond.getValueType()));
21350 // Add the base if non-zero.
21351 if (FalseC->getAPIntValue() != 0)
21352 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21353 SDValue(FalseC, 0));
21360 // Canonicalize max and min:
21361 // (x > y) ? x : y -> (x >= y) ? x : y
21362 // (x < y) ? x : y -> (x <= y) ? x : y
21363 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21364 // the need for an extra compare
21365 // against zero. e.g.
21366 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21368 // testl %edi, %edi
21370 // cmovgl %edi, %eax
21374 // cmovsl %eax, %edi
21375 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21376 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21377 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21378 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21383 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21384 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21385 Cond.getOperand(0), Cond.getOperand(1), NewCC);
21386 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21391 // Early exit check
21392 if (!TLI.isTypeLegal(VT))
21395 // Match VSELECTs into subs with unsigned saturation.
21396 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21397 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21398 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21399 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21400 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21402 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21403 // left side invert the predicate to simplify logic below.
21405 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21407 CC = ISD::getSetCCInverse(CC, true);
21408 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21412 if (Other.getNode() && Other->getNumOperands() == 2 &&
21413 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21414 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21415 SDValue CondRHS = Cond->getOperand(1);
21417 // Look for a general sub with unsigned saturation first.
21418 // x >= y ? x-y : 0 --> subus x, y
21419 // x > y ? x-y : 0 --> subus x, y
21420 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21421 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21422 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21424 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21425 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21426 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21427 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21428 // If the RHS is a constant we have to reverse the const
21429 // canonicalization.
21430 // x > C-1 ? x+-C : 0 --> subus x, C
21431 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21432 CondRHSConst->getAPIntValue() ==
21433 (-OpRHSConst->getAPIntValue() - 1))
21434 return DAG.getNode(
21435 X86ISD::SUBUS, DL, VT, OpLHS,
21436 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21438 // Another special case: If C was a sign bit, the sub has been
21439 // canonicalized into a xor.
21440 // FIXME: Would it be better to use computeKnownBits to determine
21441 // whether it's safe to decanonicalize the xor?
21442 // x s< 0 ? x^C : 0 --> subus x, C
21443 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21444 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21445 OpRHSConst->getAPIntValue().isSignBit())
21446 // Note that we have to rebuild the RHS constant here to ensure we
21447 // don't rely on particular values of undef lanes.
21448 return DAG.getNode(
21449 X86ISD::SUBUS, DL, VT, OpLHS,
21450 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21455 // Try to match a min/max vector operation.
21456 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21457 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21458 unsigned Opc = ret.first;
21459 bool NeedSplit = ret.second;
21461 if (Opc && NeedSplit) {
21462 unsigned NumElems = VT.getVectorNumElements();
21463 // Extract the LHS vectors
21464 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21465 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21467 // Extract the RHS vectors
21468 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21469 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21471 // Create min/max for each subvector
21472 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21473 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21475 // Merge the result
21476 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21478 return DAG.getNode(Opc, DL, VT, LHS, RHS);
21481 // Simplify vector selection if condition value type matches vselect
21483 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21484 assert(Cond.getValueType().isVector() &&
21485 "vector select expects a vector selector!");
21487 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21488 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21490 // Try invert the condition if true value is not all 1s and false value
21492 if (!TValIsAllOnes && !FValIsAllZeros &&
21493 // Check if the selector will be produced by CMPP*/PCMP*
21494 Cond.getOpcode() == ISD::SETCC &&
21495 // Check if SETCC has already been promoted
21496 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21497 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21498 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21500 if (TValIsAllZeros || FValIsAllOnes) {
21501 SDValue CC = Cond.getOperand(2);
21502 ISD::CondCode NewCC =
21503 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21504 Cond.getOperand(0).getValueType().isInteger());
21505 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21506 std::swap(LHS, RHS);
21507 TValIsAllOnes = FValIsAllOnes;
21508 FValIsAllZeros = TValIsAllZeros;
21512 if (TValIsAllOnes || FValIsAllZeros) {
21515 if (TValIsAllOnes && FValIsAllZeros)
21517 else if (TValIsAllOnes)
21518 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21519 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21520 else if (FValIsAllZeros)
21521 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21522 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21524 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21528 // We should generate an X86ISD::BLENDI from a vselect if its argument
21529 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21530 // constants. This specific pattern gets generated when we split a
21531 // selector for a 512 bit vector in a machine without AVX512 (but with
21532 // 256-bit vectors), during legalization:
21534 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21536 // Iff we find this pattern and the build_vectors are built from
21537 // constants, we translate the vselect into a shuffle_vector that we
21538 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21539 if ((N->getOpcode() == ISD::VSELECT ||
21540 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21541 !DCI.isBeforeLegalize()) {
21542 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21543 if (Shuffle.getNode())
21547 // If this is a *dynamic* select (non-constant condition) and we can match
21548 // this node with one of the variable blend instructions, restructure the
21549 // condition so that the blends can use the high bit of each element and use
21550 // SimplifyDemandedBits to simplify the condition operand.
21551 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21552 !DCI.isBeforeLegalize() &&
21553 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21554 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21556 // Don't optimize vector selects that map to mask-registers.
21560 // We can only handle the cases where VSELECT is directly legal on the
21561 // subtarget. We custom lower VSELECT nodes with constant conditions and
21562 // this makes it hard to see whether a dynamic VSELECT will correctly
21563 // lower, so we both check the operation's status and explicitly handle the
21564 // cases where a *dynamic* blend will fail even though a constant-condition
21565 // blend could be custom lowered.
21566 // FIXME: We should find a better way to handle this class of problems.
21567 // Potentially, we should combine constant-condition vselect nodes
21568 // pre-legalization into shuffles and not mark as many types as custom
21570 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21572 // FIXME: We don't support i16-element blends currently. We could and
21573 // should support them by making *all* the bits in the condition be set
21574 // rather than just the high bit and using an i8-element blend.
21575 if (VT.getScalarType() == MVT::i16)
21577 // Dynamic blending was only available from SSE4.1 onward.
21578 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21580 // Byte blends are only available in AVX2
21581 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21582 !Subtarget->hasAVX2())
21585 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21586 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21588 APInt KnownZero, KnownOne;
21589 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21590 DCI.isBeforeLegalizeOps());
21591 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21592 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21594 // If we changed the computation somewhere in the DAG, this change
21595 // will affect all users of Cond.
21596 // Make sure it is fine and update all the nodes so that we do not
21597 // use the generic VSELECT anymore. Otherwise, we may perform
21598 // wrong optimizations as we messed up with the actual expectation
21599 // for the vector boolean values.
21600 if (Cond != TLO.Old) {
21601 // Check all uses of that condition operand to check whether it will be
21602 // consumed by non-BLEND instructions, which may depend on all bits are
21604 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21606 if (I->getOpcode() != ISD::VSELECT)
21607 // TODO: Add other opcodes eventually lowered into BLEND.
21610 // Update all the users of the condition, before committing the change,
21611 // so that the VSELECT optimizations that expect the correct vector
21612 // boolean value will not be triggered.
21613 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21615 DAG.ReplaceAllUsesOfValueWith(
21617 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21618 Cond, I->getOperand(1), I->getOperand(2)));
21619 DCI.CommitTargetLoweringOpt(TLO);
21622 // At this point, only Cond is changed. Change the condition
21623 // just for N to keep the opportunity to optimize all other
21624 // users their own way.
21625 DAG.ReplaceAllUsesOfValueWith(
21627 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21628 TLO.New, N->getOperand(1), N->getOperand(2)));
21636 // Check whether a boolean test is testing a boolean value generated by
21637 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21640 // Simplify the following patterns:
21641 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21642 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21643 // to (Op EFLAGS Cond)
21645 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21646 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21647 // to (Op EFLAGS !Cond)
21649 // where Op could be BRCOND or CMOV.
21651 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21652 // Quit if not CMP and SUB with its value result used.
21653 if (Cmp.getOpcode() != X86ISD::CMP &&
21654 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21657 // Quit if not used as a boolean value.
21658 if (CC != X86::COND_E && CC != X86::COND_NE)
21661 // Check CMP operands. One of them should be 0 or 1 and the other should be
21662 // an SetCC or extended from it.
21663 SDValue Op1 = Cmp.getOperand(0);
21664 SDValue Op2 = Cmp.getOperand(1);
21667 const ConstantSDNode* C = nullptr;
21668 bool needOppositeCond = (CC == X86::COND_E);
21669 bool checkAgainstTrue = false; // Is it a comparison against 1?
21671 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21673 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21675 else // Quit if all operands are not constants.
21678 if (C->getZExtValue() == 1) {
21679 needOppositeCond = !needOppositeCond;
21680 checkAgainstTrue = true;
21681 } else if (C->getZExtValue() != 0)
21682 // Quit if the constant is neither 0 or 1.
21685 bool truncatedToBoolWithAnd = false;
21686 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21687 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21688 SetCC.getOpcode() == ISD::TRUNCATE ||
21689 SetCC.getOpcode() == ISD::AND) {
21690 if (SetCC.getOpcode() == ISD::AND) {
21692 ConstantSDNode *CS;
21693 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21694 CS->getZExtValue() == 1)
21696 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21697 CS->getZExtValue() == 1)
21701 SetCC = SetCC.getOperand(OpIdx);
21702 truncatedToBoolWithAnd = true;
21704 SetCC = SetCC.getOperand(0);
21707 switch (SetCC.getOpcode()) {
21708 case X86ISD::SETCC_CARRY:
21709 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21710 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21711 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21712 // truncated to i1 using 'and'.
21713 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21715 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21716 "Invalid use of SETCC_CARRY!");
21718 case X86ISD::SETCC:
21719 // Set the condition code or opposite one if necessary.
21720 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21721 if (needOppositeCond)
21722 CC = X86::GetOppositeBranchCondition(CC);
21723 return SetCC.getOperand(1);
21724 case X86ISD::CMOV: {
21725 // Check whether false/true value has canonical one, i.e. 0 or 1.
21726 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21727 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21728 // Quit if true value is not a constant.
21731 // Quit if false value is not a constant.
21733 SDValue Op = SetCC.getOperand(0);
21734 // Skip 'zext' or 'trunc' node.
21735 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21736 Op.getOpcode() == ISD::TRUNCATE)
21737 Op = Op.getOperand(0);
21738 // A special case for rdrand/rdseed, where 0 is set if false cond is
21740 if ((Op.getOpcode() != X86ISD::RDRAND &&
21741 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21744 // Quit if false value is not the constant 0 or 1.
21745 bool FValIsFalse = true;
21746 if (FVal && FVal->getZExtValue() != 0) {
21747 if (FVal->getZExtValue() != 1)
21749 // If FVal is 1, opposite cond is needed.
21750 needOppositeCond = !needOppositeCond;
21751 FValIsFalse = false;
21753 // Quit if TVal is not the constant opposite of FVal.
21754 if (FValIsFalse && TVal->getZExtValue() != 1)
21756 if (!FValIsFalse && TVal->getZExtValue() != 0)
21758 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21759 if (needOppositeCond)
21760 CC = X86::GetOppositeBranchCondition(CC);
21761 return SetCC.getOperand(3);
21768 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21770 /// (X86or (X86setcc) (X86setcc))
21771 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21772 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21773 X86::CondCode &CC1, SDValue &Flags,
21775 if (Cond->getOpcode() == X86ISD::CMP) {
21776 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21777 if (!CondOp1C || !CondOp1C->isNullValue())
21780 Cond = Cond->getOperand(0);
21785 SDValue SetCC0, SetCC1;
21786 switch (Cond->getOpcode()) {
21787 default: return false;
21794 SetCC0 = Cond->getOperand(0);
21795 SetCC1 = Cond->getOperand(1);
21799 // Make sure we have SETCC nodes, using the same flags value.
21800 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21801 SetCC1.getOpcode() != X86ISD::SETCC ||
21802 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21805 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21806 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21807 Flags = SetCC0->getOperand(1);
21811 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21812 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21813 TargetLowering::DAGCombinerInfo &DCI,
21814 const X86Subtarget *Subtarget) {
21817 // If the flag operand isn't dead, don't touch this CMOV.
21818 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21821 SDValue FalseOp = N->getOperand(0);
21822 SDValue TrueOp = N->getOperand(1);
21823 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21824 SDValue Cond = N->getOperand(3);
21826 if (CC == X86::COND_E || CC == X86::COND_NE) {
21827 switch (Cond.getOpcode()) {
21831 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21832 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21833 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21839 Flags = checkBoolTestSetCCCombine(Cond, CC);
21840 if (Flags.getNode() &&
21841 // Extra check as FCMOV only supports a subset of X86 cond.
21842 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21843 SDValue Ops[] = { FalseOp, TrueOp,
21844 DAG.getConstant(CC, DL, MVT::i8), Flags };
21845 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21848 // If this is a select between two integer constants, try to do some
21849 // optimizations. Note that the operands are ordered the opposite of SELECT
21851 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21852 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21853 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21854 // larger than FalseC (the false value).
21855 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21856 CC = X86::GetOppositeBranchCondition(CC);
21857 std::swap(TrueC, FalseC);
21858 std::swap(TrueOp, FalseOp);
21861 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21862 // This is efficient for any integer data type (including i8/i16) and
21864 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21865 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21866 DAG.getConstant(CC, DL, MVT::i8), Cond);
21868 // Zero extend the condition if needed.
21869 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21871 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21872 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21873 DAG.getConstant(ShAmt, DL, MVT::i8));
21874 if (N->getNumValues() == 2) // Dead flag value?
21875 return DCI.CombineTo(N, Cond, SDValue());
21879 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21880 // for any integer data type, including i8/i16.
21881 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21882 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21883 DAG.getConstant(CC, DL, MVT::i8), Cond);
21885 // Zero extend the condition if needed.
21886 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21887 FalseC->getValueType(0), Cond);
21888 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21889 SDValue(FalseC, 0));
21891 if (N->getNumValues() == 2) // Dead flag value?
21892 return DCI.CombineTo(N, Cond, SDValue());
21896 // Optimize cases that will turn into an LEA instruction. This requires
21897 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21898 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21899 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21900 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21902 bool isFastMultiplier = false;
21904 switch ((unsigned char)Diff) {
21906 case 1: // result = add base, cond
21907 case 2: // result = lea base( , cond*2)
21908 case 3: // result = lea base(cond, cond*2)
21909 case 4: // result = lea base( , cond*4)
21910 case 5: // result = lea base(cond, cond*4)
21911 case 8: // result = lea base( , cond*8)
21912 case 9: // result = lea base(cond, cond*8)
21913 isFastMultiplier = true;
21918 if (isFastMultiplier) {
21919 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21920 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21921 DAG.getConstant(CC, DL, MVT::i8), Cond);
21922 // Zero extend the condition if needed.
21923 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21925 // Scale the condition by the difference.
21927 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21928 DAG.getConstant(Diff, DL, Cond.getValueType()));
21930 // Add the base if non-zero.
21931 if (FalseC->getAPIntValue() != 0)
21932 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21933 SDValue(FalseC, 0));
21934 if (N->getNumValues() == 2) // Dead flag value?
21935 return DCI.CombineTo(N, Cond, SDValue());
21942 // Handle these cases:
21943 // (select (x != c), e, c) -> select (x != c), e, x),
21944 // (select (x == c), c, e) -> select (x == c), x, e)
21945 // where the c is an integer constant, and the "select" is the combination
21946 // of CMOV and CMP.
21948 // The rationale for this change is that the conditional-move from a constant
21949 // needs two instructions, however, conditional-move from a register needs
21950 // only one instruction.
21952 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21953 // some instruction-combining opportunities. This opt needs to be
21954 // postponed as late as possible.
21956 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21957 // the DCI.xxxx conditions are provided to postpone the optimization as
21958 // late as possible.
21960 ConstantSDNode *CmpAgainst = nullptr;
21961 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21962 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21963 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21965 if (CC == X86::COND_NE &&
21966 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21967 CC = X86::GetOppositeBranchCondition(CC);
21968 std::swap(TrueOp, FalseOp);
21971 if (CC == X86::COND_E &&
21972 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21973 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21974 DAG.getConstant(CC, DL, MVT::i8), Cond };
21975 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21980 // Fold and/or of setcc's to double CMOV:
21981 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21982 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21984 // This combine lets us generate:
21985 // cmovcc1 (jcc1 if we don't have CMOV)
21991 // cmovne (jne if we don't have CMOV)
21992 // When we can't use the CMOV instruction, it might increase branch
21994 // When we can use CMOV, or when there is no mispredict, this improves
21995 // throughput and reduces register pressure.
21997 if (CC == X86::COND_NE) {
21999 X86::CondCode CC0, CC1;
22001 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22003 std::swap(FalseOp, TrueOp);
22004 CC0 = X86::GetOppositeBranchCondition(CC0);
22005 CC1 = X86::GetOppositeBranchCondition(CC1);
22008 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22010 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22011 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22012 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22013 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22021 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22022 const X86Subtarget *Subtarget) {
22023 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22025 default: return SDValue();
22026 // SSE/AVX/AVX2 blend intrinsics.
22027 case Intrinsic::x86_avx2_pblendvb:
22028 // Don't try to simplify this intrinsic if we don't have AVX2.
22029 if (!Subtarget->hasAVX2())
22032 case Intrinsic::x86_avx_blendv_pd_256:
22033 case Intrinsic::x86_avx_blendv_ps_256:
22034 // Don't try to simplify this intrinsic if we don't have AVX.
22035 if (!Subtarget->hasAVX())
22038 case Intrinsic::x86_sse41_blendvps:
22039 case Intrinsic::x86_sse41_blendvpd:
22040 case Intrinsic::x86_sse41_pblendvb: {
22041 SDValue Op0 = N->getOperand(1);
22042 SDValue Op1 = N->getOperand(2);
22043 SDValue Mask = N->getOperand(3);
22045 // Don't try to simplify this intrinsic if we don't have SSE4.1.
22046 if (!Subtarget->hasSSE41())
22049 // fold (blend A, A, Mask) -> A
22052 // fold (blend A, B, allZeros) -> A
22053 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22055 // fold (blend A, B, allOnes) -> B
22056 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22059 // Simplify the case where the mask is a constant i32 value.
22060 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22061 if (C->isNullValue())
22063 if (C->isAllOnesValue())
22070 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22071 case Intrinsic::x86_sse2_psrai_w:
22072 case Intrinsic::x86_sse2_psrai_d:
22073 case Intrinsic::x86_avx2_psrai_w:
22074 case Intrinsic::x86_avx2_psrai_d:
22075 case Intrinsic::x86_sse2_psra_w:
22076 case Intrinsic::x86_sse2_psra_d:
22077 case Intrinsic::x86_avx2_psra_w:
22078 case Intrinsic::x86_avx2_psra_d: {
22079 SDValue Op0 = N->getOperand(1);
22080 SDValue Op1 = N->getOperand(2);
22081 EVT VT = Op0.getValueType();
22082 assert(VT.isVector() && "Expected a vector type!");
22084 if (isa<BuildVectorSDNode>(Op1))
22085 Op1 = Op1.getOperand(0);
22087 if (!isa<ConstantSDNode>(Op1))
22090 EVT SVT = VT.getVectorElementType();
22091 unsigned SVTBits = SVT.getSizeInBits();
22093 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22094 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22095 uint64_t ShAmt = C.getZExtValue();
22097 // Don't try to convert this shift into a ISD::SRA if the shift
22098 // count is bigger than or equal to the element size.
22099 if (ShAmt >= SVTBits)
22102 // Trivial case: if the shift count is zero, then fold this
22103 // into the first operand.
22107 // Replace this packed shift intrinsic with a target independent
22110 SDValue Splat = DAG.getConstant(C, DL, VT);
22111 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22116 /// PerformMulCombine - Optimize a single multiply with constant into two
22117 /// in order to implement it with two cheaper instructions, e.g.
22118 /// LEA + SHL, LEA + LEA.
22119 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22120 TargetLowering::DAGCombinerInfo &DCI) {
22121 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22124 EVT VT = N->getValueType(0);
22125 if (VT != MVT::i64 && VT != MVT::i32)
22128 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22131 uint64_t MulAmt = C->getZExtValue();
22132 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22135 uint64_t MulAmt1 = 0;
22136 uint64_t MulAmt2 = 0;
22137 if ((MulAmt % 9) == 0) {
22139 MulAmt2 = MulAmt / 9;
22140 } else if ((MulAmt % 5) == 0) {
22142 MulAmt2 = MulAmt / 5;
22143 } else if ((MulAmt % 3) == 0) {
22145 MulAmt2 = MulAmt / 3;
22148 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22151 if (isPowerOf2_64(MulAmt2) &&
22152 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22153 // If second multiplifer is pow2, issue it first. We want the multiply by
22154 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22156 std::swap(MulAmt1, MulAmt2);
22159 if (isPowerOf2_64(MulAmt1))
22160 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22161 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22163 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22164 DAG.getConstant(MulAmt1, DL, VT));
22166 if (isPowerOf2_64(MulAmt2))
22167 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22168 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22170 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22171 DAG.getConstant(MulAmt2, DL, VT));
22173 // Do not add new nodes to DAG combiner worklist.
22174 DCI.CombineTo(N, NewMul, false);
22179 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22180 SDValue N0 = N->getOperand(0);
22181 SDValue N1 = N->getOperand(1);
22182 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22183 EVT VT = N0.getValueType();
22185 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22186 // since the result of setcc_c is all zero's or all ones.
22187 if (VT.isInteger() && !VT.isVector() &&
22188 N1C && N0.getOpcode() == ISD::AND &&
22189 N0.getOperand(1).getOpcode() == ISD::Constant) {
22190 SDValue N00 = N0.getOperand(0);
22191 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22192 ((N00.getOpcode() == ISD::ANY_EXTEND ||
22193 N00.getOpcode() == ISD::ZERO_EXTEND) &&
22194 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22195 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22196 APInt ShAmt = N1C->getAPIntValue();
22197 Mask = Mask.shl(ShAmt);
22200 return DAG.getNode(ISD::AND, DL, VT,
22201 N00, DAG.getConstant(Mask, DL, VT));
22206 // Hardware support for vector shifts is sparse which makes us scalarize the
22207 // vector operations in many cases. Also, on sandybridge ADD is faster than
22209 // (shl V, 1) -> add V,V
22210 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22211 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22212 assert(N0.getValueType().isVector() && "Invalid vector shift type");
22213 // We shift all of the values by one. In many cases we do not have
22214 // hardware support for this operation. This is better expressed as an ADD
22216 if (N1SplatC->getZExtValue() == 1)
22217 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22223 /// \brief Returns a vector of 0s if the node in input is a vector logical
22224 /// shift by a constant amount which is known to be bigger than or equal
22225 /// to the vector element size in bits.
22226 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22227 const X86Subtarget *Subtarget) {
22228 EVT VT = N->getValueType(0);
22230 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22231 (!Subtarget->hasInt256() ||
22232 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22235 SDValue Amt = N->getOperand(1);
22237 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22238 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22239 APInt ShiftAmt = AmtSplat->getAPIntValue();
22240 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22242 // SSE2/AVX2 logical shifts always return a vector of 0s
22243 // if the shift amount is bigger than or equal to
22244 // the element size. The constant shift amount will be
22245 // encoded as a 8-bit immediate.
22246 if (ShiftAmt.trunc(8).uge(MaxAmount))
22247 return getZeroVector(VT, Subtarget, DAG, DL);
22253 /// PerformShiftCombine - Combine shifts.
22254 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22255 TargetLowering::DAGCombinerInfo &DCI,
22256 const X86Subtarget *Subtarget) {
22257 if (N->getOpcode() == ISD::SHL) {
22258 SDValue V = PerformSHLCombine(N, DAG);
22259 if (V.getNode()) return V;
22262 if (N->getOpcode() != ISD::SRA) {
22263 // Try to fold this logical shift into a zero vector.
22264 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22265 if (V.getNode()) return V;
22271 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
22272 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22273 // and friends. Likewise for OR -> CMPNEQSS.
22274 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22275 TargetLowering::DAGCombinerInfo &DCI,
22276 const X86Subtarget *Subtarget) {
22279 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22280 // we're requiring SSE2 for both.
22281 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22282 SDValue N0 = N->getOperand(0);
22283 SDValue N1 = N->getOperand(1);
22284 SDValue CMP0 = N0->getOperand(1);
22285 SDValue CMP1 = N1->getOperand(1);
22288 // The SETCCs should both refer to the same CMP.
22289 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22292 SDValue CMP00 = CMP0->getOperand(0);
22293 SDValue CMP01 = CMP0->getOperand(1);
22294 EVT VT = CMP00.getValueType();
22296 if (VT == MVT::f32 || VT == MVT::f64) {
22297 bool ExpectingFlags = false;
22298 // Check for any users that want flags:
22299 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22300 !ExpectingFlags && UI != UE; ++UI)
22301 switch (UI->getOpcode()) {
22306 ExpectingFlags = true;
22308 case ISD::CopyToReg:
22309 case ISD::SIGN_EXTEND:
22310 case ISD::ZERO_EXTEND:
22311 case ISD::ANY_EXTEND:
22315 if (!ExpectingFlags) {
22316 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22317 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22319 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22320 X86::CondCode tmp = cc0;
22325 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
22326 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22327 // FIXME: need symbolic constants for these magic numbers.
22328 // See X86ATTInstPrinter.cpp:printSSECC().
22329 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22330 if (Subtarget->hasAVX512()) {
22331 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22333 DAG.getConstant(x86cc, DL, MVT::i8));
22334 if (N->getValueType(0) != MVT::i1)
22335 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22339 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22340 CMP00.getValueType(), CMP00, CMP01,
22341 DAG.getConstant(x86cc, DL,
22344 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22345 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22347 if (is64BitFP && !Subtarget->is64Bit()) {
22348 // On a 32-bit target, we cannot bitcast the 64-bit float to a
22349 // 64-bit integer, since that's not a legal type. Since
22350 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22351 // bits, but can do this little dance to extract the lowest 32 bits
22352 // and work with those going forward.
22353 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22355 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22357 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22358 Vector32, DAG.getIntPtrConstant(0, DL));
22362 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22364 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22365 DAG.getConstant(1, DL, IntVT));
22366 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22368 return OneBitOfTruth;
22376 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22377 /// so it can be folded inside ANDNP.
22378 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22379 EVT VT = N->getValueType(0);
22381 // Match direct AllOnes for 128 and 256-bit vectors
22382 if (ISD::isBuildVectorAllOnes(N))
22385 // Look through a bit convert.
22386 if (N->getOpcode() == ISD::BITCAST)
22387 N = N->getOperand(0).getNode();
22389 // Sometimes the operand may come from a insert_subvector building a 256-bit
22391 if (VT.is256BitVector() &&
22392 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22393 SDValue V1 = N->getOperand(0);
22394 SDValue V2 = N->getOperand(1);
22396 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22397 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22398 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22399 ISD::isBuildVectorAllOnes(V2.getNode()))
22406 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22407 // register. In most cases we actually compare or select YMM-sized registers
22408 // and mixing the two types creates horrible code. This method optimizes
22409 // some of the transition sequences.
22410 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22411 TargetLowering::DAGCombinerInfo &DCI,
22412 const X86Subtarget *Subtarget) {
22413 EVT VT = N->getValueType(0);
22414 if (!VT.is256BitVector())
22417 assert((N->getOpcode() == ISD::ANY_EXTEND ||
22418 N->getOpcode() == ISD::ZERO_EXTEND ||
22419 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22421 SDValue Narrow = N->getOperand(0);
22422 EVT NarrowVT = Narrow->getValueType(0);
22423 if (!NarrowVT.is128BitVector())
22426 if (Narrow->getOpcode() != ISD::XOR &&
22427 Narrow->getOpcode() != ISD::AND &&
22428 Narrow->getOpcode() != ISD::OR)
22431 SDValue N0 = Narrow->getOperand(0);
22432 SDValue N1 = Narrow->getOperand(1);
22435 // The Left side has to be a trunc.
22436 if (N0.getOpcode() != ISD::TRUNCATE)
22439 // The type of the truncated inputs.
22440 EVT WideVT = N0->getOperand(0)->getValueType(0);
22444 // The right side has to be a 'trunc' or a constant vector.
22445 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22446 ConstantSDNode *RHSConstSplat = nullptr;
22447 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22448 RHSConstSplat = RHSBV->getConstantSplatNode();
22449 if (!RHSTrunc && !RHSConstSplat)
22452 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22454 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22457 // Set N0 and N1 to hold the inputs to the new wide operation.
22458 N0 = N0->getOperand(0);
22459 if (RHSConstSplat) {
22460 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22461 SDValue(RHSConstSplat, 0));
22462 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22463 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22464 } else if (RHSTrunc) {
22465 N1 = N1->getOperand(0);
22468 // Generate the wide operation.
22469 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22470 unsigned Opcode = N->getOpcode();
22472 case ISD::ANY_EXTEND:
22474 case ISD::ZERO_EXTEND: {
22475 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22476 APInt Mask = APInt::getAllOnesValue(InBits);
22477 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22478 return DAG.getNode(ISD::AND, DL, VT,
22479 Op, DAG.getConstant(Mask, DL, VT));
22481 case ISD::SIGN_EXTEND:
22482 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22483 Op, DAG.getValueType(NarrowVT));
22485 llvm_unreachable("Unexpected opcode");
22489 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22490 TargetLowering::DAGCombinerInfo &DCI,
22491 const X86Subtarget *Subtarget) {
22492 SDValue N0 = N->getOperand(0);
22493 SDValue N1 = N->getOperand(1);
22496 // A vector zext_in_reg may be represented as a shuffle,
22497 // feeding into a bitcast (this represents anyext) feeding into
22498 // an and with a mask.
22499 // We'd like to try to combine that into a shuffle with zero
22500 // plus a bitcast, removing the and.
22501 if (N0.getOpcode() != ISD::BITCAST ||
22502 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22505 // The other side of the AND should be a splat of 2^C, where C
22506 // is the number of bits in the source type.
22507 if (N1.getOpcode() == ISD::BITCAST)
22508 N1 = N1.getOperand(0);
22509 if (N1.getOpcode() != ISD::BUILD_VECTOR)
22511 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22513 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22514 EVT SrcType = Shuffle->getValueType(0);
22516 // We expect a single-source shuffle
22517 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22520 unsigned SrcSize = SrcType.getScalarSizeInBits();
22522 APInt SplatValue, SplatUndef;
22523 unsigned SplatBitSize;
22525 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22526 SplatBitSize, HasAnyUndefs))
22529 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22530 // Make sure the splat matches the mask we expect
22531 if (SplatBitSize > ResSize ||
22532 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22535 // Make sure the input and output size make sense
22536 if (SrcSize >= ResSize || ResSize % SrcSize)
22539 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22540 // The number of u's between each two values depends on the ratio between
22541 // the source and dest type.
22542 unsigned ZextRatio = ResSize / SrcSize;
22543 bool IsZext = true;
22544 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22545 if (i % ZextRatio) {
22546 if (Shuffle->getMaskElt(i) > 0) {
22552 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22553 // Expected element number
22563 // Ok, perform the transformation - replace the shuffle with
22564 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22565 // (instead of undef) where the k elements come from the zero vector.
22566 SmallVector<int, 8> Mask;
22567 unsigned NumElems = SrcType.getVectorNumElements();
22568 for (unsigned i = 0; i < NumElems; ++i)
22570 Mask.push_back(NumElems);
22572 Mask.push_back(i / ZextRatio);
22574 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22575 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22576 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22579 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22580 TargetLowering::DAGCombinerInfo &DCI,
22581 const X86Subtarget *Subtarget) {
22582 if (DCI.isBeforeLegalizeOps())
22585 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22588 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22591 EVT VT = N->getValueType(0);
22592 SDValue N0 = N->getOperand(0);
22593 SDValue N1 = N->getOperand(1);
22596 // Create BEXTR instructions
22597 // BEXTR is ((X >> imm) & (2**size-1))
22598 if (VT == MVT::i32 || VT == MVT::i64) {
22599 // Check for BEXTR.
22600 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22601 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22602 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22603 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22604 if (MaskNode && ShiftNode) {
22605 uint64_t Mask = MaskNode->getZExtValue();
22606 uint64_t Shift = ShiftNode->getZExtValue();
22607 if (isMask_64(Mask)) {
22608 uint64_t MaskSize = countPopulation(Mask);
22609 if (Shift + MaskSize <= VT.getSizeInBits())
22610 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22611 DAG.getConstant(Shift | (MaskSize << 8), DL,
22620 // Want to form ANDNP nodes:
22621 // 1) In the hopes of then easily combining them with OR and AND nodes
22622 // to form PBLEND/PSIGN.
22623 // 2) To match ANDN packed intrinsics
22624 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22627 // Check LHS for vnot
22628 if (N0.getOpcode() == ISD::XOR &&
22629 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22630 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22631 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22633 // Check RHS for vnot
22634 if (N1.getOpcode() == ISD::XOR &&
22635 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22636 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22637 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22642 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22643 TargetLowering::DAGCombinerInfo &DCI,
22644 const X86Subtarget *Subtarget) {
22645 if (DCI.isBeforeLegalizeOps())
22648 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22652 SDValue N0 = N->getOperand(0);
22653 SDValue N1 = N->getOperand(1);
22654 EVT VT = N->getValueType(0);
22656 // look for psign/blend
22657 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22658 if (!Subtarget->hasSSSE3() ||
22659 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22662 // Canonicalize pandn to RHS
22663 if (N0.getOpcode() == X86ISD::ANDNP)
22665 // or (and (m, y), (pandn m, x))
22666 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22667 SDValue Mask = N1.getOperand(0);
22668 SDValue X = N1.getOperand(1);
22670 if (N0.getOperand(0) == Mask)
22671 Y = N0.getOperand(1);
22672 if (N0.getOperand(1) == Mask)
22673 Y = N0.getOperand(0);
22675 // Check to see if the mask appeared in both the AND and ANDNP and
22679 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22680 // Look through mask bitcast.
22681 if (Mask.getOpcode() == ISD::BITCAST)
22682 Mask = Mask.getOperand(0);
22683 if (X.getOpcode() == ISD::BITCAST)
22684 X = X.getOperand(0);
22685 if (Y.getOpcode() == ISD::BITCAST)
22686 Y = Y.getOperand(0);
22688 EVT MaskVT = Mask.getValueType();
22690 // Validate that the Mask operand is a vector sra node.
22691 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22692 // there is no psrai.b
22693 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22694 unsigned SraAmt = ~0;
22695 if (Mask.getOpcode() == ISD::SRA) {
22696 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22697 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22698 SraAmt = AmtConst->getZExtValue();
22699 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22700 SDValue SraC = Mask.getOperand(1);
22701 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22703 if ((SraAmt + 1) != EltBits)
22708 // Now we know we at least have a plendvb with the mask val. See if
22709 // we can form a psignb/w/d.
22710 // psign = x.type == y.type == mask.type && y = sub(0, x);
22711 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22712 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22713 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22714 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22715 "Unsupported VT for PSIGN");
22716 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22717 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22719 // PBLENDVB only available on SSE 4.1
22720 if (!Subtarget->hasSSE41())
22723 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22725 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22726 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22727 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22728 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22729 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22733 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22736 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22737 MachineFunction &MF = DAG.getMachineFunction();
22739 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22741 // SHLD/SHRD instructions have lower register pressure, but on some
22742 // platforms they have higher latency than the equivalent
22743 // series of shifts/or that would otherwise be generated.
22744 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22745 // have higher latencies and we are not optimizing for size.
22746 if (!OptForSize && Subtarget->isSHLDSlow())
22749 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22751 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22753 if (!N0.hasOneUse() || !N1.hasOneUse())
22756 SDValue ShAmt0 = N0.getOperand(1);
22757 if (ShAmt0.getValueType() != MVT::i8)
22759 SDValue ShAmt1 = N1.getOperand(1);
22760 if (ShAmt1.getValueType() != MVT::i8)
22762 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22763 ShAmt0 = ShAmt0.getOperand(0);
22764 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22765 ShAmt1 = ShAmt1.getOperand(0);
22768 unsigned Opc = X86ISD::SHLD;
22769 SDValue Op0 = N0.getOperand(0);
22770 SDValue Op1 = N1.getOperand(0);
22771 if (ShAmt0.getOpcode() == ISD::SUB) {
22772 Opc = X86ISD::SHRD;
22773 std::swap(Op0, Op1);
22774 std::swap(ShAmt0, ShAmt1);
22777 unsigned Bits = VT.getSizeInBits();
22778 if (ShAmt1.getOpcode() == ISD::SUB) {
22779 SDValue Sum = ShAmt1.getOperand(0);
22780 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22781 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22782 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22783 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22784 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22785 return DAG.getNode(Opc, DL, VT,
22787 DAG.getNode(ISD::TRUNCATE, DL,
22790 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22791 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22793 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22794 return DAG.getNode(Opc, DL, VT,
22795 N0.getOperand(0), N1.getOperand(0),
22796 DAG.getNode(ISD::TRUNCATE, DL,
22803 // Generate NEG and CMOV for integer abs.
22804 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22805 EVT VT = N->getValueType(0);
22807 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22808 // 8-bit integer abs to NEG and CMOV.
22809 if (VT.isInteger() && VT.getSizeInBits() == 8)
22812 SDValue N0 = N->getOperand(0);
22813 SDValue N1 = N->getOperand(1);
22816 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22817 // and change it to SUB and CMOV.
22818 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22819 N0.getOpcode() == ISD::ADD &&
22820 N0.getOperand(1) == N1 &&
22821 N1.getOpcode() == ISD::SRA &&
22822 N1.getOperand(0) == N0.getOperand(0))
22823 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22824 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22825 // Generate SUB & CMOV.
22826 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22827 DAG.getConstant(0, DL, VT), N0.getOperand(0));
22829 SDValue Ops[] = { N0.getOperand(0), Neg,
22830 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22831 SDValue(Neg.getNode(), 1) };
22832 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22837 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22838 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22839 TargetLowering::DAGCombinerInfo &DCI,
22840 const X86Subtarget *Subtarget) {
22841 if (DCI.isBeforeLegalizeOps())
22844 if (Subtarget->hasCMov()) {
22845 SDValue RV = performIntegerAbsCombine(N, DAG);
22853 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22854 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22855 TargetLowering::DAGCombinerInfo &DCI,
22856 const X86Subtarget *Subtarget) {
22857 LoadSDNode *Ld = cast<LoadSDNode>(N);
22858 EVT RegVT = Ld->getValueType(0);
22859 EVT MemVT = Ld->getMemoryVT();
22861 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22863 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22864 // into two 16-byte operations.
22865 ISD::LoadExtType Ext = Ld->getExtensionType();
22866 unsigned Alignment = Ld->getAlignment();
22867 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22868 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22869 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22870 unsigned NumElems = RegVT.getVectorNumElements();
22874 SDValue Ptr = Ld->getBasePtr();
22875 SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22877 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22879 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22880 Ld->getPointerInfo(), Ld->isVolatile(),
22881 Ld->isNonTemporal(), Ld->isInvariant(),
22883 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22884 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22885 Ld->getPointerInfo(), Ld->isVolatile(),
22886 Ld->isNonTemporal(), Ld->isInvariant(),
22887 std::min(16U, Alignment));
22888 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22890 Load2.getValue(1));
22892 SDValue NewVec = DAG.getUNDEF(RegVT);
22893 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22894 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22895 return DCI.CombineTo(N, NewVec, TF, true);
22901 /// PerformMLOADCombine - Resolve extending loads
22902 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22903 TargetLowering::DAGCombinerInfo &DCI,
22904 const X86Subtarget *Subtarget) {
22905 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22906 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22909 EVT VT = Mld->getValueType(0);
22910 unsigned NumElems = VT.getVectorNumElements();
22911 EVT LdVT = Mld->getMemoryVT();
22914 assert(LdVT != VT && "Cannot extend to the same type");
22915 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22916 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22917 // From, To sizes and ElemCount must be pow of two
22918 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22919 "Unexpected size for extending masked load");
22921 unsigned SizeRatio = ToSz / FromSz;
22922 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22924 // Create a type on which we perform the shuffle
22925 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22926 LdVT.getScalarType(), NumElems*SizeRatio);
22927 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22929 // Convert Src0 value
22930 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22931 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22932 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22933 for (unsigned i = 0; i != NumElems; ++i)
22934 ShuffleVec[i] = i * SizeRatio;
22936 // Can't shuffle using an illegal type.
22937 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22938 && "WideVecVT should be legal");
22939 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22940 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22942 // Prepare the new mask
22944 SDValue Mask = Mld->getMask();
22945 if (Mask.getValueType() == VT) {
22946 // Mask and original value have the same type
22947 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22948 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22949 for (unsigned i = 0; i != NumElems; ++i)
22950 ShuffleVec[i] = i * SizeRatio;
22951 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22952 ShuffleVec[i] = NumElems*SizeRatio;
22953 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22954 DAG.getConstant(0, dl, WideVecVT),
22958 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22959 unsigned WidenNumElts = NumElems*SizeRatio;
22960 unsigned MaskNumElts = VT.getVectorNumElements();
22961 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22964 unsigned NumConcat = WidenNumElts / MaskNumElts;
22965 SmallVector<SDValue, 16> Ops(NumConcat);
22966 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
22968 for (unsigned i = 1; i != NumConcat; ++i)
22971 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22974 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22975 Mld->getBasePtr(), NewMask, WideSrc0,
22976 Mld->getMemoryVT(), Mld->getMemOperand(),
22978 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22979 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22982 /// PerformMSTORECombine - Resolve truncating stores
22983 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22984 const X86Subtarget *Subtarget) {
22985 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22986 if (!Mst->isTruncatingStore())
22989 EVT VT = Mst->getValue().getValueType();
22990 unsigned NumElems = VT.getVectorNumElements();
22991 EVT StVT = Mst->getMemoryVT();
22994 assert(StVT != VT && "Cannot truncate to the same type");
22995 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22996 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22998 // From, To sizes and ElemCount must be pow of two
22999 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23000 "Unexpected size for truncating masked store");
23001 // We are going to use the original vector elt for storing.
23002 // Accumulated smaller vector elements must be a multiple of the store size.
23003 assert (((NumElems * FromSz) % ToSz) == 0 &&
23004 "Unexpected ratio for truncating masked store");
23006 unsigned SizeRatio = FromSz / ToSz;
23007 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23009 // Create a type on which we perform the shuffle
23010 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23011 StVT.getScalarType(), NumElems*SizeRatio);
23013 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23015 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23016 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23017 for (unsigned i = 0; i != NumElems; ++i)
23018 ShuffleVec[i] = i * SizeRatio;
23020 // Can't shuffle using an illegal type.
23021 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23022 && "WideVecVT should be legal");
23024 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23025 DAG.getUNDEF(WideVecVT),
23029 SDValue Mask = Mst->getMask();
23030 if (Mask.getValueType() == VT) {
23031 // Mask and original value have the same type
23032 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23033 for (unsigned i = 0; i != NumElems; ++i)
23034 ShuffleVec[i] = i * SizeRatio;
23035 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23036 ShuffleVec[i] = NumElems*SizeRatio;
23037 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23038 DAG.getConstant(0, dl, WideVecVT),
23042 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23043 unsigned WidenNumElts = NumElems*SizeRatio;
23044 unsigned MaskNumElts = VT.getVectorNumElements();
23045 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23048 unsigned NumConcat = WidenNumElts / MaskNumElts;
23049 SmallVector<SDValue, 16> Ops(NumConcat);
23050 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23052 for (unsigned i = 1; i != NumConcat; ++i)
23055 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23058 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23059 NewMask, StVT, Mst->getMemOperand(), false);
23061 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23062 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23063 const X86Subtarget *Subtarget) {
23064 StoreSDNode *St = cast<StoreSDNode>(N);
23065 EVT VT = St->getValue().getValueType();
23066 EVT StVT = St->getMemoryVT();
23068 SDValue StoredVal = St->getOperand(1);
23069 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23071 // If we are saving a concatenation of two XMM registers and 32-byte stores
23072 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23073 unsigned Alignment = St->getAlignment();
23074 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23075 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23076 StVT == VT && !IsAligned) {
23077 unsigned NumElems = VT.getVectorNumElements();
23081 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23082 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23084 SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23085 SDValue Ptr0 = St->getBasePtr();
23086 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23088 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23089 St->getPointerInfo(), St->isVolatile(),
23090 St->isNonTemporal(), Alignment);
23091 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23092 St->getPointerInfo(), St->isVolatile(),
23093 St->isNonTemporal(),
23094 std::min(16U, Alignment));
23095 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23098 // Optimize trunc store (of multiple scalars) to shuffle and store.
23099 // First, pack all of the elements in one place. Next, store to memory
23100 // in fewer chunks.
23101 if (St->isTruncatingStore() && VT.isVector()) {
23102 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23103 unsigned NumElems = VT.getVectorNumElements();
23104 assert(StVT != VT && "Cannot truncate to the same type");
23105 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23106 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23108 // From, To sizes and ElemCount must be pow of two
23109 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23110 // We are going to use the original vector elt for storing.
23111 // Accumulated smaller vector elements must be a multiple of the store size.
23112 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23114 unsigned SizeRatio = FromSz / ToSz;
23116 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23118 // Create a type on which we perform the shuffle
23119 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23120 StVT.getScalarType(), NumElems*SizeRatio);
23122 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23124 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23125 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23126 for (unsigned i = 0; i != NumElems; ++i)
23127 ShuffleVec[i] = i * SizeRatio;
23129 // Can't shuffle using an illegal type.
23130 if (!TLI.isTypeLegal(WideVecVT))
23133 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23134 DAG.getUNDEF(WideVecVT),
23136 // At this point all of the data is stored at the bottom of the
23137 // register. We now need to save it to mem.
23139 // Find the largest store unit
23140 MVT StoreType = MVT::i8;
23141 for (MVT Tp : MVT::integer_valuetypes()) {
23142 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23146 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23147 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23148 (64 <= NumElems * ToSz))
23149 StoreType = MVT::f64;
23151 // Bitcast the original vector into a vector of store-size units
23152 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23153 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23154 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23155 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23156 SmallVector<SDValue, 8> Chains;
23157 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23158 TLI.getPointerTy());
23159 SDValue Ptr = St->getBasePtr();
23161 // Perform one or more big stores into memory.
23162 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23163 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23164 StoreType, ShuffWide,
23165 DAG.getIntPtrConstant(i, dl));
23166 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23167 St->getPointerInfo(), St->isVolatile(),
23168 St->isNonTemporal(), St->getAlignment());
23169 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23170 Chains.push_back(Ch);
23173 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23176 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
23177 // the FP state in cases where an emms may be missing.
23178 // A preferable solution to the general problem is to figure out the right
23179 // places to insert EMMS. This qualifies as a quick hack.
23181 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23182 if (VT.getSizeInBits() != 64)
23185 const Function *F = DAG.getMachineFunction().getFunction();
23186 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23187 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
23188 && Subtarget->hasSSE2();
23189 if ((VT.isVector() ||
23190 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23191 isa<LoadSDNode>(St->getValue()) &&
23192 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23193 St->getChain().hasOneUse() && !St->isVolatile()) {
23194 SDNode* LdVal = St->getValue().getNode();
23195 LoadSDNode *Ld = nullptr;
23196 int TokenFactorIndex = -1;
23197 SmallVector<SDValue, 8> Ops;
23198 SDNode* ChainVal = St->getChain().getNode();
23199 // Must be a store of a load. We currently handle two cases: the load
23200 // is a direct child, and it's under an intervening TokenFactor. It is
23201 // possible to dig deeper under nested TokenFactors.
23202 if (ChainVal == LdVal)
23203 Ld = cast<LoadSDNode>(St->getChain());
23204 else if (St->getValue().hasOneUse() &&
23205 ChainVal->getOpcode() == ISD::TokenFactor) {
23206 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23207 if (ChainVal->getOperand(i).getNode() == LdVal) {
23208 TokenFactorIndex = i;
23209 Ld = cast<LoadSDNode>(St->getValue());
23211 Ops.push_back(ChainVal->getOperand(i));
23215 if (!Ld || !ISD::isNormalLoad(Ld))
23218 // If this is not the MMX case, i.e. we are just turning i64 load/store
23219 // into f64 load/store, avoid the transformation if there are multiple
23220 // uses of the loaded value.
23221 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23226 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23227 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23229 if (Subtarget->is64Bit() || F64IsLegal) {
23230 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23231 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23232 Ld->getPointerInfo(), Ld->isVolatile(),
23233 Ld->isNonTemporal(), Ld->isInvariant(),
23234 Ld->getAlignment());
23235 SDValue NewChain = NewLd.getValue(1);
23236 if (TokenFactorIndex != -1) {
23237 Ops.push_back(NewChain);
23238 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23240 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23241 St->getPointerInfo(),
23242 St->isVolatile(), St->isNonTemporal(),
23243 St->getAlignment());
23246 // Otherwise, lower to two pairs of 32-bit loads / stores.
23247 SDValue LoAddr = Ld->getBasePtr();
23248 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23249 DAG.getConstant(4, LdDL, MVT::i32));
23251 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23252 Ld->getPointerInfo(),
23253 Ld->isVolatile(), Ld->isNonTemporal(),
23254 Ld->isInvariant(), Ld->getAlignment());
23255 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23256 Ld->getPointerInfo().getWithOffset(4),
23257 Ld->isVolatile(), Ld->isNonTemporal(),
23259 MinAlign(Ld->getAlignment(), 4));
23261 SDValue NewChain = LoLd.getValue(1);
23262 if (TokenFactorIndex != -1) {
23263 Ops.push_back(LoLd);
23264 Ops.push_back(HiLd);
23265 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23268 LoAddr = St->getBasePtr();
23269 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23270 DAG.getConstant(4, StDL, MVT::i32));
23272 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23273 St->getPointerInfo(),
23274 St->isVolatile(), St->isNonTemporal(),
23275 St->getAlignment());
23276 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23277 St->getPointerInfo().getWithOffset(4),
23279 St->isNonTemporal(),
23280 MinAlign(St->getAlignment(), 4));
23281 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23284 // This is similar to the above case, but here we handle a scalar 64-bit
23285 // integer store that is extracted from a vector on a 32-bit target.
23286 // If we have SSE2, then we can treat it like a floating-point double
23287 // to get past legalization. The execution dependencies fixup pass will
23288 // choose the optimal machine instruction for the store if this really is
23289 // an integer or v2f32 rather than an f64.
23290 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23291 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23292 SDValue OldExtract = St->getOperand(1);
23293 SDValue ExtOp0 = OldExtract.getOperand(0);
23294 unsigned VecSize = ExtOp0.getValueSizeInBits();
23295 MVT VecVT = MVT::getVectorVT(MVT::f64, VecSize / 64);
23296 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23297 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23298 BitCast, OldExtract.getOperand(1));
23299 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23300 St->getPointerInfo(), St->isVolatile(),
23301 St->isNonTemporal(), St->getAlignment());
23307 /// Return 'true' if this vector operation is "horizontal"
23308 /// and return the operands for the horizontal operation in LHS and RHS. A
23309 /// horizontal operation performs the binary operation on successive elements
23310 /// of its first operand, then on successive elements of its second operand,
23311 /// returning the resulting values in a vector. For example, if
23312 /// A = < float a0, float a1, float a2, float a3 >
23314 /// B = < float b0, float b1, float b2, float b3 >
23315 /// then the result of doing a horizontal operation on A and B is
23316 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23317 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23318 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23319 /// set to A, RHS to B, and the routine returns 'true'.
23320 /// Note that the binary operation should have the property that if one of the
23321 /// operands is UNDEF then the result is UNDEF.
23322 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23323 // Look for the following pattern: if
23324 // A = < float a0, float a1, float a2, float a3 >
23325 // B = < float b0, float b1, float b2, float b3 >
23327 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23328 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23329 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23330 // which is A horizontal-op B.
23332 // At least one of the operands should be a vector shuffle.
23333 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23334 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23337 MVT VT = LHS.getSimpleValueType();
23339 assert((VT.is128BitVector() || VT.is256BitVector()) &&
23340 "Unsupported vector type for horizontal add/sub");
23342 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23343 // operate independently on 128-bit lanes.
23344 unsigned NumElts = VT.getVectorNumElements();
23345 unsigned NumLanes = VT.getSizeInBits()/128;
23346 unsigned NumLaneElts = NumElts / NumLanes;
23347 assert((NumLaneElts % 2 == 0) &&
23348 "Vector type should have an even number of elements in each lane");
23349 unsigned HalfLaneElts = NumLaneElts/2;
23351 // View LHS in the form
23352 // LHS = VECTOR_SHUFFLE A, B, LMask
23353 // If LHS is not a shuffle then pretend it is the shuffle
23354 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23355 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23358 SmallVector<int, 16> LMask(NumElts);
23359 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23360 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23361 A = LHS.getOperand(0);
23362 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23363 B = LHS.getOperand(1);
23364 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23365 std::copy(Mask.begin(), Mask.end(), LMask.begin());
23367 if (LHS.getOpcode() != ISD::UNDEF)
23369 for (unsigned i = 0; i != NumElts; ++i)
23373 // Likewise, view RHS in the form
23374 // RHS = VECTOR_SHUFFLE C, D, RMask
23376 SmallVector<int, 16> RMask(NumElts);
23377 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23378 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23379 C = RHS.getOperand(0);
23380 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23381 D = RHS.getOperand(1);
23382 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23383 std::copy(Mask.begin(), Mask.end(), RMask.begin());
23385 if (RHS.getOpcode() != ISD::UNDEF)
23387 for (unsigned i = 0; i != NumElts; ++i)
23391 // Check that the shuffles are both shuffling the same vectors.
23392 if (!(A == C && B == D) && !(A == D && B == C))
23395 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23396 if (!A.getNode() && !B.getNode())
23399 // If A and B occur in reverse order in RHS, then "swap" them (which means
23400 // rewriting the mask).
23402 ShuffleVectorSDNode::commuteMask(RMask);
23404 // At this point LHS and RHS are equivalent to
23405 // LHS = VECTOR_SHUFFLE A, B, LMask
23406 // RHS = VECTOR_SHUFFLE A, B, RMask
23407 // Check that the masks correspond to performing a horizontal operation.
23408 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23409 for (unsigned i = 0; i != NumLaneElts; ++i) {
23410 int LIdx = LMask[i+l], RIdx = RMask[i+l];
23412 // Ignore any UNDEF components.
23413 if (LIdx < 0 || RIdx < 0 ||
23414 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23415 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23418 // Check that successive elements are being operated on. If not, this is
23419 // not a horizontal operation.
23420 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23421 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23422 if (!(LIdx == Index && RIdx == Index + 1) &&
23423 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23428 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23429 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23433 /// Do target-specific dag combines on floating point adds.
23434 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23435 const X86Subtarget *Subtarget) {
23436 EVT VT = N->getValueType(0);
23437 SDValue LHS = N->getOperand(0);
23438 SDValue RHS = N->getOperand(1);
23440 // Try to synthesize horizontal adds from adds of shuffles.
23441 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23442 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23443 isHorizontalBinOp(LHS, RHS, true))
23444 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23448 /// Do target-specific dag combines on floating point subs.
23449 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23450 const X86Subtarget *Subtarget) {
23451 EVT VT = N->getValueType(0);
23452 SDValue LHS = N->getOperand(0);
23453 SDValue RHS = N->getOperand(1);
23455 // Try to synthesize horizontal subs from subs of shuffles.
23456 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23457 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23458 isHorizontalBinOp(LHS, RHS, false))
23459 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23463 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23464 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23465 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23467 // F[X]OR(0.0, x) -> x
23468 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23469 if (C->getValueAPF().isPosZero())
23470 return N->getOperand(1);
23472 // F[X]OR(x, 0.0) -> x
23473 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23474 if (C->getValueAPF().isPosZero())
23475 return N->getOperand(0);
23479 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23480 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23481 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23483 // Only perform optimizations if UnsafeMath is used.
23484 if (!DAG.getTarget().Options.UnsafeFPMath)
23487 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23488 // into FMINC and FMAXC, which are Commutative operations.
23489 unsigned NewOp = 0;
23490 switch (N->getOpcode()) {
23491 default: llvm_unreachable("unknown opcode");
23492 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
23493 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
23496 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23497 N->getOperand(0), N->getOperand(1));
23500 /// Do target-specific dag combines on X86ISD::FAND nodes.
23501 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23502 // FAND(0.0, x) -> 0.0
23503 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23504 if (C->getValueAPF().isPosZero())
23505 return N->getOperand(0);
23507 // FAND(x, 0.0) -> 0.0
23508 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23509 if (C->getValueAPF().isPosZero())
23510 return N->getOperand(1);
23515 /// Do target-specific dag combines on X86ISD::FANDN nodes
23516 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23517 // FANDN(0.0, x) -> x
23518 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23519 if (C->getValueAPF().isPosZero())
23520 return N->getOperand(1);
23522 // FANDN(x, 0.0) -> 0.0
23523 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23524 if (C->getValueAPF().isPosZero())
23525 return N->getOperand(1);
23530 static SDValue PerformBTCombine(SDNode *N,
23532 TargetLowering::DAGCombinerInfo &DCI) {
23533 // BT ignores high bits in the bit index operand.
23534 SDValue Op1 = N->getOperand(1);
23535 if (Op1.hasOneUse()) {
23536 unsigned BitWidth = Op1.getValueSizeInBits();
23537 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23538 APInt KnownZero, KnownOne;
23539 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23540 !DCI.isBeforeLegalizeOps());
23541 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23542 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23543 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23544 DCI.CommitTargetLoweringOpt(TLO);
23549 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23550 SDValue Op = N->getOperand(0);
23551 if (Op.getOpcode() == ISD::BITCAST)
23552 Op = Op.getOperand(0);
23553 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23554 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23555 VT.getVectorElementType().getSizeInBits() ==
23556 OpVT.getVectorElementType().getSizeInBits()) {
23557 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23562 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23563 const X86Subtarget *Subtarget) {
23564 EVT VT = N->getValueType(0);
23565 if (!VT.isVector())
23568 SDValue N0 = N->getOperand(0);
23569 SDValue N1 = N->getOperand(1);
23570 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23573 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23574 // both SSE and AVX2 since there is no sign-extended shift right
23575 // operation on a vector with 64-bit elements.
23576 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23577 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23578 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23579 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23580 SDValue N00 = N0.getOperand(0);
23582 // EXTLOAD has a better solution on AVX2,
23583 // it may be replaced with X86ISD::VSEXT node.
23584 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23585 if (!ISD::isNormalLoad(N00.getNode()))
23588 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23589 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23591 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23597 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23598 TargetLowering::DAGCombinerInfo &DCI,
23599 const X86Subtarget *Subtarget) {
23600 SDValue N0 = N->getOperand(0);
23601 EVT VT = N->getValueType(0);
23603 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23604 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23605 // This exposes the sext to the sdivrem lowering, so that it directly extends
23606 // from AH (which we otherwise need to do contortions to access).
23607 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23608 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23610 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23611 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23612 N0.getOperand(0), N0.getOperand(1));
23613 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23614 return R.getValue(1);
23617 if (!DCI.isBeforeLegalizeOps())
23620 if (!Subtarget->hasFp256())
23623 if (VT.isVector() && VT.getSizeInBits() == 256) {
23624 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23632 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23633 const X86Subtarget* Subtarget) {
23635 EVT VT = N->getValueType(0);
23637 // Let legalize expand this if it isn't a legal type yet.
23638 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23641 EVT ScalarVT = VT.getScalarType();
23642 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23643 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23646 SDValue A = N->getOperand(0);
23647 SDValue B = N->getOperand(1);
23648 SDValue C = N->getOperand(2);
23650 bool NegA = (A.getOpcode() == ISD::FNEG);
23651 bool NegB = (B.getOpcode() == ISD::FNEG);
23652 bool NegC = (C.getOpcode() == ISD::FNEG);
23654 // Negative multiplication when NegA xor NegB
23655 bool NegMul = (NegA != NegB);
23657 A = A.getOperand(0);
23659 B = B.getOperand(0);
23661 C = C.getOperand(0);
23665 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23667 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23669 return DAG.getNode(Opcode, dl, VT, A, B, C);
23672 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23673 TargetLowering::DAGCombinerInfo &DCI,
23674 const X86Subtarget *Subtarget) {
23675 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23676 // (and (i32 x86isd::setcc_carry), 1)
23677 // This eliminates the zext. This transformation is necessary because
23678 // ISD::SETCC is always legalized to i8.
23680 SDValue N0 = N->getOperand(0);
23681 EVT VT = N->getValueType(0);
23683 if (N0.getOpcode() == ISD::AND &&
23685 N0.getOperand(0).hasOneUse()) {
23686 SDValue N00 = N0.getOperand(0);
23687 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23688 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23689 if (!C || C->getZExtValue() != 1)
23691 return DAG.getNode(ISD::AND, dl, VT,
23692 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23693 N00.getOperand(0), N00.getOperand(1)),
23694 DAG.getConstant(1, dl, VT));
23698 if (N0.getOpcode() == ISD::TRUNCATE &&
23700 N0.getOperand(0).hasOneUse()) {
23701 SDValue N00 = N0.getOperand(0);
23702 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23703 return DAG.getNode(ISD::AND, dl, VT,
23704 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23705 N00.getOperand(0), N00.getOperand(1)),
23706 DAG.getConstant(1, dl, VT));
23709 if (VT.is256BitVector()) {
23710 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23715 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23716 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23717 // This exposes the zext to the udivrem lowering, so that it directly extends
23718 // from AH (which we otherwise need to do contortions to access).
23719 if (N0.getOpcode() == ISD::UDIVREM &&
23720 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23721 (VT == MVT::i32 || VT == MVT::i64)) {
23722 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23723 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23724 N0.getOperand(0), N0.getOperand(1));
23725 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23726 return R.getValue(1);
23732 // Optimize x == -y --> x+y == 0
23733 // x != -y --> x+y != 0
23734 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23735 const X86Subtarget* Subtarget) {
23736 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23737 SDValue LHS = N->getOperand(0);
23738 SDValue RHS = N->getOperand(1);
23739 EVT VT = N->getValueType(0);
23742 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23743 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23744 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23745 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23746 LHS.getOperand(1));
23747 return DAG.getSetCC(DL, N->getValueType(0), addV,
23748 DAG.getConstant(0, DL, addV.getValueType()), CC);
23750 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23751 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23752 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23753 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23754 RHS.getOperand(1));
23755 return DAG.getSetCC(DL, N->getValueType(0), addV,
23756 DAG.getConstant(0, DL, addV.getValueType()), CC);
23759 if (VT.getScalarType() == MVT::i1 &&
23760 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23762 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23763 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23764 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23766 if (!IsSEXT0 || !IsVZero1) {
23767 // Swap the operands and update the condition code.
23768 std::swap(LHS, RHS);
23769 CC = ISD::getSetCCSwappedOperands(CC);
23771 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23772 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23773 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23776 if (IsSEXT0 && IsVZero1) {
23777 assert(VT == LHS.getOperand(0).getValueType() &&
23778 "Uexpected operand type");
23779 if (CC == ISD::SETGT)
23780 return DAG.getConstant(0, DL, VT);
23781 if (CC == ISD::SETLE)
23782 return DAG.getConstant(1, DL, VT);
23783 if (CC == ISD::SETEQ || CC == ISD::SETGE)
23784 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23786 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23787 "Unexpected condition code!");
23788 return LHS.getOperand(0);
23795 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23796 SelectionDAG &DAG) {
23798 MVT VT = Load->getSimpleValueType(0);
23799 MVT EVT = VT.getVectorElementType();
23800 SDValue Addr = Load->getOperand(1);
23801 SDValue NewAddr = DAG.getNode(
23802 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23803 DAG.getConstant(Index * EVT.getStoreSize(), dl,
23804 Addr.getSimpleValueType()));
23807 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23808 DAG.getMachineFunction().getMachineMemOperand(
23809 Load->getMemOperand(), 0, EVT.getStoreSize()));
23813 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23814 const X86Subtarget *Subtarget) {
23816 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23817 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23818 "X86insertps is only defined for v4x32");
23820 SDValue Ld = N->getOperand(1);
23821 if (MayFoldLoad(Ld)) {
23822 // Extract the countS bits from the immediate so we can get the proper
23823 // address when narrowing the vector load to a specific element.
23824 // When the second source op is a memory address, insertps doesn't use
23825 // countS and just gets an f32 from that address.
23826 unsigned DestIndex =
23827 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23829 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23831 // Create this as a scalar to vector to match the instruction pattern.
23832 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23833 // countS bits are ignored when loading from memory on insertps, which
23834 // means we don't need to explicitly set them to 0.
23835 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23836 LoadScalarToVector, N->getOperand(2));
23841 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23842 SDValue V0 = N->getOperand(0);
23843 SDValue V1 = N->getOperand(1);
23845 EVT VT = N->getValueType(0);
23847 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23848 // operands and changing the mask to 1. This saves us a bunch of
23849 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23850 // x86InstrInfo knows how to commute this back after instruction selection
23851 // if it would help register allocation.
23853 // TODO: If optimizing for size or a processor that doesn't suffer from
23854 // partial register update stalls, this should be transformed into a MOVSD
23855 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23857 if (VT == MVT::v2f64)
23858 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23859 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23860 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23861 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23867 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23868 // as "sbb reg,reg", since it can be extended without zext and produces
23869 // an all-ones bit which is more useful than 0/1 in some cases.
23870 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23873 return DAG.getNode(ISD::AND, DL, VT,
23874 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23875 DAG.getConstant(X86::COND_B, DL, MVT::i8),
23877 DAG.getConstant(1, DL, VT));
23878 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23879 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23880 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23881 DAG.getConstant(X86::COND_B, DL, MVT::i8),
23885 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23886 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23887 TargetLowering::DAGCombinerInfo &DCI,
23888 const X86Subtarget *Subtarget) {
23890 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23891 SDValue EFLAGS = N->getOperand(1);
23893 if (CC == X86::COND_A) {
23894 // Try to convert COND_A into COND_B in an attempt to facilitate
23895 // materializing "setb reg".
23897 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23898 // cannot take an immediate as its first operand.
23900 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23901 EFLAGS.getValueType().isInteger() &&
23902 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23903 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23904 EFLAGS.getNode()->getVTList(),
23905 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23906 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23907 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23911 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23912 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23914 if (CC == X86::COND_B)
23915 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23919 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23920 if (Flags.getNode()) {
23921 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23922 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23928 // Optimize branch condition evaluation.
23930 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23931 TargetLowering::DAGCombinerInfo &DCI,
23932 const X86Subtarget *Subtarget) {
23934 SDValue Chain = N->getOperand(0);
23935 SDValue Dest = N->getOperand(1);
23936 SDValue EFLAGS = N->getOperand(3);
23937 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23941 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23942 if (Flags.getNode()) {
23943 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23944 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23951 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23952 SelectionDAG &DAG) {
23953 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23954 // optimize away operation when it's from a constant.
23956 // The general transformation is:
23957 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23958 // AND(VECTOR_CMP(x,y), constant2)
23959 // constant2 = UNARYOP(constant)
23961 // Early exit if this isn't a vector operation, the operand of the
23962 // unary operation isn't a bitwise AND, or if the sizes of the operations
23963 // aren't the same.
23964 EVT VT = N->getValueType(0);
23965 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23966 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23967 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23970 // Now check that the other operand of the AND is a constant. We could
23971 // make the transformation for non-constant splats as well, but it's unclear
23972 // that would be a benefit as it would not eliminate any operations, just
23973 // perform one more step in scalar code before moving to the vector unit.
23974 if (BuildVectorSDNode *BV =
23975 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23976 // Bail out if the vector isn't a constant.
23977 if (!BV->isConstant())
23980 // Everything checks out. Build up the new and improved node.
23982 EVT IntVT = BV->getValueType(0);
23983 // Create a new constant of the appropriate type for the transformed
23985 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23986 // The AND node needs bitcasts to/from an integer vector type around it.
23987 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23988 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23989 N->getOperand(0)->getOperand(0), MaskConst);
23990 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23997 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23998 const X86Subtarget *Subtarget) {
23999 // First try to optimize away the conversion entirely when it's
24000 // conditionally from a constant. Vectors only.
24001 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24002 if (Res != SDValue())
24005 // Now move on to more general possibilities.
24006 SDValue Op0 = N->getOperand(0);
24007 EVT InVT = Op0->getValueType(0);
24009 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24010 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24012 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24013 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24014 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24017 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24018 // a 32-bit target where SSE doesn't support i64->FP operations.
24019 if (Op0.getOpcode() == ISD::LOAD) {
24020 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24021 EVT VT = Ld->getValueType(0);
24022 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24023 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24024 !Subtarget->is64Bit() && VT == MVT::i64) {
24025 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24026 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24027 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24034 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24035 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24036 X86TargetLowering::DAGCombinerInfo &DCI) {
24037 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24038 // the result is either zero or one (depending on the input carry bit).
24039 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24040 if (X86::isZeroNode(N->getOperand(0)) &&
24041 X86::isZeroNode(N->getOperand(1)) &&
24042 // We don't have a good way to replace an EFLAGS use, so only do this when
24044 SDValue(N, 1).use_empty()) {
24046 EVT VT = N->getValueType(0);
24047 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24048 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24049 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24050 DAG.getConstant(X86::COND_B, DL,
24053 DAG.getConstant(1, DL, VT));
24054 return DCI.CombineTo(N, Res1, CarryOut);
24060 // fold (add Y, (sete X, 0)) -> adc 0, Y
24061 // (add Y, (setne X, 0)) -> sbb -1, Y
24062 // (sub (sete X, 0), Y) -> sbb 0, Y
24063 // (sub (setne X, 0), Y) -> adc -1, Y
24064 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24067 // Look through ZExts.
24068 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24069 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24072 SDValue SetCC = Ext.getOperand(0);
24073 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24076 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24077 if (CC != X86::COND_E && CC != X86::COND_NE)
24080 SDValue Cmp = SetCC.getOperand(1);
24081 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24082 !X86::isZeroNode(Cmp.getOperand(1)) ||
24083 !Cmp.getOperand(0).getValueType().isInteger())
24086 SDValue CmpOp0 = Cmp.getOperand(0);
24087 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24088 DAG.getConstant(1, DL, CmpOp0.getValueType()));
24090 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24091 if (CC == X86::COND_NE)
24092 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24093 DL, OtherVal.getValueType(), OtherVal,
24094 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24096 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24097 DL, OtherVal.getValueType(), OtherVal,
24098 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24101 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24102 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24103 const X86Subtarget *Subtarget) {
24104 EVT VT = N->getValueType(0);
24105 SDValue Op0 = N->getOperand(0);
24106 SDValue Op1 = N->getOperand(1);
24108 // Try to synthesize horizontal adds from adds of shuffles.
24109 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24110 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24111 isHorizontalBinOp(Op0, Op1, true))
24112 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24114 return OptimizeConditionalInDecrement(N, DAG);
24117 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24118 const X86Subtarget *Subtarget) {
24119 SDValue Op0 = N->getOperand(0);
24120 SDValue Op1 = N->getOperand(1);
24122 // X86 can't encode an immediate LHS of a sub. See if we can push the
24123 // negation into a preceding instruction.
24124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24125 // If the RHS of the sub is a XOR with one use and a constant, invert the
24126 // immediate. Then add one to the LHS of the sub so we can turn
24127 // X-Y -> X+~Y+1, saving one register.
24128 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24129 isa<ConstantSDNode>(Op1.getOperand(1))) {
24130 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24131 EVT VT = Op0.getValueType();
24132 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24134 DAG.getConstant(~XorC, SDLoc(Op1), VT));
24135 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24136 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24140 // Try to synthesize horizontal adds from adds of shuffles.
24141 EVT VT = N->getValueType(0);
24142 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24143 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24144 isHorizontalBinOp(Op0, Op1, true))
24145 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24147 return OptimizeConditionalInDecrement(N, DAG);
24150 /// performVZEXTCombine - Performs build vector combines
24151 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24152 TargetLowering::DAGCombinerInfo &DCI,
24153 const X86Subtarget *Subtarget) {
24155 MVT VT = N->getSimpleValueType(0);
24156 SDValue Op = N->getOperand(0);
24157 MVT OpVT = Op.getSimpleValueType();
24158 MVT OpEltVT = OpVT.getVectorElementType();
24159 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24161 // (vzext (bitcast (vzext (x)) -> (vzext x)
24163 while (V.getOpcode() == ISD::BITCAST)
24164 V = V.getOperand(0);
24166 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24167 MVT InnerVT = V.getSimpleValueType();
24168 MVT InnerEltVT = InnerVT.getVectorElementType();
24170 // If the element sizes match exactly, we can just do one larger vzext. This
24171 // is always an exact type match as vzext operates on integer types.
24172 if (OpEltVT == InnerEltVT) {
24173 assert(OpVT == InnerVT && "Types must match for vzext!");
24174 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24177 // The only other way we can combine them is if only a single element of the
24178 // inner vzext is used in the input to the outer vzext.
24179 if (InnerEltVT.getSizeInBits() < InputBits)
24182 // In this case, the inner vzext is completely dead because we're going to
24183 // only look at bits inside of the low element. Just do the outer vzext on
24184 // a bitcast of the input to the inner.
24185 return DAG.getNode(X86ISD::VZEXT, DL, VT,
24186 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24189 // Check if we can bypass extracting and re-inserting an element of an input
24190 // vector. Essentialy:
24191 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24192 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24193 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24194 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24195 SDValue ExtractedV = V.getOperand(0);
24196 SDValue OrigV = ExtractedV.getOperand(0);
24197 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24198 if (ExtractIdx->getZExtValue() == 0) {
24199 MVT OrigVT = OrigV.getSimpleValueType();
24200 // Extract a subvector if necessary...
24201 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24202 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24203 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24204 OrigVT.getVectorNumElements() / Ratio);
24205 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24206 DAG.getIntPtrConstant(0, DL));
24208 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24209 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24216 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24217 DAGCombinerInfo &DCI) const {
24218 SelectionDAG &DAG = DCI.DAG;
24219 switch (N->getOpcode()) {
24221 case ISD::EXTRACT_VECTOR_ELT:
24222 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24225 case X86ISD::SHRUNKBLEND:
24226 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24227 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
24228 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24229 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
24230 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
24231 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
24232 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
24235 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
24236 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
24237 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
24238 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
24239 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
24240 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24241 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
24242 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
24243 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24244 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
24245 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
24247 case X86ISD::FOR: return PerformFORCombine(N, DAG);
24249 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
24250 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
24251 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
24252 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
24253 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
24254 case ISD::ANY_EXTEND:
24255 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
24256 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
24257 case ISD::SIGN_EXTEND_INREG:
24258 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24259 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24260 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
24261 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24262 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24263 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
24264 case X86ISD::SHUFP: // Handle all target specific shuffles
24265 case X86ISD::PALIGNR:
24266 case X86ISD::UNPCKH:
24267 case X86ISD::UNPCKL:
24268 case X86ISD::MOVHLPS:
24269 case X86ISD::MOVLHPS:
24270 case X86ISD::PSHUFB:
24271 case X86ISD::PSHUFD:
24272 case X86ISD::PSHUFHW:
24273 case X86ISD::PSHUFLW:
24274 case X86ISD::MOVSS:
24275 case X86ISD::MOVSD:
24276 case X86ISD::VPERMILPI:
24277 case X86ISD::VPERM2X128:
24278 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24279 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
24280 case ISD::INTRINSIC_WO_CHAIN:
24281 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24282 case X86ISD::INSERTPS: {
24283 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24284 return PerformINSERTPSCombine(N, DAG, Subtarget);
24287 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
24293 /// isTypeDesirableForOp - Return true if the target has native support for
24294 /// the specified value type and it is 'desirable' to use the type for the
24295 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24296 /// instruction encodings are longer and some i16 instructions are slow.
24297 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24298 if (!isTypeLegal(VT))
24300 if (VT != MVT::i16)
24307 case ISD::SIGN_EXTEND:
24308 case ISD::ZERO_EXTEND:
24309 case ISD::ANY_EXTEND:
24322 /// IsDesirableToPromoteOp - This method query the target whether it is
24323 /// beneficial for dag combiner to promote the specified node. If true, it
24324 /// should return the desired promotion type by reference.
24325 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24326 EVT VT = Op.getValueType();
24327 if (VT != MVT::i16)
24330 bool Promote = false;
24331 bool Commute = false;
24332 switch (Op.getOpcode()) {
24335 LoadSDNode *LD = cast<LoadSDNode>(Op);
24336 // If the non-extending load has a single use and it's not live out, then it
24337 // might be folded.
24338 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24339 Op.hasOneUse()*/) {
24340 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24341 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24342 // The only case where we'd want to promote LOAD (rather then it being
24343 // promoted as an operand is when it's only use is liveout.
24344 if (UI->getOpcode() != ISD::CopyToReg)
24351 case ISD::SIGN_EXTEND:
24352 case ISD::ZERO_EXTEND:
24353 case ISD::ANY_EXTEND:
24358 SDValue N0 = Op.getOperand(0);
24359 // Look out for (store (shl (load), x)).
24360 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24373 SDValue N0 = Op.getOperand(0);
24374 SDValue N1 = Op.getOperand(1);
24375 if (!Commute && MayFoldLoad(N1))
24377 // Avoid disabling potential load folding opportunities.
24378 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24380 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24390 //===----------------------------------------------------------------------===//
24391 // X86 Inline Assembly Support
24392 //===----------------------------------------------------------------------===//
24394 // Helper to match a string separated by whitespace.
24395 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24396 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24398 for (StringRef Piece : Pieces) {
24399 if (!S.startswith(Piece)) // Check if the piece matches.
24402 S = S.substr(Piece.size());
24403 StringRef::size_type Pos = S.find_first_not_of(" \t");
24404 if (Pos == 0) // We matched a prefix.
24413 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24415 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24416 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24417 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24418 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24420 if (AsmPieces.size() == 3)
24422 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24429 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24430 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24432 std::string AsmStr = IA->getAsmString();
24434 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24435 if (!Ty || Ty->getBitWidth() % 16 != 0)
24438 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24439 SmallVector<StringRef, 4> AsmPieces;
24440 SplitString(AsmStr, AsmPieces, ";\n");
24442 switch (AsmPieces.size()) {
24443 default: return false;
24445 // FIXME: this should verify that we are targeting a 486 or better. If not,
24446 // we will turn this bswap into something that will be lowered to logical
24447 // ops instead of emitting the bswap asm. For now, we don't support 486 or
24448 // lower so don't worry about this.
24450 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24451 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24452 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24453 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24454 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24455 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24456 // No need to check constraints, nothing other than the equivalent of
24457 // "=r,0" would be valid here.
24458 return IntrinsicLowering::LowerToByteSwap(CI);
24461 // rorw $$8, ${0:w} --> llvm.bswap.i16
24462 if (CI->getType()->isIntegerTy(16) &&
24463 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24464 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24465 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24467 const std::string &ConstraintsStr = IA->getConstraintString();
24468 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24469 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24470 if (clobbersFlagRegisters(AsmPieces))
24471 return IntrinsicLowering::LowerToByteSwap(CI);
24475 if (CI->getType()->isIntegerTy(32) &&
24476 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24477 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24478 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24479 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24481 const std::string &ConstraintsStr = IA->getConstraintString();
24482 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24483 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24484 if (clobbersFlagRegisters(AsmPieces))
24485 return IntrinsicLowering::LowerToByteSwap(CI);
24488 if (CI->getType()->isIntegerTy(64)) {
24489 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24490 if (Constraints.size() >= 2 &&
24491 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24492 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24493 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
24494 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24495 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24496 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24497 return IntrinsicLowering::LowerToByteSwap(CI);
24505 /// getConstraintType - Given a constraint letter, return the type of
24506 /// constraint it is for this target.
24507 X86TargetLowering::ConstraintType
24508 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24509 if (Constraint.size() == 1) {
24510 switch (Constraint[0]) {
24521 return C_RegisterClass;
24545 return TargetLowering::getConstraintType(Constraint);
24548 /// Examine constraint type and operand type and determine a weight value.
24549 /// This object must already have been set up with the operand type
24550 /// and the current alternative constraint selected.
24551 TargetLowering::ConstraintWeight
24552 X86TargetLowering::getSingleConstraintMatchWeight(
24553 AsmOperandInfo &info, const char *constraint) const {
24554 ConstraintWeight weight = CW_Invalid;
24555 Value *CallOperandVal = info.CallOperandVal;
24556 // If we don't have a value, we can't do a match,
24557 // but allow it at the lowest weight.
24558 if (!CallOperandVal)
24560 Type *type = CallOperandVal->getType();
24561 // Look at the constraint type.
24562 switch (*constraint) {
24564 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24575 if (CallOperandVal->getType()->isIntegerTy())
24576 weight = CW_SpecificReg;
24581 if (type->isFloatingPointTy())
24582 weight = CW_SpecificReg;
24585 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24586 weight = CW_SpecificReg;
24590 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24591 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24592 weight = CW_Register;
24595 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24596 if (C->getZExtValue() <= 31)
24597 weight = CW_Constant;
24601 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24602 if (C->getZExtValue() <= 63)
24603 weight = CW_Constant;
24607 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24608 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24609 weight = CW_Constant;
24613 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24614 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24615 weight = CW_Constant;
24619 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24620 if (C->getZExtValue() <= 3)
24621 weight = CW_Constant;
24625 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24626 if (C->getZExtValue() <= 0xff)
24627 weight = CW_Constant;
24632 if (isa<ConstantFP>(CallOperandVal)) {
24633 weight = CW_Constant;
24637 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24638 if ((C->getSExtValue() >= -0x80000000LL) &&
24639 (C->getSExtValue() <= 0x7fffffffLL))
24640 weight = CW_Constant;
24644 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24645 if (C->getZExtValue() <= 0xffffffff)
24646 weight = CW_Constant;
24653 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24654 /// with another that has more specific requirements based on the type of the
24655 /// corresponding operand.
24656 const char *X86TargetLowering::
24657 LowerXConstraint(EVT ConstraintVT) const {
24658 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24659 // 'f' like normal targets.
24660 if (ConstraintVT.isFloatingPoint()) {
24661 if (Subtarget->hasSSE2())
24663 if (Subtarget->hasSSE1())
24667 return TargetLowering::LowerXConstraint(ConstraintVT);
24670 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24671 /// vector. If it is invalid, don't add anything to Ops.
24672 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24673 std::string &Constraint,
24674 std::vector<SDValue>&Ops,
24675 SelectionDAG &DAG) const {
24678 // Only support length 1 constraints for now.
24679 if (Constraint.length() > 1) return;
24681 char ConstraintLetter = Constraint[0];
24682 switch (ConstraintLetter) {
24685 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24686 if (C->getZExtValue() <= 31) {
24687 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24688 Op.getValueType());
24694 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24695 if (C->getZExtValue() <= 63) {
24696 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24697 Op.getValueType());
24703 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24704 if (isInt<8>(C->getSExtValue())) {
24705 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24706 Op.getValueType());
24712 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24713 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24714 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24715 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24716 Op.getValueType());
24722 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24723 if (C->getZExtValue() <= 3) {
24724 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24725 Op.getValueType());
24731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24732 if (C->getZExtValue() <= 255) {
24733 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24734 Op.getValueType());
24740 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24741 if (C->getZExtValue() <= 127) {
24742 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24743 Op.getValueType());
24749 // 32-bit signed value
24750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24751 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24752 C->getSExtValue())) {
24753 // Widen to 64 bits here to get it sign extended.
24754 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24757 // FIXME gcc accepts some relocatable values here too, but only in certain
24758 // memory models; it's complicated.
24763 // 32-bit unsigned value
24764 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24765 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24766 C->getZExtValue())) {
24767 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24768 Op.getValueType());
24772 // FIXME gcc accepts some relocatable values here too, but only in certain
24773 // memory models; it's complicated.
24777 // Literal immediates are always ok.
24778 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24779 // Widen to 64 bits here to get it sign extended.
24780 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24784 // In any sort of PIC mode addresses need to be computed at runtime by
24785 // adding in a register or some sort of table lookup. These can't
24786 // be used as immediates.
24787 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24790 // If we are in non-pic codegen mode, we allow the address of a global (with
24791 // an optional displacement) to be used with 'i'.
24792 GlobalAddressSDNode *GA = nullptr;
24793 int64_t Offset = 0;
24795 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24797 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24798 Offset += GA->getOffset();
24800 } else if (Op.getOpcode() == ISD::ADD) {
24801 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24802 Offset += C->getZExtValue();
24803 Op = Op.getOperand(0);
24806 } else if (Op.getOpcode() == ISD::SUB) {
24807 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24808 Offset += -C->getZExtValue();
24809 Op = Op.getOperand(0);
24814 // Otherwise, this isn't something we can handle, reject it.
24818 const GlobalValue *GV = GA->getGlobal();
24819 // If we require an extra load to get this address, as in PIC mode, we
24820 // can't accept it.
24821 if (isGlobalStubReference(
24822 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24825 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24826 GA->getValueType(0), Offset);
24831 if (Result.getNode()) {
24832 Ops.push_back(Result);
24835 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24838 std::pair<unsigned, const TargetRegisterClass *>
24839 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24840 const std::string &Constraint,
24842 // First, see if this is a constraint that directly corresponds to an LLVM
24844 if (Constraint.size() == 1) {
24845 // GCC Constraint Letters
24846 switch (Constraint[0]) {
24848 // TODO: Slight differences here in allocation order and leaving
24849 // RIP in the class. Do they matter any more here than they do
24850 // in the normal allocation?
24851 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24852 if (Subtarget->is64Bit()) {
24853 if (VT == MVT::i32 || VT == MVT::f32)
24854 return std::make_pair(0U, &X86::GR32RegClass);
24855 if (VT == MVT::i16)
24856 return std::make_pair(0U, &X86::GR16RegClass);
24857 if (VT == MVT::i8 || VT == MVT::i1)
24858 return std::make_pair(0U, &X86::GR8RegClass);
24859 if (VT == MVT::i64 || VT == MVT::f64)
24860 return std::make_pair(0U, &X86::GR64RegClass);
24863 // 32-bit fallthrough
24864 case 'Q': // Q_REGS
24865 if (VT == MVT::i32 || VT == MVT::f32)
24866 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24867 if (VT == MVT::i16)
24868 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24869 if (VT == MVT::i8 || VT == MVT::i1)
24870 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24871 if (VT == MVT::i64)
24872 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24874 case 'r': // GENERAL_REGS
24875 case 'l': // INDEX_REGS
24876 if (VT == MVT::i8 || VT == MVT::i1)
24877 return std::make_pair(0U, &X86::GR8RegClass);
24878 if (VT == MVT::i16)
24879 return std::make_pair(0U, &X86::GR16RegClass);
24880 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24881 return std::make_pair(0U, &X86::GR32RegClass);
24882 return std::make_pair(0U, &X86::GR64RegClass);
24883 case 'R': // LEGACY_REGS
24884 if (VT == MVT::i8 || VT == MVT::i1)
24885 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24886 if (VT == MVT::i16)
24887 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24888 if (VT == MVT::i32 || !Subtarget->is64Bit())
24889 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24890 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24891 case 'f': // FP Stack registers.
24892 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24893 // value to the correct fpstack register class.
24894 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24895 return std::make_pair(0U, &X86::RFP32RegClass);
24896 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24897 return std::make_pair(0U, &X86::RFP64RegClass);
24898 return std::make_pair(0U, &X86::RFP80RegClass);
24899 case 'y': // MMX_REGS if MMX allowed.
24900 if (!Subtarget->hasMMX()) break;
24901 return std::make_pair(0U, &X86::VR64RegClass);
24902 case 'Y': // SSE_REGS if SSE2 allowed
24903 if (!Subtarget->hasSSE2()) break;
24905 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24906 if (!Subtarget->hasSSE1()) break;
24908 switch (VT.SimpleTy) {
24910 // Scalar SSE types.
24913 return std::make_pair(0U, &X86::FR32RegClass);
24916 return std::make_pair(0U, &X86::FR64RegClass);
24924 return std::make_pair(0U, &X86::VR128RegClass);
24932 return std::make_pair(0U, &X86::VR256RegClass);
24937 return std::make_pair(0U, &X86::VR512RegClass);
24943 // Use the default implementation in TargetLowering to convert the register
24944 // constraint into a member of a register class.
24945 std::pair<unsigned, const TargetRegisterClass*> Res;
24946 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24948 // Not found as a standard register?
24950 // Map st(0) -> st(7) -> ST0
24951 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24952 tolower(Constraint[1]) == 's' &&
24953 tolower(Constraint[2]) == 't' &&
24954 Constraint[3] == '(' &&
24955 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24956 Constraint[5] == ')' &&
24957 Constraint[6] == '}') {
24959 Res.first = X86::FP0+Constraint[4]-'0';
24960 Res.second = &X86::RFP80RegClass;
24964 // GCC allows "st(0)" to be called just plain "st".
24965 if (StringRef("{st}").equals_lower(Constraint)) {
24966 Res.first = X86::FP0;
24967 Res.second = &X86::RFP80RegClass;
24972 if (StringRef("{flags}").equals_lower(Constraint)) {
24973 Res.first = X86::EFLAGS;
24974 Res.second = &X86::CCRRegClass;
24978 // 'A' means EAX + EDX.
24979 if (Constraint == "A") {
24980 Res.first = X86::EAX;
24981 Res.second = &X86::GR32_ADRegClass;
24987 // Otherwise, check to see if this is a register class of the wrong value
24988 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24989 // turn into {ax},{dx}.
24990 if (Res.second->hasType(VT))
24991 return Res; // Correct type already, nothing to do.
24993 // All of the single-register GCC register classes map their values onto
24994 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
24995 // really want an 8-bit or 32-bit register, map to the appropriate register
24996 // class and return the appropriate register.
24997 if (Res.second == &X86::GR16RegClass) {
24998 if (VT == MVT::i8 || VT == MVT::i1) {
24999 unsigned DestReg = 0;
25000 switch (Res.first) {
25002 case X86::AX: DestReg = X86::AL; break;
25003 case X86::DX: DestReg = X86::DL; break;
25004 case X86::CX: DestReg = X86::CL; break;
25005 case X86::BX: DestReg = X86::BL; break;
25008 Res.first = DestReg;
25009 Res.second = &X86::GR8RegClass;
25011 } else if (VT == MVT::i32 || VT == MVT::f32) {
25012 unsigned DestReg = 0;
25013 switch (Res.first) {
25015 case X86::AX: DestReg = X86::EAX; break;
25016 case X86::DX: DestReg = X86::EDX; break;
25017 case X86::CX: DestReg = X86::ECX; break;
25018 case X86::BX: DestReg = X86::EBX; break;
25019 case X86::SI: DestReg = X86::ESI; break;
25020 case X86::DI: DestReg = X86::EDI; break;
25021 case X86::BP: DestReg = X86::EBP; break;
25022 case X86::SP: DestReg = X86::ESP; break;
25025 Res.first = DestReg;
25026 Res.second = &X86::GR32RegClass;
25028 } else if (VT == MVT::i64 || VT == MVT::f64) {
25029 unsigned DestReg = 0;
25030 switch (Res.first) {
25032 case X86::AX: DestReg = X86::RAX; break;
25033 case X86::DX: DestReg = X86::RDX; break;
25034 case X86::CX: DestReg = X86::RCX; break;
25035 case X86::BX: DestReg = X86::RBX; break;
25036 case X86::SI: DestReg = X86::RSI; break;
25037 case X86::DI: DestReg = X86::RDI; break;
25038 case X86::BP: DestReg = X86::RBP; break;
25039 case X86::SP: DestReg = X86::RSP; break;
25042 Res.first = DestReg;
25043 Res.second = &X86::GR64RegClass;
25046 } else if (Res.second == &X86::FR32RegClass ||
25047 Res.second == &X86::FR64RegClass ||
25048 Res.second == &X86::VR128RegClass ||
25049 Res.second == &X86::VR256RegClass ||
25050 Res.second == &X86::FR32XRegClass ||
25051 Res.second == &X86::FR64XRegClass ||
25052 Res.second == &X86::VR128XRegClass ||
25053 Res.second == &X86::VR256XRegClass ||
25054 Res.second == &X86::VR512RegClass) {
25055 // Handle references to XMM physical registers that got mapped into the
25056 // wrong class. This can happen with constraints like {xmm0} where the
25057 // target independent register mapper will just pick the first match it can
25058 // find, ignoring the required type.
25060 if (VT == MVT::f32 || VT == MVT::i32)
25061 Res.second = &X86::FR32RegClass;
25062 else if (VT == MVT::f64 || VT == MVT::i64)
25063 Res.second = &X86::FR64RegClass;
25064 else if (X86::VR128RegClass.hasType(VT))
25065 Res.second = &X86::VR128RegClass;
25066 else if (X86::VR256RegClass.hasType(VT))
25067 Res.second = &X86::VR256RegClass;
25068 else if (X86::VR512RegClass.hasType(VT))
25069 Res.second = &X86::VR512RegClass;
25075 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25077 // Scaling factors are not free at all.
25078 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25079 // will take 2 allocations in the out of order engine instead of 1
25080 // for plain addressing mode, i.e. inst (reg1).
25082 // vaddps (%rsi,%drx), %ymm0, %ymm1
25083 // Requires two allocations (one for the load, one for the computation)
25085 // vaddps (%rsi), %ymm0, %ymm1
25086 // Requires just 1 allocation, i.e., freeing allocations for other operations
25087 // and having less micro operations to execute.
25089 // For some X86 architectures, this is even worse because for instance for
25090 // stores, the complex addressing mode forces the instruction to use the
25091 // "load" ports instead of the dedicated "store" port.
25092 // E.g., on Haswell:
25093 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25094 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25095 if (isLegalAddressingMode(AM, Ty))
25096 // Scale represents reg2 * scale, thus account for 1
25097 // as soon as we use a second register.
25098 return AM.Scale != 0;
25102 bool X86TargetLowering::isTargetFTOL() const {
25103 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();