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 (!Subtarget->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 (!Subtarget->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 (!Subtarget->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 (Subtarget->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 (!Subtarget->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 (!Subtarget->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 (!Subtarget->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 (!Subtarget->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);
754 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755 // split/scalarized right now.
756 if (VT.getVectorElementType() == MVT::f16)
757 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
761 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762 // with -msoft-float, disable use of MMX as well.
763 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765 // No operations on x86mmx supported, everything uses intrinsics.
768 // MMX-sized vectors (other than x86mmx) are expected to be expanded
769 // into smaller operations.
770 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771 setOperationAction(ISD::MULHS, MMXTy, Expand);
772 setOperationAction(ISD::AND, MMXTy, Expand);
773 setOperationAction(ISD::OR, MMXTy, Expand);
774 setOperationAction(ISD::XOR, MMXTy, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
776 setOperationAction(ISD::SELECT, MMXTy, Expand);
777 setOperationAction(ISD::BITCAST, MMXTy, Expand);
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
781 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
784 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
785 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
786 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
787 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
788 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
789 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
790 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
791 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
792 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
793 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
794 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
797 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
800 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
803 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804 // registers cannot be used even for integer operations.
805 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
810 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
811 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
812 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
813 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
814 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
815 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
816 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
817 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
818 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
819 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
820 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
821 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
822 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
823 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
824 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
825 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
826 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
827 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
828 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
829 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
831 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
832 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
834 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
835 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
836 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
837 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
840 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
843 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
845 // Only provide customized ctpop vector bit twiddling for vector types we
846 // know to perform better than using the popcnt instructions on each vector
847 // element. If popcnt isn't supported, always provide the custom version.
848 if (!Subtarget->hasPOPCNT()) {
849 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
850 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
853 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
854 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
855 MVT VT = (MVT::SimpleValueType)i;
856 // Do not attempt to custom lower non-power-of-2 vectors
857 if (!isPowerOf2_32(VT.getVectorNumElements()))
859 // Do not attempt to custom lower non-128-bit vectors
860 if (!VT.is128BitVector())
862 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
863 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
864 setOperationAction(ISD::VSELECT, VT, Custom);
865 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
868 // We support custom legalizing of sext and anyext loads for specific
869 // memory vector types which we can load as a scalar (or sequence of
870 // scalars) and extend in-register to a legal 128-bit vector type. For sext
871 // loads these must work with a single scalar load.
872 for (MVT VT : MVT::integer_vector_valuetypes()) {
873 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
884 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
885 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
887 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
888 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
889 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
893 if (Subtarget->is64Bit()) {
894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
895 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
898 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900 MVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to promote non-128-bit vectors
903 if (!VT.is128BitVector())
906 setOperationAction(ISD::AND, VT, Promote);
907 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
908 setOperationAction(ISD::OR, VT, Promote);
909 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
910 setOperationAction(ISD::XOR, VT, Promote);
911 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
912 setOperationAction(ISD::LOAD, VT, Promote);
913 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
914 setOperationAction(ISD::SELECT, VT, Promote);
915 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
918 // Custom lower v2i64 and v2f64 selects.
919 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
920 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
921 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
922 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
924 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
925 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
927 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
928 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
929 // As there is no 64-bit GPR available, we need build a special custom
930 // sequence to convert from v2i32 to v2f32.
931 if (!Subtarget->is64Bit())
932 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
934 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
935 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
937 for (MVT VT : MVT::fp_vector_valuetypes())
938 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
940 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
941 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
942 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
945 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
948 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
949 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
950 setOperationAction(ISD::FRINT, RoundedTy, Legal);
951 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
954 // FIXME: Do we need to handle scalar-to-vector here?
955 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
957 // We directly match byte blends in the backend as they match the VSELECT
959 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
961 // SSE41 brings specific instructions for doing vector sign extend even in
962 // cases where we don't have SRA.
963 for (MVT VT : MVT::integer_vector_valuetypes()) {
964 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
965 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
966 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
969 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
970 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
971 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
972 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
973 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
977 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
978 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
979 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
980 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
984 // i8 and i16 vectors are custom because the source register and source
985 // source memory operand types are not the same width. f32 vectors are
986 // custom since the immediate controlling the insert encodes additional
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
990 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
998 // FIXME: these should be Legal, but that's only for the case where
999 // the index is constant. For now custom expand to deal with that.
1000 if (Subtarget->is64Bit()) {
1001 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1006 if (Subtarget->hasSSE2()) {
1007 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1008 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1010 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1011 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1013 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1014 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1016 // In the customized shift lowering, the legal cases in AVX2 will be
1018 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1019 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1021 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1022 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1024 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1027 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1028 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1029 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1030 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1031 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1032 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1033 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1035 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1036 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1037 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1039 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1040 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1041 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1042 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1043 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1050 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1052 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1053 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1054 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1055 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1060 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1063 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1065 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1066 // even though v8i16 is a legal type.
1067 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1068 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1069 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1071 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1072 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1073 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1075 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1076 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1078 for (MVT VT : MVT::fp_vector_valuetypes())
1079 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1081 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1082 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1084 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1085 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1087 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1088 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1090 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1091 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1092 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1093 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1095 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1096 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1097 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1099 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1100 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1101 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1102 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1103 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1104 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1105 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1106 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1107 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1108 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1109 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1110 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1112 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1113 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1114 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1115 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1116 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1117 setOperationAction(ISD::FMA, MVT::f32, Legal);
1118 setOperationAction(ISD::FMA, MVT::f64, Legal);
1121 if (Subtarget->hasInt256()) {
1122 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1123 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1124 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1125 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1127 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1128 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1129 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1130 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1132 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1133 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1134 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1135 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1137 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1138 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1139 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1140 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1142 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1143 // when we have a 256bit-wide blend with immediate.
1144 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1146 // Only provide customized ctpop vector bit twiddling for vector types we
1147 // know to perform better than using the popcnt instructions on each
1148 // vector element. If popcnt isn't supported, always provide the custom
1150 if (!Subtarget->hasPOPCNT())
1151 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1153 // Custom CTPOP always performs better on natively supported v8i32
1154 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1156 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1157 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1158 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1159 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1160 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1161 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1162 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1164 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1165 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1166 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1167 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1168 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1169 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1171 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1172 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1173 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1174 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1176 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1177 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1178 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1181 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1182 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1183 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1184 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1187 // In the customized shift lowering, the legal cases in AVX2 will be
1189 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1190 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1192 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1193 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1195 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1197 // Custom lower several nodes for 256-bit types.
1198 for (MVT VT : MVT::vector_valuetypes()) {
1199 if (VT.getScalarSizeInBits() >= 32) {
1200 setOperationAction(ISD::MLOAD, VT, Legal);
1201 setOperationAction(ISD::MSTORE, VT, Legal);
1203 // Extract subvector is special because the value type
1204 // (result) is 128-bit but the source is 256-bit wide.
1205 if (VT.is128BitVector()) {
1206 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1208 // Do not attempt to custom lower other non-256-bit vectors
1209 if (!VT.is256BitVector())
1212 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1213 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1214 setOperationAction(ISD::VSELECT, VT, Custom);
1215 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1216 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1217 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1218 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1219 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1222 if (Subtarget->hasInt256())
1223 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1226 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1227 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1228 MVT VT = (MVT::SimpleValueType)i;
1230 // Do not attempt to promote non-256-bit vectors
1231 if (!VT.is256BitVector())
1234 setOperationAction(ISD::AND, VT, Promote);
1235 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1236 setOperationAction(ISD::OR, VT, Promote);
1237 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1238 setOperationAction(ISD::XOR, VT, Promote);
1239 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1240 setOperationAction(ISD::LOAD, VT, Promote);
1241 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1242 setOperationAction(ISD::SELECT, VT, Promote);
1243 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1247 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1248 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1249 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1250 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1251 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1253 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1254 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1255 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1257 for (MVT VT : MVT::fp_vector_valuetypes())
1258 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1260 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1261 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1262 setOperationAction(ISD::XOR, MVT::i1, Legal);
1263 setOperationAction(ISD::OR, MVT::i1, Legal);
1264 setOperationAction(ISD::AND, MVT::i1, Legal);
1265 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1266 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1267 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1268 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1269 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1271 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1272 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1273 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1274 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1275 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1276 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1278 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1279 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1280 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1281 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1282 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1283 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1284 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1285 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1287 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1288 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1289 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1290 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1291 if (Subtarget->is64Bit()) {
1292 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1293 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1294 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1295 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1297 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1298 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1299 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1300 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1301 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1302 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1303 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1304 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1305 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1306 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1307 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1308 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1309 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1310 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1311 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1312 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1314 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1315 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1316 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1317 if (Subtarget->hasDQI()) {
1318 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1319 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1321 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1322 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1323 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1324 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1325 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1326 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1327 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1328 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1329 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1330 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1331 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1332 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1333 if (Subtarget->hasDQI()) {
1334 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1335 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1337 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1338 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1340 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1342 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1348 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1349 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1350 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1351 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1352 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1354 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1355 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1357 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1359 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1360 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1361 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1362 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1363 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1364 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1365 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1366 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1367 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1368 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1369 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1371 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1372 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1374 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1375 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1377 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1379 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1380 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1382 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1383 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1385 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1386 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1388 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1389 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1390 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1391 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1392 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1393 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1395 if (Subtarget->hasCDI()) {
1396 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1397 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1399 if (Subtarget->hasDQI()) {
1400 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1401 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1402 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1404 // Custom lower several nodes.
1405 for (MVT VT : MVT::vector_valuetypes()) {
1406 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1408 setOperationAction(ISD::AND, VT, Legal);
1409 setOperationAction(ISD::OR, VT, Legal);
1410 setOperationAction(ISD::XOR, VT, Legal);
1412 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1413 setOperationAction(ISD::MGATHER, VT, Custom);
1414 setOperationAction(ISD::MSCATTER, VT, Custom);
1416 // Extract subvector is special because the value type
1417 // (result) is 256/128-bit but the source is 512-bit wide.
1418 if (VT.is128BitVector() || VT.is256BitVector()) {
1419 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1421 if (VT.getVectorElementType() == MVT::i1)
1422 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1424 // Do not attempt to custom lower other non-512-bit vectors
1425 if (!VT.is512BitVector())
1428 if (EltSize >= 32) {
1429 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1430 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1431 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1432 setOperationAction(ISD::VSELECT, VT, Legal);
1433 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1434 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1435 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1436 setOperationAction(ISD::MLOAD, VT, Legal);
1437 setOperationAction(ISD::MSTORE, VT, Legal);
1440 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1441 MVT VT = (MVT::SimpleValueType)i;
1443 // Do not attempt to promote non-512-bit vectors.
1444 if (!VT.is512BitVector())
1447 setOperationAction(ISD::SELECT, VT, Promote);
1448 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1452 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1453 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1454 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1456 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1457 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1459 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1460 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1461 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1462 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1463 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1464 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1465 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1466 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1467 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1468 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1469 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1470 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1471 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1472 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1473 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1475 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1476 const MVT VT = (MVT::SimpleValueType)i;
1478 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1480 // Do not attempt to promote non-512-bit vectors.
1481 if (!VT.is512BitVector())
1485 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1486 setOperationAction(ISD::VSELECT, VT, Legal);
1491 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1492 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1493 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1495 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1496 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1497 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1498 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1499 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1500 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1501 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1502 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1504 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1505 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1506 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1507 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1508 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1509 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1512 // We want to custom lower some of our intrinsics.
1513 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1514 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1515 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1516 if (!Subtarget->is64Bit())
1517 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1519 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1520 // handle type legalization for these operations here.
1522 // FIXME: We really should do custom legalization for addition and
1523 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1524 // than generic legalization for 64-bit multiplication-with-overflow, though.
1525 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1526 // Add/Sub/Mul with overflow operations are custom lowered.
1528 setOperationAction(ISD::SADDO, VT, Custom);
1529 setOperationAction(ISD::UADDO, VT, Custom);
1530 setOperationAction(ISD::SSUBO, VT, Custom);
1531 setOperationAction(ISD::USUBO, VT, Custom);
1532 setOperationAction(ISD::SMULO, VT, Custom);
1533 setOperationAction(ISD::UMULO, VT, Custom);
1537 if (!Subtarget->is64Bit()) {
1538 // These libcalls are not available in 32-bit.
1539 setLibcallName(RTLIB::SHL_I128, nullptr);
1540 setLibcallName(RTLIB::SRL_I128, nullptr);
1541 setLibcallName(RTLIB::SRA_I128, nullptr);
1544 // Combine sin / cos into one node or libcall if possible.
1545 if (Subtarget->hasSinCos()) {
1546 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1547 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1548 if (Subtarget->isTargetDarwin()) {
1549 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1550 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1551 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1552 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1556 if (Subtarget->isTargetWin64()) {
1557 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1558 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1559 setOperationAction(ISD::SREM, MVT::i128, Custom);
1560 setOperationAction(ISD::UREM, MVT::i128, Custom);
1561 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1562 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1565 // We have target-specific dag combine patterns for the following nodes:
1566 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1567 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1568 setTargetDAGCombine(ISD::BITCAST);
1569 setTargetDAGCombine(ISD::VSELECT);
1570 setTargetDAGCombine(ISD::SELECT);
1571 setTargetDAGCombine(ISD::SHL);
1572 setTargetDAGCombine(ISD::SRA);
1573 setTargetDAGCombine(ISD::SRL);
1574 setTargetDAGCombine(ISD::OR);
1575 setTargetDAGCombine(ISD::AND);
1576 setTargetDAGCombine(ISD::ADD);
1577 setTargetDAGCombine(ISD::FADD);
1578 setTargetDAGCombine(ISD::FSUB);
1579 setTargetDAGCombine(ISD::FMA);
1580 setTargetDAGCombine(ISD::SUB);
1581 setTargetDAGCombine(ISD::LOAD);
1582 setTargetDAGCombine(ISD::MLOAD);
1583 setTargetDAGCombine(ISD::STORE);
1584 setTargetDAGCombine(ISD::MSTORE);
1585 setTargetDAGCombine(ISD::ZERO_EXTEND);
1586 setTargetDAGCombine(ISD::ANY_EXTEND);
1587 setTargetDAGCombine(ISD::SIGN_EXTEND);
1588 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1589 setTargetDAGCombine(ISD::TRUNCATE);
1590 setTargetDAGCombine(ISD::SINT_TO_FP);
1591 setTargetDAGCombine(ISD::SETCC);
1592 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1593 setTargetDAGCombine(ISD::BUILD_VECTOR);
1594 setTargetDAGCombine(ISD::MUL);
1595 setTargetDAGCombine(ISD::XOR);
1597 computeRegisterProperties(Subtarget->getRegisterInfo());
1599 // On Darwin, -Os means optimize for size without hurting performance,
1600 // do not reduce the limit.
1601 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1602 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1603 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1604 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1605 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1606 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1607 setPrefLoopAlignment(4); // 2^4 bytes.
1609 // Predictable cmov don't hurt on atom because it's in-order.
1610 PredictableSelectIsExpensive = !Subtarget->isAtom();
1611 EnableExtLdPromotion = true;
1612 setPrefFunctionAlignment(4); // 2^4 bytes.
1614 verifyIntrinsicTables();
1617 // This has so far only been implemented for 64-bit MachO.
1618 bool X86TargetLowering::useLoadStackGuardNode() const {
1619 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1622 TargetLoweringBase::LegalizeTypeAction
1623 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1624 if (ExperimentalVectorWideningLegalization &&
1625 VT.getVectorNumElements() != 1 &&
1626 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1627 return TypeWidenVector;
1629 return TargetLoweringBase::getPreferredVectorAction(VT);
1632 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1634 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1636 const unsigned NumElts = VT.getVectorNumElements();
1637 const EVT EltVT = VT.getVectorElementType();
1638 if (VT.is512BitVector()) {
1639 if (Subtarget->hasAVX512())
1640 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1641 EltVT == MVT::f32 || EltVT == MVT::f64)
1643 case 8: return MVT::v8i1;
1644 case 16: return MVT::v16i1;
1646 if (Subtarget->hasBWI())
1647 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1649 case 32: return MVT::v32i1;
1650 case 64: return MVT::v64i1;
1654 if (VT.is256BitVector() || VT.is128BitVector()) {
1655 if (Subtarget->hasVLX())
1656 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1657 EltVT == MVT::f32 || EltVT == MVT::f64)
1659 case 2: return MVT::v2i1;
1660 case 4: return MVT::v4i1;
1661 case 8: return MVT::v8i1;
1663 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1664 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1666 case 8: return MVT::v8i1;
1667 case 16: return MVT::v16i1;
1668 case 32: return MVT::v32i1;
1672 return VT.changeVectorElementTypeToInteger();
1675 /// Helper for getByValTypeAlignment to determine
1676 /// the desired ByVal argument alignment.
1677 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1680 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1681 if (VTy->getBitWidth() == 128)
1683 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1684 unsigned EltAlign = 0;
1685 getMaxByValAlign(ATy->getElementType(), EltAlign);
1686 if (EltAlign > MaxAlign)
1687 MaxAlign = EltAlign;
1688 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1689 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1690 unsigned EltAlign = 0;
1691 getMaxByValAlign(STy->getElementType(i), EltAlign);
1692 if (EltAlign > MaxAlign)
1693 MaxAlign = EltAlign;
1700 /// Return the desired alignment for ByVal aggregate
1701 /// function arguments in the caller parameter area. For X86, aggregates
1702 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1703 /// are at 4-byte boundaries.
1704 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1705 if (Subtarget->is64Bit()) {
1706 // Max of 8 and alignment of type.
1707 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1714 if (Subtarget->hasSSE1())
1715 getMaxByValAlign(Ty, Align);
1719 /// Returns the target specific optimal type for load
1720 /// and store operations as a result of memset, memcpy, and memmove
1721 /// lowering. If DstAlign is zero that means it's safe to destination
1722 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1723 /// means there isn't a need to check it against alignment requirement,
1724 /// probably because the source does not need to be loaded. If 'IsMemset' is
1725 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1726 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1727 /// source is constant so it does not need to be loaded.
1728 /// It returns EVT::Other if the type should be determined using generic
1729 /// target-independent logic.
1731 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1732 unsigned DstAlign, unsigned SrcAlign,
1733 bool IsMemset, bool ZeroMemset,
1735 MachineFunction &MF) const {
1736 const Function *F = MF.getFunction();
1737 if ((!IsMemset || ZeroMemset) &&
1738 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1740 (Subtarget->isUnalignedMemAccessFast() ||
1741 ((DstAlign == 0 || DstAlign >= 16) &&
1742 (SrcAlign == 0 || SrcAlign >= 16)))) {
1744 if (Subtarget->hasInt256())
1746 if (Subtarget->hasFp256())
1749 if (Subtarget->hasSSE2())
1751 if (Subtarget->hasSSE1())
1753 } else if (!MemcpyStrSrc && Size >= 8 &&
1754 !Subtarget->is64Bit() &&
1755 Subtarget->hasSSE2()) {
1756 // Do not use f64 to lower memcpy if source is string constant. It's
1757 // better to use i32 to avoid the loads.
1761 if (Subtarget->is64Bit() && Size >= 8)
1766 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1768 return X86ScalarSSEf32;
1769 else if (VT == MVT::f64)
1770 return X86ScalarSSEf64;
1775 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1780 *Fast = Subtarget->isUnalignedMemAccessFast();
1784 /// Return the entry encoding for a jump table in the
1785 /// current function. The returned value is a member of the
1786 /// MachineJumpTableInfo::JTEntryKind enum.
1787 unsigned X86TargetLowering::getJumpTableEncoding() const {
1788 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1790 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1791 Subtarget->isPICStyleGOT())
1792 return MachineJumpTableInfo::EK_Custom32;
1794 // Otherwise, use the normal jump table encoding heuristics.
1795 return TargetLowering::getJumpTableEncoding();
1798 bool X86TargetLowering::useSoftFloat() const {
1799 return Subtarget->useSoftFloat();
1803 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1804 const MachineBasicBlock *MBB,
1805 unsigned uid,MCContext &Ctx) const{
1806 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1807 Subtarget->isPICStyleGOT());
1808 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1810 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1811 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1814 /// Returns relocation base for the given PIC jumptable.
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816 SelectionDAG &DAG) const {
1817 if (!Subtarget->is64Bit())
1818 // This doesn't have SDLoc associated with it, but is not really the
1819 // same as a Register.
1820 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1824 /// This returns the relocation base for the given PIC jumptable,
1825 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1826 const MCExpr *X86TargetLowering::
1827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1828 MCContext &Ctx) const {
1829 // X86-64 uses RIP relative addressing based on the jump table label.
1830 if (Subtarget->isPICStyleRIPRel())
1831 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833 // Otherwise, the reference is relative to the PIC base.
1834 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1837 std::pair<const TargetRegisterClass *, uint8_t>
1838 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1840 const TargetRegisterClass *RRC = nullptr;
1842 switch (VT.SimpleTy) {
1844 return TargetLowering::findRepresentativeClass(TRI, VT);
1845 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1846 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1849 RRC = &X86::VR64RegClass;
1851 case MVT::f32: case MVT::f64:
1852 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1853 case MVT::v4f32: case MVT::v2f64:
1854 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1856 RRC = &X86::VR128RegClass;
1859 return std::make_pair(RRC, Cost);
1862 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1863 unsigned &Offset) const {
1864 if (!Subtarget->isTargetLinux())
1867 if (Subtarget->is64Bit()) {
1868 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1870 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1882 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1883 unsigned DestAS) const {
1884 assert(SrcAS != DestAS && "Expected different address spaces!");
1886 return SrcAS < 256 && DestAS < 256;
1889 //===----------------------------------------------------------------------===//
1890 // Return Value Calling Convention Implementation
1891 //===----------------------------------------------------------------------===//
1893 #include "X86GenCallingConv.inc"
1896 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1897 MachineFunction &MF, bool isVarArg,
1898 const SmallVectorImpl<ISD::OutputArg> &Outs,
1899 LLVMContext &Context) const {
1900 SmallVector<CCValAssign, 16> RVLocs;
1901 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1902 return CCInfo.CheckReturn(Outs, RetCC_X86);
1905 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1906 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1911 X86TargetLowering::LowerReturn(SDValue Chain,
1912 CallingConv::ID CallConv, bool isVarArg,
1913 const SmallVectorImpl<ISD::OutputArg> &Outs,
1914 const SmallVectorImpl<SDValue> &OutVals,
1915 SDLoc dl, SelectionDAG &DAG) const {
1916 MachineFunction &MF = DAG.getMachineFunction();
1917 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1919 SmallVector<CCValAssign, 16> RVLocs;
1920 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1921 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1924 SmallVector<SDValue, 6> RetOps;
1925 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1926 // Operand #1 = Bytes To Pop
1927 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1930 // Copy the result values into the output registers.
1931 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1932 CCValAssign &VA = RVLocs[i];
1933 assert(VA.isRegLoc() && "Can only return in registers!");
1934 SDValue ValToCopy = OutVals[i];
1935 EVT ValVT = ValToCopy.getValueType();
1937 // Promote values to the appropriate types.
1938 if (VA.getLocInfo() == CCValAssign::SExt)
1939 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1940 else if (VA.getLocInfo() == CCValAssign::ZExt)
1941 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942 else if (VA.getLocInfo() == CCValAssign::AExt) {
1943 if (ValVT.getScalarType() == MVT::i1)
1944 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1948 else if (VA.getLocInfo() == CCValAssign::BCvt)
1949 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1952 "Unexpected FP-extend for return value.");
1954 // If this is x86-64, and we disabled SSE, we can't return FP values,
1955 // or SSE or MMX vectors.
1956 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1957 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1958 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1959 report_fatal_error("SSE register return with SSE disabled");
1961 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1962 // llvm-gcc has never done it right and no one has noticed, so this
1963 // should be OK for now.
1964 if (ValVT == MVT::f64 &&
1965 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1966 report_fatal_error("SSE2 register return with SSE2 disabled");
1968 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1969 // the RET instruction and handled by the FP Stackifier.
1970 if (VA.getLocReg() == X86::FP0 ||
1971 VA.getLocReg() == X86::FP1) {
1972 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1973 // change the value to the FP stack register class.
1974 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1975 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1976 RetOps.push_back(ValToCopy);
1977 // Don't emit a copytoreg.
1981 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1982 // which is returned in RAX / RDX.
1983 if (Subtarget->is64Bit()) {
1984 if (ValVT == MVT::x86mmx) {
1985 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1986 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1987 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989 // If we don't have SSE2 available, convert to v4f32 so the generated
1990 // register is legal.
1991 if (!Subtarget->hasSSE2())
1992 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1997 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1998 Flag = Chain.getValue(1);
1999 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2002 // The x86-64 ABIs require that for returning structs by value we copy
2003 // the sret argument into %rax/%eax (depending on ABI) for the return.
2004 // Win32 requires us to put the sret argument to %eax as well.
2005 // We saved the argument into a virtual register in the entry block,
2006 // so now we copy the value out and into %rax/%eax.
2008 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2009 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2010 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2011 // either case FuncInfo->setSRetReturnReg() will have been called.
2012 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2013 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2014 "No need for an sret register");
2015 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2018 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019 X86::RAX : X86::EAX;
2020 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021 Flag = Chain.getValue(1);
2023 // RAX/EAX now acts like a return value.
2024 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2027 RetOps[0] = Chain; // Update chain.
2029 // Add the flag if we have it.
2031 RetOps.push_back(Flag);
2033 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037 if (N->getNumValues() != 1)
2039 if (!N->hasNUsesOfValue(1, 0))
2042 SDValue TCChain = Chain;
2043 SDNode *Copy = *N->use_begin();
2044 if (Copy->getOpcode() == ISD::CopyToReg) {
2045 // If the copy has a glue operand, we conservatively assume it isn't safe to
2046 // perform a tail call.
2047 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2049 TCChain = Copy->getOperand(0);
2050 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2053 bool HasRet = false;
2054 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2056 if (UI->getOpcode() != X86ISD::RET_FLAG)
2058 // If we are returning more than one value, we can definitely
2059 // not make a tail call see PR19530
2060 if (UI->getNumOperands() > 4)
2062 if (UI->getNumOperands() == 4 &&
2063 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2076 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2077 ISD::NodeType ExtendKind) const {
2079 // TODO: Is this also valid on 32-bit?
2080 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2081 ReturnMVT = MVT::i8;
2083 ReturnMVT = MVT::i32;
2085 EVT MinVT = getRegisterType(Context, ReturnMVT);
2086 return VT.bitsLT(MinVT) ? MinVT : VT;
2089 /// Lower the result values of a call into the
2090 /// appropriate copies out of appropriate physical registers.
2093 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2094 CallingConv::ID CallConv, bool isVarArg,
2095 const SmallVectorImpl<ISD::InputArg> &Ins,
2096 SDLoc dl, SelectionDAG &DAG,
2097 SmallVectorImpl<SDValue> &InVals) const {
2099 // Assign locations to each value returned by this call.
2100 SmallVector<CCValAssign, 16> RVLocs;
2101 bool Is64Bit = Subtarget->is64Bit();
2102 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2104 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2106 // Copy all of the result registers out of their specified physreg.
2107 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2108 CCValAssign &VA = RVLocs[i];
2109 EVT CopyVT = VA.getLocVT();
2111 // If this is x86-64, and we disabled SSE, we can't return FP values
2112 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2113 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2114 report_fatal_error("SSE register return with SSE disabled");
2117 // If we prefer to use the value in xmm registers, copy it out as f80 and
2118 // use a truncate to move it from fp stack reg to xmm reg.
2119 bool RoundAfterCopy = false;
2120 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2121 isScalarFPTypeInSSEReg(VA.getValVT())) {
2123 RoundAfterCopy = (CopyVT != VA.getLocVT());
2126 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2127 CopyVT, InFlag).getValue(1);
2128 SDValue Val = Chain.getValue(0);
2131 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2132 // This truncation won't change the value.
2133 DAG.getIntPtrConstant(1, dl));
2135 InFlag = Chain.getValue(2);
2136 InVals.push_back(Val);
2142 //===----------------------------------------------------------------------===//
2143 // C & StdCall & Fast Calling Convention implementation
2144 //===----------------------------------------------------------------------===//
2145 // StdCall calling convention seems to be standard for many Windows' API
2146 // routines and around. It differs from C calling convention just a little:
2147 // callee should clean up the stack, not caller. Symbols should be also
2148 // decorated in some fancy way :) It doesn't support any vector arguments.
2149 // For info on fast calling convention see Fast Calling Convention (tail call)
2150 // implementation LowerX86_32FastCCCallTo.
2152 /// CallIsStructReturn - Determines whether a call uses struct return
2154 enum StructReturnType {
2159 static StructReturnType
2160 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2162 return NotStructReturn;
2164 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2165 if (!Flags.isSRet())
2166 return NotStructReturn;
2167 if (Flags.isInReg())
2168 return RegStructReturn;
2169 return StackStructReturn;
2172 /// Determines whether a function uses struct return semantics.
2173 static StructReturnType
2174 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2176 return NotStructReturn;
2178 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2179 if (!Flags.isSRet())
2180 return NotStructReturn;
2181 if (Flags.isInReg())
2182 return RegStructReturn;
2183 return StackStructReturn;
2186 /// Make a copy of an aggregate at address specified by "Src" to address
2187 /// "Dst" with size and alignment information specified by the specific
2188 /// parameter attribute. The copy will be passed as a byval function parameter.
2190 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2191 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2193 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2195 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2196 /*isVolatile*/false, /*AlwaysInline=*/true,
2197 /*isTailCall*/false,
2198 MachinePointerInfo(), MachinePointerInfo());
2201 /// Return true if the calling convention is one that
2202 /// supports tail call optimization.
2203 static bool IsTailCallConvention(CallingConv::ID CC) {
2204 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2205 CC == CallingConv::HiPE);
2208 /// \brief Return true if the calling convention is a C calling convention.
2209 static bool IsCCallConvention(CallingConv::ID CC) {
2210 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2211 CC == CallingConv::X86_64_SysV);
2214 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2215 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2219 CallingConv::ID CalleeCC = CS.getCallingConv();
2220 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2226 /// Return true if the function is being made into
2227 /// a tailcall target by changing its ABI.
2228 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2229 bool GuaranteedTailCallOpt) {
2230 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2234 X86TargetLowering::LowerMemArgument(SDValue Chain,
2235 CallingConv::ID CallConv,
2236 const SmallVectorImpl<ISD::InputArg> &Ins,
2237 SDLoc dl, SelectionDAG &DAG,
2238 const CCValAssign &VA,
2239 MachineFrameInfo *MFI,
2241 // Create the nodes corresponding to a load from this parameter slot.
2242 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2243 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2244 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2245 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2248 // If value is passed by pointer we have address passed instead of the value
2250 if (VA.getLocInfo() == CCValAssign::Indirect)
2251 ValVT = VA.getLocVT();
2253 ValVT = VA.getValVT();
2255 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2256 // changed with more analysis.
2257 // In case of tail call optimization mark all arguments mutable. Since they
2258 // could be overwritten by lowering of arguments in case of a tail call.
2259 if (Flags.isByVal()) {
2260 unsigned Bytes = Flags.getByValSize();
2261 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2262 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2263 return DAG.getFrameIndex(FI, getPointerTy());
2265 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2266 VA.getLocMemOffset(), isImmutable);
2267 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2268 return DAG.getLoad(ValVT, dl, Chain, FIN,
2269 MachinePointerInfo::getFixedStack(FI),
2270 false, false, false, 0);
2274 // FIXME: Get this from tablegen.
2275 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2276 const X86Subtarget *Subtarget) {
2277 assert(Subtarget->is64Bit());
2279 if (Subtarget->isCallingConvWin64(CallConv)) {
2280 static const MCPhysReg GPR64ArgRegsWin64[] = {
2281 X86::RCX, X86::RDX, X86::R8, X86::R9
2283 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2286 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2287 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2289 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2292 // FIXME: Get this from tablegen.
2293 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2294 CallingConv::ID CallConv,
2295 const X86Subtarget *Subtarget) {
2296 assert(Subtarget->is64Bit());
2297 if (Subtarget->isCallingConvWin64(CallConv)) {
2298 // The XMM registers which might contain var arg parameters are shadowed
2299 // in their paired GPR. So we only need to save the GPR to their home
2301 // TODO: __vectorcall will change this.
2305 const Function *Fn = MF.getFunction();
2306 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2307 bool isSoftFloat = Subtarget->useSoftFloat();
2308 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2309 "SSE register cannot be used when SSE is disabled!");
2310 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2311 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2315 static const MCPhysReg XMMArgRegs64Bit[] = {
2316 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2317 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2319 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2323 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2324 CallingConv::ID CallConv,
2326 const SmallVectorImpl<ISD::InputArg> &Ins,
2329 SmallVectorImpl<SDValue> &InVals)
2331 MachineFunction &MF = DAG.getMachineFunction();
2332 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2333 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2335 const Function* Fn = MF.getFunction();
2336 if (Fn->hasExternalLinkage() &&
2337 Subtarget->isTargetCygMing() &&
2338 Fn->getName() == "main")
2339 FuncInfo->setForceFramePointer(true);
2341 MachineFrameInfo *MFI = MF.getFrameInfo();
2342 bool Is64Bit = Subtarget->is64Bit();
2343 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2345 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2346 "Var args not supported with calling convention fastcc, ghc or hipe");
2348 // Assign locations to all of the incoming arguments.
2349 SmallVector<CCValAssign, 16> ArgLocs;
2350 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2352 // Allocate shadow area for Win64
2354 CCInfo.AllocateStack(32, 8);
2356 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2358 unsigned LastVal = ~0U;
2360 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2361 CCValAssign &VA = ArgLocs[i];
2362 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2364 assert(VA.getValNo() != LastVal &&
2365 "Don't support value assigned to multiple locs yet");
2367 LastVal = VA.getValNo();
2369 if (VA.isRegLoc()) {
2370 EVT RegVT = VA.getLocVT();
2371 const TargetRegisterClass *RC;
2372 if (RegVT == MVT::i32)
2373 RC = &X86::GR32RegClass;
2374 else if (Is64Bit && RegVT == MVT::i64)
2375 RC = &X86::GR64RegClass;
2376 else if (RegVT == MVT::f32)
2377 RC = &X86::FR32RegClass;
2378 else if (RegVT == MVT::f64)
2379 RC = &X86::FR64RegClass;
2380 else if (RegVT.is512BitVector())
2381 RC = &X86::VR512RegClass;
2382 else if (RegVT.is256BitVector())
2383 RC = &X86::VR256RegClass;
2384 else if (RegVT.is128BitVector())
2385 RC = &X86::VR128RegClass;
2386 else if (RegVT == MVT::x86mmx)
2387 RC = &X86::VR64RegClass;
2388 else if (RegVT == MVT::i1)
2389 RC = &X86::VK1RegClass;
2390 else if (RegVT == MVT::v8i1)
2391 RC = &X86::VK8RegClass;
2392 else if (RegVT == MVT::v16i1)
2393 RC = &X86::VK16RegClass;
2394 else if (RegVT == MVT::v32i1)
2395 RC = &X86::VK32RegClass;
2396 else if (RegVT == MVT::v64i1)
2397 RC = &X86::VK64RegClass;
2399 llvm_unreachable("Unknown argument type!");
2401 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2402 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2404 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2405 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2407 if (VA.getLocInfo() == CCValAssign::SExt)
2408 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2409 DAG.getValueType(VA.getValVT()));
2410 else if (VA.getLocInfo() == CCValAssign::ZExt)
2411 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2412 DAG.getValueType(VA.getValVT()));
2413 else if (VA.getLocInfo() == CCValAssign::BCvt)
2414 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2416 if (VA.isExtInLoc()) {
2417 // Handle MMX values passed in XMM regs.
2418 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2419 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2421 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2424 assert(VA.isMemLoc());
2425 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2428 // If value is passed via pointer - do a load.
2429 if (VA.getLocInfo() == CCValAssign::Indirect)
2430 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2431 MachinePointerInfo(), false, false, false, 0);
2433 InVals.push_back(ArgValue);
2436 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2437 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2438 // The x86-64 ABIs require that for returning structs by value we copy
2439 // the sret argument into %rax/%eax (depending on ABI) for the return.
2440 // Win32 requires us to put the sret argument to %eax as well.
2441 // Save the argument into a virtual register so that we can access it
2442 // from the return points.
2443 if (Ins[i].Flags.isSRet()) {
2444 unsigned Reg = FuncInfo->getSRetReturnReg();
2446 MVT PtrTy = getPointerTy();
2447 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2448 FuncInfo->setSRetReturnReg(Reg);
2450 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2451 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2457 unsigned StackSize = CCInfo.getNextStackOffset();
2458 // Align stack specially for tail calls.
2459 if (FuncIsMadeTailCallSafe(CallConv,
2460 MF.getTarget().Options.GuaranteedTailCallOpt))
2461 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2463 // If the function takes variable number of arguments, make a frame index for
2464 // the start of the first vararg value... for expansion of llvm.va_start. We
2465 // can skip this if there are no va_start calls.
2466 if (MFI->hasVAStart() &&
2467 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2468 CallConv != CallingConv::X86_ThisCall))) {
2469 FuncInfo->setVarArgsFrameIndex(
2470 MFI->CreateFixedObject(1, StackSize, true));
2473 MachineModuleInfo &MMI = MF.getMMI();
2474 const Function *WinEHParent = nullptr;
2475 if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2476 WinEHParent = MMI.getWinEHParent(Fn);
2477 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2478 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2480 // Figure out if XMM registers are in use.
2481 assert(!(Subtarget->useSoftFloat() &&
2482 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2483 "SSE register cannot be used when SSE is disabled!");
2485 // 64-bit calling conventions support varargs and register parameters, so we
2486 // have to do extra work to spill them in the prologue.
2487 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2488 // Find the first unallocated argument registers.
2489 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2490 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2491 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2492 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2493 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2494 "SSE register cannot be used when SSE is disabled!");
2496 // Gather all the live in physical registers.
2497 SmallVector<SDValue, 6> LiveGPRs;
2498 SmallVector<SDValue, 8> LiveXMMRegs;
2500 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2501 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2503 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2505 if (!ArgXMMs.empty()) {
2506 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2507 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2508 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2509 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2510 LiveXMMRegs.push_back(
2511 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2516 // Get to the caller-allocated home save location. Add 8 to account
2517 // for the return address.
2518 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2519 FuncInfo->setRegSaveFrameIndex(
2520 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2521 // Fixup to set vararg frame on shadow area (4 x i64).
2523 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2525 // For X86-64, if there are vararg parameters that are passed via
2526 // registers, then we must store them to their spots on the stack so
2527 // they may be loaded by deferencing the result of va_next.
2528 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2529 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2530 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2531 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2534 // Store the integer parameter registers.
2535 SmallVector<SDValue, 8> MemOps;
2536 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2538 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2539 for (SDValue Val : LiveGPRs) {
2540 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2541 DAG.getIntPtrConstant(Offset, dl));
2543 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2544 MachinePointerInfo::getFixedStack(
2545 FuncInfo->getRegSaveFrameIndex(), Offset),
2547 MemOps.push_back(Store);
2551 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2552 // Now store the XMM (fp + vector) parameter registers.
2553 SmallVector<SDValue, 12> SaveXMMOps;
2554 SaveXMMOps.push_back(Chain);
2555 SaveXMMOps.push_back(ALVal);
2556 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2557 FuncInfo->getRegSaveFrameIndex(), dl));
2558 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2559 FuncInfo->getVarArgsFPOffset(), dl));
2560 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2562 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2563 MVT::Other, SaveXMMOps));
2566 if (!MemOps.empty())
2567 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2568 } else if (IsWinEHOutlined) {
2569 // Get to the caller-allocated home save location. Add 8 to account
2570 // for the return address.
2571 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2572 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2573 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2575 MMI.getWinEHFuncInfo(Fn)
2576 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2577 FuncInfo->getRegSaveFrameIndex();
2579 // Store the second integer parameter (rdx) into rsp+16 relative to the
2580 // stack pointer at the entry of the function.
2582 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2583 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2584 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2585 Chain = DAG.getStore(
2586 Val.getValue(1), dl, Val, RSFIN,
2587 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2588 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2591 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2592 // Find the largest legal vector type.
2593 MVT VecVT = MVT::Other;
2594 // FIXME: Only some x86_32 calling conventions support AVX512.
2595 if (Subtarget->hasAVX512() &&
2596 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2597 CallConv == CallingConv::Intel_OCL_BI)))
2598 VecVT = MVT::v16f32;
2599 else if (Subtarget->hasAVX())
2601 else if (Subtarget->hasSSE2())
2604 // We forward some GPRs and some vector types.
2605 SmallVector<MVT, 2> RegParmTypes;
2606 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2607 RegParmTypes.push_back(IntVT);
2608 if (VecVT != MVT::Other)
2609 RegParmTypes.push_back(VecVT);
2611 // Compute the set of forwarded registers. The rest are scratch.
2612 SmallVectorImpl<ForwardedRegister> &Forwards =
2613 FuncInfo->getForwardedMustTailRegParms();
2614 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2616 // Conservatively forward AL on x86_64, since it might be used for varargs.
2617 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2618 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2619 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2622 // Copy all forwards from physical to virtual registers.
2623 for (ForwardedRegister &F : Forwards) {
2624 // FIXME: Can we use a less constrained schedule?
2625 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2626 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2627 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2631 // Some CCs need callee pop.
2632 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2633 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2634 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2636 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2637 // If this is an sret function, the return should pop the hidden pointer.
2638 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2639 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2640 argsAreStructReturn(Ins) == StackStructReturn)
2641 FuncInfo->setBytesToPopOnReturn(4);
2645 // RegSaveFrameIndex is X86-64 only.
2646 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2647 if (CallConv == CallingConv::X86_FastCall ||
2648 CallConv == CallingConv::X86_ThisCall)
2649 // fastcc functions can't have varargs.
2650 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2653 FuncInfo->setArgumentStackSize(StackSize);
2655 if (IsWinEHParent) {
2656 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2657 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2658 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2659 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2660 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2661 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2662 /*isVolatile=*/true,
2663 /*isNonTemporal=*/false, /*Alignment=*/0);
2670 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2671 SDValue StackPtr, SDValue Arg,
2672 SDLoc dl, SelectionDAG &DAG,
2673 const CCValAssign &VA,
2674 ISD::ArgFlagsTy Flags) const {
2675 unsigned LocMemOffset = VA.getLocMemOffset();
2676 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2677 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2678 if (Flags.isByVal())
2679 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2681 return DAG.getStore(Chain, dl, Arg, PtrOff,
2682 MachinePointerInfo::getStack(LocMemOffset),
2686 /// Emit a load of return address if tail call
2687 /// optimization is performed and it is required.
2689 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2690 SDValue &OutRetAddr, SDValue Chain,
2691 bool IsTailCall, bool Is64Bit,
2692 int FPDiff, SDLoc dl) const {
2693 // Adjust the Return address stack slot.
2694 EVT VT = getPointerTy();
2695 OutRetAddr = getReturnAddressFrameIndex(DAG);
2697 // Load the "old" Return address.
2698 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2699 false, false, false, 0);
2700 return SDValue(OutRetAddr.getNode(), 1);
2703 /// Emit a store of the return address if tail call
2704 /// optimization is performed and it is required (FPDiff!=0).
2705 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2706 SDValue Chain, SDValue RetAddrFrIdx,
2707 EVT PtrVT, unsigned SlotSize,
2708 int FPDiff, SDLoc dl) {
2709 // Store the return address to the appropriate stack slot.
2710 if (!FPDiff) return Chain;
2711 // Calculate the new stack slot for the return address.
2712 int NewReturnAddrFI =
2713 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2715 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2716 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2717 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2723 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2724 SmallVectorImpl<SDValue> &InVals) const {
2725 SelectionDAG &DAG = CLI.DAG;
2727 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2728 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2729 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2730 SDValue Chain = CLI.Chain;
2731 SDValue Callee = CLI.Callee;
2732 CallingConv::ID CallConv = CLI.CallConv;
2733 bool &isTailCall = CLI.IsTailCall;
2734 bool isVarArg = CLI.IsVarArg;
2736 MachineFunction &MF = DAG.getMachineFunction();
2737 bool Is64Bit = Subtarget->is64Bit();
2738 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2739 StructReturnType SR = callIsStructReturn(Outs);
2740 bool IsSibcall = false;
2741 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2743 if (MF.getTarget().Options.DisableTailCalls)
2746 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2748 // Force this to be a tail call. The verifier rules are enough to ensure
2749 // that we can lower this successfully without moving the return address
2752 } else if (isTailCall) {
2753 // Check if it's really possible to do a tail call.
2754 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2755 isVarArg, SR != NotStructReturn,
2756 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2757 Outs, OutVals, Ins, DAG);
2759 // Sibcalls are automatically detected tailcalls which do not require
2761 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2768 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2769 "Var args not supported with calling convention fastcc, ghc or hipe");
2771 // Analyze operands of the call, assigning locations to each operand.
2772 SmallVector<CCValAssign, 16> ArgLocs;
2773 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2775 // Allocate shadow area for Win64
2777 CCInfo.AllocateStack(32, 8);
2779 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2781 // Get a count of how many bytes are to be pushed on the stack.
2782 unsigned NumBytes = CCInfo.getNextStackOffset();
2784 // This is a sibcall. The memory operands are available in caller's
2785 // own caller's stack.
2787 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2788 IsTailCallConvention(CallConv))
2789 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2792 if (isTailCall && !IsSibcall && !IsMustTail) {
2793 // Lower arguments at fp - stackoffset + fpdiff.
2794 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2796 FPDiff = NumBytesCallerPushed - NumBytes;
2798 // Set the delta of movement of the returnaddr stackslot.
2799 // But only set if delta is greater than previous delta.
2800 if (FPDiff < X86Info->getTCReturnAddrDelta())
2801 X86Info->setTCReturnAddrDelta(FPDiff);
2804 unsigned NumBytesToPush = NumBytes;
2805 unsigned NumBytesToPop = NumBytes;
2807 // If we have an inalloca argument, all stack space has already been allocated
2808 // for us and be right at the top of the stack. We don't support multiple
2809 // arguments passed in memory when using inalloca.
2810 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2812 if (!ArgLocs.back().isMemLoc())
2813 report_fatal_error("cannot use inalloca attribute on a register "
2815 if (ArgLocs.back().getLocMemOffset() != 0)
2816 report_fatal_error("any parameter with the inalloca attribute must be "
2817 "the only memory argument");
2821 Chain = DAG.getCALLSEQ_START(
2822 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2824 SDValue RetAddrFrIdx;
2825 // Load return address for tail calls.
2826 if (isTailCall && FPDiff)
2827 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2828 Is64Bit, FPDiff, dl);
2830 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2831 SmallVector<SDValue, 8> MemOpChains;
2834 // Walk the register/memloc assignments, inserting copies/loads. In the case
2835 // of tail call optimization arguments are handle later.
2836 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2837 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2838 // Skip inalloca arguments, they have already been written.
2839 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2840 if (Flags.isInAlloca())
2843 CCValAssign &VA = ArgLocs[i];
2844 EVT RegVT = VA.getLocVT();
2845 SDValue Arg = OutVals[i];
2846 bool isByVal = Flags.isByVal();
2848 // Promote the value if needed.
2849 switch (VA.getLocInfo()) {
2850 default: llvm_unreachable("Unknown loc info!");
2851 case CCValAssign::Full: break;
2852 case CCValAssign::SExt:
2853 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2855 case CCValAssign::ZExt:
2856 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2858 case CCValAssign::AExt:
2859 if (Arg.getValueType().getScalarType() == MVT::i1)
2860 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2861 else if (RegVT.is128BitVector()) {
2862 // Special case: passing MMX values in XMM registers.
2863 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2864 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2865 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2867 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2869 case CCValAssign::BCvt:
2870 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2872 case CCValAssign::Indirect: {
2873 // Store the argument.
2874 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2875 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2876 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2877 MachinePointerInfo::getFixedStack(FI),
2884 if (VA.isRegLoc()) {
2885 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2886 if (isVarArg && IsWin64) {
2887 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2888 // shadow reg if callee is a varargs function.
2889 unsigned ShadowReg = 0;
2890 switch (VA.getLocReg()) {
2891 case X86::XMM0: ShadowReg = X86::RCX; break;
2892 case X86::XMM1: ShadowReg = X86::RDX; break;
2893 case X86::XMM2: ShadowReg = X86::R8; break;
2894 case X86::XMM3: ShadowReg = X86::R9; break;
2897 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2899 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2900 assert(VA.isMemLoc());
2901 if (!StackPtr.getNode())
2902 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2904 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2905 dl, DAG, VA, Flags));
2909 if (!MemOpChains.empty())
2910 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2912 if (Subtarget->isPICStyleGOT()) {
2913 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2916 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2917 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2919 // If we are tail calling and generating PIC/GOT style code load the
2920 // address of the callee into ECX. The value in ecx is used as target of
2921 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2922 // for tail calls on PIC/GOT architectures. Normally we would just put the
2923 // address of GOT into ebx and then call target@PLT. But for tail calls
2924 // ebx would be restored (since ebx is callee saved) before jumping to the
2927 // Note: The actual moving to ECX is done further down.
2928 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2929 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2930 !G->getGlobal()->hasProtectedVisibility())
2931 Callee = LowerGlobalAddress(Callee, DAG);
2932 else if (isa<ExternalSymbolSDNode>(Callee))
2933 Callee = LowerExternalSymbol(Callee, DAG);
2937 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2938 // From AMD64 ABI document:
2939 // For calls that may call functions that use varargs or stdargs
2940 // (prototype-less calls or calls to functions containing ellipsis (...) in
2941 // the declaration) %al is used as hidden argument to specify the number
2942 // of SSE registers used. The contents of %al do not need to match exactly
2943 // the number of registers, but must be an ubound on the number of SSE
2944 // registers used and is in the range 0 - 8 inclusive.
2946 // Count the number of XMM registers allocated.
2947 static const MCPhysReg XMMArgRegs[] = {
2948 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2949 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2951 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2952 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2953 && "SSE registers cannot be used when SSE is disabled");
2955 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2956 DAG.getConstant(NumXMMRegs, dl,
2960 if (isVarArg && IsMustTail) {
2961 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2962 for (const auto &F : Forwards) {
2963 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2964 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2968 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2969 // don't need this because the eligibility check rejects calls that require
2970 // shuffling arguments passed in memory.
2971 if (!IsSibcall && isTailCall) {
2972 // Force all the incoming stack arguments to be loaded from the stack
2973 // before any new outgoing arguments are stored to the stack, because the
2974 // outgoing stack slots may alias the incoming argument stack slots, and
2975 // the alias isn't otherwise explicit. This is slightly more conservative
2976 // than necessary, because it means that each store effectively depends
2977 // on every argument instead of just those arguments it would clobber.
2978 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2980 SmallVector<SDValue, 8> MemOpChains2;
2983 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2984 CCValAssign &VA = ArgLocs[i];
2987 assert(VA.isMemLoc());
2988 SDValue Arg = OutVals[i];
2989 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2990 // Skip inalloca arguments. They don't require any work.
2991 if (Flags.isInAlloca())
2993 // Create frame index.
2994 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2995 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2996 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2997 FIN = DAG.getFrameIndex(FI, getPointerTy());
2999 if (Flags.isByVal()) {
3000 // Copy relative to framepointer.
3001 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3002 if (!StackPtr.getNode())
3003 StackPtr = DAG.getCopyFromReg(Chain, dl,
3004 RegInfo->getStackRegister(),
3006 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3008 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3012 // Store relative to framepointer.
3013 MemOpChains2.push_back(
3014 DAG.getStore(ArgChain, dl, Arg, FIN,
3015 MachinePointerInfo::getFixedStack(FI),
3020 if (!MemOpChains2.empty())
3021 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3023 // Store the return address to the appropriate stack slot.
3024 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3025 getPointerTy(), RegInfo->getSlotSize(),
3029 // Build a sequence of copy-to-reg nodes chained together with token chain
3030 // and flag operands which copy the outgoing args into registers.
3032 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3033 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3034 RegsToPass[i].second, InFlag);
3035 InFlag = Chain.getValue(1);
3038 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3039 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3040 // In the 64-bit large code model, we have to make all calls
3041 // through a register, since the call instruction's 32-bit
3042 // pc-relative offset may not be large enough to hold the whole
3044 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3045 // If the callee is a GlobalAddress node (quite common, every direct call
3046 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3048 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3050 // We should use extra load for direct calls to dllimported functions in
3052 const GlobalValue *GV = G->getGlobal();
3053 if (!GV->hasDLLImportStorageClass()) {
3054 unsigned char OpFlags = 0;
3055 bool ExtraLoad = false;
3056 unsigned WrapperKind = ISD::DELETED_NODE;
3058 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3059 // external symbols most go through the PLT in PIC mode. If the symbol
3060 // has hidden or protected visibility, or if it is static or local, then
3061 // we don't need to use the PLT - we can directly call it.
3062 if (Subtarget->isTargetELF() &&
3063 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3064 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3065 OpFlags = X86II::MO_PLT;
3066 } else if (Subtarget->isPICStyleStubAny() &&
3067 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3068 (!Subtarget->getTargetTriple().isMacOSX() ||
3069 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3070 // PC-relative references to external symbols should go through $stub,
3071 // unless we're building with the leopard linker or later, which
3072 // automatically synthesizes these stubs.
3073 OpFlags = X86II::MO_DARWIN_STUB;
3074 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3075 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3076 // If the function is marked as non-lazy, generate an indirect call
3077 // which loads from the GOT directly. This avoids runtime overhead
3078 // at the cost of eager binding (and one extra byte of encoding).
3079 OpFlags = X86II::MO_GOTPCREL;
3080 WrapperKind = X86ISD::WrapperRIP;
3084 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3085 G->getOffset(), OpFlags);
3087 // Add a wrapper if needed.
3088 if (WrapperKind != ISD::DELETED_NODE)
3089 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3090 // Add extra indirection if needed.
3092 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3093 MachinePointerInfo::getGOT(),
3094 false, false, false, 0);
3096 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3097 unsigned char OpFlags = 0;
3099 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3100 // external symbols should go through the PLT.
3101 if (Subtarget->isTargetELF() &&
3102 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3103 OpFlags = X86II::MO_PLT;
3104 } else if (Subtarget->isPICStyleStubAny() &&
3105 (!Subtarget->getTargetTriple().isMacOSX() ||
3106 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3107 // PC-relative references to external symbols should go through $stub,
3108 // unless we're building with the leopard linker or later, which
3109 // automatically synthesizes these stubs.
3110 OpFlags = X86II::MO_DARWIN_STUB;
3113 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3115 } else if (Subtarget->isTarget64BitILP32() &&
3116 Callee->getValueType(0) == MVT::i32) {
3117 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3118 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3121 // Returns a chain & a flag for retval copy to use.
3122 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3123 SmallVector<SDValue, 8> Ops;
3125 if (!IsSibcall && isTailCall) {
3126 Chain = DAG.getCALLSEQ_END(Chain,
3127 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3128 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3129 InFlag = Chain.getValue(1);
3132 Ops.push_back(Chain);
3133 Ops.push_back(Callee);
3136 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3138 // Add argument registers to the end of the list so that they are known live
3140 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3141 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3142 RegsToPass[i].second.getValueType()));
3144 // Add a register mask operand representing the call-preserved registers.
3145 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3146 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3147 assert(Mask && "Missing call preserved mask for calling convention");
3148 Ops.push_back(DAG.getRegisterMask(Mask));
3150 if (InFlag.getNode())
3151 Ops.push_back(InFlag);
3155 //// If this is the first return lowered for this function, add the regs
3156 //// to the liveout set for the function.
3157 // This isn't right, although it's probably harmless on x86; liveouts
3158 // should be computed from returns not tail calls. Consider a void
3159 // function making a tail call to a function returning int.
3160 MF.getFrameInfo()->setHasTailCall();
3161 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3164 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3165 InFlag = Chain.getValue(1);
3167 // Create the CALLSEQ_END node.
3168 unsigned NumBytesForCalleeToPop;
3169 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3170 DAG.getTarget().Options.GuaranteedTailCallOpt))
3171 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3172 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3173 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3174 SR == StackStructReturn)
3175 // If this is a call to a struct-return function, the callee
3176 // pops the hidden struct pointer, so we have to push it back.
3177 // This is common for Darwin/X86, Linux & Mingw32 targets.
3178 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3179 NumBytesForCalleeToPop = 4;
3181 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3183 // Returns a flag for retval copy to use.
3185 Chain = DAG.getCALLSEQ_END(Chain,
3186 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3187 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3190 InFlag = Chain.getValue(1);
3193 // Handle result values, copying them out of physregs into vregs that we
3195 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3196 Ins, dl, DAG, InVals);
3199 //===----------------------------------------------------------------------===//
3200 // Fast Calling Convention (tail call) implementation
3201 //===----------------------------------------------------------------------===//
3203 // Like std call, callee cleans arguments, convention except that ECX is
3204 // reserved for storing the tail called function address. Only 2 registers are
3205 // free for argument passing (inreg). Tail call optimization is performed
3207 // * tailcallopt is enabled
3208 // * caller/callee are fastcc
3209 // On X86_64 architecture with GOT-style position independent code only local
3210 // (within module) calls are supported at the moment.
3211 // To keep the stack aligned according to platform abi the function
3212 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3213 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3214 // If a tail called function callee has more arguments than the caller the
3215 // caller needs to make sure that there is room to move the RETADDR to. This is
3216 // achieved by reserving an area the size of the argument delta right after the
3217 // original RETADDR, but before the saved framepointer or the spilled registers
3218 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3230 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3231 /// for a 16 byte align requirement.
3233 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3234 SelectionDAG& DAG) const {
3235 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3236 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3237 unsigned StackAlignment = TFI.getStackAlignment();
3238 uint64_t AlignMask = StackAlignment - 1;
3239 int64_t Offset = StackSize;
3240 unsigned SlotSize = RegInfo->getSlotSize();
3241 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3242 // Number smaller than 12 so just add the difference.
3243 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3245 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3246 Offset = ((~AlignMask) & Offset) + StackAlignment +
3247 (StackAlignment-SlotSize);
3252 /// MatchingStackOffset - Return true if the given stack call argument is
3253 /// already available in the same position (relatively) of the caller's
3254 /// incoming argument stack.
3256 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3257 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3258 const X86InstrInfo *TII) {
3259 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3261 if (Arg.getOpcode() == ISD::CopyFromReg) {
3262 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3263 if (!TargetRegisterInfo::isVirtualRegister(VR))
3265 MachineInstr *Def = MRI->getVRegDef(VR);
3268 if (!Flags.isByVal()) {
3269 if (!TII->isLoadFromStackSlot(Def, FI))
3272 unsigned Opcode = Def->getOpcode();
3273 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3274 Opcode == X86::LEA64_32r) &&
3275 Def->getOperand(1).isFI()) {
3276 FI = Def->getOperand(1).getIndex();
3277 Bytes = Flags.getByValSize();
3281 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3282 if (Flags.isByVal())
3283 // ByVal argument is passed in as a pointer but it's now being
3284 // dereferenced. e.g.
3285 // define @foo(%struct.X* %A) {
3286 // tail call @bar(%struct.X* byval %A)
3289 SDValue Ptr = Ld->getBasePtr();
3290 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3293 FI = FINode->getIndex();
3294 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3295 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3296 FI = FINode->getIndex();
3297 Bytes = Flags.getByValSize();
3301 assert(FI != INT_MAX);
3302 if (!MFI->isFixedObjectIndex(FI))
3304 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3307 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3308 /// for tail call optimization. Targets which want to do tail call
3309 /// optimization should implement this function.
3311 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3312 CallingConv::ID CalleeCC,
3314 bool isCalleeStructRet,
3315 bool isCallerStructRet,
3317 const SmallVectorImpl<ISD::OutputArg> &Outs,
3318 const SmallVectorImpl<SDValue> &OutVals,
3319 const SmallVectorImpl<ISD::InputArg> &Ins,
3320 SelectionDAG &DAG) const {
3321 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3324 // If -tailcallopt is specified, make fastcc functions tail-callable.
3325 const MachineFunction &MF = DAG.getMachineFunction();
3326 const Function *CallerF = MF.getFunction();
3328 // If the function return type is x86_fp80 and the callee return type is not,
3329 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3330 // perform a tailcall optimization here.
3331 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3334 CallingConv::ID CallerCC = CallerF->getCallingConv();
3335 bool CCMatch = CallerCC == CalleeCC;
3336 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3337 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3339 // Win64 functions have extra shadow space for argument homing. Don't do the
3340 // sibcall if the caller and callee have mismatched expectations for this
3342 if (IsCalleeWin64 != IsCallerWin64)
3345 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3346 if (IsTailCallConvention(CalleeCC) && CCMatch)
3351 // Look for obvious safe cases to perform tail call optimization that do not
3352 // require ABI changes. This is what gcc calls sibcall.
3354 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3355 // emit a special epilogue.
3356 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3357 if (RegInfo->needsStackRealignment(MF))
3360 // Also avoid sibcall optimization if either caller or callee uses struct
3361 // return semantics.
3362 if (isCalleeStructRet || isCallerStructRet)
3365 // An stdcall/thiscall caller is expected to clean up its arguments; the
3366 // callee isn't going to do that.
3367 // FIXME: this is more restrictive than needed. We could produce a tailcall
3368 // when the stack adjustment matches. For example, with a thiscall that takes
3369 // only one argument.
3370 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3371 CallerCC == CallingConv::X86_ThisCall))
3374 // Do not sibcall optimize vararg calls unless all arguments are passed via
3376 if (isVarArg && !Outs.empty()) {
3378 // Optimizing for varargs on Win64 is unlikely to be safe without
3379 // additional testing.
3380 if (IsCalleeWin64 || IsCallerWin64)
3383 SmallVector<CCValAssign, 16> ArgLocs;
3384 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3387 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3388 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3389 if (!ArgLocs[i].isRegLoc())
3393 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3394 // stack. Therefore, if it's not used by the call it is not safe to optimize
3395 // this into a sibcall.
3396 bool Unused = false;
3397 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3404 SmallVector<CCValAssign, 16> RVLocs;
3405 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3407 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3408 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3409 CCValAssign &VA = RVLocs[i];
3410 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3415 // If the calling conventions do not match, then we'd better make sure the
3416 // results are returned in the same way as what the caller expects.
3418 SmallVector<CCValAssign, 16> RVLocs1;
3419 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3421 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3423 SmallVector<CCValAssign, 16> RVLocs2;
3424 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3426 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3428 if (RVLocs1.size() != RVLocs2.size())
3430 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3431 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3433 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3435 if (RVLocs1[i].isRegLoc()) {
3436 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3439 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3445 // If the callee takes no arguments then go on to check the results of the
3447 if (!Outs.empty()) {
3448 // Check if stack adjustment is needed. For now, do not do this if any
3449 // argument is passed on the stack.
3450 SmallVector<CCValAssign, 16> ArgLocs;
3451 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3454 // Allocate shadow area for Win64
3456 CCInfo.AllocateStack(32, 8);
3458 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3459 if (CCInfo.getNextStackOffset()) {
3460 MachineFunction &MF = DAG.getMachineFunction();
3461 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3464 // Check if the arguments are already laid out in the right way as
3465 // the caller's fixed stack objects.
3466 MachineFrameInfo *MFI = MF.getFrameInfo();
3467 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3468 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3469 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3470 CCValAssign &VA = ArgLocs[i];
3471 SDValue Arg = OutVals[i];
3472 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3473 if (VA.getLocInfo() == CCValAssign::Indirect)
3475 if (!VA.isRegLoc()) {
3476 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3483 // If the tailcall address may be in a register, then make sure it's
3484 // possible to register allocate for it. In 32-bit, the call address can
3485 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3486 // callee-saved registers are restored. These happen to be the same
3487 // registers used to pass 'inreg' arguments so watch out for those.
3488 if (!Subtarget->is64Bit() &&
3489 ((!isa<GlobalAddressSDNode>(Callee) &&
3490 !isa<ExternalSymbolSDNode>(Callee)) ||
3491 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3492 unsigned NumInRegs = 0;
3493 // In PIC we need an extra register to formulate the address computation
3495 unsigned MaxInRegs =
3496 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3498 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3499 CCValAssign &VA = ArgLocs[i];
3502 unsigned Reg = VA.getLocReg();
3505 case X86::EAX: case X86::EDX: case X86::ECX:
3506 if (++NumInRegs == MaxInRegs)
3518 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3519 const TargetLibraryInfo *libInfo) const {
3520 return X86::createFastISel(funcInfo, libInfo);
3523 //===----------------------------------------------------------------------===//
3524 // Other Lowering Hooks
3525 //===----------------------------------------------------------------------===//
3527 static bool MayFoldLoad(SDValue Op) {
3528 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3531 static bool MayFoldIntoStore(SDValue Op) {
3532 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3535 static bool isTargetShuffle(unsigned Opcode) {
3537 default: return false;
3538 case X86ISD::BLENDI:
3539 case X86ISD::PSHUFB:
3540 case X86ISD::PSHUFD:
3541 case X86ISD::PSHUFHW:
3542 case X86ISD::PSHUFLW:
3544 case X86ISD::PALIGNR:
3545 case X86ISD::MOVLHPS:
3546 case X86ISD::MOVLHPD:
3547 case X86ISD::MOVHLPS:
3548 case X86ISD::MOVLPS:
3549 case X86ISD::MOVLPD:
3550 case X86ISD::MOVSHDUP:
3551 case X86ISD::MOVSLDUP:
3552 case X86ISD::MOVDDUP:
3555 case X86ISD::UNPCKL:
3556 case X86ISD::UNPCKH:
3557 case X86ISD::VPERMILPI:
3558 case X86ISD::VPERM2X128:
3559 case X86ISD::VPERMI:
3564 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3565 SDValue V1, unsigned TargetMask,
3566 SelectionDAG &DAG) {
3568 default: llvm_unreachable("Unknown x86 shuffle node");
3569 case X86ISD::PSHUFD:
3570 case X86ISD::PSHUFHW:
3571 case X86ISD::PSHUFLW:
3572 case X86ISD::VPERMILPI:
3573 case X86ISD::VPERMI:
3574 return DAG.getNode(Opc, dl, VT, V1,
3575 DAG.getConstant(TargetMask, dl, MVT::i8));
3579 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3580 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3582 default: llvm_unreachable("Unknown x86 shuffle node");
3583 case X86ISD::MOVLHPS:
3584 case X86ISD::MOVLHPD:
3585 case X86ISD::MOVHLPS:
3586 case X86ISD::MOVLPS:
3587 case X86ISD::MOVLPD:
3590 case X86ISD::UNPCKL:
3591 case X86ISD::UNPCKH:
3592 return DAG.getNode(Opc, dl, VT, V1, V2);
3596 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3597 MachineFunction &MF = DAG.getMachineFunction();
3598 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3599 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3600 int ReturnAddrIndex = FuncInfo->getRAIndex();
3602 if (ReturnAddrIndex == 0) {
3603 // Set up a frame object for the return address.
3604 unsigned SlotSize = RegInfo->getSlotSize();
3605 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3608 FuncInfo->setRAIndex(ReturnAddrIndex);
3611 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3614 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3615 bool hasSymbolicDisplacement) {
3616 // Offset should fit into 32 bit immediate field.
3617 if (!isInt<32>(Offset))
3620 // If we don't have a symbolic displacement - we don't have any extra
3622 if (!hasSymbolicDisplacement)
3625 // FIXME: Some tweaks might be needed for medium code model.
3626 if (M != CodeModel::Small && M != CodeModel::Kernel)
3629 // For small code model we assume that latest object is 16MB before end of 31
3630 // bits boundary. We may also accept pretty large negative constants knowing
3631 // that all objects are in the positive half of address space.
3632 if (M == CodeModel::Small && Offset < 16*1024*1024)
3635 // For kernel code model we know that all object resist in the negative half
3636 // of 32bits address space. We may not accept negative offsets, since they may
3637 // be just off and we may accept pretty large positive ones.
3638 if (M == CodeModel::Kernel && Offset >= 0)
3644 /// isCalleePop - Determines whether the callee is required to pop its
3645 /// own arguments. Callee pop is necessary to support tail calls.
3646 bool X86::isCalleePop(CallingConv::ID CallingConv,
3647 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3648 switch (CallingConv) {
3651 case CallingConv::X86_StdCall:
3652 case CallingConv::X86_FastCall:
3653 case CallingConv::X86_ThisCall:
3655 case CallingConv::Fast:
3656 case CallingConv::GHC:
3657 case CallingConv::HiPE:
3664 /// \brief Return true if the condition is an unsigned comparison operation.
3665 static bool isX86CCUnsigned(unsigned X86CC) {
3667 default: llvm_unreachable("Invalid integer condition!");
3668 case X86::COND_E: return true;
3669 case X86::COND_G: return false;
3670 case X86::COND_GE: return false;
3671 case X86::COND_L: return false;
3672 case X86::COND_LE: return false;
3673 case X86::COND_NE: return true;
3674 case X86::COND_B: return true;
3675 case X86::COND_A: return true;
3676 case X86::COND_BE: return true;
3677 case X86::COND_AE: return true;
3679 llvm_unreachable("covered switch fell through?!");
3682 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3683 /// specific condition code, returning the condition code and the LHS/RHS of the
3684 /// comparison to make.
3685 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3686 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3688 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3689 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3690 // X > -1 -> X == 0, jump !sign.
3691 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3692 return X86::COND_NS;
3694 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3695 // X < 0 -> X == 0, jump on sign.
3698 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3700 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3701 return X86::COND_LE;
3705 switch (SetCCOpcode) {
3706 default: llvm_unreachable("Invalid integer condition!");
3707 case ISD::SETEQ: return X86::COND_E;
3708 case ISD::SETGT: return X86::COND_G;
3709 case ISD::SETGE: return X86::COND_GE;
3710 case ISD::SETLT: return X86::COND_L;
3711 case ISD::SETLE: return X86::COND_LE;
3712 case ISD::SETNE: return X86::COND_NE;
3713 case ISD::SETULT: return X86::COND_B;
3714 case ISD::SETUGT: return X86::COND_A;
3715 case ISD::SETULE: return X86::COND_BE;
3716 case ISD::SETUGE: return X86::COND_AE;
3720 // First determine if it is required or is profitable to flip the operands.
3722 // If LHS is a foldable load, but RHS is not, flip the condition.
3723 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3724 !ISD::isNON_EXTLoad(RHS.getNode())) {
3725 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3726 std::swap(LHS, RHS);
3729 switch (SetCCOpcode) {
3735 std::swap(LHS, RHS);
3739 // On a floating point condition, the flags are set as follows:
3741 // 0 | 0 | 0 | X > Y
3742 // 0 | 0 | 1 | X < Y
3743 // 1 | 0 | 0 | X == Y
3744 // 1 | 1 | 1 | unordered
3745 switch (SetCCOpcode) {
3746 default: llvm_unreachable("Condcode should be pre-legalized away");
3748 case ISD::SETEQ: return X86::COND_E;
3749 case ISD::SETOLT: // flipped
3751 case ISD::SETGT: return X86::COND_A;
3752 case ISD::SETOLE: // flipped
3754 case ISD::SETGE: return X86::COND_AE;
3755 case ISD::SETUGT: // flipped
3757 case ISD::SETLT: return X86::COND_B;
3758 case ISD::SETUGE: // flipped
3760 case ISD::SETLE: return X86::COND_BE;
3762 case ISD::SETNE: return X86::COND_NE;
3763 case ISD::SETUO: return X86::COND_P;
3764 case ISD::SETO: return X86::COND_NP;
3766 case ISD::SETUNE: return X86::COND_INVALID;
3770 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3771 /// code. Current x86 isa includes the following FP cmov instructions:
3772 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3773 static bool hasFPCMov(unsigned X86CC) {
3789 /// isFPImmLegal - Returns true if the target can instruction select the
3790 /// specified FP immediate natively. If false, the legalizer will
3791 /// materialize the FP immediate as a load from a constant pool.
3792 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3793 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3794 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3800 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3801 ISD::LoadExtType ExtTy,
3803 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3804 // relocation target a movq or addq instruction: don't let the load shrink.
3805 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3806 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3807 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3808 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3812 /// \brief Returns true if it is beneficial to convert a load of a constant
3813 /// to just the constant itself.
3814 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3816 assert(Ty->isIntegerTy());
3818 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3819 if (BitSize == 0 || BitSize > 64)
3824 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3825 unsigned Index) const {
3826 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3829 return (Index == 0 || Index == ResVT.getVectorNumElements());
3832 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3833 // Speculate cttz only if we can directly use TZCNT.
3834 return Subtarget->hasBMI();
3837 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3838 // Speculate ctlz only if we can directly use LZCNT.
3839 return Subtarget->hasLZCNT();
3842 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3843 /// the specified range (L, H].
3844 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3845 return (Val < 0) || (Val >= Low && Val < Hi);
3848 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3849 /// specified value.
3850 static bool isUndefOrEqual(int Val, int CmpVal) {
3851 return (Val < 0 || Val == CmpVal);
3854 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3855 /// from position Pos and ending in Pos+Size, falls within the specified
3856 /// sequential range (Low, Low+Size]. or is undef.
3857 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3858 unsigned Pos, unsigned Size, int Low) {
3859 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3860 if (!isUndefOrEqual(Mask[i], Low))
3865 /// isVEXTRACTIndex - Return true if the specified
3866 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3867 /// suitable for instruction that extract 128 or 256 bit vectors
3868 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3869 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3870 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3873 // The index should be aligned on a vecWidth-bit boundary.
3875 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3877 MVT VT = N->getSimpleValueType(0);
3878 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3879 bool Result = (Index * ElSize) % vecWidth == 0;
3884 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3885 /// operand specifies a subvector insert that is suitable for input to
3886 /// insertion of 128 or 256-bit subvectors
3887 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3888 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3889 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3891 // The index should be aligned on a vecWidth-bit boundary.
3893 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3895 MVT VT = N->getSimpleValueType(0);
3896 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3897 bool Result = (Index * ElSize) % vecWidth == 0;
3902 bool X86::isVINSERT128Index(SDNode *N) {
3903 return isVINSERTIndex(N, 128);
3906 bool X86::isVINSERT256Index(SDNode *N) {
3907 return isVINSERTIndex(N, 256);
3910 bool X86::isVEXTRACT128Index(SDNode *N) {
3911 return isVEXTRACTIndex(N, 128);
3914 bool X86::isVEXTRACT256Index(SDNode *N) {
3915 return isVEXTRACTIndex(N, 256);
3918 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3919 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3920 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3921 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3924 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3926 MVT VecVT = N->getOperand(0).getSimpleValueType();
3927 MVT ElVT = VecVT.getVectorElementType();
3929 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3930 return Index / NumElemsPerChunk;
3933 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3934 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3935 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3936 llvm_unreachable("Illegal insert subvector for VINSERT");
3939 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3941 MVT VecVT = N->getSimpleValueType(0);
3942 MVT ElVT = VecVT.getVectorElementType();
3944 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3945 return Index / NumElemsPerChunk;
3948 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3949 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3950 /// and VINSERTI128 instructions.
3951 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3952 return getExtractVEXTRACTImmediate(N, 128);
3955 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3956 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3957 /// and VINSERTI64x4 instructions.
3958 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3959 return getExtractVEXTRACTImmediate(N, 256);
3962 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3963 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3964 /// and VINSERTI128 instructions.
3965 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3966 return getInsertVINSERTImmediate(N, 128);
3969 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3970 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3971 /// and VINSERTI64x4 instructions.
3972 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3973 return getInsertVINSERTImmediate(N, 256);
3976 /// isZero - Returns true if Elt is a constant integer zero
3977 static bool isZero(SDValue V) {
3978 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3979 return C && C->isNullValue();
3982 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3984 bool X86::isZeroNode(SDValue Elt) {
3987 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3988 return CFP->getValueAPF().isPosZero();
3992 /// getZeroVector - Returns a vector of specified type with all zero elements.
3994 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3995 SelectionDAG &DAG, SDLoc dl) {
3996 assert(VT.isVector() && "Expected a vector type");
3998 // Always build SSE zero vectors as <4 x i32> bitcasted
3999 // to their dest type. This ensures they get CSE'd.
4001 if (VT.is128BitVector()) { // SSE
4002 if (Subtarget->hasSSE2()) { // SSE2
4003 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4004 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4006 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4007 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4009 } else if (VT.is256BitVector()) { // AVX
4010 if (Subtarget->hasInt256()) { // AVX2
4011 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4012 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4013 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4015 // 256-bit logic and arithmetic instructions in AVX are all
4016 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4017 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4018 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4019 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4021 } else if (VT.is512BitVector()) { // AVX-512
4022 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4023 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4024 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4025 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4026 } else if (VT.getScalarType() == MVT::i1) {
4028 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4029 && "Unexpected vector type");
4030 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4031 && "Unexpected vector type");
4032 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4033 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4034 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4036 llvm_unreachable("Unexpected vector type");
4038 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4041 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4042 SelectionDAG &DAG, SDLoc dl,
4043 unsigned vectorWidth) {
4044 assert((vectorWidth == 128 || vectorWidth == 256) &&
4045 "Unsupported vector width");
4046 EVT VT = Vec.getValueType();
4047 EVT ElVT = VT.getVectorElementType();
4048 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4049 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4050 VT.getVectorNumElements()/Factor);
4052 // Extract from UNDEF is UNDEF.
4053 if (Vec.getOpcode() == ISD::UNDEF)
4054 return DAG.getUNDEF(ResultVT);
4056 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4057 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4059 // This is the index of the first element of the vectorWidth-bit chunk
4061 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4064 // If the input is a buildvector just emit a smaller one.
4065 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4066 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4067 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4070 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4071 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4074 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4075 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4076 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4077 /// instructions or a simple subregister reference. Idx is an index in the
4078 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4079 /// lowering EXTRACT_VECTOR_ELT operations easier.
4080 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4081 SelectionDAG &DAG, SDLoc dl) {
4082 assert((Vec.getValueType().is256BitVector() ||
4083 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4084 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4087 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4088 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4089 SelectionDAG &DAG, SDLoc dl) {
4090 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4091 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4094 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4095 unsigned IdxVal, SelectionDAG &DAG,
4096 SDLoc dl, unsigned vectorWidth) {
4097 assert((vectorWidth == 128 || vectorWidth == 256) &&
4098 "Unsupported vector width");
4099 // Inserting UNDEF is Result
4100 if (Vec.getOpcode() == ISD::UNDEF)
4102 EVT VT = Vec.getValueType();
4103 EVT ElVT = VT.getVectorElementType();
4104 EVT ResultVT = Result.getValueType();
4106 // Insert the relevant vectorWidth bits.
4107 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4109 // This is the index of the first element of the vectorWidth-bit chunk
4111 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4114 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4115 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4118 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4119 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4120 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4121 /// simple superregister reference. Idx is an index in the 128 bits
4122 /// we want. It need not be aligned to a 128-bit boundary. That makes
4123 /// lowering INSERT_VECTOR_ELT operations easier.
4124 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4125 SelectionDAG &DAG, SDLoc dl) {
4126 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4128 // For insertion into the zero index (low half) of a 256-bit vector, it is
4129 // more efficient to generate a blend with immediate instead of an insert*128.
4130 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4131 // extend the subvector to the size of the result vector. Make sure that
4132 // we are not recursing on that node by checking for undef here.
4133 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4134 Result.getOpcode() != ISD::UNDEF) {
4135 EVT ResultVT = Result.getValueType();
4136 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4137 SDValue Undef = DAG.getUNDEF(ResultVT);
4138 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4141 // The blend instruction, and therefore its mask, depend on the data type.
4142 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4143 if (ScalarType.isFloatingPoint()) {
4144 // Choose either vblendps (float) or vblendpd (double).
4145 unsigned ScalarSize = ScalarType.getSizeInBits();
4146 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4147 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4148 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4149 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4152 const X86Subtarget &Subtarget =
4153 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4155 // AVX2 is needed for 256-bit integer blend support.
4156 // Integers must be cast to 32-bit because there is only vpblendd;
4157 // vpblendw can't be used for this because it has a handicapped mask.
4159 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4160 // is still more efficient than using the wrong domain vinsertf128 that
4161 // will be created by InsertSubVector().
4162 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4164 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4165 Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4166 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4167 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4170 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4173 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4174 SelectionDAG &DAG, SDLoc dl) {
4175 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4176 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4179 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4180 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4181 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4182 /// large BUILD_VECTORS.
4183 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4184 unsigned NumElems, SelectionDAG &DAG,
4186 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4187 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4190 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4191 unsigned NumElems, SelectionDAG &DAG,
4193 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4194 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4197 /// getOnesVector - Returns a vector of specified type with all bits set.
4198 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4199 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4200 /// Then bitcast to their original type, ensuring they get CSE'd.
4201 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4203 assert(VT.isVector() && "Expected a vector type");
4205 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4207 if (VT.is256BitVector()) {
4208 if (HasInt256) { // AVX2
4209 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4210 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4212 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4213 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4215 } else if (VT.is128BitVector()) {
4216 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4218 llvm_unreachable("Unexpected vector type");
4220 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4223 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4224 /// operation of specified width.
4225 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4227 unsigned NumElems = VT.getVectorNumElements();
4228 SmallVector<int, 8> Mask;
4229 Mask.push_back(NumElems);
4230 for (unsigned i = 1; i != NumElems; ++i)
4232 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4235 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4236 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4238 unsigned NumElems = VT.getVectorNumElements();
4239 SmallVector<int, 8> Mask;
4240 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4242 Mask.push_back(i + NumElems);
4244 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4247 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4248 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4250 unsigned NumElems = VT.getVectorNumElements();
4251 SmallVector<int, 8> Mask;
4252 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4253 Mask.push_back(i + Half);
4254 Mask.push_back(i + NumElems + Half);
4256 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4259 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4260 /// vector of zero or undef vector. This produces a shuffle where the low
4261 /// element of V2 is swizzled into the zero/undef vector, landing at element
4262 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4263 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4265 const X86Subtarget *Subtarget,
4266 SelectionDAG &DAG) {
4267 MVT VT = V2.getSimpleValueType();
4269 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4270 unsigned NumElems = VT.getVectorNumElements();
4271 SmallVector<int, 16> MaskVec;
4272 for (unsigned i = 0; i != NumElems; ++i)
4273 // If this is the insertion idx, put the low elt of V2 here.
4274 MaskVec.push_back(i == Idx ? NumElems : i);
4275 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4278 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4279 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4280 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4281 /// shuffles which use a single input multiple times, and in those cases it will
4282 /// adjust the mask to only have indices within that single input.
4283 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4284 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4285 unsigned NumElems = VT.getVectorNumElements();
4289 bool IsFakeUnary = false;
4290 switch(N->getOpcode()) {
4291 case X86ISD::BLENDI:
4292 ImmN = N->getOperand(N->getNumOperands()-1);
4293 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4296 ImmN = N->getOperand(N->getNumOperands()-1);
4297 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4298 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4300 case X86ISD::UNPCKH:
4301 DecodeUNPCKHMask(VT, Mask);
4302 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4304 case X86ISD::UNPCKL:
4305 DecodeUNPCKLMask(VT, Mask);
4306 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4308 case X86ISD::MOVHLPS:
4309 DecodeMOVHLPSMask(NumElems, Mask);
4310 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4312 case X86ISD::MOVLHPS:
4313 DecodeMOVLHPSMask(NumElems, Mask);
4314 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4316 case X86ISD::PALIGNR:
4317 ImmN = N->getOperand(N->getNumOperands()-1);
4318 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4320 case X86ISD::PSHUFD:
4321 case X86ISD::VPERMILPI:
4322 ImmN = N->getOperand(N->getNumOperands()-1);
4323 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4326 case X86ISD::PSHUFHW:
4327 ImmN = N->getOperand(N->getNumOperands()-1);
4328 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4331 case X86ISD::PSHUFLW:
4332 ImmN = N->getOperand(N->getNumOperands()-1);
4333 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4336 case X86ISD::PSHUFB: {
4338 SDValue MaskNode = N->getOperand(1);
4339 while (MaskNode->getOpcode() == ISD::BITCAST)
4340 MaskNode = MaskNode->getOperand(0);
4342 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4343 // If we have a build-vector, then things are easy.
4344 EVT VT = MaskNode.getValueType();
4345 assert(VT.isVector() &&
4346 "Can't produce a non-vector with a build_vector!");
4347 if (!VT.isInteger())
4350 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4352 SmallVector<uint64_t, 32> RawMask;
4353 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4354 SDValue Op = MaskNode->getOperand(i);
4355 if (Op->getOpcode() == ISD::UNDEF) {
4356 RawMask.push_back((uint64_t)SM_SentinelUndef);
4359 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4362 APInt MaskElement = CN->getAPIntValue();
4364 // We now have to decode the element which could be any integer size and
4365 // extract each byte of it.
4366 for (int j = 0; j < NumBytesPerElement; ++j) {
4367 // Note that this is x86 and so always little endian: the low byte is
4368 // the first byte of the mask.
4369 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4370 MaskElement = MaskElement.lshr(8);
4373 DecodePSHUFBMask(RawMask, Mask);
4377 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4381 SDValue Ptr = MaskLoad->getBasePtr();
4382 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4383 Ptr->getOpcode() == X86ISD::WrapperRIP)
4384 Ptr = Ptr->getOperand(0);
4386 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4387 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4390 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4391 DecodePSHUFBMask(C, Mask);
4399 case X86ISD::VPERMI:
4400 ImmN = N->getOperand(N->getNumOperands()-1);
4401 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4406 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4408 case X86ISD::VPERM2X128:
4409 ImmN = N->getOperand(N->getNumOperands()-1);
4410 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4411 if (Mask.empty()) return false;
4413 case X86ISD::MOVSLDUP:
4414 DecodeMOVSLDUPMask(VT, Mask);
4417 case X86ISD::MOVSHDUP:
4418 DecodeMOVSHDUPMask(VT, Mask);
4421 case X86ISD::MOVDDUP:
4422 DecodeMOVDDUPMask(VT, Mask);
4425 case X86ISD::MOVLHPD:
4426 case X86ISD::MOVLPD:
4427 case X86ISD::MOVLPS:
4428 // Not yet implemented
4430 default: llvm_unreachable("unknown target shuffle node");
4433 // If we have a fake unary shuffle, the shuffle mask is spread across two
4434 // inputs that are actually the same node. Re-map the mask to always point
4435 // into the first input.
4438 if (M >= (int)Mask.size())
4444 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4445 /// element of the result of the vector shuffle.
4446 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4449 return SDValue(); // Limit search depth.
4451 SDValue V = SDValue(N, 0);
4452 EVT VT = V.getValueType();
4453 unsigned Opcode = V.getOpcode();
4455 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4456 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4457 int Elt = SV->getMaskElt(Index);
4460 return DAG.getUNDEF(VT.getVectorElementType());
4462 unsigned NumElems = VT.getVectorNumElements();
4463 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4464 : SV->getOperand(1);
4465 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4468 // Recurse into target specific vector shuffles to find scalars.
4469 if (isTargetShuffle(Opcode)) {
4470 MVT ShufVT = V.getSimpleValueType();
4471 unsigned NumElems = ShufVT.getVectorNumElements();
4472 SmallVector<int, 16> ShuffleMask;
4475 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4478 int Elt = ShuffleMask[Index];
4480 return DAG.getUNDEF(ShufVT.getVectorElementType());
4482 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4484 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4488 // Actual nodes that may contain scalar elements
4489 if (Opcode == ISD::BITCAST) {
4490 V = V.getOperand(0);
4491 EVT SrcVT = V.getValueType();
4492 unsigned NumElems = VT.getVectorNumElements();
4494 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4498 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4499 return (Index == 0) ? V.getOperand(0)
4500 : DAG.getUNDEF(VT.getVectorElementType());
4502 if (V.getOpcode() == ISD::BUILD_VECTOR)
4503 return V.getOperand(Index);
4508 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4510 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4511 unsigned NumNonZero, unsigned NumZero,
4513 const X86Subtarget* Subtarget,
4514 const TargetLowering &TLI) {
4522 // SSE4.1 - use PINSRB to insert each byte directly.
4523 if (Subtarget->hasSSE41()) {
4524 for (unsigned i = 0; i < 16; ++i) {
4525 bool isNonZero = (NonZeros & (1 << i)) != 0;
4529 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4531 V = DAG.getUNDEF(MVT::v16i8);
4534 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4535 MVT::v16i8, V, Op.getOperand(i),
4536 DAG.getIntPtrConstant(i, dl));
4543 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4544 for (unsigned i = 0; i < 16; ++i) {
4545 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4546 if (ThisIsNonZero && First) {
4548 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4550 V = DAG.getUNDEF(MVT::v8i16);
4555 SDValue ThisElt, LastElt;
4556 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4557 if (LastIsNonZero) {
4558 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4559 MVT::i16, Op.getOperand(i-1));
4561 if (ThisIsNonZero) {
4562 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4563 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4564 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4566 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4570 if (ThisElt.getNode())
4571 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4572 DAG.getIntPtrConstant(i/2, dl));
4576 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4579 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4581 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4582 unsigned NumNonZero, unsigned NumZero,
4584 const X86Subtarget* Subtarget,
4585 const TargetLowering &TLI) {
4592 for (unsigned i = 0; i < 8; ++i) {
4593 bool isNonZero = (NonZeros & (1 << i)) != 0;
4597 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4599 V = DAG.getUNDEF(MVT::v8i16);
4602 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4603 MVT::v8i16, V, Op.getOperand(i),
4604 DAG.getIntPtrConstant(i, dl));
4611 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4612 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4613 const X86Subtarget *Subtarget,
4614 const TargetLowering &TLI) {
4615 // Find all zeroable elements.
4616 std::bitset<4> Zeroable;
4617 for (int i=0; i < 4; ++i) {
4618 SDValue Elt = Op->getOperand(i);
4619 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4621 assert(Zeroable.size() - Zeroable.count() > 1 &&
4622 "We expect at least two non-zero elements!");
4624 // We only know how to deal with build_vector nodes where elements are either
4625 // zeroable or extract_vector_elt with constant index.
4626 SDValue FirstNonZero;
4627 unsigned FirstNonZeroIdx;
4628 for (unsigned i=0; i < 4; ++i) {
4631 SDValue Elt = Op->getOperand(i);
4632 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4633 !isa<ConstantSDNode>(Elt.getOperand(1)))
4635 // Make sure that this node is extracting from a 128-bit vector.
4636 MVT VT = Elt.getOperand(0).getSimpleValueType();
4637 if (!VT.is128BitVector())
4639 if (!FirstNonZero.getNode()) {
4641 FirstNonZeroIdx = i;
4645 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4646 SDValue V1 = FirstNonZero.getOperand(0);
4647 MVT VT = V1.getSimpleValueType();
4649 // See if this build_vector can be lowered as a blend with zero.
4651 unsigned EltMaskIdx, EltIdx;
4653 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4654 if (Zeroable[EltIdx]) {
4655 // The zero vector will be on the right hand side.
4656 Mask[EltIdx] = EltIdx+4;
4660 Elt = Op->getOperand(EltIdx);
4661 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4662 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4663 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4665 Mask[EltIdx] = EltIdx;
4669 // Let the shuffle legalizer deal with blend operations.
4670 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4671 if (V1.getSimpleValueType() != VT)
4672 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4673 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4676 // See if we can lower this build_vector to a INSERTPS.
4677 if (!Subtarget->hasSSE41())
4680 SDValue V2 = Elt.getOperand(0);
4681 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4684 bool CanFold = true;
4685 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4689 SDValue Current = Op->getOperand(i);
4690 SDValue SrcVector = Current->getOperand(0);
4693 CanFold = SrcVector == V1 &&
4694 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4700 assert(V1.getNode() && "Expected at least two non-zero elements!");
4701 if (V1.getSimpleValueType() != MVT::v4f32)
4702 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4703 if (V2.getSimpleValueType() != MVT::v4f32)
4704 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4706 // Ok, we can emit an INSERTPS instruction.
4707 unsigned ZMask = Zeroable.to_ulong();
4709 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4710 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4712 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4713 DAG.getIntPtrConstant(InsertPSMask, DL));
4714 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4717 /// Return a vector logical shift node.
4718 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4719 unsigned NumBits, SelectionDAG &DAG,
4720 const TargetLowering &TLI, SDLoc dl) {
4721 assert(VT.is128BitVector() && "Unknown type for VShift");
4722 MVT ShVT = MVT::v2i64;
4723 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4724 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4725 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4726 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4727 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4728 return DAG.getNode(ISD::BITCAST, dl, VT,
4729 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4733 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4735 // Check if the scalar load can be widened into a vector load. And if
4736 // the address is "base + cst" see if the cst can be "absorbed" into
4737 // the shuffle mask.
4738 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4739 SDValue Ptr = LD->getBasePtr();
4740 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4742 EVT PVT = LD->getValueType(0);
4743 if (PVT != MVT::i32 && PVT != MVT::f32)
4748 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4749 FI = FINode->getIndex();
4751 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4752 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4753 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4754 Offset = Ptr.getConstantOperandVal(1);
4755 Ptr = Ptr.getOperand(0);
4760 // FIXME: 256-bit vector instructions don't require a strict alignment,
4761 // improve this code to support it better.
4762 unsigned RequiredAlign = VT.getSizeInBits()/8;
4763 SDValue Chain = LD->getChain();
4764 // Make sure the stack object alignment is at least 16 or 32.
4765 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4766 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4767 if (MFI->isFixedObjectIndex(FI)) {
4768 // Can't change the alignment. FIXME: It's possible to compute
4769 // the exact stack offset and reference FI + adjust offset instead.
4770 // If someone *really* cares about this. That's the way to implement it.
4773 MFI->setObjectAlignment(FI, RequiredAlign);
4777 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4778 // Ptr + (Offset & ~15).
4781 if ((Offset % RequiredAlign) & 3)
4783 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4786 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4787 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4790 int EltNo = (Offset - StartOffset) >> 2;
4791 unsigned NumElems = VT.getVectorNumElements();
4793 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4794 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4795 LD->getPointerInfo().getWithOffset(StartOffset),
4796 false, false, false, 0);
4798 SmallVector<int, 8> Mask(NumElems, EltNo);
4800 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4806 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4807 /// elements can be replaced by a single large load which has the same value as
4808 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4810 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4812 /// FIXME: we'd also like to handle the case where the last elements are zero
4813 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4814 /// There's even a handy isZeroNode for that purpose.
4815 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4816 SDLoc &DL, SelectionDAG &DAG,
4817 bool isAfterLegalize) {
4818 unsigned NumElems = Elts.size();
4820 LoadSDNode *LDBase = nullptr;
4821 unsigned LastLoadedElt = -1U;
4823 // For each element in the initializer, see if we've found a load or an undef.
4824 // If we don't find an initial load element, or later load elements are
4825 // non-consecutive, bail out.
4826 for (unsigned i = 0; i < NumElems; ++i) {
4827 SDValue Elt = Elts[i];
4828 // Look through a bitcast.
4829 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4830 Elt = Elt.getOperand(0);
4831 if (!Elt.getNode() ||
4832 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4835 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4837 LDBase = cast<LoadSDNode>(Elt.getNode());
4841 if (Elt.getOpcode() == ISD::UNDEF)
4844 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4845 EVT LdVT = Elt.getValueType();
4846 // Each loaded element must be the correct fractional portion of the
4847 // requested vector load.
4848 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4850 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4855 // If we have found an entire vector of loads and undefs, then return a large
4856 // load of the entire vector width starting at the base pointer. If we found
4857 // consecutive loads for the low half, generate a vzext_load node.
4858 if (LastLoadedElt == NumElems - 1) {
4859 assert(LDBase && "Did not find base load for merging consecutive loads");
4860 EVT EltVT = LDBase->getValueType(0);
4861 // Ensure that the input vector size for the merged loads matches the
4862 // cumulative size of the input elements.
4863 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4866 if (isAfterLegalize &&
4867 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4870 SDValue NewLd = SDValue();
4872 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4873 LDBase->getPointerInfo(), LDBase->isVolatile(),
4874 LDBase->isNonTemporal(), LDBase->isInvariant(),
4875 LDBase->getAlignment());
4877 if (LDBase->hasAnyUseOfValue(1)) {
4878 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4880 SDValue(NewLd.getNode(), 1));
4881 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4882 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4883 SDValue(NewLd.getNode(), 1));
4889 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4890 //of a v4i32 / v4f32. It's probably worth generalizing.
4891 EVT EltVT = VT.getVectorElementType();
4892 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4893 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4894 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4895 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4897 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4898 LDBase->getPointerInfo(),
4899 LDBase->getAlignment(),
4900 false/*isVolatile*/, true/*ReadMem*/,
4903 // Make sure the newly-created LOAD is in the same position as LDBase in
4904 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4905 // update uses of LDBase's output chain to use the TokenFactor.
4906 if (LDBase->hasAnyUseOfValue(1)) {
4907 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4908 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4909 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4910 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4911 SDValue(ResNode.getNode(), 1));
4914 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4919 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4920 /// to generate a splat value for the following cases:
4921 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4922 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4923 /// a scalar load, or a constant.
4924 /// The VBROADCAST node is returned when a pattern is found,
4925 /// or SDValue() otherwise.
4926 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4927 SelectionDAG &DAG) {
4928 // VBROADCAST requires AVX.
4929 // TODO: Splats could be generated for non-AVX CPUs using SSE
4930 // instructions, but there's less potential gain for only 128-bit vectors.
4931 if (!Subtarget->hasAVX())
4934 MVT VT = Op.getSimpleValueType();
4937 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4938 "Unsupported vector type for broadcast.");
4943 switch (Op.getOpcode()) {
4945 // Unknown pattern found.
4948 case ISD::BUILD_VECTOR: {
4949 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4950 BitVector UndefElements;
4951 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4953 // We need a splat of a single value to use broadcast, and it doesn't
4954 // make any sense if the value is only in one element of the vector.
4955 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4959 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4960 Ld.getOpcode() == ISD::ConstantFP);
4962 // Make sure that all of the users of a non-constant load are from the
4963 // BUILD_VECTOR node.
4964 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4969 case ISD::VECTOR_SHUFFLE: {
4970 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4972 // Shuffles must have a splat mask where the first element is
4974 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4977 SDValue Sc = Op.getOperand(0);
4978 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4979 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4981 if (!Subtarget->hasInt256())
4984 // Use the register form of the broadcast instruction available on AVX2.
4985 if (VT.getSizeInBits() >= 256)
4986 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4987 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4990 Ld = Sc.getOperand(0);
4991 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4992 Ld.getOpcode() == ISD::ConstantFP);
4994 // The scalar_to_vector node and the suspected
4995 // load node must have exactly one user.
4996 // Constants may have multiple users.
4998 // AVX-512 has register version of the broadcast
4999 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5000 Ld.getValueType().getSizeInBits() >= 32;
5001 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5008 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5009 bool IsGE256 = (VT.getSizeInBits() >= 256);
5011 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5012 // instruction to save 8 or more bytes of constant pool data.
5013 // TODO: If multiple splats are generated to load the same constant,
5014 // it may be detrimental to overall size. There needs to be a way to detect
5015 // that condition to know if this is truly a size win.
5016 const Function *F = DAG.getMachineFunction().getFunction();
5017 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5019 // Handle broadcasting a single constant scalar from the constant pool
5021 // On Sandybridge (no AVX2), it is still better to load a constant vector
5022 // from the constant pool and not to broadcast it from a scalar.
5023 // But override that restriction when optimizing for size.
5024 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5025 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5026 EVT CVT = Ld.getValueType();
5027 assert(!CVT.isVector() && "Must not broadcast a vector type");
5029 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5030 // For size optimization, also splat v2f64 and v2i64, and for size opt
5031 // with AVX2, also splat i8 and i16.
5032 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5033 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5034 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5035 const Constant *C = nullptr;
5036 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5037 C = CI->getConstantIntValue();
5038 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5039 C = CF->getConstantFPValue();
5041 assert(C && "Invalid constant type");
5043 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5044 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5045 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5046 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5047 MachinePointerInfo::getConstantPool(),
5048 false, false, false, Alignment);
5050 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5054 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5056 // Handle AVX2 in-register broadcasts.
5057 if (!IsLoad && Subtarget->hasInt256() &&
5058 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5059 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5061 // The scalar source must be a normal load.
5065 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5066 (Subtarget->hasVLX() && ScalarSize == 64))
5067 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5069 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5070 // double since there is no vbroadcastsd xmm
5071 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5072 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5073 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5076 // Unsupported broadcast.
5080 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5081 /// underlying vector and index.
5083 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5085 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5087 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5088 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5091 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5093 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5095 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5096 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5099 // In this case the vector is the extract_subvector expression and the index
5100 // is 2, as specified by the shuffle.
5101 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5102 SDValue ShuffleVec = SVOp->getOperand(0);
5103 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5104 assert(ShuffleVecVT.getVectorElementType() ==
5105 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5107 int ShuffleIdx = SVOp->getMaskElt(Idx);
5108 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5109 ExtractedFromVec = ShuffleVec;
5115 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5116 MVT VT = Op.getSimpleValueType();
5118 // Skip if insert_vec_elt is not supported.
5119 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5120 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5124 unsigned NumElems = Op.getNumOperands();
5128 SmallVector<unsigned, 4> InsertIndices;
5129 SmallVector<int, 8> Mask(NumElems, -1);
5131 for (unsigned i = 0; i != NumElems; ++i) {
5132 unsigned Opc = Op.getOperand(i).getOpcode();
5134 if (Opc == ISD::UNDEF)
5137 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5138 // Quit if more than 1 elements need inserting.
5139 if (InsertIndices.size() > 1)
5142 InsertIndices.push_back(i);
5146 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5147 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5148 // Quit if non-constant index.
5149 if (!isa<ConstantSDNode>(ExtIdx))
5151 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5153 // Quit if extracted from vector of different type.
5154 if (ExtractedFromVec.getValueType() != VT)
5157 if (!VecIn1.getNode())
5158 VecIn1 = ExtractedFromVec;
5159 else if (VecIn1 != ExtractedFromVec) {
5160 if (!VecIn2.getNode())
5161 VecIn2 = ExtractedFromVec;
5162 else if (VecIn2 != ExtractedFromVec)
5163 // Quit if more than 2 vectors to shuffle
5167 if (ExtractedFromVec == VecIn1)
5169 else if (ExtractedFromVec == VecIn2)
5170 Mask[i] = Idx + NumElems;
5173 if (!VecIn1.getNode())
5176 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5177 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5178 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5179 unsigned Idx = InsertIndices[i];
5180 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5181 DAG.getIntPtrConstant(Idx, DL));
5187 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5189 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5191 MVT VT = Op.getSimpleValueType();
5192 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5193 "Unexpected type in LowerBUILD_VECTORvXi1!");
5196 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5197 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5198 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5199 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5202 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5203 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5204 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5205 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5208 bool AllContants = true;
5209 uint64_t Immediate = 0;
5210 int NonConstIdx = -1;
5211 bool IsSplat = true;
5212 unsigned NumNonConsts = 0;
5213 unsigned NumConsts = 0;
5214 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5215 SDValue In = Op.getOperand(idx);
5216 if (In.getOpcode() == ISD::UNDEF)
5218 if (!isa<ConstantSDNode>(In)) {
5219 AllContants = false;
5224 if (cast<ConstantSDNode>(In)->getZExtValue())
5225 Immediate |= (1ULL << idx);
5227 if (In != Op.getOperand(0))
5232 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5233 DAG.getConstant(Immediate, dl, MVT::i16));
5234 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5235 DAG.getIntPtrConstant(0, dl));
5238 if (NumNonConsts == 1 && NonConstIdx != 0) {
5241 SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5242 MVT::getIntegerVT(VT.getSizeInBits()));
5243 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5246 DstVec = DAG.getUNDEF(VT);
5247 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5248 Op.getOperand(NonConstIdx),
5249 DAG.getIntPtrConstant(NonConstIdx, dl));
5251 if (!IsSplat && (NonConstIdx != 0))
5252 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5253 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5256 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5257 DAG.getConstant(-1, dl, SelectVT),
5258 DAG.getConstant(0, dl, SelectVT));
5260 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5261 DAG.getConstant((Immediate | 1), dl, SelectVT),
5262 DAG.getConstant(Immediate, dl, SelectVT));
5263 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5266 /// \brief Return true if \p N implements a horizontal binop and return the
5267 /// operands for the horizontal binop into V0 and V1.
5269 /// This is a helper function of LowerToHorizontalOp().
5270 /// This function checks that the build_vector \p N in input implements a
5271 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5272 /// operation to match.
5273 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5274 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5275 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5278 /// This function only analyzes elements of \p N whose indices are
5279 /// in range [BaseIdx, LastIdx).
5280 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5282 unsigned BaseIdx, unsigned LastIdx,
5283 SDValue &V0, SDValue &V1) {
5284 EVT VT = N->getValueType(0);
5286 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5287 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5288 "Invalid Vector in input!");
5290 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5291 bool CanFold = true;
5292 unsigned ExpectedVExtractIdx = BaseIdx;
5293 unsigned NumElts = LastIdx - BaseIdx;
5294 V0 = DAG.getUNDEF(VT);
5295 V1 = DAG.getUNDEF(VT);
5297 // Check if N implements a horizontal binop.
5298 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5299 SDValue Op = N->getOperand(i + BaseIdx);
5302 if (Op->getOpcode() == ISD::UNDEF) {
5303 // Update the expected vector extract index.
5304 if (i * 2 == NumElts)
5305 ExpectedVExtractIdx = BaseIdx;
5306 ExpectedVExtractIdx += 2;
5310 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5315 SDValue Op0 = Op.getOperand(0);
5316 SDValue Op1 = Op.getOperand(1);
5318 // Try to match the following pattern:
5319 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5320 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5321 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5322 Op0.getOperand(0) == Op1.getOperand(0) &&
5323 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5324 isa<ConstantSDNode>(Op1.getOperand(1)));
5328 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5329 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5331 if (i * 2 < NumElts) {
5332 if (V0.getOpcode() == ISD::UNDEF) {
5333 V0 = Op0.getOperand(0);
5334 if (V0.getValueType() != VT)
5338 if (V1.getOpcode() == ISD::UNDEF) {
5339 V1 = Op0.getOperand(0);
5340 if (V1.getValueType() != VT)
5343 if (i * 2 == NumElts)
5344 ExpectedVExtractIdx = BaseIdx;
5347 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5348 if (I0 == ExpectedVExtractIdx)
5349 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5350 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5351 // Try to match the following dag sequence:
5352 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5353 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5357 ExpectedVExtractIdx += 2;
5363 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5364 /// a concat_vector.
5366 /// This is a helper function of LowerToHorizontalOp().
5367 /// This function expects two 256-bit vectors called V0 and V1.
5368 /// At first, each vector is split into two separate 128-bit vectors.
5369 /// Then, the resulting 128-bit vectors are used to implement two
5370 /// horizontal binary operations.
5372 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5374 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5375 /// the two new horizontal binop.
5376 /// When Mode is set, the first horizontal binop dag node would take as input
5377 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5378 /// horizontal binop dag node would take as input the lower 128-bit of V1
5379 /// and the upper 128-bit of V1.
5381 /// HADD V0_LO, V0_HI
5382 /// HADD V1_LO, V1_HI
5384 /// Otherwise, the first horizontal binop dag node takes as input the lower
5385 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5386 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5388 /// HADD V0_LO, V1_LO
5389 /// HADD V0_HI, V1_HI
5391 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5392 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5393 /// the upper 128-bits of the result.
5394 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5395 SDLoc DL, SelectionDAG &DAG,
5396 unsigned X86Opcode, bool Mode,
5397 bool isUndefLO, bool isUndefHI) {
5398 EVT VT = V0.getValueType();
5399 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5400 "Invalid nodes in input!");
5402 unsigned NumElts = VT.getVectorNumElements();
5403 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5404 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5405 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5406 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5407 EVT NewVT = V0_LO.getValueType();
5409 SDValue LO = DAG.getUNDEF(NewVT);
5410 SDValue HI = DAG.getUNDEF(NewVT);
5413 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5414 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5415 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5416 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5417 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5419 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5420 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5421 V1_LO->getOpcode() != ISD::UNDEF))
5422 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5424 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5425 V1_HI->getOpcode() != ISD::UNDEF))
5426 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5429 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5432 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5434 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5435 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5436 EVT VT = BV->getValueType(0);
5437 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5438 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5442 unsigned NumElts = VT.getVectorNumElements();
5443 SDValue InVec0 = DAG.getUNDEF(VT);
5444 SDValue InVec1 = DAG.getUNDEF(VT);
5446 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5447 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5449 // Odd-numbered elements in the input build vector are obtained from
5450 // adding two integer/float elements.
5451 // Even-numbered elements in the input build vector are obtained from
5452 // subtracting two integer/float elements.
5453 unsigned ExpectedOpcode = ISD::FSUB;
5454 unsigned NextExpectedOpcode = ISD::FADD;
5455 bool AddFound = false;
5456 bool SubFound = false;
5458 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5459 SDValue Op = BV->getOperand(i);
5461 // Skip 'undef' values.
5462 unsigned Opcode = Op.getOpcode();
5463 if (Opcode == ISD::UNDEF) {
5464 std::swap(ExpectedOpcode, NextExpectedOpcode);
5468 // Early exit if we found an unexpected opcode.
5469 if (Opcode != ExpectedOpcode)
5472 SDValue Op0 = Op.getOperand(0);
5473 SDValue Op1 = Op.getOperand(1);
5475 // Try to match the following pattern:
5476 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5477 // Early exit if we cannot match that sequence.
5478 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5479 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5480 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5481 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5482 Op0.getOperand(1) != Op1.getOperand(1))
5485 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5489 // We found a valid add/sub node. Update the information accordingly.
5495 // Update InVec0 and InVec1.
5496 if (InVec0.getOpcode() == ISD::UNDEF) {
5497 InVec0 = Op0.getOperand(0);
5498 if (InVec0.getValueType() != VT)
5501 if (InVec1.getOpcode() == ISD::UNDEF) {
5502 InVec1 = Op1.getOperand(0);
5503 if (InVec1.getValueType() != VT)
5507 // Make sure that operands in input to each add/sub node always
5508 // come from a same pair of vectors.
5509 if (InVec0 != Op0.getOperand(0)) {
5510 if (ExpectedOpcode == ISD::FSUB)
5513 // FADD is commutable. Try to commute the operands
5514 // and then test again.
5515 std::swap(Op0, Op1);
5516 if (InVec0 != Op0.getOperand(0))
5520 if (InVec1 != Op1.getOperand(0))
5523 // Update the pair of expected opcodes.
5524 std::swap(ExpectedOpcode, NextExpectedOpcode);
5527 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5528 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5529 InVec1.getOpcode() != ISD::UNDEF)
5530 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5535 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5536 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5537 const X86Subtarget *Subtarget,
5538 SelectionDAG &DAG) {
5539 EVT VT = BV->getValueType(0);
5540 unsigned NumElts = VT.getVectorNumElements();
5541 unsigned NumUndefsLO = 0;
5542 unsigned NumUndefsHI = 0;
5543 unsigned Half = NumElts/2;
5545 // Count the number of UNDEF operands in the build_vector in input.
5546 for (unsigned i = 0, e = Half; i != e; ++i)
5547 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5550 for (unsigned i = Half, e = NumElts; i != e; ++i)
5551 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5554 // Early exit if this is either a build_vector of all UNDEFs or all the
5555 // operands but one are UNDEF.
5556 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5560 SDValue InVec0, InVec1;
5561 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5562 // Try to match an SSE3 float HADD/HSUB.
5563 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5564 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5566 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5567 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5568 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5569 // Try to match an SSSE3 integer HADD/HSUB.
5570 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5571 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5573 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5574 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5577 if (!Subtarget->hasAVX())
5580 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5581 // Try to match an AVX horizontal add/sub of packed single/double
5582 // precision floating point values from 256-bit vectors.
5583 SDValue InVec2, InVec3;
5584 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5585 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5586 ((InVec0.getOpcode() == ISD::UNDEF ||
5587 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5588 ((InVec1.getOpcode() == ISD::UNDEF ||
5589 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5590 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5592 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5593 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5594 ((InVec0.getOpcode() == ISD::UNDEF ||
5595 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5596 ((InVec1.getOpcode() == ISD::UNDEF ||
5597 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5598 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5599 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5600 // Try to match an AVX2 horizontal add/sub of signed integers.
5601 SDValue InVec2, InVec3;
5603 bool CanFold = true;
5605 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5606 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5607 ((InVec0.getOpcode() == ISD::UNDEF ||
5608 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5609 ((InVec1.getOpcode() == ISD::UNDEF ||
5610 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5611 X86Opcode = X86ISD::HADD;
5612 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5613 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5614 ((InVec0.getOpcode() == ISD::UNDEF ||
5615 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5616 ((InVec1.getOpcode() == ISD::UNDEF ||
5617 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5618 X86Opcode = X86ISD::HSUB;
5623 // Fold this build_vector into a single horizontal add/sub.
5624 // Do this only if the target has AVX2.
5625 if (Subtarget->hasAVX2())
5626 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5628 // Do not try to expand this build_vector into a pair of horizontal
5629 // add/sub if we can emit a pair of scalar add/sub.
5630 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5633 // Convert this build_vector into a pair of horizontal binop followed by
5635 bool isUndefLO = NumUndefsLO == Half;
5636 bool isUndefHI = NumUndefsHI == Half;
5637 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5638 isUndefLO, isUndefHI);
5642 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5643 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5645 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5646 X86Opcode = X86ISD::HADD;
5647 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5648 X86Opcode = X86ISD::HSUB;
5649 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5650 X86Opcode = X86ISD::FHADD;
5651 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5652 X86Opcode = X86ISD::FHSUB;
5656 // Don't try to expand this build_vector into a pair of horizontal add/sub
5657 // if we can simply emit a pair of scalar add/sub.
5658 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5661 // Convert this build_vector into two horizontal add/sub followed by
5663 bool isUndefLO = NumUndefsLO == Half;
5664 bool isUndefHI = NumUndefsHI == Half;
5665 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5666 isUndefLO, isUndefHI);
5673 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5676 MVT VT = Op.getSimpleValueType();
5677 MVT ExtVT = VT.getVectorElementType();
5678 unsigned NumElems = Op.getNumOperands();
5680 // Generate vectors for predicate vectors.
5681 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5682 return LowerBUILD_VECTORvXi1(Op, DAG);
5684 // Vectors containing all zeros can be matched by pxor and xorps later
5685 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5686 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5687 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5688 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5691 return getZeroVector(VT, Subtarget, DAG, dl);
5694 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5695 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5696 // vpcmpeqd on 256-bit vectors.
5697 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5698 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5701 if (!VT.is512BitVector())
5702 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5705 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5706 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5708 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5709 return HorizontalOp;
5710 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5713 unsigned EVTBits = ExtVT.getSizeInBits();
5715 unsigned NumZero = 0;
5716 unsigned NumNonZero = 0;
5717 unsigned NonZeros = 0;
5718 bool IsAllConstants = true;
5719 SmallSet<SDValue, 8> Values;
5720 for (unsigned i = 0; i < NumElems; ++i) {
5721 SDValue Elt = Op.getOperand(i);
5722 if (Elt.getOpcode() == ISD::UNDEF)
5725 if (Elt.getOpcode() != ISD::Constant &&
5726 Elt.getOpcode() != ISD::ConstantFP)
5727 IsAllConstants = false;
5728 if (X86::isZeroNode(Elt))
5731 NonZeros |= (1 << i);
5736 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5737 if (NumNonZero == 0)
5738 return DAG.getUNDEF(VT);
5740 // Special case for single non-zero, non-undef, element.
5741 if (NumNonZero == 1) {
5742 unsigned Idx = countTrailingZeros(NonZeros);
5743 SDValue Item = Op.getOperand(Idx);
5745 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5746 // the value are obviously zero, truncate the value to i32 and do the
5747 // insertion that way. Only do this if the value is non-constant or if the
5748 // value is a constant being inserted into element 0. It is cheaper to do
5749 // a constant pool load than it is to do a movd + shuffle.
5750 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5751 (!IsAllConstants || Idx == 0)) {
5752 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5754 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5755 EVT VecVT = MVT::v4i32;
5757 // Truncate the value (which may itself be a constant) to i32, and
5758 // convert it to a vector with movd (S2V+shuffle to zero extend).
5759 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5760 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5762 ISD::BITCAST, dl, VT,
5763 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5767 // If we have a constant or non-constant insertion into the low element of
5768 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5769 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5770 // depending on what the source datatype is.
5773 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5775 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5776 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5777 if (VT.is512BitVector()) {
5778 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5779 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5780 Item, DAG.getIntPtrConstant(0, dl));
5782 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5783 "Expected an SSE value type!");
5784 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5785 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5786 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5789 // We can't directly insert an i8 or i16 into a vector, so zero extend
5791 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5792 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5793 if (VT.is256BitVector()) {
5794 if (Subtarget->hasAVX()) {
5795 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5796 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5798 // Without AVX, we need to extend to a 128-bit vector and then
5799 // insert into the 256-bit vector.
5800 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5801 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5802 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5805 assert(VT.is128BitVector() && "Expected an SSE value type!");
5806 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5807 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5809 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5813 // Is it a vector logical left shift?
5814 if (NumElems == 2 && Idx == 1 &&
5815 X86::isZeroNode(Op.getOperand(0)) &&
5816 !X86::isZeroNode(Op.getOperand(1))) {
5817 unsigned NumBits = VT.getSizeInBits();
5818 return getVShift(true, VT,
5819 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5820 VT, Op.getOperand(1)),
5821 NumBits/2, DAG, *this, dl);
5824 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5827 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5828 // is a non-constant being inserted into an element other than the low one,
5829 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5830 // movd/movss) to move this into the low element, then shuffle it into
5832 if (EVTBits == 32) {
5833 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5834 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5838 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5839 if (Values.size() == 1) {
5840 if (EVTBits == 32) {
5841 // Instead of a shuffle like this:
5842 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5843 // Check if it's possible to issue this instead.
5844 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5845 unsigned Idx = countTrailingZeros(NonZeros);
5846 SDValue Item = Op.getOperand(Idx);
5847 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5848 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5853 // A vector full of immediates; various special cases are already
5854 // handled, so this is best done with a single constant-pool load.
5858 // For AVX-length vectors, see if we can use a vector load to get all of the
5859 // elements, otherwise build the individual 128-bit pieces and use
5860 // shuffles to put them in place.
5861 if (VT.is256BitVector() || VT.is512BitVector()) {
5862 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5864 // Check for a build vector of consecutive loads.
5865 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5868 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5870 // Build both the lower and upper subvector.
5871 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5872 makeArrayRef(&V[0], NumElems/2));
5873 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5874 makeArrayRef(&V[NumElems / 2], NumElems/2));
5876 // Recreate the wider vector with the lower and upper part.
5877 if (VT.is256BitVector())
5878 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5879 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5882 // Let legalizer expand 2-wide build_vectors.
5883 if (EVTBits == 64) {
5884 if (NumNonZero == 1) {
5885 // One half is zero or undef.
5886 unsigned Idx = countTrailingZeros(NonZeros);
5887 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5888 Op.getOperand(Idx));
5889 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5894 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5895 if (EVTBits == 8 && NumElems == 16)
5896 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5900 if (EVTBits == 16 && NumElems == 8)
5901 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5905 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5906 if (EVTBits == 32 && NumElems == 4)
5907 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5910 // If element VT is == 32 bits, turn it into a number of shuffles.
5911 SmallVector<SDValue, 8> V(NumElems);
5912 if (NumElems == 4 && NumZero > 0) {
5913 for (unsigned i = 0; i < 4; ++i) {
5914 bool isZero = !(NonZeros & (1 << i));
5916 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5918 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5921 for (unsigned i = 0; i < 2; ++i) {
5922 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5925 V[i] = V[i*2]; // Must be a zero vector.
5928 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5931 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5934 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5939 bool Reverse1 = (NonZeros & 0x3) == 2;
5940 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5944 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5945 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5947 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5950 if (Values.size() > 1 && VT.is128BitVector()) {
5951 // Check for a build vector of consecutive loads.
5952 for (unsigned i = 0; i < NumElems; ++i)
5953 V[i] = Op.getOperand(i);
5955 // Check for elements which are consecutive loads.
5956 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5959 // Check for a build vector from mostly shuffle plus few inserting.
5960 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5963 // For SSE 4.1, use insertps to put the high elements into the low element.
5964 if (Subtarget->hasSSE41()) {
5966 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5967 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5969 Result = DAG.getUNDEF(VT);
5971 for (unsigned i = 1; i < NumElems; ++i) {
5972 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5973 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5974 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5979 // Otherwise, expand into a number of unpckl*, start by extending each of
5980 // our (non-undef) elements to the full vector width with the element in the
5981 // bottom slot of the vector (which generates no code for SSE).
5982 for (unsigned i = 0; i < NumElems; ++i) {
5983 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5984 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5986 V[i] = DAG.getUNDEF(VT);
5989 // Next, we iteratively mix elements, e.g. for v4f32:
5990 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5991 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5992 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5993 unsigned EltStride = NumElems >> 1;
5994 while (EltStride != 0) {
5995 for (unsigned i = 0; i < EltStride; ++i) {
5996 // If V[i+EltStride] is undef and this is the first round of mixing,
5997 // then it is safe to just drop this shuffle: V[i] is already in the
5998 // right place, the one element (since it's the first round) being
5999 // inserted as undef can be dropped. This isn't safe for successive
6000 // rounds because they will permute elements within both vectors.
6001 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6002 EltStride == NumElems/2)
6005 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6014 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6015 // to create 256-bit vectors from two other 128-bit ones.
6016 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6018 MVT ResVT = Op.getSimpleValueType();
6020 assert((ResVT.is256BitVector() ||
6021 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6023 SDValue V1 = Op.getOperand(0);
6024 SDValue V2 = Op.getOperand(1);
6025 unsigned NumElems = ResVT.getVectorNumElements();
6026 if (ResVT.is256BitVector())
6027 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6029 if (Op.getNumOperands() == 4) {
6030 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6031 ResVT.getVectorNumElements()/2);
6032 SDValue V3 = Op.getOperand(2);
6033 SDValue V4 = Op.getOperand(3);
6034 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6035 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6037 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6040 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6041 const X86Subtarget *Subtarget,
6042 SelectionDAG & DAG) {
6044 MVT ResVT = Op.getSimpleValueType();
6045 unsigned NumOfOperands = Op.getNumOperands();
6047 assert(isPowerOf2_32(NumOfOperands) &&
6048 "Unexpected number of operands in CONCAT_VECTORS");
6050 if (NumOfOperands > 2) {
6051 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6052 ResVT.getVectorNumElements()/2);
6053 SmallVector<SDValue, 2> Ops;
6054 for (unsigned i = 0; i < NumOfOperands/2; i++)
6055 Ops.push_back(Op.getOperand(i));
6056 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6058 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6059 Ops.push_back(Op.getOperand(i));
6060 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6061 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6064 SDValue V1 = Op.getOperand(0);
6065 SDValue V2 = Op.getOperand(1);
6066 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6067 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6069 if (IsZeroV1 && IsZeroV2)
6070 return getZeroVector(ResVT, Subtarget, DAG, dl);
6072 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6073 SDValue Undef = DAG.getUNDEF(ResVT);
6074 unsigned NumElems = ResVT.getVectorNumElements();
6075 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6077 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6078 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6082 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6083 // Zero the upper bits of V1
6084 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6085 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6088 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6091 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6092 const X86Subtarget *Subtarget,
6093 SelectionDAG &DAG) {
6094 MVT VT = Op.getSimpleValueType();
6095 if (VT.getVectorElementType() == MVT::i1)
6096 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6098 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6099 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6100 Op.getNumOperands() == 4)));
6102 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6103 // from two other 128-bit ones.
6105 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6106 return LowerAVXCONCAT_VECTORS(Op, DAG);
6110 //===----------------------------------------------------------------------===//
6111 // Vector shuffle lowering
6113 // This is an experimental code path for lowering vector shuffles on x86. It is
6114 // designed to handle arbitrary vector shuffles and blends, gracefully
6115 // degrading performance as necessary. It works hard to recognize idiomatic
6116 // shuffles and lower them to optimal instruction patterns without leaving
6117 // a framework that allows reasonably efficient handling of all vector shuffle
6119 //===----------------------------------------------------------------------===//
6121 /// \brief Tiny helper function to identify a no-op mask.
6123 /// This is a somewhat boring predicate function. It checks whether the mask
6124 /// array input, which is assumed to be a single-input shuffle mask of the kind
6125 /// used by the X86 shuffle instructions (not a fully general
6126 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6127 /// in-place shuffle are 'no-op's.
6128 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6129 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6130 if (Mask[i] != -1 && Mask[i] != i)
6135 /// \brief Helper function to classify a mask as a single-input mask.
6137 /// This isn't a generic single-input test because in the vector shuffle
6138 /// lowering we canonicalize single inputs to be the first input operand. This
6139 /// means we can more quickly test for a single input by only checking whether
6140 /// an input from the second operand exists. We also assume that the size of
6141 /// mask corresponds to the size of the input vectors which isn't true in the
6142 /// fully general case.
6143 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6145 if (M >= (int)Mask.size())
6150 /// \brief Test whether there are elements crossing 128-bit lanes in this
6153 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6154 /// and we routinely test for these.
6155 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6156 int LaneSize = 128 / VT.getScalarSizeInBits();
6157 int Size = Mask.size();
6158 for (int i = 0; i < Size; ++i)
6159 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6164 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6166 /// This checks a shuffle mask to see if it is performing the same
6167 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6168 /// that it is also not lane-crossing. It may however involve a blend from the
6169 /// same lane of a second vector.
6171 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6172 /// non-trivial to compute in the face of undef lanes. The representation is
6173 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6174 /// entries from both V1 and V2 inputs to the wider mask.
6176 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6177 SmallVectorImpl<int> &RepeatedMask) {
6178 int LaneSize = 128 / VT.getScalarSizeInBits();
6179 RepeatedMask.resize(LaneSize, -1);
6180 int Size = Mask.size();
6181 for (int i = 0; i < Size; ++i) {
6184 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6185 // This entry crosses lanes, so there is no way to model this shuffle.
6188 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6189 if (RepeatedMask[i % LaneSize] == -1)
6190 // This is the first non-undef entry in this slot of a 128-bit lane.
6191 RepeatedMask[i % LaneSize] =
6192 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6193 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6194 // Found a mismatch with the repeated mask.
6200 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6203 /// This is a fast way to test a shuffle mask against a fixed pattern:
6205 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6207 /// It returns true if the mask is exactly as wide as the argument list, and
6208 /// each element of the mask is either -1 (signifying undef) or the value given
6209 /// in the argument.
6210 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6211 ArrayRef<int> ExpectedMask) {
6212 if (Mask.size() != ExpectedMask.size())
6215 int Size = Mask.size();
6217 // If the values are build vectors, we can look through them to find
6218 // equivalent inputs that make the shuffles equivalent.
6219 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6220 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6222 for (int i = 0; i < Size; ++i)
6223 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6224 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6225 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6226 if (!MaskBV || !ExpectedBV ||
6227 MaskBV->getOperand(Mask[i] % Size) !=
6228 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6235 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6237 /// This helper function produces an 8-bit shuffle immediate corresponding to
6238 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6239 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6242 /// NB: We rely heavily on "undef" masks preserving the input lane.
6243 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6244 SelectionDAG &DAG) {
6245 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6246 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6247 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6248 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6249 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6252 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6253 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6254 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6255 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6256 return DAG.getConstant(Imm, DL, MVT::i8);
6259 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6261 /// This is used as a fallback approach when first class blend instructions are
6262 /// unavailable. Currently it is only suitable for integer vectors, but could
6263 /// be generalized for floating point vectors if desirable.
6264 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6265 SDValue V2, ArrayRef<int> Mask,
6266 SelectionDAG &DAG) {
6267 assert(VT.isInteger() && "Only supports integer vector types!");
6268 MVT EltVT = VT.getScalarType();
6269 int NumEltBits = EltVT.getSizeInBits();
6270 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6271 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6273 SmallVector<SDValue, 16> MaskOps;
6274 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6275 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6276 return SDValue(); // Shuffled input!
6277 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6280 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6281 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6282 // We have to cast V2 around.
6283 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6284 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6285 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6286 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6287 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6288 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6291 /// \brief Try to emit a blend instruction for a shuffle.
6293 /// This doesn't do any checks for the availability of instructions for blending
6294 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6295 /// be matched in the backend with the type given. What it does check for is
6296 /// that the shuffle mask is in fact a blend.
6297 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6298 SDValue V2, ArrayRef<int> Mask,
6299 const X86Subtarget *Subtarget,
6300 SelectionDAG &DAG) {
6301 unsigned BlendMask = 0;
6302 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6303 if (Mask[i] >= Size) {
6304 if (Mask[i] != i + Size)
6305 return SDValue(); // Shuffled V2 input!
6306 BlendMask |= 1u << i;
6309 if (Mask[i] >= 0 && Mask[i] != i)
6310 return SDValue(); // Shuffled V1 input!
6312 switch (VT.SimpleTy) {
6317 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6318 DAG.getConstant(BlendMask, DL, MVT::i8));
6322 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6326 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6327 // that instruction.
6328 if (Subtarget->hasAVX2()) {
6329 // Scale the blend by the number of 32-bit dwords per element.
6330 int Scale = VT.getScalarSizeInBits() / 32;
6332 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6333 if (Mask[i] >= Size)
6334 for (int j = 0; j < Scale; ++j)
6335 BlendMask |= 1u << (i * Scale + j);
6337 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6338 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6339 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6340 return DAG.getNode(ISD::BITCAST, DL, VT,
6341 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6342 DAG.getConstant(BlendMask, DL, MVT::i8)));
6346 // For integer shuffles we need to expand the mask and cast the inputs to
6347 // v8i16s prior to blending.
6348 int Scale = 8 / VT.getVectorNumElements();
6350 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6351 if (Mask[i] >= Size)
6352 for (int j = 0; j < Scale; ++j)
6353 BlendMask |= 1u << (i * Scale + j);
6355 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6356 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6357 return DAG.getNode(ISD::BITCAST, DL, VT,
6358 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6359 DAG.getConstant(BlendMask, DL, MVT::i8)));
6363 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6364 SmallVector<int, 8> RepeatedMask;
6365 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6366 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6367 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6369 for (int i = 0; i < 8; ++i)
6370 if (RepeatedMask[i] >= 16)
6371 BlendMask |= 1u << i;
6372 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6373 DAG.getConstant(BlendMask, DL, MVT::i8));
6379 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6380 "256-bit byte-blends require AVX2 support!");
6382 // Scale the blend by the number of bytes per element.
6383 int Scale = VT.getScalarSizeInBits() / 8;
6385 // This form of blend is always done on bytes. Compute the byte vector
6387 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6389 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6390 // mix of LLVM's code generator and the x86 backend. We tell the code
6391 // generator that boolean values in the elements of an x86 vector register
6392 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6393 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6394 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6395 // of the element (the remaining are ignored) and 0 in that high bit would
6396 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6397 // the LLVM model for boolean values in vector elements gets the relevant
6398 // bit set, it is set backwards and over constrained relative to x86's
6400 SmallVector<SDValue, 32> VSELECTMask;
6401 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6402 for (int j = 0; j < Scale; ++j)
6403 VSELECTMask.push_back(
6404 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6405 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6408 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6409 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6411 ISD::BITCAST, DL, VT,
6412 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6413 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6418 llvm_unreachable("Not a supported integer vector type!");
6422 /// \brief Try to lower as a blend of elements from two inputs followed by
6423 /// a single-input permutation.
6425 /// This matches the pattern where we can blend elements from two inputs and
6426 /// then reduce the shuffle to a single-input permutation.
6427 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6430 SelectionDAG &DAG) {
6431 // We build up the blend mask while checking whether a blend is a viable way
6432 // to reduce the shuffle.
6433 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6434 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6436 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6440 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6442 if (BlendMask[Mask[i] % Size] == -1)
6443 BlendMask[Mask[i] % Size] = Mask[i];
6444 else if (BlendMask[Mask[i] % Size] != Mask[i])
6445 return SDValue(); // Can't blend in the needed input!
6447 PermuteMask[i] = Mask[i] % Size;
6450 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6451 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6454 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6455 /// blends and permutes.
6457 /// This matches the extremely common pattern for handling combined
6458 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6459 /// operations. It will try to pick the best arrangement of shuffles and
6461 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6465 SelectionDAG &DAG) {
6466 // Shuffle the input elements into the desired positions in V1 and V2 and
6467 // blend them together.
6468 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6469 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6470 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6471 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6472 if (Mask[i] >= 0 && Mask[i] < Size) {
6473 V1Mask[i] = Mask[i];
6475 } else if (Mask[i] >= Size) {
6476 V2Mask[i] = Mask[i] - Size;
6477 BlendMask[i] = i + Size;
6480 // Try to lower with the simpler initial blend strategy unless one of the
6481 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6482 // shuffle may be able to fold with a load or other benefit. However, when
6483 // we'll have to do 2x as many shuffles in order to achieve this, blending
6484 // first is a better strategy.
6485 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6486 if (SDValue BlendPerm =
6487 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6490 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6491 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6492 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6495 /// \brief Try to lower a vector shuffle as a byte rotation.
6497 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6498 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6499 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6500 /// try to generically lower a vector shuffle through such an pattern. It
6501 /// does not check for the profitability of lowering either as PALIGNR or
6502 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6503 /// This matches shuffle vectors that look like:
6505 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6507 /// Essentially it concatenates V1 and V2, shifts right by some number of
6508 /// elements, and takes the low elements as the result. Note that while this is
6509 /// specified as a *right shift* because x86 is little-endian, it is a *left
6510 /// rotate* of the vector lanes.
6511 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6514 const X86Subtarget *Subtarget,
6515 SelectionDAG &DAG) {
6516 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6518 int NumElts = Mask.size();
6519 int NumLanes = VT.getSizeInBits() / 128;
6520 int NumLaneElts = NumElts / NumLanes;
6522 // We need to detect various ways of spelling a rotation:
6523 // [11, 12, 13, 14, 15, 0, 1, 2]
6524 // [-1, 12, 13, 14, -1, -1, 1, -1]
6525 // [-1, -1, -1, -1, -1, -1, 1, 2]
6526 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6527 // [-1, 4, 5, 6, -1, -1, 9, -1]
6528 // [-1, 4, 5, 6, -1, -1, -1, -1]
6531 for (int l = 0; l < NumElts; l += NumLaneElts) {
6532 for (int i = 0; i < NumLaneElts; ++i) {
6533 if (Mask[l + i] == -1)
6535 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6537 // Get the mod-Size index and lane correct it.
6538 int LaneIdx = (Mask[l + i] % NumElts) - l;
6539 // Make sure it was in this lane.
6540 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6543 // Determine where a rotated vector would have started.
6544 int StartIdx = i - LaneIdx;
6546 // The identity rotation isn't interesting, stop.
6549 // If we found the tail of a vector the rotation must be the missing
6550 // front. If we found the head of a vector, it must be how much of the
6552 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6555 Rotation = CandidateRotation;
6556 else if (Rotation != CandidateRotation)
6557 // The rotations don't match, so we can't match this mask.
6560 // Compute which value this mask is pointing at.
6561 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6563 // Compute which of the two target values this index should be assigned
6564 // to. This reflects whether the high elements are remaining or the low
6565 // elements are remaining.
6566 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6568 // Either set up this value if we've not encountered it before, or check
6569 // that it remains consistent.
6572 else if (TargetV != MaskV)
6573 // This may be a rotation, but it pulls from the inputs in some
6574 // unsupported interleaving.
6579 // Check that we successfully analyzed the mask, and normalize the results.
6580 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6581 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6587 // The actual rotate instruction rotates bytes, so we need to scale the
6588 // rotation based on how many bytes are in the vector lane.
6589 int Scale = 16 / NumLaneElts;
6591 // SSSE3 targets can use the palignr instruction.
6592 if (Subtarget->hasSSSE3()) {
6593 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6594 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6595 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6596 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6598 return DAG.getNode(ISD::BITCAST, DL, VT,
6599 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6600 DAG.getConstant(Rotation * Scale, DL,
6604 assert(VT.getSizeInBits() == 128 &&
6605 "Rotate-based lowering only supports 128-bit lowering!");
6606 assert(Mask.size() <= 16 &&
6607 "Can shuffle at most 16 bytes in a 128-bit vector!");
6609 // Default SSE2 implementation
6610 int LoByteShift = 16 - Rotation * Scale;
6611 int HiByteShift = Rotation * Scale;
6613 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6614 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6615 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6617 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6618 DAG.getConstant(LoByteShift, DL, MVT::i8));
6619 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6620 DAG.getConstant(HiByteShift, DL, MVT::i8));
6621 return DAG.getNode(ISD::BITCAST, DL, VT,
6622 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6625 /// \brief Compute whether each element of a shuffle is zeroable.
6627 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6628 /// Either it is an undef element in the shuffle mask, the element of the input
6629 /// referenced is undef, or the element of the input referenced is known to be
6630 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6631 /// as many lanes with this technique as possible to simplify the remaining
6633 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6634 SDValue V1, SDValue V2) {
6635 SmallBitVector Zeroable(Mask.size(), false);
6637 while (V1.getOpcode() == ISD::BITCAST)
6638 V1 = V1->getOperand(0);
6639 while (V2.getOpcode() == ISD::BITCAST)
6640 V2 = V2->getOperand(0);
6642 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6643 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6645 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6647 // Handle the easy cases.
6648 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6653 // If this is an index into a build_vector node (which has the same number
6654 // of elements), dig out the input value and use it.
6655 SDValue V = M < Size ? V1 : V2;
6656 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6659 SDValue Input = V.getOperand(M % Size);
6660 // The UNDEF opcode check really should be dead code here, but not quite
6661 // worth asserting on (it isn't invalid, just unexpected).
6662 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6669 /// \brief Try to emit a bitmask instruction for a shuffle.
6671 /// This handles cases where we can model a blend exactly as a bitmask due to
6672 /// one of the inputs being zeroable.
6673 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6674 SDValue V2, ArrayRef<int> Mask,
6675 SelectionDAG &DAG) {
6676 MVT EltVT = VT.getScalarType();
6677 int NumEltBits = EltVT.getSizeInBits();
6678 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6679 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6680 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6682 if (EltVT.isFloatingPoint()) {
6683 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6684 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6686 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6687 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6689 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6692 if (Mask[i] % Size != i)
6693 return SDValue(); // Not a blend.
6695 V = Mask[i] < Size ? V1 : V2;
6696 else if (V != (Mask[i] < Size ? V1 : V2))
6697 return SDValue(); // Can only let one input through the mask.
6699 VMaskOps[i] = AllOnes;
6702 return SDValue(); // No non-zeroable elements!
6704 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6705 V = DAG.getNode(VT.isFloatingPoint()
6706 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6711 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6713 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6714 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6715 /// matches elements from one of the input vectors shuffled to the left or
6716 /// right with zeroable elements 'shifted in'. It handles both the strictly
6717 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6720 /// PSHL : (little-endian) left bit shift.
6721 /// [ zz, 0, zz, 2 ]
6722 /// [ -1, 4, zz, -1 ]
6723 /// PSRL : (little-endian) right bit shift.
6725 /// [ -1, -1, 7, zz]
6726 /// PSLLDQ : (little-endian) left byte shift
6727 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6728 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6729 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6730 /// PSRLDQ : (little-endian) right byte shift
6731 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6732 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6733 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6734 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6735 SDValue V2, ArrayRef<int> Mask,
6736 SelectionDAG &DAG) {
6737 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6739 int Size = Mask.size();
6740 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6742 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6743 for (int i = 0; i < Size; i += Scale)
6744 for (int j = 0; j < Shift; ++j)
6745 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6751 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6752 for (int i = 0; i != Size; i += Scale) {
6753 unsigned Pos = Left ? i + Shift : i;
6754 unsigned Low = Left ? i : i + Shift;
6755 unsigned Len = Scale - Shift;
6756 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6757 Low + (V == V1 ? 0 : Size)))
6761 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6762 bool ByteShift = ShiftEltBits > 64;
6763 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6764 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6765 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6767 // Normalize the scale for byte shifts to still produce an i64 element
6769 Scale = ByteShift ? Scale / 2 : Scale;
6771 // We need to round trip through the appropriate type for the shift.
6772 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6773 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6774 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6775 "Illegal integer vector type");
6776 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6778 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6779 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6780 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6783 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6784 // keep doubling the size of the integer elements up to that. We can
6785 // then shift the elements of the integer vector by whole multiples of
6786 // their width within the elements of the larger integer vector. Test each
6787 // multiple to see if we can find a match with the moved element indices
6788 // and that the shifted in elements are all zeroable.
6789 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6790 for (int Shift = 1; Shift != Scale; ++Shift)
6791 for (bool Left : {true, false})
6792 if (CheckZeros(Shift, Scale, Left))
6793 for (SDValue V : {V1, V2})
6794 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6801 /// \brief Lower a vector shuffle as a zero or any extension.
6803 /// Given a specific number of elements, element bit width, and extension
6804 /// stride, produce either a zero or any extension based on the available
6805 /// features of the subtarget.
6806 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6807 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6808 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6809 assert(Scale > 1 && "Need a scale to extend.");
6810 int NumElements = VT.getVectorNumElements();
6811 int EltBits = VT.getScalarSizeInBits();
6812 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6813 "Only 8, 16, and 32 bit elements can be extended.");
6814 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6816 // Found a valid zext mask! Try various lowering strategies based on the
6817 // input type and available ISA extensions.
6818 if (Subtarget->hasSSE41()) {
6819 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6820 NumElements / Scale);
6821 return DAG.getNode(ISD::BITCAST, DL, VT,
6822 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6825 // For any extends we can cheat for larger element sizes and use shuffle
6826 // instructions that can fold with a load and/or copy.
6827 if (AnyExt && EltBits == 32) {
6828 int PSHUFDMask[4] = {0, -1, 1, -1};
6830 ISD::BITCAST, DL, VT,
6831 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6832 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6833 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6835 if (AnyExt && EltBits == 16 && Scale > 2) {
6836 int PSHUFDMask[4] = {0, -1, 0, -1};
6837 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6838 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6839 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6840 int PSHUFHWMask[4] = {1, -1, -1, -1};
6842 ISD::BITCAST, DL, VT,
6843 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6844 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6845 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6848 // If this would require more than 2 unpack instructions to expand, use
6849 // pshufb when available. We can only use more than 2 unpack instructions
6850 // when zero extending i8 elements which also makes it easier to use pshufb.
6851 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6852 assert(NumElements == 16 && "Unexpected byte vector width!");
6853 SDValue PSHUFBMask[16];
6854 for (int i = 0; i < 16; ++i)
6856 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6857 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6858 return DAG.getNode(ISD::BITCAST, DL, VT,
6859 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6860 DAG.getNode(ISD::BUILD_VECTOR, DL,
6861 MVT::v16i8, PSHUFBMask)));
6864 // Otherwise emit a sequence of unpacks.
6866 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6867 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6868 : getZeroVector(InputVT, Subtarget, DAG, DL);
6869 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6870 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6874 } while (Scale > 1);
6875 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6878 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6880 /// This routine will try to do everything in its power to cleverly lower
6881 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6882 /// check for the profitability of this lowering, it tries to aggressively
6883 /// match this pattern. It will use all of the micro-architectural details it
6884 /// can to emit an efficient lowering. It handles both blends with all-zero
6885 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6886 /// masking out later).
6888 /// The reason we have dedicated lowering for zext-style shuffles is that they
6889 /// are both incredibly common and often quite performance sensitive.
6890 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6891 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6892 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6893 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6895 int Bits = VT.getSizeInBits();
6896 int NumElements = VT.getVectorNumElements();
6897 assert(VT.getScalarSizeInBits() <= 32 &&
6898 "Exceeds 32-bit integer zero extension limit");
6899 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6901 // Define a helper function to check a particular ext-scale and lower to it if
6903 auto Lower = [&](int Scale) -> SDValue {
6906 for (int i = 0; i < NumElements; ++i) {
6908 continue; // Valid anywhere but doesn't tell us anything.
6909 if (i % Scale != 0) {
6910 // Each of the extended elements need to be zeroable.
6914 // We no longer are in the anyext case.
6919 // Each of the base elements needs to be consecutive indices into the
6920 // same input vector.
6921 SDValue V = Mask[i] < NumElements ? V1 : V2;
6924 else if (InputV != V)
6925 return SDValue(); // Flip-flopping inputs.
6927 if (Mask[i] % NumElements != i / Scale)
6928 return SDValue(); // Non-consecutive strided elements.
6931 // If we fail to find an input, we have a zero-shuffle which should always
6932 // have already been handled.
6933 // FIXME: Maybe handle this here in case during blending we end up with one?
6937 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6938 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6941 // The widest scale possible for extending is to a 64-bit integer.
6942 assert(Bits % 64 == 0 &&
6943 "The number of bits in a vector must be divisible by 64 on x86!");
6944 int NumExtElements = Bits / 64;
6946 // Each iteration, try extending the elements half as much, but into twice as
6948 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6949 assert(NumElements % NumExtElements == 0 &&
6950 "The input vector size must be divisible by the extended size.");
6951 if (SDValue V = Lower(NumElements / NumExtElements))
6955 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6959 // Returns one of the source operands if the shuffle can be reduced to a
6960 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6961 auto CanZExtLowHalf = [&]() {
6962 for (int i = NumElements / 2; i != NumElements; ++i)
6965 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6967 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6972 if (SDValue V = CanZExtLowHalf()) {
6973 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6974 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6975 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6978 // No viable ext lowering found.
6982 /// \brief Try to get a scalar value for a specific element of a vector.
6984 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6985 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6986 SelectionDAG &DAG) {
6987 MVT VT = V.getSimpleValueType();
6988 MVT EltVT = VT.getVectorElementType();
6989 while (V.getOpcode() == ISD::BITCAST)
6990 V = V.getOperand(0);
6991 // If the bitcasts shift the element size, we can't extract an equivalent
6993 MVT NewVT = V.getSimpleValueType();
6994 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6997 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6998 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6999 // Ensure the scalar operand is the same size as the destination.
7000 // FIXME: Add support for scalar truncation where possible.
7001 SDValue S = V.getOperand(Idx);
7002 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7003 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7009 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7011 /// This is particularly important because the set of instructions varies
7012 /// significantly based on whether the operand is a load or not.
7013 static bool isShuffleFoldableLoad(SDValue V) {
7014 while (V.getOpcode() == ISD::BITCAST)
7015 V = V.getOperand(0);
7017 return ISD::isNON_EXTLoad(V.getNode());
7020 /// \brief Try to lower insertion of a single element into a zero vector.
7022 /// This is a common pattern that we have especially efficient patterns to lower
7023 /// across all subtarget feature sets.
7024 static SDValue lowerVectorShuffleAsElementInsertion(
7025 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7026 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7027 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7029 MVT EltVT = VT.getVectorElementType();
7031 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7032 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7034 bool IsV1Zeroable = true;
7035 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7036 if (i != V2Index && !Zeroable[i]) {
7037 IsV1Zeroable = false;
7041 // Check for a single input from a SCALAR_TO_VECTOR node.
7042 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7043 // all the smarts here sunk into that routine. However, the current
7044 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7045 // vector shuffle lowering is dead.
7046 if (SDValue V2S = getScalarValueForVectorElement(
7047 V2, Mask[V2Index] - Mask.size(), DAG)) {
7048 // We need to zext the scalar if it is smaller than an i32.
7049 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7050 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7051 // Using zext to expand a narrow element won't work for non-zero
7056 // Zero-extend directly to i32.
7058 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7060 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7061 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7062 EltVT == MVT::i16) {
7063 // Either not inserting from the low element of the input or the input
7064 // element size is too small to use VZEXT_MOVL to clear the high bits.
7068 if (!IsV1Zeroable) {
7069 // If V1 can't be treated as a zero vector we have fewer options to lower
7070 // this. We can't support integer vectors or non-zero targets cheaply, and
7071 // the V1 elements can't be permuted in any way.
7072 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7073 if (!VT.isFloatingPoint() || V2Index != 0)
7075 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7076 V1Mask[V2Index] = -1;
7077 if (!isNoopShuffleMask(V1Mask))
7079 // This is essentially a special case blend operation, but if we have
7080 // general purpose blend operations, they are always faster. Bail and let
7081 // the rest of the lowering handle these as blends.
7082 if (Subtarget->hasSSE41())
7085 // Otherwise, use MOVSD or MOVSS.
7086 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7087 "Only two types of floating point element types to handle!");
7088 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7092 // This lowering only works for the low element with floating point vectors.
7093 if (VT.isFloatingPoint() && V2Index != 0)
7096 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7098 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7101 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7102 // the desired position. Otherwise it is more efficient to do a vector
7103 // shift left. We know that we can do a vector shift left because all
7104 // the inputs are zero.
7105 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7106 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7107 V2Shuffle[V2Index] = 0;
7108 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7110 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7112 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7114 V2Index * EltVT.getSizeInBits()/8, DL,
7115 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7116 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7122 /// \brief Try to lower broadcast of a single element.
7124 /// For convenience, this code also bundles all of the subtarget feature set
7125 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7126 /// a convenient way to factor it out.
7127 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7129 const X86Subtarget *Subtarget,
7130 SelectionDAG &DAG) {
7131 if (!Subtarget->hasAVX())
7133 if (VT.isInteger() && !Subtarget->hasAVX2())
7136 // Check that the mask is a broadcast.
7137 int BroadcastIdx = -1;
7139 if (M >= 0 && BroadcastIdx == -1)
7141 else if (M >= 0 && M != BroadcastIdx)
7144 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7145 "a sorted mask where the broadcast "
7148 // Go up the chain of (vector) values to find a scalar load that we can
7149 // combine with the broadcast.
7151 switch (V.getOpcode()) {
7152 case ISD::CONCAT_VECTORS: {
7153 int OperandSize = Mask.size() / V.getNumOperands();
7154 V = V.getOperand(BroadcastIdx / OperandSize);
7155 BroadcastIdx %= OperandSize;
7159 case ISD::INSERT_SUBVECTOR: {
7160 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7161 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7165 int BeginIdx = (int)ConstantIdx->getZExtValue();
7167 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7168 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7169 BroadcastIdx -= BeginIdx;
7180 // Check if this is a broadcast of a scalar. We special case lowering
7181 // for scalars so that we can more effectively fold with loads.
7182 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7183 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7184 V = V.getOperand(BroadcastIdx);
7186 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7187 // Only AVX2 has register broadcasts.
7188 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7190 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7191 // We can't broadcast from a vector register without AVX2, and we can only
7192 // broadcast from the zero-element of a vector register.
7196 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7199 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7200 // INSERTPS when the V1 elements are already in the correct locations
7201 // because otherwise we can just always use two SHUFPS instructions which
7202 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7203 // perform INSERTPS if a single V1 element is out of place and all V2
7204 // elements are zeroable.
7205 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7207 SelectionDAG &DAG) {
7208 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7209 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7210 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7211 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7213 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7216 int V1DstIndex = -1;
7217 int V2DstIndex = -1;
7218 bool V1UsedInPlace = false;
7220 for (int i = 0; i < 4; ++i) {
7221 // Synthesize a zero mask from the zeroable elements (includes undefs).
7227 // Flag if we use any V1 inputs in place.
7229 V1UsedInPlace = true;
7233 // We can only insert a single non-zeroable element.
7234 if (V1DstIndex != -1 || V2DstIndex != -1)
7238 // V1 input out of place for insertion.
7241 // V2 input for insertion.
7246 // Don't bother if we have no (non-zeroable) element for insertion.
7247 if (V1DstIndex == -1 && V2DstIndex == -1)
7250 // Determine element insertion src/dst indices. The src index is from the
7251 // start of the inserted vector, not the start of the concatenated vector.
7252 unsigned V2SrcIndex = 0;
7253 if (V1DstIndex != -1) {
7254 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7255 // and don't use the original V2 at all.
7256 V2SrcIndex = Mask[V1DstIndex];
7257 V2DstIndex = V1DstIndex;
7260 V2SrcIndex = Mask[V2DstIndex] - 4;
7263 // If no V1 inputs are used in place, then the result is created only from
7264 // the zero mask and the V2 insertion - so remove V1 dependency.
7266 V1 = DAG.getUNDEF(MVT::v4f32);
7268 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7269 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7271 // Insert the V2 element into the desired position.
7273 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7274 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7277 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7278 /// UNPCK instruction.
7280 /// This specifically targets cases where we end up with alternating between
7281 /// the two inputs, and so can permute them into something that feeds a single
7282 /// UNPCK instruction. Note that this routine only targets integer vectors
7283 /// because for floating point vectors we have a generalized SHUFPS lowering
7284 /// strategy that handles everything that doesn't *exactly* match an unpack,
7285 /// making this clever lowering unnecessary.
7286 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7287 SDValue V2, ArrayRef<int> Mask,
7288 SelectionDAG &DAG) {
7289 assert(!VT.isFloatingPoint() &&
7290 "This routine only supports integer vectors.");
7291 assert(!isSingleInputShuffleMask(Mask) &&
7292 "This routine should only be used when blending two inputs.");
7293 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7295 int Size = Mask.size();
7297 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7298 return M >= 0 && M % Size < Size / 2;
7300 int NumHiInputs = std::count_if(
7301 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7303 bool UnpackLo = NumLoInputs >= NumHiInputs;
7305 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7306 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7307 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7309 for (int i = 0; i < Size; ++i) {
7313 // Each element of the unpack contains Scale elements from this mask.
7314 int UnpackIdx = i / Scale;
7316 // We only handle the case where V1 feeds the first slots of the unpack.
7317 // We rely on canonicalization to ensure this is the case.
7318 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7321 // Setup the mask for this input. The indexing is tricky as we have to
7322 // handle the unpack stride.
7323 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7324 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7328 // If we will have to shuffle both inputs to use the unpack, check whether
7329 // we can just unpack first and shuffle the result. If so, skip this unpack.
7330 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7331 !isNoopShuffleMask(V2Mask))
7334 // Shuffle the inputs into place.
7335 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7336 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7338 // Cast the inputs to the type we will use to unpack them.
7339 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7340 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7342 // Unpack the inputs and cast the result back to the desired type.
7343 return DAG.getNode(ISD::BITCAST, DL, VT,
7344 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7345 DL, UnpackVT, V1, V2));
7348 // We try each unpack from the largest to the smallest to try and find one
7349 // that fits this mask.
7350 int OrigNumElements = VT.getVectorNumElements();
7351 int OrigScalarSize = VT.getScalarSizeInBits();
7352 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7353 int Scale = ScalarSize / OrigScalarSize;
7354 int NumElements = OrigNumElements / Scale;
7355 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7356 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7360 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7362 if (NumLoInputs == 0 || NumHiInputs == 0) {
7363 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7364 "We have to have *some* inputs!");
7365 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7367 // FIXME: We could consider the total complexity of the permute of each
7368 // possible unpacking. Or at the least we should consider how many
7369 // half-crossings are created.
7370 // FIXME: We could consider commuting the unpacks.
7372 SmallVector<int, 32> PermMask;
7373 PermMask.assign(Size, -1);
7374 for (int i = 0; i < Size; ++i) {
7378 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7381 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7383 return DAG.getVectorShuffle(
7384 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7386 DAG.getUNDEF(VT), PermMask);
7392 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7394 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7395 /// support for floating point shuffles but not integer shuffles. These
7396 /// instructions will incur a domain crossing penalty on some chips though so
7397 /// it is better to avoid lowering through this for integer vectors where
7399 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7400 const X86Subtarget *Subtarget,
7401 SelectionDAG &DAG) {
7403 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7404 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7405 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7406 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7407 ArrayRef<int> Mask = SVOp->getMask();
7408 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7410 if (isSingleInputShuffleMask(Mask)) {
7411 // Use low duplicate instructions for masks that match their pattern.
7412 if (Subtarget->hasSSE3())
7413 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7414 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7416 // Straight shuffle of a single input vector. Simulate this by using the
7417 // single input as both of the "inputs" to this instruction..
7418 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7420 if (Subtarget->hasAVX()) {
7421 // If we have AVX, we can use VPERMILPS which will allow folding a load
7422 // into the shuffle.
7423 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7424 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7427 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7428 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7430 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7431 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7433 // If we have a single input, insert that into V1 if we can do so cheaply.
7434 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7435 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7436 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7438 // Try inverting the insertion since for v2 masks it is easy to do and we
7439 // can't reliably sort the mask one way or the other.
7440 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7441 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7442 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7443 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7447 // Try to use one of the special instruction patterns to handle two common
7448 // blend patterns if a zero-blend above didn't work.
7449 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7450 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7451 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7452 // We can either use a special instruction to load over the low double or
7453 // to move just the low double.
7455 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7457 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7459 if (Subtarget->hasSSE41())
7460 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7464 // Use dedicated unpack instructions for masks that match their pattern.
7465 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7466 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7467 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7468 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7470 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7471 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7472 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7475 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7477 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7478 /// the integer unit to minimize domain crossing penalties. However, for blends
7479 /// it falls back to the floating point shuffle operation with appropriate bit
7481 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7482 const X86Subtarget *Subtarget,
7483 SelectionDAG &DAG) {
7485 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7486 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7487 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7488 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7489 ArrayRef<int> Mask = SVOp->getMask();
7490 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7492 if (isSingleInputShuffleMask(Mask)) {
7493 // Check for being able to broadcast a single element.
7494 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7495 Mask, Subtarget, DAG))
7498 // Straight shuffle of a single input vector. For everything from SSE2
7499 // onward this has a single fast instruction with no scary immediates.
7500 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7501 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7502 int WidenedMask[4] = {
7503 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7504 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7506 ISD::BITCAST, DL, MVT::v2i64,
7507 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7508 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7510 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7511 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7512 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7513 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7515 // If we have a blend of two PACKUS operations an the blend aligns with the
7516 // low and half halves, we can just merge the PACKUS operations. This is
7517 // particularly important as it lets us merge shuffles that this routine itself
7519 auto GetPackNode = [](SDValue V) {
7520 while (V.getOpcode() == ISD::BITCAST)
7521 V = V.getOperand(0);
7523 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7525 if (SDValue V1Pack = GetPackNode(V1))
7526 if (SDValue V2Pack = GetPackNode(V2))
7527 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7528 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7529 Mask[0] == 0 ? V1Pack.getOperand(0)
7530 : V1Pack.getOperand(1),
7531 Mask[1] == 2 ? V2Pack.getOperand(0)
7532 : V2Pack.getOperand(1)));
7534 // Try to use shift instructions.
7536 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7539 // When loading a scalar and then shuffling it into a vector we can often do
7540 // the insertion cheaply.
7541 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7542 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7544 // Try inverting the insertion since for v2 masks it is easy to do and we
7545 // can't reliably sort the mask one way or the other.
7546 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7547 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7548 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7551 // We have different paths for blend lowering, but they all must use the
7552 // *exact* same predicate.
7553 bool IsBlendSupported = Subtarget->hasSSE41();
7554 if (IsBlendSupported)
7555 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7559 // Use dedicated unpack instructions for masks that match their pattern.
7560 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7561 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7562 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7563 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7565 // Try to use byte rotation instructions.
7566 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7567 if (Subtarget->hasSSSE3())
7568 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7569 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7572 // If we have direct support for blends, we should lower by decomposing into
7573 // a permute. That will be faster than the domain cross.
7574 if (IsBlendSupported)
7575 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7578 // We implement this with SHUFPD which is pretty lame because it will likely
7579 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7580 // However, all the alternatives are still more cycles and newer chips don't
7581 // have this problem. It would be really nice if x86 had better shuffles here.
7582 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7583 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7584 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7585 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7588 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7590 /// This is used to disable more specialized lowerings when the shufps lowering
7591 /// will happen to be efficient.
7592 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7593 // This routine only handles 128-bit shufps.
7594 assert(Mask.size() == 4 && "Unsupported mask size!");
7596 // To lower with a single SHUFPS we need to have the low half and high half
7597 // each requiring a single input.
7598 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7600 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7606 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7608 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7609 /// It makes no assumptions about whether this is the *best* lowering, it simply
7611 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7612 ArrayRef<int> Mask, SDValue V1,
7613 SDValue V2, SelectionDAG &DAG) {
7614 SDValue LowV = V1, HighV = V2;
7615 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7618 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7620 if (NumV2Elements == 1) {
7622 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7625 // Compute the index adjacent to V2Index and in the same half by toggling
7627 int V2AdjIndex = V2Index ^ 1;
7629 if (Mask[V2AdjIndex] == -1) {
7630 // Handles all the cases where we have a single V2 element and an undef.
7631 // This will only ever happen in the high lanes because we commute the
7632 // vector otherwise.
7634 std::swap(LowV, HighV);
7635 NewMask[V2Index] -= 4;
7637 // Handle the case where the V2 element ends up adjacent to a V1 element.
7638 // To make this work, blend them together as the first step.
7639 int V1Index = V2AdjIndex;
7640 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7641 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7642 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7644 // Now proceed to reconstruct the final blend as we have the necessary
7645 // high or low half formed.
7652 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7653 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7655 } else if (NumV2Elements == 2) {
7656 if (Mask[0] < 4 && Mask[1] < 4) {
7657 // Handle the easy case where we have V1 in the low lanes and V2 in the
7661 } else if (Mask[2] < 4 && Mask[3] < 4) {
7662 // We also handle the reversed case because this utility may get called
7663 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7664 // arrange things in the right direction.
7670 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7671 // trying to place elements directly, just blend them and set up the final
7672 // shuffle to place them.
7674 // The first two blend mask elements are for V1, the second two are for
7676 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7677 Mask[2] < 4 ? Mask[2] : Mask[3],
7678 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7679 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7680 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7681 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7683 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7686 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7687 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7688 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7689 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7692 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7693 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7696 /// \brief Lower 4-lane 32-bit floating point shuffles.
7698 /// Uses instructions exclusively from the floating point unit to minimize
7699 /// domain crossing penalties, as these are sufficient to implement all v4f32
7701 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7702 const X86Subtarget *Subtarget,
7703 SelectionDAG &DAG) {
7705 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7706 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7707 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7708 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7709 ArrayRef<int> Mask = SVOp->getMask();
7710 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7713 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7715 if (NumV2Elements == 0) {
7716 // Check for being able to broadcast a single element.
7717 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7718 Mask, Subtarget, DAG))
7721 // Use even/odd duplicate instructions for masks that match their pattern.
7722 if (Subtarget->hasSSE3()) {
7723 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7724 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7725 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7726 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7729 if (Subtarget->hasAVX()) {
7730 // If we have AVX, we can use VPERMILPS which will allow folding a load
7731 // into the shuffle.
7732 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7733 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7736 // Otherwise, use a straight shuffle of a single input vector. We pass the
7737 // input vector to both operands to simulate this with a SHUFPS.
7738 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7739 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7742 // There are special ways we can lower some single-element blends. However, we
7743 // have custom ways we can lower more complex single-element blends below that
7744 // we defer to if both this and BLENDPS fail to match, so restrict this to
7745 // when the V2 input is targeting element 0 of the mask -- that is the fast
7747 if (NumV2Elements == 1 && Mask[0] >= 4)
7748 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7749 Mask, Subtarget, DAG))
7752 if (Subtarget->hasSSE41()) {
7753 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7757 // Use INSERTPS if we can complete the shuffle efficiently.
7758 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7761 if (!isSingleSHUFPSMask(Mask))
7762 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7763 DL, MVT::v4f32, V1, V2, Mask, DAG))
7767 // Use dedicated unpack instructions for masks that match their pattern.
7768 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7769 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7770 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7771 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7772 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7773 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7774 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7775 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7777 // Otherwise fall back to a SHUFPS lowering strategy.
7778 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7781 /// \brief Lower 4-lane i32 vector shuffles.
7783 /// We try to handle these with integer-domain shuffles where we can, but for
7784 /// blends we use the floating point domain blend instructions.
7785 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7786 const X86Subtarget *Subtarget,
7787 SelectionDAG &DAG) {
7789 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7790 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7791 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7792 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7793 ArrayRef<int> Mask = SVOp->getMask();
7794 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7796 // Whenever we can lower this as a zext, that instruction is strictly faster
7797 // than any alternative. It also allows us to fold memory operands into the
7798 // shuffle in many cases.
7799 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7800 Mask, Subtarget, DAG))
7804 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7806 if (NumV2Elements == 0) {
7807 // Check for being able to broadcast a single element.
7808 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7809 Mask, Subtarget, DAG))
7812 // Straight shuffle of a single input vector. For everything from SSE2
7813 // onward this has a single fast instruction with no scary immediates.
7814 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7815 // but we aren't actually going to use the UNPCK instruction because doing
7816 // so prevents folding a load into this instruction or making a copy.
7817 const int UnpackLoMask[] = {0, 0, 1, 1};
7818 const int UnpackHiMask[] = {2, 2, 3, 3};
7819 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7820 Mask = UnpackLoMask;
7821 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7822 Mask = UnpackHiMask;
7824 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7825 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7828 // Try to use shift instructions.
7830 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7833 // There are special ways we can lower some single-element blends.
7834 if (NumV2Elements == 1)
7835 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7836 Mask, Subtarget, DAG))
7839 // We have different paths for blend lowering, but they all must use the
7840 // *exact* same predicate.
7841 bool IsBlendSupported = Subtarget->hasSSE41();
7842 if (IsBlendSupported)
7843 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7847 if (SDValue Masked =
7848 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7851 // Use dedicated unpack instructions for masks that match their pattern.
7852 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7853 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7854 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7855 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7856 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7857 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7858 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7859 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7861 // Try to use byte rotation instructions.
7862 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7863 if (Subtarget->hasSSSE3())
7864 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7865 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7868 // If we have direct support for blends, we should lower by decomposing into
7869 // a permute. That will be faster than the domain cross.
7870 if (IsBlendSupported)
7871 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7874 // Try to lower by permuting the inputs into an unpack instruction.
7875 if (SDValue Unpack =
7876 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7879 // We implement this with SHUFPS because it can blend from two vectors.
7880 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7881 // up the inputs, bypassing domain shift penalties that we would encur if we
7882 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7884 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7885 DAG.getVectorShuffle(
7887 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7888 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7891 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7892 /// shuffle lowering, and the most complex part.
7894 /// The lowering strategy is to try to form pairs of input lanes which are
7895 /// targeted at the same half of the final vector, and then use a dword shuffle
7896 /// to place them onto the right half, and finally unpack the paired lanes into
7897 /// their final position.
7899 /// The exact breakdown of how to form these dword pairs and align them on the
7900 /// correct sides is really tricky. See the comments within the function for
7901 /// more of the details.
7903 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7904 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7905 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7906 /// vector, form the analogous 128-bit 8-element Mask.
7907 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7908 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7909 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7910 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7911 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7913 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7914 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7915 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7917 SmallVector<int, 4> LoInputs;
7918 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7919 [](int M) { return M >= 0; });
7920 std::sort(LoInputs.begin(), LoInputs.end());
7921 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7922 SmallVector<int, 4> HiInputs;
7923 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7924 [](int M) { return M >= 0; });
7925 std::sort(HiInputs.begin(), HiInputs.end());
7926 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7928 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7929 int NumHToL = LoInputs.size() - NumLToL;
7931 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7932 int NumHToH = HiInputs.size() - NumLToH;
7933 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7934 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7935 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7936 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7938 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7939 // such inputs we can swap two of the dwords across the half mark and end up
7940 // with <=2 inputs to each half in each half. Once there, we can fall through
7941 // to the generic code below. For example:
7943 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7944 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7946 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7947 // and an existing 2-into-2 on the other half. In this case we may have to
7948 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7949 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7950 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7951 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7952 // half than the one we target for fixing) will be fixed when we re-enter this
7953 // path. We will also combine away any sequence of PSHUFD instructions that
7954 // result into a single instruction. Here is an example of the tricky case:
7956 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7957 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7959 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7961 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7962 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7964 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7965 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7967 // The result is fine to be handled by the generic logic.
7968 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7969 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7970 int AOffset, int BOffset) {
7971 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7972 "Must call this with A having 3 or 1 inputs from the A half.");
7973 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7974 "Must call this with B having 1 or 3 inputs from the B half.");
7975 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7976 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7978 // Compute the index of dword with only one word among the three inputs in
7979 // a half by taking the sum of the half with three inputs and subtracting
7980 // the sum of the actual three inputs. The difference is the remaining
7983 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7984 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7985 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7986 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7987 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7988 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7989 int TripleNonInputIdx =
7990 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7991 TripleDWord = TripleNonInputIdx / 2;
7993 // We use xor with one to compute the adjacent DWord to whichever one the
7995 OneInputDWord = (OneInput / 2) ^ 1;
7997 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7998 // and BToA inputs. If there is also such a problem with the BToB and AToB
7999 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8000 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8001 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8002 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8003 // Compute how many inputs will be flipped by swapping these DWords. We
8005 // to balance this to ensure we don't form a 3-1 shuffle in the other
8007 int NumFlippedAToBInputs =
8008 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8009 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8010 int NumFlippedBToBInputs =
8011 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8012 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8013 if ((NumFlippedAToBInputs == 1 &&
8014 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8015 (NumFlippedBToBInputs == 1 &&
8016 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8017 // We choose whether to fix the A half or B half based on whether that
8018 // half has zero flipped inputs. At zero, we may not be able to fix it
8019 // with that half. We also bias towards fixing the B half because that
8020 // will more commonly be the high half, and we have to bias one way.
8021 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8022 ArrayRef<int> Inputs) {
8023 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8024 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8025 PinnedIdx ^ 1) != Inputs.end();
8026 // Determine whether the free index is in the flipped dword or the
8027 // unflipped dword based on where the pinned index is. We use this bit
8028 // in an xor to conditionally select the adjacent dword.
8029 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8030 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8031 FixFreeIdx) != Inputs.end();
8032 if (IsFixIdxInput == IsFixFreeIdxInput)
8034 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8035 FixFreeIdx) != Inputs.end();
8036 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8037 "We need to be changing the number of flipped inputs!");
8038 int PSHUFHalfMask[] = {0, 1, 2, 3};
8039 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8040 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8042 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8045 if (M != -1 && M == FixIdx)
8047 else if (M != -1 && M == FixFreeIdx)
8050 if (NumFlippedBToBInputs != 0) {
8052 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8053 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8055 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8057 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8058 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8063 int PSHUFDMask[] = {0, 1, 2, 3};
8064 PSHUFDMask[ADWord] = BDWord;
8065 PSHUFDMask[BDWord] = ADWord;
8066 V = DAG.getNode(ISD::BITCAST, DL, VT,
8067 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8068 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8069 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8072 // Adjust the mask to match the new locations of A and B.
8074 if (M != -1 && M/2 == ADWord)
8075 M = 2 * BDWord + M % 2;
8076 else if (M != -1 && M/2 == BDWord)
8077 M = 2 * ADWord + M % 2;
8079 // Recurse back into this routine to re-compute state now that this isn't
8080 // a 3 and 1 problem.
8081 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8084 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8085 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8086 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8087 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8089 // At this point there are at most two inputs to the low and high halves from
8090 // each half. That means the inputs can always be grouped into dwords and
8091 // those dwords can then be moved to the correct half with a dword shuffle.
8092 // We use at most one low and one high word shuffle to collect these paired
8093 // inputs into dwords, and finally a dword shuffle to place them.
8094 int PSHUFLMask[4] = {-1, -1, -1, -1};
8095 int PSHUFHMask[4] = {-1, -1, -1, -1};
8096 int PSHUFDMask[4] = {-1, -1, -1, -1};
8098 // First fix the masks for all the inputs that are staying in their
8099 // original halves. This will then dictate the targets of the cross-half
8101 auto fixInPlaceInputs =
8102 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8103 MutableArrayRef<int> SourceHalfMask,
8104 MutableArrayRef<int> HalfMask, int HalfOffset) {
8105 if (InPlaceInputs.empty())
8107 if (InPlaceInputs.size() == 1) {
8108 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8109 InPlaceInputs[0] - HalfOffset;
8110 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8113 if (IncomingInputs.empty()) {
8114 // Just fix all of the in place inputs.
8115 for (int Input : InPlaceInputs) {
8116 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8117 PSHUFDMask[Input / 2] = Input / 2;
8122 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8123 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8124 InPlaceInputs[0] - HalfOffset;
8125 // Put the second input next to the first so that they are packed into
8126 // a dword. We find the adjacent index by toggling the low bit.
8127 int AdjIndex = InPlaceInputs[0] ^ 1;
8128 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8129 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8130 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8132 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8133 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8135 // Now gather the cross-half inputs and place them into a free dword of
8136 // their target half.
8137 // FIXME: This operation could almost certainly be simplified dramatically to
8138 // look more like the 3-1 fixing operation.
8139 auto moveInputsToRightHalf = [&PSHUFDMask](
8140 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8141 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8142 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8144 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8145 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8147 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8149 int LowWord = Word & ~1;
8150 int HighWord = Word | 1;
8151 return isWordClobbered(SourceHalfMask, LowWord) ||
8152 isWordClobbered(SourceHalfMask, HighWord);
8155 if (IncomingInputs.empty())
8158 if (ExistingInputs.empty()) {
8159 // Map any dwords with inputs from them into the right half.
8160 for (int Input : IncomingInputs) {
8161 // If the source half mask maps over the inputs, turn those into
8162 // swaps and use the swapped lane.
8163 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8164 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8165 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8166 Input - SourceOffset;
8167 // We have to swap the uses in our half mask in one sweep.
8168 for (int &M : HalfMask)
8169 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8171 else if (M == Input)
8172 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8174 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8175 Input - SourceOffset &&
8176 "Previous placement doesn't match!");
8178 // Note that this correctly re-maps both when we do a swap and when
8179 // we observe the other side of the swap above. We rely on that to
8180 // avoid swapping the members of the input list directly.
8181 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8184 // Map the input's dword into the correct half.
8185 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8186 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8188 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8190 "Previous placement doesn't match!");
8193 // And just directly shift any other-half mask elements to be same-half
8194 // as we will have mirrored the dword containing the element into the
8195 // same position within that half.
8196 for (int &M : HalfMask)
8197 if (M >= SourceOffset && M < SourceOffset + 4) {
8198 M = M - SourceOffset + DestOffset;
8199 assert(M >= 0 && "This should never wrap below zero!");
8204 // Ensure we have the input in a viable dword of its current half. This
8205 // is particularly tricky because the original position may be clobbered
8206 // by inputs being moved and *staying* in that half.
8207 if (IncomingInputs.size() == 1) {
8208 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8209 int InputFixed = std::find(std::begin(SourceHalfMask),
8210 std::end(SourceHalfMask), -1) -
8211 std::begin(SourceHalfMask) + SourceOffset;
8212 SourceHalfMask[InputFixed - SourceOffset] =
8213 IncomingInputs[0] - SourceOffset;
8214 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8216 IncomingInputs[0] = InputFixed;
8218 } else if (IncomingInputs.size() == 2) {
8219 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8220 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8221 // We have two non-adjacent or clobbered inputs we need to extract from
8222 // the source half. To do this, we need to map them into some adjacent
8223 // dword slot in the source mask.
8224 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8225 IncomingInputs[1] - SourceOffset};
8227 // If there is a free slot in the source half mask adjacent to one of
8228 // the inputs, place the other input in it. We use (Index XOR 1) to
8229 // compute an adjacent index.
8230 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8231 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8232 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8233 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8234 InputsFixed[1] = InputsFixed[0] ^ 1;
8235 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8236 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8237 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8238 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8239 InputsFixed[0] = InputsFixed[1] ^ 1;
8240 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8241 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8242 // The two inputs are in the same DWord but it is clobbered and the
8243 // adjacent DWord isn't used at all. Move both inputs to the free
8245 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8246 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8247 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8248 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8250 // The only way we hit this point is if there is no clobbering
8251 // (because there are no off-half inputs to this half) and there is no
8252 // free slot adjacent to one of the inputs. In this case, we have to
8253 // swap an input with a non-input.
8254 for (int i = 0; i < 4; ++i)
8255 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8256 "We can't handle any clobbers here!");
8257 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8258 "Cannot have adjacent inputs here!");
8260 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8261 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8263 // We also have to update the final source mask in this case because
8264 // it may need to undo the above swap.
8265 for (int &M : FinalSourceHalfMask)
8266 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8267 M = InputsFixed[1] + SourceOffset;
8268 else if (M == InputsFixed[1] + SourceOffset)
8269 M = (InputsFixed[0] ^ 1) + SourceOffset;
8271 InputsFixed[1] = InputsFixed[0] ^ 1;
8274 // Point everything at the fixed inputs.
8275 for (int &M : HalfMask)
8276 if (M == IncomingInputs[0])
8277 M = InputsFixed[0] + SourceOffset;
8278 else if (M == IncomingInputs[1])
8279 M = InputsFixed[1] + SourceOffset;
8281 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8282 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8285 llvm_unreachable("Unhandled input size!");
8288 // Now hoist the DWord down to the right half.
8289 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8290 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8291 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8292 for (int &M : HalfMask)
8293 for (int Input : IncomingInputs)
8295 M = FreeDWord * 2 + Input % 2;
8297 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8298 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8299 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8300 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8302 // Now enact all the shuffles we've computed to move the inputs into their
8304 if (!isNoopShuffleMask(PSHUFLMask))
8305 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8306 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8307 if (!isNoopShuffleMask(PSHUFHMask))
8308 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8309 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8310 if (!isNoopShuffleMask(PSHUFDMask))
8311 V = DAG.getNode(ISD::BITCAST, DL, VT,
8312 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8313 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8314 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8317 // At this point, each half should contain all its inputs, and we can then
8318 // just shuffle them into their final position.
8319 assert(std::count_if(LoMask.begin(), LoMask.end(),
8320 [](int M) { return M >= 4; }) == 0 &&
8321 "Failed to lift all the high half inputs to the low mask!");
8322 assert(std::count_if(HiMask.begin(), HiMask.end(),
8323 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8324 "Failed to lift all the low half inputs to the high mask!");
8326 // Do a half shuffle for the low mask.
8327 if (!isNoopShuffleMask(LoMask))
8328 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8329 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8331 // Do a half shuffle with the high mask after shifting its values down.
8332 for (int &M : HiMask)
8335 if (!isNoopShuffleMask(HiMask))
8336 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8337 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8342 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8343 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8344 SDValue V2, ArrayRef<int> Mask,
8345 SelectionDAG &DAG, bool &V1InUse,
8347 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8353 int Size = Mask.size();
8354 int Scale = 16 / Size;
8355 for (int i = 0; i < 16; ++i) {
8356 if (Mask[i / Scale] == -1) {
8357 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8359 const int ZeroMask = 0x80;
8360 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8362 int V2Idx = Mask[i / Scale] < Size
8364 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8365 if (Zeroable[i / Scale])
8366 V1Idx = V2Idx = ZeroMask;
8367 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8368 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8369 V1InUse |= (ZeroMask != V1Idx);
8370 V2InUse |= (ZeroMask != V2Idx);
8375 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8376 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8377 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8379 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8380 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8381 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8383 // If we need shuffled inputs from both, blend the two.
8385 if (V1InUse && V2InUse)
8386 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8388 V = V1InUse ? V1 : V2;
8390 // Cast the result back to the correct type.
8391 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8394 /// \brief Generic lowering of 8-lane i16 shuffles.
8396 /// This handles both single-input shuffles and combined shuffle/blends with
8397 /// two inputs. The single input shuffles are immediately delegated to
8398 /// a dedicated lowering routine.
8400 /// The blends are lowered in one of three fundamental ways. If there are few
8401 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8402 /// of the input is significantly cheaper when lowered as an interleaving of
8403 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8404 /// halves of the inputs separately (making them have relatively few inputs)
8405 /// and then concatenate them.
8406 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8407 const X86Subtarget *Subtarget,
8408 SelectionDAG &DAG) {
8410 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8411 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8412 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8413 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8414 ArrayRef<int> OrigMask = SVOp->getMask();
8415 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8416 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8417 MutableArrayRef<int> Mask(MaskStorage);
8419 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8421 // Whenever we can lower this as a zext, that instruction is strictly faster
8422 // than any alternative.
8423 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8424 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8427 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8429 auto isV2 = [](int M) { return M >= 8; };
8431 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8433 if (NumV2Inputs == 0) {
8434 // Check for being able to broadcast a single element.
8435 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8436 Mask, Subtarget, DAG))
8439 // Try to use shift instructions.
8441 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8444 // Use dedicated unpack instructions for masks that match their pattern.
8445 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8446 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8447 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8448 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8450 // Try to use byte rotation instructions.
8451 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8452 Mask, Subtarget, DAG))
8455 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8459 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8460 "All single-input shuffles should be canonicalized to be V1-input "
8463 // Try to use shift instructions.
8465 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8468 // There are special ways we can lower some single-element blends.
8469 if (NumV2Inputs == 1)
8470 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8471 Mask, Subtarget, DAG))
8474 // We have different paths for blend lowering, but they all must use the
8475 // *exact* same predicate.
8476 bool IsBlendSupported = Subtarget->hasSSE41();
8477 if (IsBlendSupported)
8478 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8482 if (SDValue Masked =
8483 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8486 // Use dedicated unpack instructions for masks that match their pattern.
8487 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8488 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8489 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8490 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8492 // Try to use byte rotation instructions.
8493 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8494 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8497 if (SDValue BitBlend =
8498 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8501 if (SDValue Unpack =
8502 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8505 // If we can't directly blend but can use PSHUFB, that will be better as it
8506 // can both shuffle and set up the inefficient blend.
8507 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8508 bool V1InUse, V2InUse;
8509 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8513 // We can always bit-blend if we have to so the fallback strategy is to
8514 // decompose into single-input permutes and blends.
8515 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8519 /// \brief Check whether a compaction lowering can be done by dropping even
8520 /// elements and compute how many times even elements must be dropped.
8522 /// This handles shuffles which take every Nth element where N is a power of
8523 /// two. Example shuffle masks:
8525 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8526 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8527 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8528 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8529 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8530 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8532 /// Any of these lanes can of course be undef.
8534 /// This routine only supports N <= 3.
8535 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8538 /// \returns N above, or the number of times even elements must be dropped if
8539 /// there is such a number. Otherwise returns zero.
8540 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8541 // Figure out whether we're looping over two inputs or just one.
8542 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8544 // The modulus for the shuffle vector entries is based on whether this is
8545 // a single input or not.
8546 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8547 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8548 "We should only be called with masks with a power-of-2 size!");
8550 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8552 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8553 // and 2^3 simultaneously. This is because we may have ambiguity with
8554 // partially undef inputs.
8555 bool ViableForN[3] = {true, true, true};
8557 for (int i = 0, e = Mask.size(); i < e; ++i) {
8558 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8563 bool IsAnyViable = false;
8564 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8565 if (ViableForN[j]) {
8568 // The shuffle mask must be equal to (i * 2^N) % M.
8569 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8572 ViableForN[j] = false;
8574 // Early exit if we exhaust the possible powers of two.
8579 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8583 // Return 0 as there is no viable power of two.
8587 /// \brief Generic lowering of v16i8 shuffles.
8589 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8590 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8591 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8592 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8594 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8595 const X86Subtarget *Subtarget,
8596 SelectionDAG &DAG) {
8598 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8599 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8600 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8601 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8602 ArrayRef<int> Mask = SVOp->getMask();
8603 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8605 // Try to use shift instructions.
8607 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8610 // Try to use byte rotation instructions.
8611 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8612 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8615 // Try to use a zext lowering.
8616 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8617 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8621 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8623 // For single-input shuffles, there are some nicer lowering tricks we can use.
8624 if (NumV2Elements == 0) {
8625 // Check for being able to broadcast a single element.
8626 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8627 Mask, Subtarget, DAG))
8630 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8631 // Notably, this handles splat and partial-splat shuffles more efficiently.
8632 // However, it only makes sense if the pre-duplication shuffle simplifies
8633 // things significantly. Currently, this means we need to be able to
8634 // express the pre-duplication shuffle as an i16 shuffle.
8636 // FIXME: We should check for other patterns which can be widened into an
8637 // i16 shuffle as well.
8638 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8639 for (int i = 0; i < 16; i += 2)
8640 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8645 auto tryToWidenViaDuplication = [&]() -> SDValue {
8646 if (!canWidenViaDuplication(Mask))
8648 SmallVector<int, 4> LoInputs;
8649 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8650 [](int M) { return M >= 0 && M < 8; });
8651 std::sort(LoInputs.begin(), LoInputs.end());
8652 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8654 SmallVector<int, 4> HiInputs;
8655 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8656 [](int M) { return M >= 8; });
8657 std::sort(HiInputs.begin(), HiInputs.end());
8658 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8661 bool TargetLo = LoInputs.size() >= HiInputs.size();
8662 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8663 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8665 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8666 SmallDenseMap<int, int, 8> LaneMap;
8667 for (int I : InPlaceInputs) {
8668 PreDupI16Shuffle[I/2] = I/2;
8671 int j = TargetLo ? 0 : 4, je = j + 4;
8672 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8673 // Check if j is already a shuffle of this input. This happens when
8674 // there are two adjacent bytes after we move the low one.
8675 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8676 // If we haven't yet mapped the input, search for a slot into which
8678 while (j < je && PreDupI16Shuffle[j] != -1)
8682 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8685 // Map this input with the i16 shuffle.
8686 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8689 // Update the lane map based on the mapping we ended up with.
8690 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8693 ISD::BITCAST, DL, MVT::v16i8,
8694 DAG.getVectorShuffle(MVT::v8i16, DL,
8695 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8696 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8698 // Unpack the bytes to form the i16s that will be shuffled into place.
8699 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8700 MVT::v16i8, V1, V1);
8702 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8703 for (int i = 0; i < 16; ++i)
8704 if (Mask[i] != -1) {
8705 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8706 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8707 if (PostDupI16Shuffle[i / 2] == -1)
8708 PostDupI16Shuffle[i / 2] = MappedMask;
8710 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8711 "Conflicting entrties in the original shuffle!");
8714 ISD::BITCAST, DL, MVT::v16i8,
8715 DAG.getVectorShuffle(MVT::v8i16, DL,
8716 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8717 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8719 if (SDValue V = tryToWidenViaDuplication())
8723 // Use dedicated unpack instructions for masks that match their pattern.
8724 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8725 0, 16, 1, 17, 2, 18, 3, 19,
8727 4, 20, 5, 21, 6, 22, 7, 23}))
8728 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8729 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8730 8, 24, 9, 25, 10, 26, 11, 27,
8732 12, 28, 13, 29, 14, 30, 15, 31}))
8733 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8735 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8736 // with PSHUFB. It is important to do this before we attempt to generate any
8737 // blends but after all of the single-input lowerings. If the single input
8738 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8739 // want to preserve that and we can DAG combine any longer sequences into
8740 // a PSHUFB in the end. But once we start blending from multiple inputs,
8741 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8742 // and there are *very* few patterns that would actually be faster than the
8743 // PSHUFB approach because of its ability to zero lanes.
8745 // FIXME: The only exceptions to the above are blends which are exact
8746 // interleavings with direct instructions supporting them. We currently don't
8747 // handle those well here.
8748 if (Subtarget->hasSSSE3()) {
8749 bool V1InUse = false;
8750 bool V2InUse = false;
8752 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8753 DAG, V1InUse, V2InUse);
8755 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8756 // do so. This avoids using them to handle blends-with-zero which is
8757 // important as a single pshufb is significantly faster for that.
8758 if (V1InUse && V2InUse) {
8759 if (Subtarget->hasSSE41())
8760 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8761 Mask, Subtarget, DAG))
8764 // We can use an unpack to do the blending rather than an or in some
8765 // cases. Even though the or may be (very minorly) more efficient, we
8766 // preference this lowering because there are common cases where part of
8767 // the complexity of the shuffles goes away when we do the final blend as
8769 // FIXME: It might be worth trying to detect if the unpack-feeding
8770 // shuffles will both be pshufb, in which case we shouldn't bother with
8772 if (SDValue Unpack =
8773 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8780 // There are special ways we can lower some single-element blends.
8781 if (NumV2Elements == 1)
8782 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8783 Mask, Subtarget, DAG))
8786 if (SDValue BitBlend =
8787 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8790 // Check whether a compaction lowering can be done. This handles shuffles
8791 // which take every Nth element for some even N. See the helper function for
8794 // We special case these as they can be particularly efficiently handled with
8795 // the PACKUSB instruction on x86 and they show up in common patterns of
8796 // rearranging bytes to truncate wide elements.
8797 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8798 // NumEvenDrops is the power of two stride of the elements. Another way of
8799 // thinking about it is that we need to drop the even elements this many
8800 // times to get the original input.
8801 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8803 // First we need to zero all the dropped bytes.
8804 assert(NumEvenDrops <= 3 &&
8805 "No support for dropping even elements more than 3 times.");
8806 // We use the mask type to pick which bytes are preserved based on how many
8807 // elements are dropped.
8808 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8809 SDValue ByteClearMask =
8810 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8811 DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8812 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8814 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8816 // Now pack things back together.
8817 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8818 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8819 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8820 for (int i = 1; i < NumEvenDrops; ++i) {
8821 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8822 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8828 // Handle multi-input cases by blending single-input shuffles.
8829 if (NumV2Elements > 0)
8830 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8833 // The fallback path for single-input shuffles widens this into two v8i16
8834 // vectors with unpacks, shuffles those, and then pulls them back together
8838 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8839 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8840 for (int i = 0; i < 16; ++i)
8842 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8844 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8846 SDValue VLoHalf, VHiHalf;
8847 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8848 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8850 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8851 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8852 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8853 [](int M) { return M >= 0 && M % 2 == 1; })) {
8854 // Use a mask to drop the high bytes.
8855 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8856 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8857 DAG.getConstant(0x00FF, DL, MVT::v8i16));
8859 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8860 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8862 // Squash the masks to point directly into VLoHalf.
8863 for (int &M : LoBlendMask)
8866 for (int &M : HiBlendMask)
8870 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8871 // VHiHalf so that we can blend them as i16s.
8872 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8873 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8874 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8875 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8878 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8879 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8881 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8884 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8886 /// This routine breaks down the specific type of 128-bit shuffle and
8887 /// dispatches to the lowering routines accordingly.
8888 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8889 MVT VT, const X86Subtarget *Subtarget,
8890 SelectionDAG &DAG) {
8891 switch (VT.SimpleTy) {
8893 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8895 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8897 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8899 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8901 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8903 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8906 llvm_unreachable("Unimplemented!");
8910 /// \brief Helper function to test whether a shuffle mask could be
8911 /// simplified by widening the elements being shuffled.
8913 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8914 /// leaves it in an unspecified state.
8916 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8917 /// shuffle masks. The latter have the special property of a '-2' representing
8918 /// a zero-ed lane of a vector.
8919 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8920 SmallVectorImpl<int> &WidenedMask) {
8921 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8922 // If both elements are undef, its trivial.
8923 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8924 WidenedMask.push_back(SM_SentinelUndef);
8928 // Check for an undef mask and a mask value properly aligned to fit with
8929 // a pair of values. If we find such a case, use the non-undef mask's value.
8930 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8931 WidenedMask.push_back(Mask[i + 1] / 2);
8934 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8935 WidenedMask.push_back(Mask[i] / 2);
8939 // When zeroing, we need to spread the zeroing across both lanes to widen.
8940 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8941 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8942 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8943 WidenedMask.push_back(SM_SentinelZero);
8949 // Finally check if the two mask values are adjacent and aligned with
8951 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8952 WidenedMask.push_back(Mask[i] / 2);
8956 // Otherwise we can't safely widen the elements used in this shuffle.
8959 assert(WidenedMask.size() == Mask.size() / 2 &&
8960 "Incorrect size of mask after widening the elements!");
8965 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8967 /// This routine just extracts two subvectors, shuffles them independently, and
8968 /// then concatenates them back together. This should work effectively with all
8969 /// AVX vector shuffle types.
8970 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8971 SDValue V2, ArrayRef<int> Mask,
8972 SelectionDAG &DAG) {
8973 assert(VT.getSizeInBits() >= 256 &&
8974 "Only for 256-bit or wider vector shuffles!");
8975 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8976 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8978 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8979 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8981 int NumElements = VT.getVectorNumElements();
8982 int SplitNumElements = NumElements / 2;
8983 MVT ScalarVT = VT.getScalarType();
8984 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8986 // Rather than splitting build-vectors, just build two narrower build
8987 // vectors. This helps shuffling with splats and zeros.
8988 auto SplitVector = [&](SDValue V) {
8989 while (V.getOpcode() == ISD::BITCAST)
8990 V = V->getOperand(0);
8992 MVT OrigVT = V.getSimpleValueType();
8993 int OrigNumElements = OrigVT.getVectorNumElements();
8994 int OrigSplitNumElements = OrigNumElements / 2;
8995 MVT OrigScalarVT = OrigVT.getScalarType();
8996 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9000 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9002 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9003 DAG.getIntPtrConstant(0, DL));
9004 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9005 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9008 SmallVector<SDValue, 16> LoOps, HiOps;
9009 for (int i = 0; i < OrigSplitNumElements; ++i) {
9010 LoOps.push_back(BV->getOperand(i));
9011 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9013 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9014 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9016 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9017 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9020 SDValue LoV1, HiV1, LoV2, HiV2;
9021 std::tie(LoV1, HiV1) = SplitVector(V1);
9022 std::tie(LoV2, HiV2) = SplitVector(V2);
9024 // Now create two 4-way blends of these half-width vectors.
9025 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9026 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9027 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9028 for (int i = 0; i < SplitNumElements; ++i) {
9029 int M = HalfMask[i];
9030 if (M >= NumElements) {
9031 if (M >= NumElements + SplitNumElements)
9035 V2BlendMask.push_back(M - NumElements);
9036 V1BlendMask.push_back(-1);
9037 BlendMask.push_back(SplitNumElements + i);
9038 } else if (M >= 0) {
9039 if (M >= SplitNumElements)
9043 V2BlendMask.push_back(-1);
9044 V1BlendMask.push_back(M);
9045 BlendMask.push_back(i);
9047 V2BlendMask.push_back(-1);
9048 V1BlendMask.push_back(-1);
9049 BlendMask.push_back(-1);
9053 // Because the lowering happens after all combining takes place, we need to
9054 // manually combine these blend masks as much as possible so that we create
9055 // a minimal number of high-level vector shuffle nodes.
9057 // First try just blending the halves of V1 or V2.
9058 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9059 return DAG.getUNDEF(SplitVT);
9060 if (!UseLoV2 && !UseHiV2)
9061 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9062 if (!UseLoV1 && !UseHiV1)
9063 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9065 SDValue V1Blend, V2Blend;
9066 if (UseLoV1 && UseHiV1) {
9068 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9070 // We only use half of V1 so map the usage down into the final blend mask.
9071 V1Blend = UseLoV1 ? LoV1 : HiV1;
9072 for (int i = 0; i < SplitNumElements; ++i)
9073 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9074 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9076 if (UseLoV2 && UseHiV2) {
9078 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9080 // We only use half of V2 so map the usage down into the final blend mask.
9081 V2Blend = UseLoV2 ? LoV2 : HiV2;
9082 for (int i = 0; i < SplitNumElements; ++i)
9083 if (BlendMask[i] >= SplitNumElements)
9084 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9086 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9088 SDValue Lo = HalfBlend(LoMask);
9089 SDValue Hi = HalfBlend(HiMask);
9090 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9093 /// \brief Either split a vector in halves or decompose the shuffles and the
9096 /// This is provided as a good fallback for many lowerings of non-single-input
9097 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9098 /// between splitting the shuffle into 128-bit components and stitching those
9099 /// back together vs. extracting the single-input shuffles and blending those
9101 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9102 SDValue V2, ArrayRef<int> Mask,
9103 SelectionDAG &DAG) {
9104 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9105 "lower single-input shuffles as it "
9106 "could then recurse on itself.");
9107 int Size = Mask.size();
9109 // If this can be modeled as a broadcast of two elements followed by a blend,
9110 // prefer that lowering. This is especially important because broadcasts can
9111 // often fold with memory operands.
9112 auto DoBothBroadcast = [&] {
9113 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9116 if (V2BroadcastIdx == -1)
9117 V2BroadcastIdx = M - Size;
9118 else if (M - Size != V2BroadcastIdx)
9120 } else if (M >= 0) {
9121 if (V1BroadcastIdx == -1)
9123 else if (M != V1BroadcastIdx)
9128 if (DoBothBroadcast())
9129 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9132 // If the inputs all stem from a single 128-bit lane of each input, then we
9133 // split them rather than blending because the split will decompose to
9134 // unusually few instructions.
9135 int LaneCount = VT.getSizeInBits() / 128;
9136 int LaneSize = Size / LaneCount;
9137 SmallBitVector LaneInputs[2];
9138 LaneInputs[0].resize(LaneCount, false);
9139 LaneInputs[1].resize(LaneCount, false);
9140 for (int i = 0; i < Size; ++i)
9142 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9143 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9144 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9146 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9147 // that the decomposed single-input shuffles don't end up here.
9148 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9151 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9152 /// a permutation and blend of those lanes.
9154 /// This essentially blends the out-of-lane inputs to each lane into the lane
9155 /// from a permuted copy of the vector. This lowering strategy results in four
9156 /// instructions in the worst case for a single-input cross lane shuffle which
9157 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9158 /// of. Special cases for each particular shuffle pattern should be handled
9159 /// prior to trying this lowering.
9160 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9161 SDValue V1, SDValue V2,
9163 SelectionDAG &DAG) {
9164 // FIXME: This should probably be generalized for 512-bit vectors as well.
9165 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9166 int LaneSize = Mask.size() / 2;
9168 // If there are only inputs from one 128-bit lane, splitting will in fact be
9169 // less expensive. The flags track whether the given lane contains an element
9170 // that crosses to another lane.
9171 bool LaneCrossing[2] = {false, false};
9172 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9173 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9174 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9175 if (!LaneCrossing[0] || !LaneCrossing[1])
9176 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9178 if (isSingleInputShuffleMask(Mask)) {
9179 SmallVector<int, 32> FlippedBlendMask;
9180 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9181 FlippedBlendMask.push_back(
9182 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9184 : Mask[i] % LaneSize +
9185 (i / LaneSize) * LaneSize + Size));
9187 // Flip the vector, and blend the results which should now be in-lane. The
9188 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9189 // 5 for the high source. The value 3 selects the high half of source 2 and
9190 // the value 2 selects the low half of source 2. We only use source 2 to
9191 // allow folding it into a memory operand.
9192 unsigned PERMMask = 3 | 2 << 4;
9193 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9194 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9195 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9198 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9199 // will be handled by the above logic and a blend of the results, much like
9200 // other patterns in AVX.
9201 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9204 /// \brief Handle lowering 2-lane 128-bit shuffles.
9205 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9206 SDValue V2, ArrayRef<int> Mask,
9207 const X86Subtarget *Subtarget,
9208 SelectionDAG &DAG) {
9209 // TODO: If minimizing size and one of the inputs is a zero vector and the
9210 // the zero vector has only one use, we could use a VPERM2X128 to save the
9211 // instruction bytes needed to explicitly generate the zero vector.
9213 // Blends are faster and handle all the non-lane-crossing cases.
9214 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9218 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9219 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9221 // If either input operand is a zero vector, use VPERM2X128 because its mask
9222 // allows us to replace the zero input with an implicit zero.
9223 if (!IsV1Zero && !IsV2Zero) {
9224 // Check for patterns which can be matched with a single insert of a 128-bit
9226 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9227 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9228 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9229 VT.getVectorNumElements() / 2);
9230 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9231 DAG.getIntPtrConstant(0, DL));
9232 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9233 OnlyUsesV1 ? V1 : V2,
9234 DAG.getIntPtrConstant(0, DL));
9235 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9239 // Otherwise form a 128-bit permutation. After accounting for undefs,
9240 // convert the 64-bit shuffle mask selection values into 128-bit
9241 // selection bits by dividing the indexes by 2 and shifting into positions
9242 // defined by a vperm2*128 instruction's immediate control byte.
9244 // The immediate permute control byte looks like this:
9245 // [1:0] - select 128 bits from sources for low half of destination
9247 // [3] - zero low half of destination
9248 // [5:4] - select 128 bits from sources for high half of destination
9250 // [7] - zero high half of destination
9252 int MaskLO = Mask[0];
9253 if (MaskLO == SM_SentinelUndef)
9254 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9256 int MaskHI = Mask[2];
9257 if (MaskHI == SM_SentinelUndef)
9258 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9260 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9262 // If either input is a zero vector, replace it with an undef input.
9263 // Shuffle mask values < 4 are selecting elements of V1.
9264 // Shuffle mask values >= 4 are selecting elements of V2.
9265 // Adjust each half of the permute mask by clearing the half that was
9266 // selecting the zero vector and setting the zero mask bit.
9268 V1 = DAG.getUNDEF(VT);
9270 PermMask = (PermMask & 0xf0) | 0x08;
9272 PermMask = (PermMask & 0x0f) | 0x80;
9275 V2 = DAG.getUNDEF(VT);
9277 PermMask = (PermMask & 0xf0) | 0x08;
9279 PermMask = (PermMask & 0x0f) | 0x80;
9282 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9283 DAG.getConstant(PermMask, DL, MVT::i8));
9286 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9287 /// shuffling each lane.
9289 /// This will only succeed when the result of fixing the 128-bit lanes results
9290 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9291 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9292 /// the lane crosses early and then use simpler shuffles within each lane.
9294 /// FIXME: It might be worthwhile at some point to support this without
9295 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9296 /// in x86 only floating point has interesting non-repeating shuffles, and even
9297 /// those are still *marginally* more expensive.
9298 static SDValue lowerVectorShuffleByMerging128BitLanes(
9299 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9300 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9301 assert(!isSingleInputShuffleMask(Mask) &&
9302 "This is only useful with multiple inputs.");
9304 int Size = Mask.size();
9305 int LaneSize = 128 / VT.getScalarSizeInBits();
9306 int NumLanes = Size / LaneSize;
9307 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9309 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9310 // check whether the in-128-bit lane shuffles share a repeating pattern.
9311 SmallVector<int, 4> Lanes;
9312 Lanes.resize(NumLanes, -1);
9313 SmallVector<int, 4> InLaneMask;
9314 InLaneMask.resize(LaneSize, -1);
9315 for (int i = 0; i < Size; ++i) {
9319 int j = i / LaneSize;
9322 // First entry we've seen for this lane.
9323 Lanes[j] = Mask[i] / LaneSize;
9324 } else if (Lanes[j] != Mask[i] / LaneSize) {
9325 // This doesn't match the lane selected previously!
9329 // Check that within each lane we have a consistent shuffle mask.
9330 int k = i % LaneSize;
9331 if (InLaneMask[k] < 0) {
9332 InLaneMask[k] = Mask[i] % LaneSize;
9333 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9334 // This doesn't fit a repeating in-lane mask.
9339 // First shuffle the lanes into place.
9340 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9341 VT.getSizeInBits() / 64);
9342 SmallVector<int, 8> LaneMask;
9343 LaneMask.resize(NumLanes * 2, -1);
9344 for (int i = 0; i < NumLanes; ++i)
9345 if (Lanes[i] >= 0) {
9346 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9347 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9350 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9351 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9352 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9354 // Cast it back to the type we actually want.
9355 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9357 // Now do a simple shuffle that isn't lane crossing.
9358 SmallVector<int, 8> NewMask;
9359 NewMask.resize(Size, -1);
9360 for (int i = 0; i < Size; ++i)
9362 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9363 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9364 "Must not introduce lane crosses at this point!");
9366 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9369 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9372 /// This returns true if the elements from a particular input are already in the
9373 /// slot required by the given mask and require no permutation.
9374 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9375 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9376 int Size = Mask.size();
9377 for (int i = 0; i < Size; ++i)
9378 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9384 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9386 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9387 /// isn't available.
9388 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9389 const X86Subtarget *Subtarget,
9390 SelectionDAG &DAG) {
9392 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9393 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9394 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9395 ArrayRef<int> Mask = SVOp->getMask();
9396 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9398 SmallVector<int, 4> WidenedMask;
9399 if (canWidenShuffleElements(Mask, WidenedMask))
9400 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9403 if (isSingleInputShuffleMask(Mask)) {
9404 // Check for being able to broadcast a single element.
9405 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9406 Mask, Subtarget, DAG))
9409 // Use low duplicate instructions for masks that match their pattern.
9410 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9411 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9413 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9414 // Non-half-crossing single input shuffles can be lowerid with an
9415 // interleaved permutation.
9416 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9417 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9418 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9419 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9422 // With AVX2 we have direct support for this permutation.
9423 if (Subtarget->hasAVX2())
9424 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9425 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9427 // Otherwise, fall back.
9428 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9432 // X86 has dedicated unpack instructions that can handle specific blend
9433 // operations: UNPCKH and UNPCKL.
9434 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9435 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9436 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9437 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9438 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9439 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9440 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9441 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9443 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9447 // Check if the blend happens to exactly fit that of SHUFPD.
9448 if ((Mask[0] == -1 || Mask[0] < 2) &&
9449 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9450 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9451 (Mask[3] == -1 || Mask[3] >= 6)) {
9452 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9453 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9454 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9455 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9457 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9458 (Mask[1] == -1 || Mask[1] < 2) &&
9459 (Mask[2] == -1 || Mask[2] >= 6) &&
9460 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9461 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9462 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9463 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9464 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9467 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9468 // shuffle. However, if we have AVX2 and either inputs are already in place,
9469 // we will be able to shuffle even across lanes the other input in a single
9470 // instruction so skip this pattern.
9471 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9472 isShuffleMaskInputInPlace(1, Mask))))
9473 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9474 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9477 // If we have AVX2 then we always want to lower with a blend because an v4 we
9478 // can fully permute the elements.
9479 if (Subtarget->hasAVX2())
9480 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9483 // Otherwise fall back on generic lowering.
9484 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9487 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9489 /// This routine is only called when we have AVX2 and thus a reasonable
9490 /// instruction set for v4i64 shuffling..
9491 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9492 const X86Subtarget *Subtarget,
9493 SelectionDAG &DAG) {
9495 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9496 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9497 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9498 ArrayRef<int> Mask = SVOp->getMask();
9499 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9500 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9502 SmallVector<int, 4> WidenedMask;
9503 if (canWidenShuffleElements(Mask, WidenedMask))
9504 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9507 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9511 // Check for being able to broadcast a single element.
9512 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9513 Mask, Subtarget, DAG))
9516 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9517 // use lower latency instructions that will operate on both 128-bit lanes.
9518 SmallVector<int, 2> RepeatedMask;
9519 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9520 if (isSingleInputShuffleMask(Mask)) {
9521 int PSHUFDMask[] = {-1, -1, -1, -1};
9522 for (int i = 0; i < 2; ++i)
9523 if (RepeatedMask[i] >= 0) {
9524 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9525 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9528 ISD::BITCAST, DL, MVT::v4i64,
9529 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9530 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9531 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9535 // AVX2 provides a direct instruction for permuting a single input across
9537 if (isSingleInputShuffleMask(Mask))
9538 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9539 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9541 // Try to use shift instructions.
9543 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9546 // Use dedicated unpack instructions for masks that match their pattern.
9547 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9548 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9549 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9550 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9551 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9552 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9553 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9554 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9556 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9557 // shuffle. However, if we have AVX2 and either inputs are already in place,
9558 // we will be able to shuffle even across lanes the other input in a single
9559 // instruction so skip this pattern.
9560 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9561 isShuffleMaskInputInPlace(1, Mask))))
9562 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9563 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9566 // Otherwise fall back on generic blend lowering.
9567 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9571 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9573 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9574 /// isn't available.
9575 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9576 const X86Subtarget *Subtarget,
9577 SelectionDAG &DAG) {
9579 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9580 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9581 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9582 ArrayRef<int> Mask = SVOp->getMask();
9583 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9585 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9589 // Check for being able to broadcast a single element.
9590 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9591 Mask, Subtarget, DAG))
9594 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9595 // options to efficiently lower the shuffle.
9596 SmallVector<int, 4> RepeatedMask;
9597 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9598 assert(RepeatedMask.size() == 4 &&
9599 "Repeated masks must be half the mask width!");
9601 // Use even/odd duplicate instructions for masks that match their pattern.
9602 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9603 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9604 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9605 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9607 if (isSingleInputShuffleMask(Mask))
9608 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9609 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9611 // Use dedicated unpack instructions for masks that match their pattern.
9612 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9613 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9614 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9615 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9616 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9617 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9618 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9619 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9621 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9622 // have already handled any direct blends. We also need to squash the
9623 // repeated mask into a simulated v4f32 mask.
9624 for (int i = 0; i < 4; ++i)
9625 if (RepeatedMask[i] >= 8)
9626 RepeatedMask[i] -= 4;
9627 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9630 // If we have a single input shuffle with different shuffle patterns in the
9631 // two 128-bit lanes use the variable mask to VPERMILPS.
9632 if (isSingleInputShuffleMask(Mask)) {
9633 SDValue VPermMask[8];
9634 for (int i = 0; i < 8; ++i)
9635 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9636 : DAG.getConstant(Mask[i], DL, MVT::i32);
9637 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9639 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9640 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9642 if (Subtarget->hasAVX2())
9643 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9644 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9645 DAG.getNode(ISD::BUILD_VECTOR, DL,
9646 MVT::v8i32, VPermMask)),
9649 // Otherwise, fall back.
9650 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9654 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9656 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9657 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9660 // If we have AVX2 then we always want to lower with a blend because at v8 we
9661 // can fully permute the elements.
9662 if (Subtarget->hasAVX2())
9663 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9666 // Otherwise fall back on generic lowering.
9667 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9670 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9672 /// This routine is only called when we have AVX2 and thus a reasonable
9673 /// instruction set for v8i32 shuffling..
9674 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9675 const X86Subtarget *Subtarget,
9676 SelectionDAG &DAG) {
9678 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9679 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9680 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9681 ArrayRef<int> Mask = SVOp->getMask();
9682 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9683 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9685 // Whenever we can lower this as a zext, that instruction is strictly faster
9686 // than any alternative. It also allows us to fold memory operands into the
9687 // shuffle in many cases.
9688 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9689 Mask, Subtarget, DAG))
9692 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9696 // Check for being able to broadcast a single element.
9697 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9698 Mask, Subtarget, DAG))
9701 // If the shuffle mask is repeated in each 128-bit lane we can use more
9702 // efficient instructions that mirror the shuffles across the two 128-bit
9704 SmallVector<int, 4> RepeatedMask;
9705 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9706 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9707 if (isSingleInputShuffleMask(Mask))
9708 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9709 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9711 // Use dedicated unpack instructions for masks that match their pattern.
9712 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9713 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9714 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9715 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9716 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9717 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9718 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9719 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9722 // Try to use shift instructions.
9724 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9727 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9728 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9731 // If the shuffle patterns aren't repeated but it is a single input, directly
9732 // generate a cross-lane VPERMD instruction.
9733 if (isSingleInputShuffleMask(Mask)) {
9734 SDValue VPermMask[8];
9735 for (int i = 0; i < 8; ++i)
9736 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9737 : DAG.getConstant(Mask[i], DL, MVT::i32);
9739 X86ISD::VPERMV, DL, MVT::v8i32,
9740 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9743 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9745 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9746 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9749 // Otherwise fall back on generic blend lowering.
9750 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9754 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9756 /// This routine is only called when we have AVX2 and thus a reasonable
9757 /// instruction set for v16i16 shuffling..
9758 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9759 const X86Subtarget *Subtarget,
9760 SelectionDAG &DAG) {
9762 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9763 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9764 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9765 ArrayRef<int> Mask = SVOp->getMask();
9766 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9767 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9769 // Whenever we can lower this as a zext, that instruction is strictly faster
9770 // than any alternative. It also allows us to fold memory operands into the
9771 // shuffle in many cases.
9772 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9773 Mask, Subtarget, DAG))
9776 // Check for being able to broadcast a single element.
9777 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9778 Mask, Subtarget, DAG))
9781 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9785 // Use dedicated unpack instructions for masks that match their pattern.
9786 if (isShuffleEquivalent(V1, V2, Mask,
9787 {// First 128-bit lane:
9788 0, 16, 1, 17, 2, 18, 3, 19,
9789 // Second 128-bit lane:
9790 8, 24, 9, 25, 10, 26, 11, 27}))
9791 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9792 if (isShuffleEquivalent(V1, V2, Mask,
9793 {// First 128-bit lane:
9794 4, 20, 5, 21, 6, 22, 7, 23,
9795 // Second 128-bit lane:
9796 12, 28, 13, 29, 14, 30, 15, 31}))
9797 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9799 // Try to use shift instructions.
9801 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9804 // Try to use byte rotation instructions.
9805 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9806 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9809 if (isSingleInputShuffleMask(Mask)) {
9810 // There are no generalized cross-lane shuffle operations available on i16
9812 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9813 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9816 SmallVector<int, 8> RepeatedMask;
9817 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9818 // As this is a single-input shuffle, the repeated mask should be
9819 // a strictly valid v8i16 mask that we can pass through to the v8i16
9820 // lowering to handle even the v16 case.
9821 return lowerV8I16GeneralSingleInputVectorShuffle(
9822 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9825 SDValue PSHUFBMask[32];
9826 for (int i = 0; i < 16; ++i) {
9827 if (Mask[i] == -1) {
9828 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9832 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9833 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9834 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9835 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9838 ISD::BITCAST, DL, MVT::v16i16,
9840 X86ISD::PSHUFB, DL, MVT::v32i8,
9841 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9842 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9845 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9847 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9848 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9851 // Otherwise fall back on generic lowering.
9852 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9855 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9857 /// This routine is only called when we have AVX2 and thus a reasonable
9858 /// instruction set for v32i8 shuffling..
9859 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9860 const X86Subtarget *Subtarget,
9861 SelectionDAG &DAG) {
9863 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9864 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9865 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9866 ArrayRef<int> Mask = SVOp->getMask();
9867 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9868 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9870 // Whenever we can lower this as a zext, that instruction is strictly faster
9871 // than any alternative. It also allows us to fold memory operands into the
9872 // shuffle in many cases.
9873 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9874 Mask, Subtarget, DAG))
9877 // Check for being able to broadcast a single element.
9878 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9879 Mask, Subtarget, DAG))
9882 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9886 // Use dedicated unpack instructions for masks that match their pattern.
9887 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9889 if (isShuffleEquivalent(
9891 {// First 128-bit lane:
9892 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9893 // Second 128-bit lane:
9894 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9895 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9896 if (isShuffleEquivalent(
9898 {// First 128-bit lane:
9899 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9900 // Second 128-bit lane:
9901 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9902 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9904 // Try to use shift instructions.
9906 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9909 // Try to use byte rotation instructions.
9910 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9911 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9914 if (isSingleInputShuffleMask(Mask)) {
9915 // There are no generalized cross-lane shuffle operations available on i8
9917 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9918 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9921 SDValue PSHUFBMask[32];
9922 for (int i = 0; i < 32; ++i)
9925 ? DAG.getUNDEF(MVT::i8)
9926 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9930 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9931 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9934 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9936 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9937 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9940 // Otherwise fall back on generic lowering.
9941 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9944 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9946 /// This routine either breaks down the specific type of a 256-bit x86 vector
9947 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9948 /// together based on the available instructions.
9949 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9950 MVT VT, const X86Subtarget *Subtarget,
9951 SelectionDAG &DAG) {
9953 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9954 ArrayRef<int> Mask = SVOp->getMask();
9956 // If we have a single input to the zero element, insert that into V1 if we
9957 // can do so cheaply.
9958 int NumElts = VT.getVectorNumElements();
9959 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9960 return M >= NumElts;
9963 if (NumV2Elements == 1 && Mask[0] >= NumElts)
9964 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9965 DL, VT, V1, V2, Mask, Subtarget, DAG))
9968 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9969 // check for those subtargets here and avoid much of the subtarget querying in
9970 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9971 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9972 // floating point types there eventually, just immediately cast everything to
9973 // a float and operate entirely in that domain.
9974 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9975 int ElementBits = VT.getScalarSizeInBits();
9976 if (ElementBits < 32)
9977 // No floating point type available, decompose into 128-bit vectors.
9978 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9980 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9981 VT.getVectorNumElements());
9982 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9983 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9984 return DAG.getNode(ISD::BITCAST, DL, VT,
9985 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9988 switch (VT.SimpleTy) {
9990 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9992 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9994 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9996 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9998 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10000 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10003 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10007 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10008 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10009 const X86Subtarget *Subtarget,
10010 SelectionDAG &DAG) {
10012 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10013 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10014 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10015 ArrayRef<int> Mask = SVOp->getMask();
10016 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10018 // X86 has dedicated unpack instructions that can handle specific blend
10019 // operations: UNPCKH and UNPCKL.
10020 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10021 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10022 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10023 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10025 // FIXME: Implement direct support for this type!
10026 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10029 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10030 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10031 const X86Subtarget *Subtarget,
10032 SelectionDAG &DAG) {
10034 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10035 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10036 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10037 ArrayRef<int> Mask = SVOp->getMask();
10038 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10040 // Use dedicated unpack instructions for masks that match their pattern.
10041 if (isShuffleEquivalent(V1, V2, Mask,
10042 {// First 128-bit lane.
10043 0, 16, 1, 17, 4, 20, 5, 21,
10044 // Second 128-bit lane.
10045 8, 24, 9, 25, 12, 28, 13, 29}))
10046 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10047 if (isShuffleEquivalent(V1, V2, Mask,
10048 {// First 128-bit lane.
10049 2, 18, 3, 19, 6, 22, 7, 23,
10050 // Second 128-bit lane.
10051 10, 26, 11, 27, 14, 30, 15, 31}))
10052 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10054 // FIXME: Implement direct support for this type!
10055 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10058 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10059 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10060 const X86Subtarget *Subtarget,
10061 SelectionDAG &DAG) {
10063 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10064 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10065 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10066 ArrayRef<int> Mask = SVOp->getMask();
10067 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10069 // X86 has dedicated unpack instructions that can handle specific blend
10070 // operations: UNPCKH and UNPCKL.
10071 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10072 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10073 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10074 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10076 // FIXME: Implement direct support for this type!
10077 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10080 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10081 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10082 const X86Subtarget *Subtarget,
10083 SelectionDAG &DAG) {
10085 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10086 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10087 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10088 ArrayRef<int> Mask = SVOp->getMask();
10089 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10091 // Use dedicated unpack instructions for masks that match their pattern.
10092 if (isShuffleEquivalent(V1, V2, Mask,
10093 {// First 128-bit lane.
10094 0, 16, 1, 17, 4, 20, 5, 21,
10095 // Second 128-bit lane.
10096 8, 24, 9, 25, 12, 28, 13, 29}))
10097 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10098 if (isShuffleEquivalent(V1, V2, Mask,
10099 {// First 128-bit lane.
10100 2, 18, 3, 19, 6, 22, 7, 23,
10101 // Second 128-bit lane.
10102 10, 26, 11, 27, 14, 30, 15, 31}))
10103 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10105 // FIXME: Implement direct support for this type!
10106 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10109 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10110 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10111 const X86Subtarget *Subtarget,
10112 SelectionDAG &DAG) {
10114 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10115 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10116 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10117 ArrayRef<int> Mask = SVOp->getMask();
10118 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10119 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10121 // FIXME: Implement direct support for this type!
10122 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10125 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10126 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10127 const X86Subtarget *Subtarget,
10128 SelectionDAG &DAG) {
10130 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10131 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10132 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10133 ArrayRef<int> Mask = SVOp->getMask();
10134 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10135 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10137 // FIXME: Implement direct support for this type!
10138 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10141 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10143 /// This routine either breaks down the specific type of a 512-bit x86 vector
10144 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10145 /// together based on the available instructions.
10146 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10147 MVT VT, const X86Subtarget *Subtarget,
10148 SelectionDAG &DAG) {
10150 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10151 ArrayRef<int> Mask = SVOp->getMask();
10152 assert(Subtarget->hasAVX512() &&
10153 "Cannot lower 512-bit vectors w/ basic ISA!");
10155 // Check for being able to broadcast a single element.
10156 if (SDValue Broadcast =
10157 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10160 // Dispatch to each element type for lowering. If we don't have supprot for
10161 // specific element type shuffles at 512 bits, immediately split them and
10162 // lower them. Each lowering routine of a given type is allowed to assume that
10163 // the requisite ISA extensions for that element type are available.
10164 switch (VT.SimpleTy) {
10166 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10168 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10170 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10172 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10174 if (Subtarget->hasBWI())
10175 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10178 if (Subtarget->hasBWI())
10179 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10183 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10186 // Otherwise fall back on splitting.
10187 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10190 /// \brief Top-level lowering for x86 vector shuffles.
10192 /// This handles decomposition, canonicalization, and lowering of all x86
10193 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10194 /// above in helper routines. The canonicalization attempts to widen shuffles
10195 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10196 /// s.t. only one of the two inputs needs to be tested, etc.
10197 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10198 SelectionDAG &DAG) {
10199 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10200 ArrayRef<int> Mask = SVOp->getMask();
10201 SDValue V1 = Op.getOperand(0);
10202 SDValue V2 = Op.getOperand(1);
10203 MVT VT = Op.getSimpleValueType();
10204 int NumElements = VT.getVectorNumElements();
10207 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10209 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10210 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10211 if (V1IsUndef && V2IsUndef)
10212 return DAG.getUNDEF(VT);
10214 // When we create a shuffle node we put the UNDEF node to second operand,
10215 // but in some cases the first operand may be transformed to UNDEF.
10216 // In this case we should just commute the node.
10218 return DAG.getCommutedVectorShuffle(*SVOp);
10220 // Check for non-undef masks pointing at an undef vector and make the masks
10221 // undef as well. This makes it easier to match the shuffle based solely on
10225 if (M >= NumElements) {
10226 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10227 for (int &M : NewMask)
10228 if (M >= NumElements)
10230 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10233 // We actually see shuffles that are entirely re-arrangements of a set of
10234 // zero inputs. This mostly happens while decomposing complex shuffles into
10235 // simple ones. Directly lower these as a buildvector of zeros.
10236 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10237 if (Zeroable.all())
10238 return getZeroVector(VT, Subtarget, DAG, dl);
10240 // Try to collapse shuffles into using a vector type with fewer elements but
10241 // wider element types. We cap this to not form integers or floating point
10242 // elements wider than 64 bits, but it might be interesting to form i128
10243 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10244 SmallVector<int, 16> WidenedMask;
10245 if (VT.getScalarSizeInBits() < 64 &&
10246 canWidenShuffleElements(Mask, WidenedMask)) {
10247 MVT NewEltVT = VT.isFloatingPoint()
10248 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10249 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10250 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10251 // Make sure that the new vector type is legal. For example, v2f64 isn't
10253 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10254 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10255 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10256 return DAG.getNode(ISD::BITCAST, dl, VT,
10257 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10261 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10262 for (int M : SVOp->getMask())
10264 ++NumUndefElements;
10265 else if (M < NumElements)
10270 // Commute the shuffle as needed such that more elements come from V1 than
10271 // V2. This allows us to match the shuffle pattern strictly on how many
10272 // elements come from V1 without handling the symmetric cases.
10273 if (NumV2Elements > NumV1Elements)
10274 return DAG.getCommutedVectorShuffle(*SVOp);
10276 // When the number of V1 and V2 elements are the same, try to minimize the
10277 // number of uses of V2 in the low half of the vector. When that is tied,
10278 // ensure that the sum of indices for V1 is equal to or lower than the sum
10279 // indices for V2. When those are equal, try to ensure that the number of odd
10280 // indices for V1 is lower than the number of odd indices for V2.
10281 if (NumV1Elements == NumV2Elements) {
10282 int LowV1Elements = 0, LowV2Elements = 0;
10283 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10284 if (M >= NumElements)
10288 if (LowV2Elements > LowV1Elements) {
10289 return DAG.getCommutedVectorShuffle(*SVOp);
10290 } else if (LowV2Elements == LowV1Elements) {
10291 int SumV1Indices = 0, SumV2Indices = 0;
10292 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10293 if (SVOp->getMask()[i] >= NumElements)
10295 else if (SVOp->getMask()[i] >= 0)
10297 if (SumV2Indices < SumV1Indices) {
10298 return DAG.getCommutedVectorShuffle(*SVOp);
10299 } else if (SumV2Indices == SumV1Indices) {
10300 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10301 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10302 if (SVOp->getMask()[i] >= NumElements)
10303 NumV2OddIndices += i % 2;
10304 else if (SVOp->getMask()[i] >= 0)
10305 NumV1OddIndices += i % 2;
10306 if (NumV2OddIndices < NumV1OddIndices)
10307 return DAG.getCommutedVectorShuffle(*SVOp);
10312 // For each vector width, delegate to a specialized lowering routine.
10313 if (VT.getSizeInBits() == 128)
10314 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10316 if (VT.getSizeInBits() == 256)
10317 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10319 // Force AVX-512 vectors to be scalarized for now.
10320 // FIXME: Implement AVX-512 support!
10321 if (VT.getSizeInBits() == 512)
10322 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10324 llvm_unreachable("Unimplemented!");
10327 // This function assumes its argument is a BUILD_VECTOR of constants or
10328 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10330 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10331 unsigned &MaskValue) {
10333 unsigned NumElems = BuildVector->getNumOperands();
10334 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10335 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10336 unsigned NumElemsInLane = NumElems / NumLanes;
10338 // Blend for v16i16 should be symetric for the both lanes.
10339 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10340 SDValue EltCond = BuildVector->getOperand(i);
10341 SDValue SndLaneEltCond =
10342 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10344 int Lane1Cond = -1, Lane2Cond = -1;
10345 if (isa<ConstantSDNode>(EltCond))
10346 Lane1Cond = !isZero(EltCond);
10347 if (isa<ConstantSDNode>(SndLaneEltCond))
10348 Lane2Cond = !isZero(SndLaneEltCond);
10350 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10351 // Lane1Cond != 0, means we want the first argument.
10352 // Lane1Cond == 0, means we want the second argument.
10353 // The encoding of this argument is 0 for the first argument, 1
10354 // for the second. Therefore, invert the condition.
10355 MaskValue |= !Lane1Cond << i;
10356 else if (Lane1Cond < 0)
10357 MaskValue |= !Lane2Cond << i;
10364 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10365 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10366 const X86Subtarget *Subtarget,
10367 SelectionDAG &DAG) {
10368 SDValue Cond = Op.getOperand(0);
10369 SDValue LHS = Op.getOperand(1);
10370 SDValue RHS = Op.getOperand(2);
10372 MVT VT = Op.getSimpleValueType();
10374 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10376 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10378 // Only non-legal VSELECTs reach this lowering, convert those into generic
10379 // shuffles and re-use the shuffle lowering path for blends.
10380 SmallVector<int, 32> Mask;
10381 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10382 SDValue CondElt = CondBV->getOperand(i);
10384 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10386 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10389 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10390 // A vselect where all conditions and data are constants can be optimized into
10391 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10392 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10393 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10394 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10397 // Try to lower this to a blend-style vector shuffle. This can handle all
10398 // constant condition cases.
10399 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10402 // Variable blends are only legal from SSE4.1 onward.
10403 if (!Subtarget->hasSSE41())
10406 // Only some types will be legal on some subtargets. If we can emit a legal
10407 // VSELECT-matching blend, return Op, and but if we need to expand, return
10409 switch (Op.getSimpleValueType().SimpleTy) {
10411 // Most of the vector types have blends past SSE4.1.
10415 // The byte blends for AVX vectors were introduced only in AVX2.
10416 if (Subtarget->hasAVX2())
10423 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10424 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10427 // FIXME: We should custom lower this by fixing the condition and using i8
10433 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10434 MVT VT = Op.getSimpleValueType();
10437 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10440 if (VT.getSizeInBits() == 8) {
10441 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10442 Op.getOperand(0), Op.getOperand(1));
10443 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10444 DAG.getValueType(VT));
10445 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10448 if (VT.getSizeInBits() == 16) {
10449 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10450 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10452 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10453 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10454 DAG.getNode(ISD::BITCAST, dl,
10457 Op.getOperand(1)));
10458 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10459 Op.getOperand(0), Op.getOperand(1));
10460 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10461 DAG.getValueType(VT));
10462 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10465 if (VT == MVT::f32) {
10466 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10467 // the result back to FR32 register. It's only worth matching if the
10468 // result has a single use which is a store or a bitcast to i32. And in
10469 // the case of a store, it's not worth it if the index is a constant 0,
10470 // because a MOVSSmr can be used instead, which is smaller and faster.
10471 if (!Op.hasOneUse())
10473 SDNode *User = *Op.getNode()->use_begin();
10474 if ((User->getOpcode() != ISD::STORE ||
10475 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10476 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10477 (User->getOpcode() != ISD::BITCAST ||
10478 User->getValueType(0) != MVT::i32))
10480 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10481 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10484 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10487 if (VT == MVT::i32 || VT == MVT::i64) {
10488 // ExtractPS/pextrq works with constant index.
10489 if (isa<ConstantSDNode>(Op.getOperand(1)))
10495 /// Extract one bit from mask vector, like v16i1 or v8i1.
10496 /// AVX-512 feature.
10498 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10499 SDValue Vec = Op.getOperand(0);
10501 MVT VecVT = Vec.getSimpleValueType();
10502 SDValue Idx = Op.getOperand(1);
10503 MVT EltVT = Op.getSimpleValueType();
10505 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10506 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10507 "Unexpected vector type in ExtractBitFromMaskVector");
10509 // variable index can't be handled in mask registers,
10510 // extend vector to VR512
10511 if (!isa<ConstantSDNode>(Idx)) {
10512 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10513 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10514 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10515 ExtVT.getVectorElementType(), Ext, Idx);
10516 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10519 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10520 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10521 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10522 rc = getRegClassFor(MVT::v16i1);
10523 unsigned MaxSift = rc->getSize()*8 - 1;
10524 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10525 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10526 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10527 DAG.getConstant(MaxSift, dl, MVT::i8));
10528 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10529 DAG.getIntPtrConstant(0, dl));
10533 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10534 SelectionDAG &DAG) const {
10536 SDValue Vec = Op.getOperand(0);
10537 MVT VecVT = Vec.getSimpleValueType();
10538 SDValue Idx = Op.getOperand(1);
10540 if (Op.getSimpleValueType() == MVT::i1)
10541 return ExtractBitFromMaskVector(Op, DAG);
10543 if (!isa<ConstantSDNode>(Idx)) {
10544 if (VecVT.is512BitVector() ||
10545 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10546 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10549 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10550 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10551 MaskEltVT.getSizeInBits());
10553 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10554 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10555 getZeroVector(MaskVT, Subtarget, DAG, dl),
10556 Idx, DAG.getConstant(0, dl, getPointerTy()));
10557 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10558 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10559 Perm, DAG.getConstant(0, dl, getPointerTy()));
10564 // If this is a 256-bit vector result, first extract the 128-bit vector and
10565 // then extract the element from the 128-bit vector.
10566 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10568 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10569 // Get the 128-bit vector.
10570 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10571 MVT EltVT = VecVT.getVectorElementType();
10573 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10575 //if (IdxVal >= NumElems/2)
10576 // IdxVal -= NumElems/2;
10577 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10578 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10579 DAG.getConstant(IdxVal, dl, MVT::i32));
10582 assert(VecVT.is128BitVector() && "Unexpected vector length");
10584 if (Subtarget->hasSSE41()) {
10585 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10590 MVT VT = Op.getSimpleValueType();
10591 // TODO: handle v16i8.
10592 if (VT.getSizeInBits() == 16) {
10593 SDValue Vec = Op.getOperand(0);
10594 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10596 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10597 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10598 DAG.getNode(ISD::BITCAST, dl,
10600 Op.getOperand(1)));
10601 // Transform it so it match pextrw which produces a 32-bit result.
10602 MVT EltVT = MVT::i32;
10603 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10604 Op.getOperand(0), Op.getOperand(1));
10605 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10606 DAG.getValueType(VT));
10607 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10610 if (VT.getSizeInBits() == 32) {
10611 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10615 // SHUFPS the element to the lowest double word, then movss.
10616 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10617 MVT VVT = Op.getOperand(0).getSimpleValueType();
10618 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10619 DAG.getUNDEF(VVT), Mask);
10620 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10621 DAG.getIntPtrConstant(0, dl));
10624 if (VT.getSizeInBits() == 64) {
10625 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10626 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10627 // to match extract_elt for f64.
10628 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10632 // UNPCKHPD the element to the lowest double word, then movsd.
10633 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10634 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10635 int Mask[2] = { 1, -1 };
10636 MVT VVT = Op.getOperand(0).getSimpleValueType();
10637 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10638 DAG.getUNDEF(VVT), Mask);
10639 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10640 DAG.getIntPtrConstant(0, dl));
10646 /// Insert one bit to mask vector, like v16i1 or v8i1.
10647 /// AVX-512 feature.
10649 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10651 SDValue Vec = Op.getOperand(0);
10652 SDValue Elt = Op.getOperand(1);
10653 SDValue Idx = Op.getOperand(2);
10654 MVT VecVT = Vec.getSimpleValueType();
10656 if (!isa<ConstantSDNode>(Idx)) {
10657 // Non constant index. Extend source and destination,
10658 // insert element and then truncate the result.
10659 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10660 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10661 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10662 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10663 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10664 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10667 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10668 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10669 if (Vec.getOpcode() == ISD::UNDEF)
10670 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10671 DAG.getConstant(IdxVal, dl, MVT::i8));
10672 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10673 unsigned MaxSift = rc->getSize()*8 - 1;
10674 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10675 DAG.getConstant(MaxSift, dl, MVT::i8));
10676 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10677 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10678 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10681 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10682 SelectionDAG &DAG) const {
10683 MVT VT = Op.getSimpleValueType();
10684 MVT EltVT = VT.getVectorElementType();
10686 if (EltVT == MVT::i1)
10687 return InsertBitToMaskVector(Op, DAG);
10690 SDValue N0 = Op.getOperand(0);
10691 SDValue N1 = Op.getOperand(1);
10692 SDValue N2 = Op.getOperand(2);
10693 if (!isa<ConstantSDNode>(N2))
10695 auto *N2C = cast<ConstantSDNode>(N2);
10696 unsigned IdxVal = N2C->getZExtValue();
10698 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10699 // into that, and then insert the subvector back into the result.
10700 if (VT.is256BitVector() || VT.is512BitVector()) {
10701 // With a 256-bit vector, we can insert into the zero element efficiently
10702 // using a blend if we have AVX or AVX2 and the right data type.
10703 if (VT.is256BitVector() && IdxVal == 0) {
10704 // TODO: It is worthwhile to cast integer to floating point and back
10705 // and incur a domain crossing penalty if that's what we'll end up
10706 // doing anyway after extracting to a 128-bit vector.
10707 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10708 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10709 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10710 N2 = DAG.getIntPtrConstant(1, dl);
10711 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10715 // Get the desired 128-bit vector chunk.
10716 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10718 // Insert the element into the desired chunk.
10719 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10720 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10722 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10723 DAG.getConstant(IdxIn128, dl, MVT::i32));
10725 // Insert the changed part back into the bigger vector
10726 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10728 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10730 if (Subtarget->hasSSE41()) {
10731 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10733 if (VT == MVT::v8i16) {
10734 Opc = X86ISD::PINSRW;
10736 assert(VT == MVT::v16i8);
10737 Opc = X86ISD::PINSRB;
10740 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10742 if (N1.getValueType() != MVT::i32)
10743 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10744 if (N2.getValueType() != MVT::i32)
10745 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10746 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10749 if (EltVT == MVT::f32) {
10750 // Bits [7:6] of the constant are the source select. This will always be
10751 // zero here. The DAG Combiner may combine an extract_elt index into
10752 // these bits. For example (insert (extract, 3), 2) could be matched by
10753 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10754 // Bits [5:4] of the constant are the destination select. This is the
10755 // value of the incoming immediate.
10756 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10757 // combine either bitwise AND or insert of float 0.0 to set these bits.
10759 const Function *F = DAG.getMachineFunction().getFunction();
10760 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10761 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10762 // If this is an insertion of 32-bits into the low 32-bits of
10763 // a vector, we prefer to generate a blend with immediate rather
10764 // than an insertps. Blends are simpler operations in hardware and so
10765 // will always have equal or better performance than insertps.
10766 // But if optimizing for size and there's a load folding opportunity,
10767 // generate insertps because blendps does not have a 32-bit memory
10769 N2 = DAG.getIntPtrConstant(1, dl);
10770 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10771 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10773 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10774 // Create this as a scalar to vector..
10775 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10776 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10779 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10780 // PINSR* works with constant index.
10785 if (EltVT == MVT::i8)
10788 if (EltVT.getSizeInBits() == 16) {
10789 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10790 // as its second argument.
10791 if (N1.getValueType() != MVT::i32)
10792 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10793 if (N2.getValueType() != MVT::i32)
10794 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10795 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10800 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10802 MVT OpVT = Op.getSimpleValueType();
10804 // If this is a 256-bit vector result, first insert into a 128-bit
10805 // vector and then insert into the 256-bit vector.
10806 if (!OpVT.is128BitVector()) {
10807 // Insert into a 128-bit vector.
10808 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10809 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10810 OpVT.getVectorNumElements() / SizeFactor);
10812 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10814 // Insert the 128-bit vector.
10815 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10818 if (OpVT == MVT::v1i64 &&
10819 Op.getOperand(0).getValueType() == MVT::i64)
10820 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10822 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10823 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10824 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10825 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10828 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10829 // a simple subregister reference or explicit instructions to grab
10830 // upper bits of a vector.
10831 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10832 SelectionDAG &DAG) {
10834 SDValue In = Op.getOperand(0);
10835 SDValue Idx = Op.getOperand(1);
10836 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10837 MVT ResVT = Op.getSimpleValueType();
10838 MVT InVT = In.getSimpleValueType();
10840 if (Subtarget->hasFp256()) {
10841 if (ResVT.is128BitVector() &&
10842 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10843 isa<ConstantSDNode>(Idx)) {
10844 return Extract128BitVector(In, IdxVal, DAG, dl);
10846 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10847 isa<ConstantSDNode>(Idx)) {
10848 return Extract256BitVector(In, IdxVal, DAG, dl);
10854 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10855 // simple superregister reference or explicit instructions to insert
10856 // the upper bits of a vector.
10857 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10858 SelectionDAG &DAG) {
10859 if (!Subtarget->hasAVX())
10863 SDValue Vec = Op.getOperand(0);
10864 SDValue SubVec = Op.getOperand(1);
10865 SDValue Idx = Op.getOperand(2);
10867 if (!isa<ConstantSDNode>(Idx))
10870 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10871 MVT OpVT = Op.getSimpleValueType();
10872 MVT SubVecVT = SubVec.getSimpleValueType();
10874 // Fold two 16-byte subvector loads into one 32-byte load:
10875 // (insert_subvector (insert_subvector undef, (load addr), 0),
10876 // (load addr + 16), Elts/2)
10878 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10879 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10880 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10881 !Subtarget->isUnalignedMem32Slow()) {
10882 SDValue SubVec2 = Vec.getOperand(1);
10883 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10884 if (Idx2->getZExtValue() == 0) {
10885 SDValue Ops[] = { SubVec2, SubVec };
10886 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10893 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10894 SubVecVT.is128BitVector())
10895 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10897 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10898 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10900 if (OpVT.getVectorElementType() == MVT::i1) {
10901 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10903 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10904 SDValue Undef = DAG.getUNDEF(OpVT);
10905 unsigned NumElems = OpVT.getVectorNumElements();
10906 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10908 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10909 // Zero upper bits of the Vec
10910 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10911 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10913 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10915 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10916 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10919 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10921 // Zero upper bits of the Vec2
10922 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10923 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10924 // Zero lower bits of the Vec
10925 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10926 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10927 // Merge them together
10928 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10934 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10935 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10936 // one of the above mentioned nodes. It has to be wrapped because otherwise
10937 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10938 // be used to form addressing mode. These wrapped nodes will be selected
10941 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10942 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10944 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10945 // global base reg.
10946 unsigned char OpFlag = 0;
10947 unsigned WrapperKind = X86ISD::Wrapper;
10948 CodeModel::Model M = DAG.getTarget().getCodeModel();
10950 if (Subtarget->isPICStyleRIPRel() &&
10951 (M == CodeModel::Small || M == CodeModel::Kernel))
10952 WrapperKind = X86ISD::WrapperRIP;
10953 else if (Subtarget->isPICStyleGOT())
10954 OpFlag = X86II::MO_GOTOFF;
10955 else if (Subtarget->isPICStyleStubPIC())
10956 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10958 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10959 CP->getAlignment(),
10960 CP->getOffset(), OpFlag);
10962 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10963 // With PIC, the address is actually $g + Offset.
10965 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10966 DAG.getNode(X86ISD::GlobalBaseReg,
10967 SDLoc(), getPointerTy()),
10974 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10975 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10977 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10978 // global base reg.
10979 unsigned char OpFlag = 0;
10980 unsigned WrapperKind = X86ISD::Wrapper;
10981 CodeModel::Model M = DAG.getTarget().getCodeModel();
10983 if (Subtarget->isPICStyleRIPRel() &&
10984 (M == CodeModel::Small || M == CodeModel::Kernel))
10985 WrapperKind = X86ISD::WrapperRIP;
10986 else if (Subtarget->isPICStyleGOT())
10987 OpFlag = X86II::MO_GOTOFF;
10988 else if (Subtarget->isPICStyleStubPIC())
10989 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10991 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10994 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10996 // With PIC, the address is actually $g + Offset.
10998 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10999 DAG.getNode(X86ISD::GlobalBaseReg,
11000 SDLoc(), getPointerTy()),
11007 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11008 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11010 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11011 // global base reg.
11012 unsigned char OpFlag = 0;
11013 unsigned WrapperKind = X86ISD::Wrapper;
11014 CodeModel::Model M = DAG.getTarget().getCodeModel();
11016 if (Subtarget->isPICStyleRIPRel() &&
11017 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11018 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11019 OpFlag = X86II::MO_GOTPCREL;
11020 WrapperKind = X86ISD::WrapperRIP;
11021 } else if (Subtarget->isPICStyleGOT()) {
11022 OpFlag = X86II::MO_GOT;
11023 } else if (Subtarget->isPICStyleStubPIC()) {
11024 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11025 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11026 OpFlag = X86II::MO_DARWIN_NONLAZY;
11029 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11032 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11034 // With PIC, the address is actually $g + Offset.
11035 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11036 !Subtarget->is64Bit()) {
11037 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11038 DAG.getNode(X86ISD::GlobalBaseReg,
11039 SDLoc(), getPointerTy()),
11043 // For symbols that require a load from a stub to get the address, emit the
11045 if (isGlobalStubReference(OpFlag))
11046 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11047 MachinePointerInfo::getGOT(), false, false, false, 0);
11053 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11054 // Create the TargetBlockAddressAddress node.
11055 unsigned char OpFlags =
11056 Subtarget->ClassifyBlockAddressReference();
11057 CodeModel::Model M = DAG.getTarget().getCodeModel();
11058 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11059 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11061 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11064 if (Subtarget->isPICStyleRIPRel() &&
11065 (M == CodeModel::Small || M == CodeModel::Kernel))
11066 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11068 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11070 // With PIC, the address is actually $g + Offset.
11071 if (isGlobalRelativeToPICBase(OpFlags)) {
11072 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11073 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11081 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11082 int64_t Offset, SelectionDAG &DAG) const {
11083 // Create the TargetGlobalAddress node, folding in the constant
11084 // offset if it is legal.
11085 unsigned char OpFlags =
11086 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11087 CodeModel::Model M = DAG.getTarget().getCodeModel();
11089 if (OpFlags == X86II::MO_NO_FLAG &&
11090 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11091 // A direct static reference to a global.
11092 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11095 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11098 if (Subtarget->isPICStyleRIPRel() &&
11099 (M == CodeModel::Small || M == CodeModel::Kernel))
11100 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11102 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11104 // With PIC, the address is actually $g + Offset.
11105 if (isGlobalRelativeToPICBase(OpFlags)) {
11106 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11107 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11111 // For globals that require a load from a stub to get the address, emit the
11113 if (isGlobalStubReference(OpFlags))
11114 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11115 MachinePointerInfo::getGOT(), false, false, false, 0);
11117 // If there was a non-zero offset that we didn't fold, create an explicit
11118 // addition for it.
11120 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11121 DAG.getConstant(Offset, dl, getPointerTy()));
11127 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11128 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11129 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11130 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11134 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11135 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11136 unsigned char OperandFlags, bool LocalDynamic = false) {
11137 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11138 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11140 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11141 GA->getValueType(0),
11145 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11149 SDValue Ops[] = { Chain, TGA, *InFlag };
11150 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11152 SDValue Ops[] = { Chain, TGA };
11153 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11156 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11157 MFI->setAdjustsStack(true);
11158 MFI->setHasCalls(true);
11160 SDValue Flag = Chain.getValue(1);
11161 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11164 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11166 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11169 SDLoc dl(GA); // ? function entry point might be better
11170 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11171 DAG.getNode(X86ISD::GlobalBaseReg,
11172 SDLoc(), PtrVT), InFlag);
11173 InFlag = Chain.getValue(1);
11175 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11178 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11180 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11182 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11183 X86::RAX, X86II::MO_TLSGD);
11186 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11192 // Get the start address of the TLS block for this module.
11193 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11194 .getInfo<X86MachineFunctionInfo>();
11195 MFI->incNumLocalDynamicTLSAccesses();
11199 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11200 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11203 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11204 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11205 InFlag = Chain.getValue(1);
11206 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11207 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11210 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11214 unsigned char OperandFlags = X86II::MO_DTPOFF;
11215 unsigned WrapperKind = X86ISD::Wrapper;
11216 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11217 GA->getValueType(0),
11218 GA->getOffset(), OperandFlags);
11219 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11221 // Add x@dtpoff with the base.
11222 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11225 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11226 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11227 const EVT PtrVT, TLSModel::Model model,
11228 bool is64Bit, bool isPIC) {
11231 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11232 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11233 is64Bit ? 257 : 256));
11235 SDValue ThreadPointer =
11236 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11237 MachinePointerInfo(Ptr), false, false, false, 0);
11239 unsigned char OperandFlags = 0;
11240 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11242 unsigned WrapperKind = X86ISD::Wrapper;
11243 if (model == TLSModel::LocalExec) {
11244 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11245 } else if (model == TLSModel::InitialExec) {
11247 OperandFlags = X86II::MO_GOTTPOFF;
11248 WrapperKind = X86ISD::WrapperRIP;
11250 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11253 llvm_unreachable("Unexpected model");
11256 // emit "addl x@ntpoff,%eax" (local exec)
11257 // or "addl x@indntpoff,%eax" (initial exec)
11258 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11260 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11261 GA->getOffset(), OperandFlags);
11262 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11264 if (model == TLSModel::InitialExec) {
11265 if (isPIC && !is64Bit) {
11266 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11267 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11271 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11272 MachinePointerInfo::getGOT(), false, false, false, 0);
11275 // The address of the thread local variable is the add of the thread
11276 // pointer with the offset of the variable.
11277 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11281 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11283 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11284 const GlobalValue *GV = GA->getGlobal();
11286 if (Subtarget->isTargetELF()) {
11287 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11290 case TLSModel::GeneralDynamic:
11291 if (Subtarget->is64Bit())
11292 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11293 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11294 case TLSModel::LocalDynamic:
11295 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11296 Subtarget->is64Bit());
11297 case TLSModel::InitialExec:
11298 case TLSModel::LocalExec:
11299 return LowerToTLSExecModel(
11300 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11301 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11303 llvm_unreachable("Unknown TLS model.");
11306 if (Subtarget->isTargetDarwin()) {
11307 // Darwin only has one model of TLS. Lower to that.
11308 unsigned char OpFlag = 0;
11309 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11310 X86ISD::WrapperRIP : X86ISD::Wrapper;
11312 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11313 // global base reg.
11314 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11315 !Subtarget->is64Bit();
11317 OpFlag = X86II::MO_TLVP_PIC_BASE;
11319 OpFlag = X86II::MO_TLVP;
11321 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11322 GA->getValueType(0),
11323 GA->getOffset(), OpFlag);
11324 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11326 // With PIC32, the address is actually $g + Offset.
11328 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11329 DAG.getNode(X86ISD::GlobalBaseReg,
11330 SDLoc(), getPointerTy()),
11333 // Lowering the machine isd will make sure everything is in the right
11335 SDValue Chain = DAG.getEntryNode();
11336 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11337 SDValue Args[] = { Chain, Offset };
11338 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11340 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11341 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11342 MFI->setAdjustsStack(true);
11344 // And our return value (tls address) is in the standard call return value
11346 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11347 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11348 Chain.getValue(1));
11351 if (Subtarget->isTargetKnownWindowsMSVC() ||
11352 Subtarget->isTargetWindowsGNU()) {
11353 // Just use the implicit TLS architecture
11354 // Need to generate someting similar to:
11355 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11357 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11358 // mov rcx, qword [rdx+rcx*8]
11359 // mov eax, .tls$:tlsvar
11360 // [rax+rcx] contains the address
11361 // Windows 64bit: gs:0x58
11362 // Windows 32bit: fs:__tls_array
11365 SDValue Chain = DAG.getEntryNode();
11367 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11368 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11369 // use its literal value of 0x2C.
11370 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11371 ? Type::getInt8PtrTy(*DAG.getContext(),
11373 : Type::getInt32PtrTy(*DAG.getContext(),
11377 Subtarget->is64Bit()
11378 ? DAG.getIntPtrConstant(0x58, dl)
11379 : (Subtarget->isTargetWindowsGNU()
11380 ? DAG.getIntPtrConstant(0x2C, dl)
11381 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11383 SDValue ThreadPointer =
11384 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11385 MachinePointerInfo(Ptr), false, false, false, 0);
11387 // Load the _tls_index variable
11388 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11389 if (Subtarget->is64Bit())
11390 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11391 IDX, MachinePointerInfo(), MVT::i32,
11392 false, false, false, 0);
11394 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11395 false, false, false, 0);
11397 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11399 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11401 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11402 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11403 false, false, false, 0);
11405 // Get the offset of start of .tls section
11406 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11407 GA->getValueType(0),
11408 GA->getOffset(), X86II::MO_SECREL);
11409 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11411 // The address of the thread local variable is the add of the thread
11412 // pointer with the offset of the variable.
11413 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11416 llvm_unreachable("TLS not implemented for this target.");
11419 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11420 /// and take a 2 x i32 value to shift plus a shift amount.
11421 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11422 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11423 MVT VT = Op.getSimpleValueType();
11424 unsigned VTBits = VT.getSizeInBits();
11426 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11427 SDValue ShOpLo = Op.getOperand(0);
11428 SDValue ShOpHi = Op.getOperand(1);
11429 SDValue ShAmt = Op.getOperand(2);
11430 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11431 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11433 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11434 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11435 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11436 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11437 : DAG.getConstant(0, dl, VT);
11439 SDValue Tmp2, Tmp3;
11440 if (Op.getOpcode() == ISD::SHL_PARTS) {
11441 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11442 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11444 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11445 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11448 // If the shift amount is larger or equal than the width of a part we can't
11449 // rely on the results of shld/shrd. Insert a test and select the appropriate
11450 // values for large shift amounts.
11451 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11452 DAG.getConstant(VTBits, dl, MVT::i8));
11453 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11454 AndNode, DAG.getConstant(0, dl, MVT::i8));
11457 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11458 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11459 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11461 if (Op.getOpcode() == ISD::SHL_PARTS) {
11462 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11463 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11465 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11466 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11469 SDValue Ops[2] = { Lo, Hi };
11470 return DAG.getMergeValues(Ops, dl);
11473 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11474 SelectionDAG &DAG) const {
11475 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11478 if (SrcVT.isVector()) {
11479 if (SrcVT.getVectorElementType() == MVT::i1) {
11480 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11481 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11482 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11483 Op.getOperand(0)));
11488 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11489 "Unknown SINT_TO_FP to lower!");
11491 // These are really Legal; return the operand so the caller accepts it as
11493 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11495 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11496 Subtarget->is64Bit()) {
11500 unsigned Size = SrcVT.getSizeInBits()/8;
11501 MachineFunction &MF = DAG.getMachineFunction();
11502 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11503 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11504 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11506 MachinePointerInfo::getFixedStack(SSFI),
11508 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11511 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11513 SelectionDAG &DAG) const {
11517 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11519 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11521 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11523 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11525 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11526 MachineMemOperand *MMO;
11528 int SSFI = FI->getIndex();
11530 DAG.getMachineFunction()
11531 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11532 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11534 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11535 StackSlot = StackSlot.getOperand(1);
11537 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11538 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11540 Tys, Ops, SrcVT, MMO);
11543 Chain = Result.getValue(1);
11544 SDValue InFlag = Result.getValue(2);
11546 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11547 // shouldn't be necessary except that RFP cannot be live across
11548 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11549 MachineFunction &MF = DAG.getMachineFunction();
11550 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11551 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11552 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11553 Tys = DAG.getVTList(MVT::Other);
11555 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11557 MachineMemOperand *MMO =
11558 DAG.getMachineFunction()
11559 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11560 MachineMemOperand::MOStore, SSFISize, SSFISize);
11562 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11563 Ops, Op.getValueType(), MMO);
11564 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11565 MachinePointerInfo::getFixedStack(SSFI),
11566 false, false, false, 0);
11572 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11573 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11574 SelectionDAG &DAG) const {
11575 // This algorithm is not obvious. Here it is what we're trying to output:
11578 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11579 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11581 haddpd %xmm0, %xmm0
11583 pshufd $0x4e, %xmm0, %xmm1
11589 LLVMContext *Context = DAG.getContext();
11591 // Build some magic constants.
11592 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11593 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11594 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11596 SmallVector<Constant*,2> CV1;
11598 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11599 APInt(64, 0x4330000000000000ULL))));
11601 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11602 APInt(64, 0x4530000000000000ULL))));
11603 Constant *C1 = ConstantVector::get(CV1);
11604 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11606 // Load the 64-bit value into an XMM register.
11607 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11609 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11610 MachinePointerInfo::getConstantPool(),
11611 false, false, false, 16);
11612 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11613 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11616 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11617 MachinePointerInfo::getConstantPool(),
11618 false, false, false, 16);
11619 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11620 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11623 if (Subtarget->hasSSE3()) {
11624 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11625 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11627 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11628 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11630 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11631 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11635 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11636 DAG.getIntPtrConstant(0, dl));
11639 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11640 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11641 SelectionDAG &DAG) const {
11643 // FP constant to bias correct the final result.
11644 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11647 // Load the 32-bit value into an XMM register.
11648 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11651 // Zero out the upper parts of the register.
11652 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11654 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11655 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11656 DAG.getIntPtrConstant(0, dl));
11658 // Or the load with the bias.
11659 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11660 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11661 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11662 MVT::v2f64, Load)),
11663 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11664 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11665 MVT::v2f64, Bias)));
11666 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11667 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11668 DAG.getIntPtrConstant(0, dl));
11670 // Subtract the bias.
11671 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11673 // Handle final rounding.
11674 EVT DestVT = Op.getValueType();
11676 if (DestVT.bitsLT(MVT::f64))
11677 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11678 DAG.getIntPtrConstant(0, dl));
11679 if (DestVT.bitsGT(MVT::f64))
11680 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11682 // Handle final rounding.
11686 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11687 const X86Subtarget &Subtarget) {
11688 // The algorithm is the following:
11689 // #ifdef __SSE4_1__
11690 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11691 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11692 // (uint4) 0x53000000, 0xaa);
11694 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11695 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11697 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11698 // return (float4) lo + fhi;
11701 SDValue V = Op->getOperand(0);
11702 EVT VecIntVT = V.getValueType();
11703 bool Is128 = VecIntVT == MVT::v4i32;
11704 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11705 // If we convert to something else than the supported type, e.g., to v4f64,
11707 if (VecFloatVT != Op->getValueType(0))
11710 unsigned NumElts = VecIntVT.getVectorNumElements();
11711 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11712 "Unsupported custom type");
11713 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11715 // In the #idef/#else code, we have in common:
11716 // - The vector of constants:
11722 // Create the splat vector for 0x4b000000.
11723 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11724 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11725 CstLow, CstLow, CstLow, CstLow};
11726 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11727 makeArrayRef(&CstLowArray[0], NumElts));
11728 // Create the splat vector for 0x53000000.
11729 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11730 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11731 CstHigh, CstHigh, CstHigh, CstHigh};
11732 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11733 makeArrayRef(&CstHighArray[0], NumElts));
11735 // Create the right shift.
11736 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11737 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11738 CstShift, CstShift, CstShift, CstShift};
11739 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11740 makeArrayRef(&CstShiftArray[0], NumElts));
11741 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11744 if (Subtarget.hasSSE41()) {
11745 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11746 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11747 SDValue VecCstLowBitcast =
11748 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11749 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11750 // Low will be bitcasted right away, so do not bother bitcasting back to its
11752 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11753 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11754 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11755 // (uint4) 0x53000000, 0xaa);
11756 SDValue VecCstHighBitcast =
11757 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11758 SDValue VecShiftBitcast =
11759 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11760 // High will be bitcasted right away, so do not bother bitcasting back to
11761 // its original type.
11762 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11763 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11765 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11766 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11767 CstMask, CstMask, CstMask);
11768 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11769 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11770 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11772 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11773 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11776 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11777 SDValue CstFAdd = DAG.getConstantFP(
11778 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11779 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11780 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11781 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11782 makeArrayRef(&CstFAddArray[0], NumElts));
11784 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11785 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11787 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11788 // return (float4) lo + fhi;
11789 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11790 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11793 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11794 SelectionDAG &DAG) const {
11795 SDValue N0 = Op.getOperand(0);
11796 MVT SVT = N0.getSimpleValueType();
11799 switch (SVT.SimpleTy) {
11801 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11806 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11807 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11808 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11812 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11815 if (Subtarget->hasAVX512())
11816 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11817 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11819 llvm_unreachable(nullptr);
11822 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11823 SelectionDAG &DAG) const {
11824 SDValue N0 = Op.getOperand(0);
11827 if (Op.getValueType().isVector())
11828 return lowerUINT_TO_FP_vec(Op, DAG);
11830 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11831 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11832 // the optimization here.
11833 if (DAG.SignBitIsZero(N0))
11834 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11836 MVT SrcVT = N0.getSimpleValueType();
11837 MVT DstVT = Op.getSimpleValueType();
11838 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11839 return LowerUINT_TO_FP_i64(Op, DAG);
11840 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11841 return LowerUINT_TO_FP_i32(Op, DAG);
11842 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11845 // Make a 64-bit buffer, and use it to build an FILD.
11846 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11847 if (SrcVT == MVT::i32) {
11848 SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11849 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11850 getPointerTy(), StackSlot, WordOff);
11851 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11852 StackSlot, MachinePointerInfo(),
11854 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11855 OffsetSlot, MachinePointerInfo(),
11857 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11861 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11862 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11863 StackSlot, MachinePointerInfo(),
11865 // For i64 source, we need to add the appropriate power of 2 if the input
11866 // was negative. This is the same as the optimization in
11867 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11868 // we must be careful to do the computation in x87 extended precision, not
11869 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11870 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11871 MachineMemOperand *MMO =
11872 DAG.getMachineFunction()
11873 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11874 MachineMemOperand::MOLoad, 8, 8);
11876 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11877 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11878 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11881 APInt FF(32, 0x5F800000ULL);
11883 // Check whether the sign bit is set.
11884 SDValue SignSet = DAG.getSetCC(dl,
11885 getSetCCResultType(*DAG.getContext(), MVT::i64),
11887 DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11889 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11890 SDValue FudgePtr = DAG.getConstantPool(
11891 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11894 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11895 SDValue Zero = DAG.getIntPtrConstant(0, dl);
11896 SDValue Four = DAG.getIntPtrConstant(4, dl);
11897 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11899 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11901 // Load the value out, extending it from f32 to f80.
11902 // FIXME: Avoid the extend by constructing the right constant pool?
11903 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11904 FudgePtr, MachinePointerInfo::getConstantPool(),
11905 MVT::f32, false, false, false, 4);
11906 // Extend everything to 80 bits to force it to be done on x87.
11907 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11908 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11909 DAG.getIntPtrConstant(0, dl));
11912 std::pair<SDValue,SDValue>
11913 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11914 bool IsSigned, bool IsReplace) const {
11917 EVT DstTy = Op.getValueType();
11919 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11920 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11924 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11925 DstTy.getSimpleVT() >= MVT::i16 &&
11926 "Unknown FP_TO_INT to lower!");
11928 // These are really Legal.
11929 if (DstTy == MVT::i32 &&
11930 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11931 return std::make_pair(SDValue(), SDValue());
11932 if (Subtarget->is64Bit() &&
11933 DstTy == MVT::i64 &&
11934 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11935 return std::make_pair(SDValue(), SDValue());
11937 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11938 // stack slot, or into the FTOL runtime function.
11939 MachineFunction &MF = DAG.getMachineFunction();
11940 unsigned MemSize = DstTy.getSizeInBits()/8;
11941 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11942 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11945 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11946 Opc = X86ISD::WIN_FTOL;
11948 switch (DstTy.getSimpleVT().SimpleTy) {
11949 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11950 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11951 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11952 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11955 SDValue Chain = DAG.getEntryNode();
11956 SDValue Value = Op.getOperand(0);
11957 EVT TheVT = Op.getOperand(0).getValueType();
11958 // FIXME This causes a redundant load/store if the SSE-class value is already
11959 // in memory, such as if it is on the callstack.
11960 if (isScalarFPTypeInSSEReg(TheVT)) {
11961 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11962 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11963 MachinePointerInfo::getFixedStack(SSFI),
11965 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11967 Chain, StackSlot, DAG.getValueType(TheVT)
11970 MachineMemOperand *MMO =
11971 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11972 MachineMemOperand::MOLoad, MemSize, MemSize);
11973 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11974 Chain = Value.getValue(1);
11975 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11976 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11979 MachineMemOperand *MMO =
11980 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11981 MachineMemOperand::MOStore, MemSize, MemSize);
11983 if (Opc != X86ISD::WIN_FTOL) {
11984 // Build the FP_TO_INT*_IN_MEM
11985 SDValue Ops[] = { Chain, Value, StackSlot };
11986 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11988 return std::make_pair(FIST, StackSlot);
11990 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11991 DAG.getVTList(MVT::Other, MVT::Glue),
11993 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11994 MVT::i32, ftol.getValue(1));
11995 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11996 MVT::i32, eax.getValue(2));
11997 SDValue Ops[] = { eax, edx };
11998 SDValue pair = IsReplace
11999 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12000 : DAG.getMergeValues(Ops, DL);
12001 return std::make_pair(pair, SDValue());
12005 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12006 const X86Subtarget *Subtarget) {
12007 MVT VT = Op->getSimpleValueType(0);
12008 SDValue In = Op->getOperand(0);
12009 MVT InVT = In.getSimpleValueType();
12012 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12013 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12015 // Optimize vectors in AVX mode:
12018 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12019 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12020 // Concat upper and lower parts.
12023 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12024 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12025 // Concat upper and lower parts.
12028 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12029 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12030 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12033 if (Subtarget->hasInt256())
12034 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12036 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12037 SDValue Undef = DAG.getUNDEF(InVT);
12038 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12039 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12040 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12042 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12043 VT.getVectorNumElements()/2);
12045 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12046 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12048 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12051 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12052 SelectionDAG &DAG) {
12053 MVT VT = Op->getSimpleValueType(0);
12054 SDValue In = Op->getOperand(0);
12055 MVT InVT = In.getSimpleValueType();
12057 unsigned int NumElts = VT.getVectorNumElements();
12058 if (NumElts != 8 && NumElts != 16)
12061 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12062 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12064 assert(InVT.getVectorElementType() == MVT::i1);
12065 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12067 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12069 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12071 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12072 if (VT.is512BitVector())
12074 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12077 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12078 SelectionDAG &DAG) {
12079 if (Subtarget->hasFp256()) {
12080 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12088 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12089 SelectionDAG &DAG) {
12091 MVT VT = Op.getSimpleValueType();
12092 SDValue In = Op.getOperand(0);
12093 MVT SVT = In.getSimpleValueType();
12095 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12096 return LowerZERO_EXTEND_AVX512(Op, DAG);
12098 if (Subtarget->hasFp256()) {
12099 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12104 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12105 VT.getVectorNumElements() != SVT.getVectorNumElements());
12109 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12111 MVT VT = Op.getSimpleValueType();
12112 SDValue In = Op.getOperand(0);
12113 MVT InVT = In.getSimpleValueType();
12115 if (VT == MVT::i1) {
12116 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12117 "Invalid scalar TRUNCATE operation");
12118 if (InVT.getSizeInBits() >= 32)
12120 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12121 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12123 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12124 "Invalid TRUNCATE operation");
12126 // move vector to mask - truncate solution for SKX
12127 if (VT.getVectorElementType() == MVT::i1) {
12128 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12129 Subtarget->hasBWI())
12130 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12131 if ((InVT.is256BitVector() || InVT.is128BitVector())
12132 && InVT.getScalarSizeInBits() <= 16 &&
12133 Subtarget->hasBWI() && Subtarget->hasVLX())
12134 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12135 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12136 Subtarget->hasDQI())
12137 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12138 if ((InVT.is256BitVector() || InVT.is128BitVector())
12139 && InVT.getScalarSizeInBits() >= 32 &&
12140 Subtarget->hasDQI() && Subtarget->hasVLX())
12141 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12143 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12144 if (VT.getVectorElementType().getSizeInBits() >=8)
12145 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12147 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12148 unsigned NumElts = InVT.getVectorNumElements();
12149 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12150 if (InVT.getSizeInBits() < 512) {
12151 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12152 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12157 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12158 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12159 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12162 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12163 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12164 if (Subtarget->hasInt256()) {
12165 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12166 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12167 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12169 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12170 DAG.getIntPtrConstant(0, DL));
12173 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12174 DAG.getIntPtrConstant(0, DL));
12175 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12176 DAG.getIntPtrConstant(2, DL));
12177 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12178 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12179 static const int ShufMask[] = {0, 2, 4, 6};
12180 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12183 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12184 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12185 if (Subtarget->hasInt256()) {
12186 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12188 SmallVector<SDValue,32> pshufbMask;
12189 for (unsigned i = 0; i < 2; ++i) {
12190 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12191 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12192 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12193 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12194 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12195 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12196 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12197 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12198 for (unsigned j = 0; j < 8; ++j)
12199 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12201 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12202 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12203 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12205 static const int ShufMask[] = {0, 2, -1, -1};
12206 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12208 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12209 DAG.getIntPtrConstant(0, DL));
12210 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12213 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12214 DAG.getIntPtrConstant(0, DL));
12216 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12217 DAG.getIntPtrConstant(4, DL));
12219 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12220 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12222 // The PSHUFB mask:
12223 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12224 -1, -1, -1, -1, -1, -1, -1, -1};
12226 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12227 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12228 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12230 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12231 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12233 // The MOVLHPS Mask:
12234 static const int ShufMask2[] = {0, 1, 4, 5};
12235 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12236 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12239 // Handle truncation of V256 to V128 using shuffles.
12240 if (!VT.is128BitVector() || !InVT.is256BitVector())
12243 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12245 unsigned NumElems = VT.getVectorNumElements();
12246 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12248 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12249 // Prepare truncation shuffle mask
12250 for (unsigned i = 0; i != NumElems; ++i)
12251 MaskVec[i] = i * 2;
12252 SDValue V = DAG.getVectorShuffle(NVT, DL,
12253 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12254 DAG.getUNDEF(NVT), &MaskVec[0]);
12255 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12256 DAG.getIntPtrConstant(0, DL));
12259 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12260 SelectionDAG &DAG) const {
12261 assert(!Op.getSimpleValueType().isVector());
12263 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12264 /*IsSigned=*/ true, /*IsReplace=*/ false);
12265 SDValue FIST = Vals.first, StackSlot = Vals.second;
12266 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12267 if (!FIST.getNode()) return Op;
12269 if (StackSlot.getNode())
12270 // Load the result.
12271 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12272 FIST, StackSlot, MachinePointerInfo(),
12273 false, false, false, 0);
12275 // The node is the result.
12279 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12280 SelectionDAG &DAG) const {
12281 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12282 /*IsSigned=*/ false, /*IsReplace=*/ false);
12283 SDValue FIST = Vals.first, StackSlot = Vals.second;
12284 assert(FIST.getNode() && "Unexpected failure");
12286 if (StackSlot.getNode())
12287 // Load the result.
12288 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12289 FIST, StackSlot, MachinePointerInfo(),
12290 false, false, false, 0);
12292 // The node is the result.
12296 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12298 MVT VT = Op.getSimpleValueType();
12299 SDValue In = Op.getOperand(0);
12300 MVT SVT = In.getSimpleValueType();
12302 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12304 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12305 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12306 In, DAG.getUNDEF(SVT)));
12309 /// The only differences between FABS and FNEG are the mask and the logic op.
12310 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12311 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12312 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12313 "Wrong opcode for lowering FABS or FNEG.");
12315 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12317 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12318 // into an FNABS. We'll lower the FABS after that if it is still in use.
12320 for (SDNode *User : Op->uses())
12321 if (User->getOpcode() == ISD::FNEG)
12324 SDValue Op0 = Op.getOperand(0);
12325 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12328 MVT VT = Op.getSimpleValueType();
12329 // Assume scalar op for initialization; update for vector if needed.
12330 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12331 // generate a 16-byte vector constant and logic op even for the scalar case.
12332 // Using a 16-byte mask allows folding the load of the mask with
12333 // the logic op, so it can save (~4 bytes) on code size.
12335 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12336 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12337 // decide if we should generate a 16-byte constant mask when we only need 4 or
12338 // 8 bytes for the scalar case.
12339 if (VT.isVector()) {
12340 EltVT = VT.getVectorElementType();
12341 NumElts = VT.getVectorNumElements();
12344 unsigned EltBits = EltVT.getSizeInBits();
12345 LLVMContext *Context = DAG.getContext();
12346 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12348 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12349 Constant *C = ConstantInt::get(*Context, MaskElt);
12350 C = ConstantVector::getSplat(NumElts, C);
12351 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12352 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12353 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12354 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12355 MachinePointerInfo::getConstantPool(),
12356 false, false, false, Alignment);
12358 if (VT.isVector()) {
12359 // For a vector, cast operands to a vector type, perform the logic op,
12360 // and cast the result back to the original value type.
12361 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12362 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12363 SDValue Operand = IsFNABS ?
12364 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12365 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12366 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12367 return DAG.getNode(ISD::BITCAST, dl, VT,
12368 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12371 // If not vector, then scalar.
12372 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12373 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12374 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12377 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12379 LLVMContext *Context = DAG.getContext();
12380 SDValue Op0 = Op.getOperand(0);
12381 SDValue Op1 = Op.getOperand(1);
12383 MVT VT = Op.getSimpleValueType();
12384 MVT SrcVT = Op1.getSimpleValueType();
12386 // If second operand is smaller, extend it first.
12387 if (SrcVT.bitsLT(VT)) {
12388 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12391 // And if it is bigger, shrink it first.
12392 if (SrcVT.bitsGT(VT)) {
12393 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12397 // At this point the operands and the result should have the same
12398 // type, and that won't be f80 since that is not custom lowered.
12400 const fltSemantics &Sem =
12401 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12402 const unsigned SizeInBits = VT.getSizeInBits();
12404 SmallVector<Constant *, 4> CV(
12405 VT == MVT::f64 ? 2 : 4,
12406 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12408 // First, clear all bits but the sign bit from the second operand (sign).
12409 CV[0] = ConstantFP::get(*Context,
12410 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12411 Constant *C = ConstantVector::get(CV);
12412 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12413 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12414 MachinePointerInfo::getConstantPool(),
12415 false, false, false, 16);
12416 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12418 // Next, clear the sign bit from the first operand (magnitude).
12419 // If it's a constant, we can clear it here.
12420 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12421 APFloat APF = Op0CN->getValueAPF();
12422 // If the magnitude is a positive zero, the sign bit alone is enough.
12423 if (APF.isPosZero())
12426 CV[0] = ConstantFP::get(*Context, APF);
12428 CV[0] = ConstantFP::get(
12430 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12432 C = ConstantVector::get(CV);
12433 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12434 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12435 MachinePointerInfo::getConstantPool(),
12436 false, false, false, 16);
12437 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12438 if (!isa<ConstantFPSDNode>(Op0))
12439 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12441 // OR the magnitude value with the sign bit.
12442 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12445 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12446 SDValue N0 = Op.getOperand(0);
12448 MVT VT = Op.getSimpleValueType();
12450 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12451 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12452 DAG.getConstant(1, dl, VT));
12453 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12456 // Check whether an OR'd tree is PTEST-able.
12457 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12458 SelectionDAG &DAG) {
12459 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12461 if (!Subtarget->hasSSE41())
12464 if (!Op->hasOneUse())
12467 SDNode *N = Op.getNode();
12470 SmallVector<SDValue, 8> Opnds;
12471 DenseMap<SDValue, unsigned> VecInMap;
12472 SmallVector<SDValue, 8> VecIns;
12473 EVT VT = MVT::Other;
12475 // Recognize a special case where a vector is casted into wide integer to
12477 Opnds.push_back(N->getOperand(0));
12478 Opnds.push_back(N->getOperand(1));
12480 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12481 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12482 // BFS traverse all OR'd operands.
12483 if (I->getOpcode() == ISD::OR) {
12484 Opnds.push_back(I->getOperand(0));
12485 Opnds.push_back(I->getOperand(1));
12486 // Re-evaluate the number of nodes to be traversed.
12487 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12491 // Quit if a non-EXTRACT_VECTOR_ELT
12492 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12495 // Quit if without a constant index.
12496 SDValue Idx = I->getOperand(1);
12497 if (!isa<ConstantSDNode>(Idx))
12500 SDValue ExtractedFromVec = I->getOperand(0);
12501 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12502 if (M == VecInMap.end()) {
12503 VT = ExtractedFromVec.getValueType();
12504 // Quit if not 128/256-bit vector.
12505 if (!VT.is128BitVector() && !VT.is256BitVector())
12507 // Quit if not the same type.
12508 if (VecInMap.begin() != VecInMap.end() &&
12509 VT != VecInMap.begin()->first.getValueType())
12511 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12512 VecIns.push_back(ExtractedFromVec);
12514 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12517 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12518 "Not extracted from 128-/256-bit vector.");
12520 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12522 for (DenseMap<SDValue, unsigned>::const_iterator
12523 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12524 // Quit if not all elements are used.
12525 if (I->second != FullMask)
12529 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12531 // Cast all vectors into TestVT for PTEST.
12532 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12533 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12535 // If more than one full vectors are evaluated, OR them first before PTEST.
12536 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12537 // Each iteration will OR 2 nodes and append the result until there is only
12538 // 1 node left, i.e. the final OR'd value of all vectors.
12539 SDValue LHS = VecIns[Slot];
12540 SDValue RHS = VecIns[Slot + 1];
12541 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12544 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12545 VecIns.back(), VecIns.back());
12548 /// \brief return true if \c Op has a use that doesn't just read flags.
12549 static bool hasNonFlagsUse(SDValue Op) {
12550 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12552 SDNode *User = *UI;
12553 unsigned UOpNo = UI.getOperandNo();
12554 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12555 // Look pass truncate.
12556 UOpNo = User->use_begin().getOperandNo();
12557 User = *User->use_begin();
12560 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12561 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12567 /// Emit nodes that will be selected as "test Op0,Op0", or something
12569 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12570 SelectionDAG &DAG) const {
12571 if (Op.getValueType() == MVT::i1) {
12572 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12573 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12574 DAG.getConstant(0, dl, MVT::i8));
12576 // CF and OF aren't always set the way we want. Determine which
12577 // of these we need.
12578 bool NeedCF = false;
12579 bool NeedOF = false;
12582 case X86::COND_A: case X86::COND_AE:
12583 case X86::COND_B: case X86::COND_BE:
12586 case X86::COND_G: case X86::COND_GE:
12587 case X86::COND_L: case X86::COND_LE:
12588 case X86::COND_O: case X86::COND_NO: {
12589 // Check if we really need to set the
12590 // Overflow flag. If NoSignedWrap is present
12591 // that is not actually needed.
12592 switch (Op->getOpcode()) {
12597 const BinaryWithFlagsSDNode *BinNode =
12598 cast<BinaryWithFlagsSDNode>(Op.getNode());
12599 if (BinNode->Flags.hasNoSignedWrap())
12609 // See if we can use the EFLAGS value from the operand instead of
12610 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12611 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12612 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12613 // Emit a CMP with 0, which is the TEST pattern.
12614 //if (Op.getValueType() == MVT::i1)
12615 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12616 // DAG.getConstant(0, MVT::i1));
12617 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12618 DAG.getConstant(0, dl, Op.getValueType()));
12620 unsigned Opcode = 0;
12621 unsigned NumOperands = 0;
12623 // Truncate operations may prevent the merge of the SETCC instruction
12624 // and the arithmetic instruction before it. Attempt to truncate the operands
12625 // of the arithmetic instruction and use a reduced bit-width instruction.
12626 bool NeedTruncation = false;
12627 SDValue ArithOp = Op;
12628 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12629 SDValue Arith = Op->getOperand(0);
12630 // Both the trunc and the arithmetic op need to have one user each.
12631 if (Arith->hasOneUse())
12632 switch (Arith.getOpcode()) {
12639 NeedTruncation = true;
12645 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12646 // which may be the result of a CAST. We use the variable 'Op', which is the
12647 // non-casted variable when we check for possible users.
12648 switch (ArithOp.getOpcode()) {
12650 // Due to an isel shortcoming, be conservative if this add is likely to be
12651 // selected as part of a load-modify-store instruction. When the root node
12652 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12653 // uses of other nodes in the match, such as the ADD in this case. This
12654 // leads to the ADD being left around and reselected, with the result being
12655 // two adds in the output. Alas, even if none our users are stores, that
12656 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12657 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12658 // climbing the DAG back to the root, and it doesn't seem to be worth the
12660 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12661 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12662 if (UI->getOpcode() != ISD::CopyToReg &&
12663 UI->getOpcode() != ISD::SETCC &&
12664 UI->getOpcode() != ISD::STORE)
12667 if (ConstantSDNode *C =
12668 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12669 // An add of one will be selected as an INC.
12670 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12671 Opcode = X86ISD::INC;
12676 // An add of negative one (subtract of one) will be selected as a DEC.
12677 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12678 Opcode = X86ISD::DEC;
12684 // Otherwise use a regular EFLAGS-setting add.
12685 Opcode = X86ISD::ADD;
12690 // If we have a constant logical shift that's only used in a comparison
12691 // against zero turn it into an equivalent AND. This allows turning it into
12692 // a TEST instruction later.
12693 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12694 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12695 EVT VT = Op.getValueType();
12696 unsigned BitWidth = VT.getSizeInBits();
12697 unsigned ShAmt = Op->getConstantOperandVal(1);
12698 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12700 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12701 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12702 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12703 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12705 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12706 DAG.getConstant(Mask, dl, VT));
12707 DAG.ReplaceAllUsesWith(Op, New);
12713 // If the primary and result isn't used, don't bother using X86ISD::AND,
12714 // because a TEST instruction will be better.
12715 if (!hasNonFlagsUse(Op))
12721 // Due to the ISEL shortcoming noted above, be conservative if this op is
12722 // likely to be selected as part of a load-modify-store instruction.
12723 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12724 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12725 if (UI->getOpcode() == ISD::STORE)
12728 // Otherwise use a regular EFLAGS-setting instruction.
12729 switch (ArithOp.getOpcode()) {
12730 default: llvm_unreachable("unexpected operator!");
12731 case ISD::SUB: Opcode = X86ISD::SUB; break;
12732 case ISD::XOR: Opcode = X86ISD::XOR; break;
12733 case ISD::AND: Opcode = X86ISD::AND; break;
12735 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12736 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12737 if (EFLAGS.getNode())
12740 Opcode = X86ISD::OR;
12754 return SDValue(Op.getNode(), 1);
12760 // If we found that truncation is beneficial, perform the truncation and
12762 if (NeedTruncation) {
12763 EVT VT = Op.getValueType();
12764 SDValue WideVal = Op->getOperand(0);
12765 EVT WideVT = WideVal.getValueType();
12766 unsigned ConvertedOp = 0;
12767 // Use a target machine opcode to prevent further DAGCombine
12768 // optimizations that may separate the arithmetic operations
12769 // from the setcc node.
12770 switch (WideVal.getOpcode()) {
12772 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12773 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12774 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12775 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12776 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12781 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12782 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12783 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12784 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12790 // Emit a CMP with 0, which is the TEST pattern.
12791 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12792 DAG.getConstant(0, dl, Op.getValueType()));
12794 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12795 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12797 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12798 DAG.ReplaceAllUsesWith(Op, New);
12799 return SDValue(New.getNode(), 1);
12802 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12804 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12805 SDLoc dl, SelectionDAG &DAG) const {
12806 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12807 if (C->getAPIntValue() == 0)
12808 return EmitTest(Op0, X86CC, dl, DAG);
12810 if (Op0.getValueType() == MVT::i1)
12811 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12814 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12815 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12816 // Do the comparison at i32 if it's smaller, besides the Atom case.
12817 // This avoids subregister aliasing issues. Keep the smaller reference
12818 // if we're optimizing for size, however, as that'll allow better folding
12819 // of memory operations.
12820 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12821 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12822 Attribute::MinSize) &&
12823 !Subtarget->isAtom()) {
12824 unsigned ExtendOp =
12825 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12826 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12827 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12829 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12830 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12831 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12833 return SDValue(Sub.getNode(), 1);
12835 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12838 /// Convert a comparison if required by the subtarget.
12839 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12840 SelectionDAG &DAG) const {
12841 // If the subtarget does not support the FUCOMI instruction, floating-point
12842 // comparisons have to be converted.
12843 if (Subtarget->hasCMov() ||
12844 Cmp.getOpcode() != X86ISD::CMP ||
12845 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12846 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12849 // The instruction selector will select an FUCOM instruction instead of
12850 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12851 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12852 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12854 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12855 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12856 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12857 DAG.getConstant(8, dl, MVT::i8));
12858 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12859 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12862 /// The minimum architected relative accuracy is 2^-12. We need one
12863 /// Newton-Raphson step to have a good float result (24 bits of precision).
12864 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12865 DAGCombinerInfo &DCI,
12866 unsigned &RefinementSteps,
12867 bool &UseOneConstNR) const {
12868 // FIXME: We should use instruction latency models to calculate the cost of
12869 // each potential sequence, but this is very hard to do reliably because
12870 // at least Intel's Core* chips have variable timing based on the number of
12871 // significant digits in the divisor and/or sqrt operand.
12872 if (!Subtarget->useSqrtEst())
12875 EVT VT = Op.getValueType();
12877 // SSE1 has rsqrtss and rsqrtps.
12878 // TODO: Add support for AVX512 (v16f32).
12879 // It is likely not profitable to do this for f64 because a double-precision
12880 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12881 // instructions: convert to single, rsqrtss, convert back to double, refine
12882 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12883 // along with FMA, this could be a throughput win.
12884 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12885 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12886 RefinementSteps = 1;
12887 UseOneConstNR = false;
12888 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12893 /// The minimum architected relative accuracy is 2^-12. We need one
12894 /// Newton-Raphson step to have a good float result (24 bits of precision).
12895 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12896 DAGCombinerInfo &DCI,
12897 unsigned &RefinementSteps) const {
12898 // FIXME: We should use instruction latency models to calculate the cost of
12899 // each potential sequence, but this is very hard to do reliably because
12900 // at least Intel's Core* chips have variable timing based on the number of
12901 // significant digits in the divisor.
12902 if (!Subtarget->useReciprocalEst())
12905 EVT VT = Op.getValueType();
12907 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12908 // TODO: Add support for AVX512 (v16f32).
12909 // It is likely not profitable to do this for f64 because a double-precision
12910 // reciprocal estimate with refinement on x86 prior to FMA requires
12911 // 15 instructions: convert to single, rcpss, convert back to double, refine
12912 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12913 // along with FMA, this could be a throughput win.
12914 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12915 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12916 RefinementSteps = ReciprocalEstimateRefinementSteps;
12917 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12922 /// If we have at least two divisions that use the same divisor, convert to
12923 /// multplication by a reciprocal. This may need to be adjusted for a given
12924 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12925 /// This is because we still need one division to calculate the reciprocal and
12926 /// then we need two multiplies by that reciprocal as replacements for the
12927 /// original divisions.
12928 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12929 return NumUsers > 1;
12932 static bool isAllOnes(SDValue V) {
12933 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12934 return C && C->isAllOnesValue();
12937 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12938 /// if it's possible.
12939 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12940 SDLoc dl, SelectionDAG &DAG) const {
12941 SDValue Op0 = And.getOperand(0);
12942 SDValue Op1 = And.getOperand(1);
12943 if (Op0.getOpcode() == ISD::TRUNCATE)
12944 Op0 = Op0.getOperand(0);
12945 if (Op1.getOpcode() == ISD::TRUNCATE)
12946 Op1 = Op1.getOperand(0);
12949 if (Op1.getOpcode() == ISD::SHL)
12950 std::swap(Op0, Op1);
12951 if (Op0.getOpcode() == ISD::SHL) {
12952 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12953 if (And00C->getZExtValue() == 1) {
12954 // If we looked past a truncate, check that it's only truncating away
12956 unsigned BitWidth = Op0.getValueSizeInBits();
12957 unsigned AndBitWidth = And.getValueSizeInBits();
12958 if (BitWidth > AndBitWidth) {
12960 DAG.computeKnownBits(Op0, Zeros, Ones);
12961 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12965 RHS = Op0.getOperand(1);
12967 } else if (Op1.getOpcode() == ISD::Constant) {
12968 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12969 uint64_t AndRHSVal = AndRHS->getZExtValue();
12970 SDValue AndLHS = Op0;
12972 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12973 LHS = AndLHS.getOperand(0);
12974 RHS = AndLHS.getOperand(1);
12977 // Use BT if the immediate can't be encoded in a TEST instruction.
12978 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12980 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12984 if (LHS.getNode()) {
12985 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12986 // instruction. Since the shift amount is in-range-or-undefined, we know
12987 // that doing a bittest on the i32 value is ok. We extend to i32 because
12988 // the encoding for the i16 version is larger than the i32 version.
12989 // Also promote i16 to i32 for performance / code size reason.
12990 if (LHS.getValueType() == MVT::i8 ||
12991 LHS.getValueType() == MVT::i16)
12992 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12994 // If the operand types disagree, extend the shift amount to match. Since
12995 // BT ignores high bits (like shifts) we can use anyextend.
12996 if (LHS.getValueType() != RHS.getValueType())
12997 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12999 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13000 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13001 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13002 DAG.getConstant(Cond, dl, MVT::i8), BT);
13008 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13010 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13015 // SSE Condition code mapping:
13024 switch (SetCCOpcode) {
13025 default: llvm_unreachable("Unexpected SETCC condition");
13027 case ISD::SETEQ: SSECC = 0; break;
13029 case ISD::SETGT: Swap = true; // Fallthrough
13031 case ISD::SETOLT: SSECC = 1; break;
13033 case ISD::SETGE: Swap = true; // Fallthrough
13035 case ISD::SETOLE: SSECC = 2; break;
13036 case ISD::SETUO: SSECC = 3; break;
13038 case ISD::SETNE: SSECC = 4; break;
13039 case ISD::SETULE: Swap = true; // Fallthrough
13040 case ISD::SETUGE: SSECC = 5; break;
13041 case ISD::SETULT: Swap = true; // Fallthrough
13042 case ISD::SETUGT: SSECC = 6; break;
13043 case ISD::SETO: SSECC = 7; break;
13045 case ISD::SETONE: SSECC = 8; break;
13048 std::swap(Op0, Op1);
13053 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13054 // ones, and then concatenate the result back.
13055 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13056 MVT VT = Op.getSimpleValueType();
13058 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13059 "Unsupported value type for operation");
13061 unsigned NumElems = VT.getVectorNumElements();
13063 SDValue CC = Op.getOperand(2);
13065 // Extract the LHS vectors
13066 SDValue LHS = Op.getOperand(0);
13067 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13068 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13070 // Extract the RHS vectors
13071 SDValue RHS = Op.getOperand(1);
13072 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13073 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13075 // Issue the operation on the smaller types and concatenate the result back
13076 MVT EltVT = VT.getVectorElementType();
13077 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13078 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13079 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13080 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13083 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13084 SDValue Op0 = Op.getOperand(0);
13085 SDValue Op1 = Op.getOperand(1);
13086 SDValue CC = Op.getOperand(2);
13087 MVT VT = Op.getSimpleValueType();
13090 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13091 "Unexpected type for boolean compare operation");
13092 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13093 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13094 DAG.getConstant(-1, dl, VT));
13095 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13096 DAG.getConstant(-1, dl, VT));
13097 switch (SetCCOpcode) {
13098 default: llvm_unreachable("Unexpected SETCC condition");
13100 // (x != y) -> ~(x ^ y)
13101 return DAG.getNode(ISD::XOR, dl, VT,
13102 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13103 DAG.getConstant(-1, dl, VT));
13105 // (x == y) -> (x ^ y)
13106 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13109 // (x > y) -> (x & ~y)
13110 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13113 // (x < y) -> (~x & y)
13114 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13117 // (x <= y) -> (~x | y)
13118 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13121 // (x >=y) -> (x | ~y)
13122 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13126 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13127 const X86Subtarget *Subtarget) {
13128 SDValue Op0 = Op.getOperand(0);
13129 SDValue Op1 = Op.getOperand(1);
13130 SDValue CC = Op.getOperand(2);
13131 MVT VT = Op.getSimpleValueType();
13134 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13135 Op.getValueType().getScalarType() == MVT::i1 &&
13136 "Cannot set masked compare for this operation");
13138 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13140 bool Unsigned = false;
13143 switch (SetCCOpcode) {
13144 default: llvm_unreachable("Unexpected SETCC condition");
13145 case ISD::SETNE: SSECC = 4; break;
13146 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13147 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13148 case ISD::SETLT: Swap = true; //fall-through
13149 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13150 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13151 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13152 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13153 case ISD::SETULE: Unsigned = true; //fall-through
13154 case ISD::SETLE: SSECC = 2; break;
13158 std::swap(Op0, Op1);
13160 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13161 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13162 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13163 DAG.getConstant(SSECC, dl, MVT::i8));
13166 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13167 /// operand \p Op1. If non-trivial (for example because it's not constant)
13168 /// return an empty value.
13169 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13171 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13175 MVT VT = Op1.getSimpleValueType();
13176 MVT EVT = VT.getVectorElementType();
13177 unsigned n = VT.getVectorNumElements();
13178 SmallVector<SDValue, 8> ULTOp1;
13180 for (unsigned i = 0; i < n; ++i) {
13181 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13182 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13185 // Avoid underflow.
13186 APInt Val = Elt->getAPIntValue();
13190 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13193 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13196 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13197 SelectionDAG &DAG) {
13198 SDValue Op0 = Op.getOperand(0);
13199 SDValue Op1 = Op.getOperand(1);
13200 SDValue CC = Op.getOperand(2);
13201 MVT VT = Op.getSimpleValueType();
13202 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13203 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13208 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13209 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13212 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13213 unsigned Opc = X86ISD::CMPP;
13214 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13215 assert(VT.getVectorNumElements() <= 16);
13216 Opc = X86ISD::CMPM;
13218 // In the two special cases we can't handle, emit two comparisons.
13221 unsigned CombineOpc;
13222 if (SetCCOpcode == ISD::SETUEQ) {
13223 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13225 assert(SetCCOpcode == ISD::SETONE);
13226 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13229 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13230 DAG.getConstant(CC0, dl, MVT::i8));
13231 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13232 DAG.getConstant(CC1, dl, MVT::i8));
13233 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13235 // Handle all other FP comparisons here.
13236 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13237 DAG.getConstant(SSECC, dl, MVT::i8));
13240 // Break 256-bit integer vector compare into smaller ones.
13241 if (VT.is256BitVector() && !Subtarget->hasInt256())
13242 return Lower256IntVSETCC(Op, DAG);
13244 EVT OpVT = Op1.getValueType();
13245 if (OpVT.getVectorElementType() == MVT::i1)
13246 return LowerBoolVSETCC_AVX512(Op, DAG);
13248 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13249 if (Subtarget->hasAVX512()) {
13250 if (Op1.getValueType().is512BitVector() ||
13251 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13252 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13253 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13255 // In AVX-512 architecture setcc returns mask with i1 elements,
13256 // But there is no compare instruction for i8 and i16 elements in KNL.
13257 // We are not talking about 512-bit operands in this case, these
13258 // types are illegal.
13260 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13261 OpVT.getVectorElementType().getSizeInBits() >= 8))
13262 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13263 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13266 // We are handling one of the integer comparisons here. Since SSE only has
13267 // GT and EQ comparisons for integer, swapping operands and multiple
13268 // operations may be required for some comparisons.
13270 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13271 bool Subus = false;
13273 switch (SetCCOpcode) {
13274 default: llvm_unreachable("Unexpected SETCC condition");
13275 case ISD::SETNE: Invert = true;
13276 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13277 case ISD::SETLT: Swap = true;
13278 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13279 case ISD::SETGE: Swap = true;
13280 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13281 Invert = true; break;
13282 case ISD::SETULT: Swap = true;
13283 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13284 FlipSigns = true; break;
13285 case ISD::SETUGE: Swap = true;
13286 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13287 FlipSigns = true; Invert = true; break;
13290 // Special case: Use min/max operations for SETULE/SETUGE
13291 MVT VET = VT.getVectorElementType();
13293 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13294 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13297 switch (SetCCOpcode) {
13299 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13300 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13303 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13306 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13307 if (!MinMax && hasSubus) {
13308 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13310 // t = psubus Op0, Op1
13311 // pcmpeq t, <0..0>
13312 switch (SetCCOpcode) {
13314 case ISD::SETULT: {
13315 // If the comparison is against a constant we can turn this into a
13316 // setule. With psubus, setule does not require a swap. This is
13317 // beneficial because the constant in the register is no longer
13318 // destructed as the destination so it can be hoisted out of a loop.
13319 // Only do this pre-AVX since vpcmp* is no longer destructive.
13320 if (Subtarget->hasAVX())
13322 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13323 if (ULEOp1.getNode()) {
13325 Subus = true; Invert = false; Swap = false;
13329 // Psubus is better than flip-sign because it requires no inversion.
13330 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13331 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13335 Opc = X86ISD::SUBUS;
13341 std::swap(Op0, Op1);
13343 // Check that the operation in question is available (most are plain SSE2,
13344 // but PCMPGTQ and PCMPEQQ have different requirements).
13345 if (VT == MVT::v2i64) {
13346 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13347 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13349 // First cast everything to the right type.
13350 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13351 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13353 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13354 // bits of the inputs before performing those operations. The lower
13355 // compare is always unsigned.
13358 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13360 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13361 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13362 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13363 Sign, Zero, Sign, Zero);
13365 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13366 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13368 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13369 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13370 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13372 // Create masks for only the low parts/high parts of the 64 bit integers.
13373 static const int MaskHi[] = { 1, 1, 3, 3 };
13374 static const int MaskLo[] = { 0, 0, 2, 2 };
13375 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13376 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13377 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13379 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13380 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13383 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13385 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13388 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13389 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13390 // pcmpeqd + pshufd + pand.
13391 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13393 // First cast everything to the right type.
13394 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13395 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13398 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13400 // Make sure the lower and upper halves are both all-ones.
13401 static const int Mask[] = { 1, 0, 3, 2 };
13402 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13403 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13406 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13408 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13412 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13413 // bits of the inputs before performing those operations.
13415 EVT EltVT = VT.getVectorElementType();
13416 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13418 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13419 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13422 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13424 // If the logical-not of the result is required, perform that now.
13426 Result = DAG.getNOT(dl, Result, VT);
13429 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13432 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13433 getZeroVector(VT, Subtarget, DAG, dl));
13438 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13440 MVT VT = Op.getSimpleValueType();
13442 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13444 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13445 && "SetCC type must be 8-bit or 1-bit integer");
13446 SDValue Op0 = Op.getOperand(0);
13447 SDValue Op1 = Op.getOperand(1);
13449 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13451 // Optimize to BT if possible.
13452 // Lower (X & (1 << N)) == 0 to BT(X, N).
13453 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13454 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13455 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13456 Op1.getOpcode() == ISD::Constant &&
13457 cast<ConstantSDNode>(Op1)->isNullValue() &&
13458 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13459 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13460 if (NewSetCC.getNode()) {
13462 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13467 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13469 if (Op1.getOpcode() == ISD::Constant &&
13470 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13471 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13472 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13474 // If the input is a setcc, then reuse the input setcc or use a new one with
13475 // the inverted condition.
13476 if (Op0.getOpcode() == X86ISD::SETCC) {
13477 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13478 bool Invert = (CC == ISD::SETNE) ^
13479 cast<ConstantSDNode>(Op1)->isNullValue();
13483 CCode = X86::GetOppositeBranchCondition(CCode);
13484 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13485 DAG.getConstant(CCode, dl, MVT::i8),
13486 Op0.getOperand(1));
13488 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13492 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13493 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13494 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13496 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13497 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13500 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13501 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13502 if (X86CC == X86::COND_INVALID)
13505 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13506 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13507 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13508 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13510 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13514 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13515 static bool isX86LogicalCmp(SDValue Op) {
13516 unsigned Opc = Op.getNode()->getOpcode();
13517 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13518 Opc == X86ISD::SAHF)
13520 if (Op.getResNo() == 1 &&
13521 (Opc == X86ISD::ADD ||
13522 Opc == X86ISD::SUB ||
13523 Opc == X86ISD::ADC ||
13524 Opc == X86ISD::SBB ||
13525 Opc == X86ISD::SMUL ||
13526 Opc == X86ISD::UMUL ||
13527 Opc == X86ISD::INC ||
13528 Opc == X86ISD::DEC ||
13529 Opc == X86ISD::OR ||
13530 Opc == X86ISD::XOR ||
13531 Opc == X86ISD::AND))
13534 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13540 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13541 if (V.getOpcode() != ISD::TRUNCATE)
13544 SDValue VOp0 = V.getOperand(0);
13545 unsigned InBits = VOp0.getValueSizeInBits();
13546 unsigned Bits = V.getValueSizeInBits();
13547 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13550 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13551 bool addTest = true;
13552 SDValue Cond = Op.getOperand(0);
13553 SDValue Op1 = Op.getOperand(1);
13554 SDValue Op2 = Op.getOperand(2);
13556 EVT VT = Op1.getValueType();
13559 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13560 // are available or VBLENDV if AVX is available.
13561 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13562 if (Cond.getOpcode() == ISD::SETCC &&
13563 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13564 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13565 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13566 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13567 int SSECC = translateX86FSETCC(
13568 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13571 if (Subtarget->hasAVX512()) {
13572 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13573 DAG.getConstant(SSECC, DL, MVT::i8));
13574 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13577 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13578 DAG.getConstant(SSECC, DL, MVT::i8));
13580 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13581 // of 3 logic instructions for size savings and potentially speed.
13582 // Unfortunately, there is no scalar form of VBLENDV.
13584 // If either operand is a constant, don't try this. We can expect to
13585 // optimize away at least one of the logic instructions later in that
13586 // case, so that sequence would be faster than a variable blend.
13588 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13589 // uses XMM0 as the selection register. That may need just as many
13590 // instructions as the AND/ANDN/OR sequence due to register moves, so
13593 if (Subtarget->hasAVX() &&
13594 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13596 // Convert to vectors, do a VSELECT, and convert back to scalar.
13597 // All of the conversions should be optimized away.
13599 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13600 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13601 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13602 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13604 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13605 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13607 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13609 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13610 VSel, DAG.getIntPtrConstant(0, DL));
13612 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13613 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13614 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13618 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13619 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13620 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13621 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13622 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13623 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13624 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13626 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13629 if (Cond.getOpcode() == ISD::SETCC) {
13630 SDValue NewCond = LowerSETCC(Cond, DAG);
13631 if (NewCond.getNode())
13635 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13636 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13637 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13638 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13639 if (Cond.getOpcode() == X86ISD::SETCC &&
13640 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13641 isZero(Cond.getOperand(1).getOperand(1))) {
13642 SDValue Cmp = Cond.getOperand(1);
13644 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13646 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13647 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13648 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13650 SDValue CmpOp0 = Cmp.getOperand(0);
13651 // Apply further optimizations for special cases
13652 // (select (x != 0), -1, 0) -> neg & sbb
13653 // (select (x == 0), 0, -1) -> neg & sbb
13654 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13655 if (YC->isNullValue() &&
13656 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13657 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13658 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13659 DAG.getConstant(0, DL,
13660 CmpOp0.getValueType()),
13662 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13663 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13664 SDValue(Neg.getNode(), 1));
13668 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13669 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13670 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13672 SDValue Res = // Res = 0 or -1.
13673 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13674 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13676 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13677 Res = DAG.getNOT(DL, Res, Res.getValueType());
13679 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13680 if (!N2C || !N2C->isNullValue())
13681 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13686 // Look past (and (setcc_carry (cmp ...)), 1).
13687 if (Cond.getOpcode() == ISD::AND &&
13688 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13689 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13690 if (C && C->getAPIntValue() == 1)
13691 Cond = Cond.getOperand(0);
13694 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13695 // setting operand in place of the X86ISD::SETCC.
13696 unsigned CondOpcode = Cond.getOpcode();
13697 if (CondOpcode == X86ISD::SETCC ||
13698 CondOpcode == X86ISD::SETCC_CARRY) {
13699 CC = Cond.getOperand(0);
13701 SDValue Cmp = Cond.getOperand(1);
13702 unsigned Opc = Cmp.getOpcode();
13703 MVT VT = Op.getSimpleValueType();
13705 bool IllegalFPCMov = false;
13706 if (VT.isFloatingPoint() && !VT.isVector() &&
13707 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13708 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13710 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13711 Opc == X86ISD::BT) { // FIXME
13715 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13716 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13717 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13718 Cond.getOperand(0).getValueType() != MVT::i8)) {
13719 SDValue LHS = Cond.getOperand(0);
13720 SDValue RHS = Cond.getOperand(1);
13721 unsigned X86Opcode;
13724 switch (CondOpcode) {
13725 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13726 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13727 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13728 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13729 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13730 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13731 default: llvm_unreachable("unexpected overflowing operator");
13733 if (CondOpcode == ISD::UMULO)
13734 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13737 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13739 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13741 if (CondOpcode == ISD::UMULO)
13742 Cond = X86Op.getValue(2);
13744 Cond = X86Op.getValue(1);
13746 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13751 // Look pass the truncate if the high bits are known zero.
13752 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13753 Cond = Cond.getOperand(0);
13755 // We know the result of AND is compared against zero. Try to match
13757 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13758 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13759 if (NewSetCC.getNode()) {
13760 CC = NewSetCC.getOperand(0);
13761 Cond = NewSetCC.getOperand(1);
13768 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13769 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13772 // a < b ? -1 : 0 -> RES = ~setcc_carry
13773 // a < b ? 0 : -1 -> RES = setcc_carry
13774 // a >= b ? -1 : 0 -> RES = setcc_carry
13775 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13776 if (Cond.getOpcode() == X86ISD::SUB) {
13777 Cond = ConvertCmpIfNecessary(Cond, DAG);
13778 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13780 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13781 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13782 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13783 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13785 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13786 return DAG.getNOT(DL, Res, Res.getValueType());
13791 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13792 // widen the cmov and push the truncate through. This avoids introducing a new
13793 // branch during isel and doesn't add any extensions.
13794 if (Op.getValueType() == MVT::i8 &&
13795 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13796 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13797 if (T1.getValueType() == T2.getValueType() &&
13798 // Blacklist CopyFromReg to avoid partial register stalls.
13799 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13800 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13801 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13802 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13806 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13807 // condition is true.
13808 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13809 SDValue Ops[] = { Op2, Op1, CC, Cond };
13810 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13813 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13814 SelectionDAG &DAG) {
13815 MVT VT = Op->getSimpleValueType(0);
13816 SDValue In = Op->getOperand(0);
13817 MVT InVT = In.getSimpleValueType();
13818 MVT VTElt = VT.getVectorElementType();
13819 MVT InVTElt = InVT.getVectorElementType();
13823 if ((InVTElt == MVT::i1) &&
13824 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13825 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13827 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13828 VTElt.getSizeInBits() <= 16)) ||
13830 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13831 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13833 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13834 VTElt.getSizeInBits() >= 32))))
13835 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13837 unsigned int NumElts = VT.getVectorNumElements();
13839 if (NumElts != 8 && NumElts != 16)
13842 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13843 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13844 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13845 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13848 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13849 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13851 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13854 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13856 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13857 if (VT.is512BitVector())
13859 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13862 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13863 SelectionDAG &DAG) {
13864 MVT VT = Op->getSimpleValueType(0);
13865 SDValue In = Op->getOperand(0);
13866 MVT InVT = In.getSimpleValueType();
13869 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13870 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13872 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13873 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13874 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13877 if (Subtarget->hasInt256())
13878 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13880 // Optimize vectors in AVX mode
13881 // Sign extend v8i16 to v8i32 and
13884 // Divide input vector into two parts
13885 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13886 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13887 // concat the vectors to original VT
13889 unsigned NumElems = InVT.getVectorNumElements();
13890 SDValue Undef = DAG.getUNDEF(InVT);
13892 SmallVector<int,8> ShufMask1(NumElems, -1);
13893 for (unsigned i = 0; i != NumElems/2; ++i)
13896 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13898 SmallVector<int,8> ShufMask2(NumElems, -1);
13899 for (unsigned i = 0; i != NumElems/2; ++i)
13900 ShufMask2[i] = i + NumElems/2;
13902 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13904 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13905 VT.getVectorNumElements()/2);
13907 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13908 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13910 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13913 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13914 // may emit an illegal shuffle but the expansion is still better than scalar
13915 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13916 // we'll emit a shuffle and a arithmetic shift.
13917 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13918 // TODO: It is possible to support ZExt by zeroing the undef values during
13919 // the shuffle phase or after the shuffle.
13920 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13921 SelectionDAG &DAG) {
13922 MVT RegVT = Op.getSimpleValueType();
13923 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13924 assert(RegVT.isInteger() &&
13925 "We only custom lower integer vector sext loads.");
13927 // Nothing useful we can do without SSE2 shuffles.
13928 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13930 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13932 EVT MemVT = Ld->getMemoryVT();
13933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13934 unsigned RegSz = RegVT.getSizeInBits();
13936 ISD::LoadExtType Ext = Ld->getExtensionType();
13938 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13939 && "Only anyext and sext are currently implemented.");
13940 assert(MemVT != RegVT && "Cannot extend to the same type");
13941 assert(MemVT.isVector() && "Must load a vector from memory");
13943 unsigned NumElems = RegVT.getVectorNumElements();
13944 unsigned MemSz = MemVT.getSizeInBits();
13945 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13947 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13948 // The only way in which we have a legal 256-bit vector result but not the
13949 // integer 256-bit operations needed to directly lower a sextload is if we
13950 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13951 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13952 // correctly legalized. We do this late to allow the canonical form of
13953 // sextload to persist throughout the rest of the DAG combiner -- it wants
13954 // to fold together any extensions it can, and so will fuse a sign_extend
13955 // of an sextload into a sextload targeting a wider value.
13957 if (MemSz == 128) {
13958 // Just switch this to a normal load.
13959 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13960 "it must be a legal 128-bit vector "
13962 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13963 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13964 Ld->isInvariant(), Ld->getAlignment());
13966 assert(MemSz < 128 &&
13967 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13968 // Do an sext load to a 128-bit vector type. We want to use the same
13969 // number of elements, but elements half as wide. This will end up being
13970 // recursively lowered by this routine, but will succeed as we definitely
13971 // have all the necessary features if we're using AVX1.
13973 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13974 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13976 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13977 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13978 Ld->isNonTemporal(), Ld->isInvariant(),
13979 Ld->getAlignment());
13982 // Replace chain users with the new chain.
13983 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13984 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13986 // Finally, do a normal sign-extend to the desired register.
13987 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13990 // All sizes must be a power of two.
13991 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13992 "Non-power-of-two elements are not custom lowered!");
13994 // Attempt to load the original value using scalar loads.
13995 // Find the largest scalar type that divides the total loaded size.
13996 MVT SclrLoadTy = MVT::i8;
13997 for (MVT Tp : MVT::integer_valuetypes()) {
13998 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14003 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14004 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14006 SclrLoadTy = MVT::f64;
14008 // Calculate the number of scalar loads that we need to perform
14009 // in order to load our vector from memory.
14010 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14012 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14013 "Can only lower sext loads with a single scalar load!");
14015 unsigned loadRegZize = RegSz;
14016 if (Ext == ISD::SEXTLOAD && RegSz == 256)
14019 // Represent our vector as a sequence of elements which are the
14020 // largest scalar that we can load.
14021 EVT LoadUnitVecVT = EVT::getVectorVT(
14022 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14024 // Represent the data using the same element type that is stored in
14025 // memory. In practice, we ''widen'' MemVT.
14027 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14028 loadRegZize / MemVT.getScalarType().getSizeInBits());
14030 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14031 "Invalid vector type");
14033 // We can't shuffle using an illegal type.
14034 assert(TLI.isTypeLegal(WideVecVT) &&
14035 "We only lower types that form legal widened vector types");
14037 SmallVector<SDValue, 8> Chains;
14038 SDValue Ptr = Ld->getBasePtr();
14039 SDValue Increment =
14040 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14041 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14043 for (unsigned i = 0; i < NumLoads; ++i) {
14044 // Perform a single load.
14045 SDValue ScalarLoad =
14046 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14047 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14048 Ld->getAlignment());
14049 Chains.push_back(ScalarLoad.getValue(1));
14050 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14051 // another round of DAGCombining.
14053 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14055 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14056 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14058 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14061 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14063 // Bitcast the loaded value to a vector of the original element type, in
14064 // the size of the target vector type.
14065 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14066 unsigned SizeRatio = RegSz / MemSz;
14068 if (Ext == ISD::SEXTLOAD) {
14069 // If we have SSE4.1, we can directly emit a VSEXT node.
14070 if (Subtarget->hasSSE41()) {
14071 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14072 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14076 // Otherwise we'll shuffle the small elements in the high bits of the
14077 // larger type and perform an arithmetic shift. If the shift is not legal
14078 // it's better to scalarize.
14079 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14080 "We can't implement a sext load without an arithmetic right shift!");
14082 // Redistribute the loaded elements into the different locations.
14083 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14084 for (unsigned i = 0; i != NumElems; ++i)
14085 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14087 SDValue Shuff = DAG.getVectorShuffle(
14088 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14090 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14092 // Build the arithmetic shift.
14093 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14094 MemVT.getVectorElementType().getSizeInBits();
14096 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14097 DAG.getConstant(Amt, dl, RegVT));
14099 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14103 // Redistribute the loaded elements into the different locations.
14104 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14105 for (unsigned i = 0; i != NumElems; ++i)
14106 ShuffleVec[i * SizeRatio] = i;
14108 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14109 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14111 // Bitcast to the requested type.
14112 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14113 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14117 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14118 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14119 // from the AND / OR.
14120 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14121 Opc = Op.getOpcode();
14122 if (Opc != ISD::OR && Opc != ISD::AND)
14124 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14125 Op.getOperand(0).hasOneUse() &&
14126 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14127 Op.getOperand(1).hasOneUse());
14130 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14131 // 1 and that the SETCC node has a single use.
14132 static bool isXor1OfSetCC(SDValue Op) {
14133 if (Op.getOpcode() != ISD::XOR)
14135 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14136 if (N1C && N1C->getAPIntValue() == 1) {
14137 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14138 Op.getOperand(0).hasOneUse();
14143 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14144 bool addTest = true;
14145 SDValue Chain = Op.getOperand(0);
14146 SDValue Cond = Op.getOperand(1);
14147 SDValue Dest = Op.getOperand(2);
14150 bool Inverted = false;
14152 if (Cond.getOpcode() == ISD::SETCC) {
14153 // Check for setcc([su]{add,sub,mul}o == 0).
14154 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14155 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14156 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14157 Cond.getOperand(0).getResNo() == 1 &&
14158 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14159 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14160 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14161 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14162 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14163 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14165 Cond = Cond.getOperand(0);
14167 SDValue NewCond = LowerSETCC(Cond, DAG);
14168 if (NewCond.getNode())
14173 // FIXME: LowerXALUO doesn't handle these!!
14174 else if (Cond.getOpcode() == X86ISD::ADD ||
14175 Cond.getOpcode() == X86ISD::SUB ||
14176 Cond.getOpcode() == X86ISD::SMUL ||
14177 Cond.getOpcode() == X86ISD::UMUL)
14178 Cond = LowerXALUO(Cond, DAG);
14181 // Look pass (and (setcc_carry (cmp ...)), 1).
14182 if (Cond.getOpcode() == ISD::AND &&
14183 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14184 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14185 if (C && C->getAPIntValue() == 1)
14186 Cond = Cond.getOperand(0);
14189 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14190 // setting operand in place of the X86ISD::SETCC.
14191 unsigned CondOpcode = Cond.getOpcode();
14192 if (CondOpcode == X86ISD::SETCC ||
14193 CondOpcode == X86ISD::SETCC_CARRY) {
14194 CC = Cond.getOperand(0);
14196 SDValue Cmp = Cond.getOperand(1);
14197 unsigned Opc = Cmp.getOpcode();
14198 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14199 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14203 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14207 // These can only come from an arithmetic instruction with overflow,
14208 // e.g. SADDO, UADDO.
14209 Cond = Cond.getNode()->getOperand(1);
14215 CondOpcode = Cond.getOpcode();
14216 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14217 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14218 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14219 Cond.getOperand(0).getValueType() != MVT::i8)) {
14220 SDValue LHS = Cond.getOperand(0);
14221 SDValue RHS = Cond.getOperand(1);
14222 unsigned X86Opcode;
14225 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14226 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14228 switch (CondOpcode) {
14229 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14231 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14233 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14236 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14237 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14239 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14241 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14244 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14245 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14246 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14247 default: llvm_unreachable("unexpected overflowing operator");
14250 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14251 if (CondOpcode == ISD::UMULO)
14252 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14255 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14257 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14259 if (CondOpcode == ISD::UMULO)
14260 Cond = X86Op.getValue(2);
14262 Cond = X86Op.getValue(1);
14264 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14268 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14269 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14270 if (CondOpc == ISD::OR) {
14271 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14272 // two branches instead of an explicit OR instruction with a
14274 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14275 isX86LogicalCmp(Cmp)) {
14276 CC = Cond.getOperand(0).getOperand(0);
14277 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14278 Chain, Dest, CC, Cmp);
14279 CC = Cond.getOperand(1).getOperand(0);
14283 } else { // ISD::AND
14284 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14285 // two branches instead of an explicit AND instruction with a
14286 // separate test. However, we only do this if this block doesn't
14287 // have a fall-through edge, because this requires an explicit
14288 // jmp when the condition is false.
14289 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14290 isX86LogicalCmp(Cmp) &&
14291 Op.getNode()->hasOneUse()) {
14292 X86::CondCode CCode =
14293 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14294 CCode = X86::GetOppositeBranchCondition(CCode);
14295 CC = DAG.getConstant(CCode, dl, MVT::i8);
14296 SDNode *User = *Op.getNode()->use_begin();
14297 // Look for an unconditional branch following this conditional branch.
14298 // We need this because we need to reverse the successors in order
14299 // to implement FCMP_OEQ.
14300 if (User->getOpcode() == ISD::BR) {
14301 SDValue FalseBB = User->getOperand(1);
14303 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14304 assert(NewBR == User);
14308 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14309 Chain, Dest, CC, Cmp);
14310 X86::CondCode CCode =
14311 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14312 CCode = X86::GetOppositeBranchCondition(CCode);
14313 CC = DAG.getConstant(CCode, dl, MVT::i8);
14319 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14320 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14321 // It should be transformed during dag combiner except when the condition
14322 // is set by a arithmetics with overflow node.
14323 X86::CondCode CCode =
14324 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14325 CCode = X86::GetOppositeBranchCondition(CCode);
14326 CC = DAG.getConstant(CCode, dl, MVT::i8);
14327 Cond = Cond.getOperand(0).getOperand(1);
14329 } else if (Cond.getOpcode() == ISD::SETCC &&
14330 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14331 // For FCMP_OEQ, we can emit
14332 // two branches instead of an explicit AND instruction with a
14333 // separate test. However, we only do this if this block doesn't
14334 // have a fall-through edge, because this requires an explicit
14335 // jmp when the condition is false.
14336 if (Op.getNode()->hasOneUse()) {
14337 SDNode *User = *Op.getNode()->use_begin();
14338 // Look for an unconditional branch following this conditional branch.
14339 // We need this because we need to reverse the successors in order
14340 // to implement FCMP_OEQ.
14341 if (User->getOpcode() == ISD::BR) {
14342 SDValue FalseBB = User->getOperand(1);
14344 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14345 assert(NewBR == User);
14349 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14350 Cond.getOperand(0), Cond.getOperand(1));
14351 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14352 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14353 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14354 Chain, Dest, CC, Cmp);
14355 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14360 } else if (Cond.getOpcode() == ISD::SETCC &&
14361 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14362 // For FCMP_UNE, we can emit
14363 // two branches instead of an explicit AND instruction with a
14364 // separate test. However, we only do this if this block doesn't
14365 // have a fall-through edge, because this requires an explicit
14366 // jmp when the condition is false.
14367 if (Op.getNode()->hasOneUse()) {
14368 SDNode *User = *Op.getNode()->use_begin();
14369 // Look for an unconditional branch following this conditional branch.
14370 // We need this because we need to reverse the successors in order
14371 // to implement FCMP_UNE.
14372 if (User->getOpcode() == ISD::BR) {
14373 SDValue FalseBB = User->getOperand(1);
14375 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14376 assert(NewBR == User);
14379 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14380 Cond.getOperand(0), Cond.getOperand(1));
14381 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14382 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14383 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14384 Chain, Dest, CC, Cmp);
14385 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14395 // Look pass the truncate if the high bits are known zero.
14396 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14397 Cond = Cond.getOperand(0);
14399 // We know the result of AND is compared against zero. Try to match
14401 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14402 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14403 if (NewSetCC.getNode()) {
14404 CC = NewSetCC.getOperand(0);
14405 Cond = NewSetCC.getOperand(1);
14412 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14413 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14414 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14416 Cond = ConvertCmpIfNecessary(Cond, DAG);
14417 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14418 Chain, Dest, CC, Cond);
14421 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14422 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14423 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14424 // that the guard pages used by the OS virtual memory manager are allocated in
14425 // correct sequence.
14427 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14428 SelectionDAG &DAG) const {
14429 MachineFunction &MF = DAG.getMachineFunction();
14430 bool SplitStack = MF.shouldSplitStack();
14431 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14436 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14437 SDNode* Node = Op.getNode();
14439 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14440 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14441 " not tell us which reg is the stack pointer!");
14442 EVT VT = Node->getValueType(0);
14443 SDValue Tmp1 = SDValue(Node, 0);
14444 SDValue Tmp2 = SDValue(Node, 1);
14445 SDValue Tmp3 = Node->getOperand(2);
14446 SDValue Chain = Tmp1.getOperand(0);
14448 // Chain the dynamic stack allocation so that it doesn't modify the stack
14449 // pointer when other instructions are using the stack.
14450 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14453 SDValue Size = Tmp2.getOperand(1);
14454 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14455 Chain = SP.getValue(1);
14456 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14457 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14458 unsigned StackAlign = TFI.getStackAlignment();
14459 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14460 if (Align > StackAlign)
14461 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14462 DAG.getConstant(-(uint64_t)Align, dl, VT));
14463 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14465 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14466 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14469 SDValue Ops[2] = { Tmp1, Tmp2 };
14470 return DAG.getMergeValues(Ops, dl);
14474 SDValue Chain = Op.getOperand(0);
14475 SDValue Size = Op.getOperand(1);
14476 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14477 EVT VT = Op.getNode()->getValueType(0);
14479 bool Is64Bit = Subtarget->is64Bit();
14480 EVT SPTy = getPointerTy();
14483 MachineRegisterInfo &MRI = MF.getRegInfo();
14486 // The 64 bit implementation of segmented stacks needs to clobber both r10
14487 // r11. This makes it impossible to use it along with nested parameters.
14488 const Function *F = MF.getFunction();
14490 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14492 if (I->hasNestAttr())
14493 report_fatal_error("Cannot use segmented stacks with functions that "
14494 "have nested arguments.");
14497 const TargetRegisterClass *AddrRegClass =
14498 getRegClassFor(getPointerTy());
14499 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14500 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14501 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14502 DAG.getRegister(Vreg, SPTy));
14503 SDValue Ops1[2] = { Value, Chain };
14504 return DAG.getMergeValues(Ops1, dl);
14507 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14509 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14510 Flag = Chain.getValue(1);
14511 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14513 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14515 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14516 unsigned SPReg = RegInfo->getStackRegister();
14517 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14518 Chain = SP.getValue(1);
14521 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14522 DAG.getConstant(-(uint64_t)Align, dl, VT));
14523 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14526 SDValue Ops1[2] = { SP, Chain };
14527 return DAG.getMergeValues(Ops1, dl);
14531 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14532 MachineFunction &MF = DAG.getMachineFunction();
14533 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14535 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14538 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14539 // vastart just stores the address of the VarArgsFrameIndex slot into the
14540 // memory location argument.
14541 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14543 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14544 MachinePointerInfo(SV), false, false, 0);
14548 // gp_offset (0 - 6 * 8)
14549 // fp_offset (48 - 48 + 8 * 16)
14550 // overflow_arg_area (point to parameters coming in memory).
14552 SmallVector<SDValue, 8> MemOps;
14553 SDValue FIN = Op.getOperand(1);
14555 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14556 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14558 FIN, MachinePointerInfo(SV), false, false, 0);
14559 MemOps.push_back(Store);
14562 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14563 FIN, DAG.getIntPtrConstant(4, DL));
14564 Store = DAG.getStore(Op.getOperand(0), DL,
14565 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14567 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14568 MemOps.push_back(Store);
14570 // Store ptr to overflow_arg_area
14571 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14572 FIN, DAG.getIntPtrConstant(4, DL));
14573 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14575 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14576 MachinePointerInfo(SV, 8),
14578 MemOps.push_back(Store);
14580 // Store ptr to reg_save_area.
14581 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14582 FIN, DAG.getIntPtrConstant(8, DL));
14583 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14585 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14586 MachinePointerInfo(SV, 16), false, false, 0);
14587 MemOps.push_back(Store);
14588 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14591 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14592 assert(Subtarget->is64Bit() &&
14593 "LowerVAARG only handles 64-bit va_arg!");
14594 assert((Subtarget->isTargetLinux() ||
14595 Subtarget->isTargetDarwin()) &&
14596 "Unhandled target in LowerVAARG");
14597 assert(Op.getNode()->getNumOperands() == 4);
14598 SDValue Chain = Op.getOperand(0);
14599 SDValue SrcPtr = Op.getOperand(1);
14600 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14601 unsigned Align = Op.getConstantOperandVal(3);
14604 EVT ArgVT = Op.getNode()->getValueType(0);
14605 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14606 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14609 // Decide which area this value should be read from.
14610 // TODO: Implement the AMD64 ABI in its entirety. This simple
14611 // selection mechanism works only for the basic types.
14612 if (ArgVT == MVT::f80) {
14613 llvm_unreachable("va_arg for f80 not yet implemented");
14614 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14615 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14616 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14617 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14619 llvm_unreachable("Unhandled argument type in LowerVAARG");
14622 if (ArgMode == 2) {
14623 // Sanity Check: Make sure using fp_offset makes sense.
14624 assert(!Subtarget->useSoftFloat() &&
14625 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14626 Attribute::NoImplicitFloat)) &&
14627 Subtarget->hasSSE1());
14630 // Insert VAARG_64 node into the DAG
14631 // VAARG_64 returns two values: Variable Argument Address, Chain
14632 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14633 DAG.getConstant(ArgMode, dl, MVT::i8),
14634 DAG.getConstant(Align, dl, MVT::i32)};
14635 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14636 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14637 VTs, InstOps, MVT::i64,
14638 MachinePointerInfo(SV),
14640 /*Volatile=*/false,
14642 /*WriteMem=*/true);
14643 Chain = VAARG.getValue(1);
14645 // Load the next argument and return it
14646 return DAG.getLoad(ArgVT, dl,
14649 MachinePointerInfo(),
14650 false, false, false, 0);
14653 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14654 SelectionDAG &DAG) {
14655 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14656 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14657 SDValue Chain = Op.getOperand(0);
14658 SDValue DstPtr = Op.getOperand(1);
14659 SDValue SrcPtr = Op.getOperand(2);
14660 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14661 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14664 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14665 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14667 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14670 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14671 // amount is a constant. Takes immediate version of shift as input.
14672 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14673 SDValue SrcOp, uint64_t ShiftAmt,
14674 SelectionDAG &DAG) {
14675 MVT ElementType = VT.getVectorElementType();
14677 // Fold this packed shift into its first operand if ShiftAmt is 0.
14681 // Check for ShiftAmt >= element width
14682 if (ShiftAmt >= ElementType.getSizeInBits()) {
14683 if (Opc == X86ISD::VSRAI)
14684 ShiftAmt = ElementType.getSizeInBits() - 1;
14686 return DAG.getConstant(0, dl, VT);
14689 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14690 && "Unknown target vector shift-by-constant node");
14692 // Fold this packed vector shift into a build vector if SrcOp is a
14693 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14694 if (VT == SrcOp.getSimpleValueType() &&
14695 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14696 SmallVector<SDValue, 8> Elts;
14697 unsigned NumElts = SrcOp->getNumOperands();
14698 ConstantSDNode *ND;
14701 default: llvm_unreachable(nullptr);
14702 case X86ISD::VSHLI:
14703 for (unsigned i=0; i!=NumElts; ++i) {
14704 SDValue CurrentOp = SrcOp->getOperand(i);
14705 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14706 Elts.push_back(CurrentOp);
14709 ND = cast<ConstantSDNode>(CurrentOp);
14710 const APInt &C = ND->getAPIntValue();
14711 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14714 case X86ISD::VSRLI:
14715 for (unsigned i=0; i!=NumElts; ++i) {
14716 SDValue CurrentOp = SrcOp->getOperand(i);
14717 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14718 Elts.push_back(CurrentOp);
14721 ND = cast<ConstantSDNode>(CurrentOp);
14722 const APInt &C = ND->getAPIntValue();
14723 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14726 case X86ISD::VSRAI:
14727 for (unsigned i=0; i!=NumElts; ++i) {
14728 SDValue CurrentOp = SrcOp->getOperand(i);
14729 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14730 Elts.push_back(CurrentOp);
14733 ND = cast<ConstantSDNode>(CurrentOp);
14734 const APInt &C = ND->getAPIntValue();
14735 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14740 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14743 return DAG.getNode(Opc, dl, VT, SrcOp,
14744 DAG.getConstant(ShiftAmt, dl, MVT::i8));
14747 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14748 // may or may not be a constant. Takes immediate version of shift as input.
14749 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14750 SDValue SrcOp, SDValue ShAmt,
14751 SelectionDAG &DAG) {
14752 MVT SVT = ShAmt.getSimpleValueType();
14753 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14755 // Catch shift-by-constant.
14756 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14757 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14758 CShAmt->getZExtValue(), DAG);
14760 // Change opcode to non-immediate version
14762 default: llvm_unreachable("Unknown target vector shift node");
14763 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14764 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14765 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14768 const X86Subtarget &Subtarget =
14769 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14770 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14771 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14772 // Let the shuffle legalizer expand this shift amount node.
14773 SDValue Op0 = ShAmt.getOperand(0);
14774 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14775 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14777 // Need to build a vector containing shift amount.
14778 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14779 SmallVector<SDValue, 4> ShOps;
14780 ShOps.push_back(ShAmt);
14781 if (SVT == MVT::i32) {
14782 ShOps.push_back(DAG.getConstant(0, dl, SVT));
14783 ShOps.push_back(DAG.getUNDEF(SVT));
14785 ShOps.push_back(DAG.getUNDEF(SVT));
14787 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14788 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14791 // The return type has to be a 128-bit type with the same element
14792 // type as the input type.
14793 MVT EltVT = VT.getVectorElementType();
14794 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14796 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14797 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14800 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14801 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14802 /// necessary casting for \p Mask when lowering masking intrinsics.
14803 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14804 SDValue PreservedSrc,
14805 const X86Subtarget *Subtarget,
14806 SelectionDAG &DAG) {
14807 EVT VT = Op.getValueType();
14808 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14809 MVT::i1, VT.getVectorNumElements());
14810 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14811 Mask.getValueType().getSizeInBits());
14814 assert(MaskVT.isSimple() && "invalid mask type");
14816 if (isAllOnes(Mask))
14819 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14820 // are extracted by EXTRACT_SUBVECTOR.
14821 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14822 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14823 DAG.getIntPtrConstant(0, dl));
14825 switch (Op.getOpcode()) {
14827 case X86ISD::PCMPEQM:
14828 case X86ISD::PCMPGTM:
14830 case X86ISD::CMPMU:
14831 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14833 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14834 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14835 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14838 /// \brief Creates an SDNode for a predicated scalar operation.
14839 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14840 /// The mask is comming as MVT::i8 and it should be truncated
14841 /// to MVT::i1 while lowering masking intrinsics.
14842 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14843 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14844 /// a scalar instruction.
14845 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14846 SDValue PreservedSrc,
14847 const X86Subtarget *Subtarget,
14848 SelectionDAG &DAG) {
14849 if (isAllOnes(Mask))
14852 EVT VT = Op.getValueType();
14854 // The mask should be of type MVT::i1
14855 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14857 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14858 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14859 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14862 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14863 SelectionDAG &DAG) {
14865 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14866 EVT VT = Op.getValueType();
14867 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14869 switch(IntrData->Type) {
14870 case INTR_TYPE_1OP:
14871 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14872 case INTR_TYPE_2OP:
14873 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14875 case INTR_TYPE_3OP:
14876 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14877 Op.getOperand(2), Op.getOperand(3));
14878 case INTR_TYPE_1OP_MASK_RM: {
14879 SDValue Src = Op.getOperand(1);
14880 SDValue Src0 = Op.getOperand(2);
14881 SDValue Mask = Op.getOperand(3);
14882 SDValue RoundingMode = Op.getOperand(4);
14883 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14885 Mask, Src0, Subtarget, DAG);
14887 case INTR_TYPE_SCALAR_MASK_RM: {
14888 SDValue Src1 = Op.getOperand(1);
14889 SDValue Src2 = Op.getOperand(2);
14890 SDValue Src0 = Op.getOperand(3);
14891 SDValue Mask = Op.getOperand(4);
14892 // There are 2 kinds of intrinsics in this group:
14893 // (1) With supress-all-exceptions (sae) - 6 operands
14894 // (2) With rounding mode and sae - 7 operands.
14895 if (Op.getNumOperands() == 6) {
14896 SDValue Sae = Op.getOperand(5);
14897 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14899 Mask, Src0, Subtarget, DAG);
14901 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14902 SDValue RoundingMode = Op.getOperand(5);
14903 SDValue Sae = Op.getOperand(6);
14904 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14905 RoundingMode, Sae),
14906 Mask, Src0, Subtarget, DAG);
14908 case INTR_TYPE_2OP_MASK: {
14909 SDValue Src1 = Op.getOperand(1);
14910 SDValue Src2 = Op.getOperand(2);
14911 SDValue PassThru = Op.getOperand(3);
14912 SDValue Mask = Op.getOperand(4);
14913 // We specify 2 possible opcodes for intrinsics with rounding modes.
14914 // First, we check if the intrinsic may have non-default rounding mode,
14915 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14916 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14917 if (IntrWithRoundingModeOpcode != 0) {
14918 SDValue Rnd = Op.getOperand(5);
14919 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14920 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14921 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14922 dl, Op.getValueType(),
14924 Mask, PassThru, Subtarget, DAG);
14927 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14929 Mask, PassThru, Subtarget, DAG);
14931 case FMA_OP_MASK: {
14932 SDValue Src1 = Op.getOperand(1);
14933 SDValue Src2 = Op.getOperand(2);
14934 SDValue Src3 = Op.getOperand(3);
14935 SDValue Mask = Op.getOperand(4);
14936 // We specify 2 possible opcodes for intrinsics with rounding modes.
14937 // First, we check if the intrinsic may have non-default rounding mode,
14938 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14939 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14940 if (IntrWithRoundingModeOpcode != 0) {
14941 SDValue Rnd = Op.getOperand(5);
14942 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14943 X86::STATIC_ROUNDING::CUR_DIRECTION)
14944 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14945 dl, Op.getValueType(),
14946 Src1, Src2, Src3, Rnd),
14947 Mask, Src1, Subtarget, DAG);
14949 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14950 dl, Op.getValueType(),
14952 Mask, Src1, Subtarget, DAG);
14955 case CMP_MASK_CC: {
14956 // Comparison intrinsics with masks.
14957 // Example of transformation:
14958 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14959 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14961 // (v8i1 (insert_subvector undef,
14962 // (v2i1 (and (PCMPEQM %a, %b),
14963 // (extract_subvector
14964 // (v8i1 (bitcast %mask)), 0))), 0))))
14965 EVT VT = Op.getOperand(1).getValueType();
14966 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14967 VT.getVectorNumElements());
14968 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14969 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14970 Mask.getValueType().getSizeInBits());
14972 if (IntrData->Type == CMP_MASK_CC) {
14973 SDValue CC = Op.getOperand(3);
14974 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14975 // We specify 2 possible opcodes for intrinsics with rounding modes.
14976 // First, we check if the intrinsic may have non-default rounding mode,
14977 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14978 if (IntrData->Opc1 != 0) {
14979 SDValue Rnd = Op.getOperand(5);
14980 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14981 X86::STATIC_ROUNDING::CUR_DIRECTION)
14982 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14983 Op.getOperand(2), CC, Rnd);
14985 //default rounding mode
14987 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14988 Op.getOperand(2), CC);
14991 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14992 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14995 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14996 DAG.getTargetConstant(0, dl,
14999 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15000 DAG.getUNDEF(BitcastVT), CmpMask,
15001 DAG.getIntPtrConstant(0, dl));
15002 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15004 case COMI: { // Comparison intrinsics
15005 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15006 SDValue LHS = Op.getOperand(1);
15007 SDValue RHS = Op.getOperand(2);
15008 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15009 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15010 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15011 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15012 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15013 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15016 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15017 Op.getOperand(1), Op.getOperand(2), DAG);
15019 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15020 Op.getSimpleValueType(),
15022 Op.getOperand(2), DAG),
15023 Op.getOperand(4), Op.getOperand(3), Subtarget,
15025 case COMPRESS_EXPAND_IN_REG: {
15026 SDValue Mask = Op.getOperand(3);
15027 SDValue DataToCompress = Op.getOperand(1);
15028 SDValue PassThru = Op.getOperand(2);
15029 if (isAllOnes(Mask)) // return data as is
15030 return Op.getOperand(1);
15031 EVT VT = Op.getValueType();
15032 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15033 VT.getVectorNumElements());
15034 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15035 Mask.getValueType().getSizeInBits());
15037 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15038 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15039 DAG.getIntPtrConstant(0, dl));
15041 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15045 SDValue Mask = Op.getOperand(3);
15046 EVT VT = Op.getValueType();
15047 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15048 VT.getVectorNumElements());
15049 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15050 Mask.getValueType().getSizeInBits());
15052 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15053 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15054 DAG.getIntPtrConstant(0, dl));
15055 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15064 default: return SDValue(); // Don't custom lower most intrinsics.
15066 case Intrinsic::x86_avx2_permd:
15067 case Intrinsic::x86_avx2_permps:
15068 // Operands intentionally swapped. Mask is last operand to intrinsic,
15069 // but second operand for node/instruction.
15070 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15071 Op.getOperand(2), Op.getOperand(1));
15073 case Intrinsic::x86_avx512_mask_valign_q_512:
15074 case Intrinsic::x86_avx512_mask_valign_d_512:
15075 // Vector source operands are swapped.
15076 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15077 Op.getValueType(), Op.getOperand(2),
15080 Op.getOperand(5), Op.getOperand(4),
15083 // ptest and testp intrinsics. The intrinsic these come from are designed to
15084 // return an integer value, not just an instruction so lower it to the ptest
15085 // or testp pattern and a setcc for the result.
15086 case Intrinsic::x86_sse41_ptestz:
15087 case Intrinsic::x86_sse41_ptestc:
15088 case Intrinsic::x86_sse41_ptestnzc:
15089 case Intrinsic::x86_avx_ptestz_256:
15090 case Intrinsic::x86_avx_ptestc_256:
15091 case Intrinsic::x86_avx_ptestnzc_256:
15092 case Intrinsic::x86_avx_vtestz_ps:
15093 case Intrinsic::x86_avx_vtestc_ps:
15094 case Intrinsic::x86_avx_vtestnzc_ps:
15095 case Intrinsic::x86_avx_vtestz_pd:
15096 case Intrinsic::x86_avx_vtestc_pd:
15097 case Intrinsic::x86_avx_vtestnzc_pd:
15098 case Intrinsic::x86_avx_vtestz_ps_256:
15099 case Intrinsic::x86_avx_vtestc_ps_256:
15100 case Intrinsic::x86_avx_vtestnzc_ps_256:
15101 case Intrinsic::x86_avx_vtestz_pd_256:
15102 case Intrinsic::x86_avx_vtestc_pd_256:
15103 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15104 bool IsTestPacked = false;
15107 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15108 case Intrinsic::x86_avx_vtestz_ps:
15109 case Intrinsic::x86_avx_vtestz_pd:
15110 case Intrinsic::x86_avx_vtestz_ps_256:
15111 case Intrinsic::x86_avx_vtestz_pd_256:
15112 IsTestPacked = true; // Fallthrough
15113 case Intrinsic::x86_sse41_ptestz:
15114 case Intrinsic::x86_avx_ptestz_256:
15116 X86CC = X86::COND_E;
15118 case Intrinsic::x86_avx_vtestc_ps:
15119 case Intrinsic::x86_avx_vtestc_pd:
15120 case Intrinsic::x86_avx_vtestc_ps_256:
15121 case Intrinsic::x86_avx_vtestc_pd_256:
15122 IsTestPacked = true; // Fallthrough
15123 case Intrinsic::x86_sse41_ptestc:
15124 case Intrinsic::x86_avx_ptestc_256:
15126 X86CC = X86::COND_B;
15128 case Intrinsic::x86_avx_vtestnzc_ps:
15129 case Intrinsic::x86_avx_vtestnzc_pd:
15130 case Intrinsic::x86_avx_vtestnzc_ps_256:
15131 case Intrinsic::x86_avx_vtestnzc_pd_256:
15132 IsTestPacked = true; // Fallthrough
15133 case Intrinsic::x86_sse41_ptestnzc:
15134 case Intrinsic::x86_avx_ptestnzc_256:
15136 X86CC = X86::COND_A;
15140 SDValue LHS = Op.getOperand(1);
15141 SDValue RHS = Op.getOperand(2);
15142 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15143 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15144 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15145 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15146 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15148 case Intrinsic::x86_avx512_kortestz_w:
15149 case Intrinsic::x86_avx512_kortestc_w: {
15150 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15151 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15152 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15153 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15154 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15155 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15156 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15159 case Intrinsic::x86_sse42_pcmpistria128:
15160 case Intrinsic::x86_sse42_pcmpestria128:
15161 case Intrinsic::x86_sse42_pcmpistric128:
15162 case Intrinsic::x86_sse42_pcmpestric128:
15163 case Intrinsic::x86_sse42_pcmpistrio128:
15164 case Intrinsic::x86_sse42_pcmpestrio128:
15165 case Intrinsic::x86_sse42_pcmpistris128:
15166 case Intrinsic::x86_sse42_pcmpestris128:
15167 case Intrinsic::x86_sse42_pcmpistriz128:
15168 case Intrinsic::x86_sse42_pcmpestriz128: {
15172 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15173 case Intrinsic::x86_sse42_pcmpistria128:
15174 Opcode = X86ISD::PCMPISTRI;
15175 X86CC = X86::COND_A;
15177 case Intrinsic::x86_sse42_pcmpestria128:
15178 Opcode = X86ISD::PCMPESTRI;
15179 X86CC = X86::COND_A;
15181 case Intrinsic::x86_sse42_pcmpistric128:
15182 Opcode = X86ISD::PCMPISTRI;
15183 X86CC = X86::COND_B;
15185 case Intrinsic::x86_sse42_pcmpestric128:
15186 Opcode = X86ISD::PCMPESTRI;
15187 X86CC = X86::COND_B;
15189 case Intrinsic::x86_sse42_pcmpistrio128:
15190 Opcode = X86ISD::PCMPISTRI;
15191 X86CC = X86::COND_O;
15193 case Intrinsic::x86_sse42_pcmpestrio128:
15194 Opcode = X86ISD::PCMPESTRI;
15195 X86CC = X86::COND_O;
15197 case Intrinsic::x86_sse42_pcmpistris128:
15198 Opcode = X86ISD::PCMPISTRI;
15199 X86CC = X86::COND_S;
15201 case Intrinsic::x86_sse42_pcmpestris128:
15202 Opcode = X86ISD::PCMPESTRI;
15203 X86CC = X86::COND_S;
15205 case Intrinsic::x86_sse42_pcmpistriz128:
15206 Opcode = X86ISD::PCMPISTRI;
15207 X86CC = X86::COND_E;
15209 case Intrinsic::x86_sse42_pcmpestriz128:
15210 Opcode = X86ISD::PCMPESTRI;
15211 X86CC = X86::COND_E;
15214 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15215 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15216 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15217 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15218 DAG.getConstant(X86CC, dl, MVT::i8),
15219 SDValue(PCMP.getNode(), 1));
15220 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15223 case Intrinsic::x86_sse42_pcmpistri128:
15224 case Intrinsic::x86_sse42_pcmpestri128: {
15226 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15227 Opcode = X86ISD::PCMPISTRI;
15229 Opcode = X86ISD::PCMPESTRI;
15231 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15232 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15233 return DAG.getNode(Opcode, dl, VTs, NewOps);
15238 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15239 SDValue Src, SDValue Mask, SDValue Base,
15240 SDValue Index, SDValue ScaleOp, SDValue Chain,
15241 const X86Subtarget * Subtarget) {
15243 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15244 assert(C && "Invalid scale type");
15245 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15246 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15247 Index.getSimpleValueType().getVectorNumElements());
15249 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15251 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15253 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15254 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15255 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15256 SDValue Segment = DAG.getRegister(0, MVT::i32);
15257 if (Src.getOpcode() == ISD::UNDEF)
15258 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15259 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15260 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15261 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15262 return DAG.getMergeValues(RetOps, dl);
15265 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15266 SDValue Src, SDValue Mask, SDValue Base,
15267 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15269 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15270 assert(C && "Invalid scale type");
15271 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15272 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15273 SDValue Segment = DAG.getRegister(0, MVT::i32);
15274 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15275 Index.getSimpleValueType().getVectorNumElements());
15277 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15279 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15281 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15282 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15283 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15284 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15285 return SDValue(Res, 1);
15288 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15289 SDValue Mask, SDValue Base, SDValue Index,
15290 SDValue ScaleOp, SDValue Chain) {
15292 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15293 assert(C && "Invalid scale type");
15294 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15295 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15296 SDValue Segment = DAG.getRegister(0, MVT::i32);
15298 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15300 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15302 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15304 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15305 //SDVTList VTs = DAG.getVTList(MVT::Other);
15306 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15307 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15308 return SDValue(Res, 0);
15311 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15312 // read performance monitor counters (x86_rdpmc).
15313 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15314 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15315 SmallVectorImpl<SDValue> &Results) {
15316 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15317 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15320 // The ECX register is used to select the index of the performance counter
15322 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15324 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15326 // Reads the content of a 64-bit performance counter and returns it in the
15327 // registers EDX:EAX.
15328 if (Subtarget->is64Bit()) {
15329 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15330 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15333 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15334 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15337 Chain = HI.getValue(1);
15339 if (Subtarget->is64Bit()) {
15340 // The EAX register is loaded with the low-order 32 bits. The EDX register
15341 // is loaded with the supported high-order bits of the counter.
15342 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15343 DAG.getConstant(32, DL, MVT::i8));
15344 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15345 Results.push_back(Chain);
15349 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15350 SDValue Ops[] = { LO, HI };
15351 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15352 Results.push_back(Pair);
15353 Results.push_back(Chain);
15356 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15357 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15358 // also used to custom lower READCYCLECOUNTER nodes.
15359 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15360 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15361 SmallVectorImpl<SDValue> &Results) {
15362 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15363 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15366 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15367 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15368 // and the EAX register is loaded with the low-order 32 bits.
15369 if (Subtarget->is64Bit()) {
15370 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15371 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15374 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15375 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15378 SDValue Chain = HI.getValue(1);
15380 if (Opcode == X86ISD::RDTSCP_DAG) {
15381 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15383 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15384 // the ECX register. Add 'ecx' explicitly to the chain.
15385 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15387 // Explicitly store the content of ECX at the location passed in input
15388 // to the 'rdtscp' intrinsic.
15389 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15390 MachinePointerInfo(), false, false, 0);
15393 if (Subtarget->is64Bit()) {
15394 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15395 // the EAX register is loaded with the low-order 32 bits.
15396 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15397 DAG.getConstant(32, DL, MVT::i8));
15398 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15399 Results.push_back(Chain);
15403 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15404 SDValue Ops[] = { LO, HI };
15405 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15406 Results.push_back(Pair);
15407 Results.push_back(Chain);
15410 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15411 SelectionDAG &DAG) {
15412 SmallVector<SDValue, 2> Results;
15414 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15416 return DAG.getMergeValues(Results, DL);
15420 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15421 SelectionDAG &DAG) {
15422 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15424 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15429 switch(IntrData->Type) {
15431 llvm_unreachable("Unknown Intrinsic Type");
15435 // Emit the node with the right value type.
15436 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15437 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15439 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15440 // Otherwise return the value from Rand, which is always 0, casted to i32.
15441 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15442 DAG.getConstant(1, dl, Op->getValueType(1)),
15443 DAG.getConstant(X86::COND_B, dl, MVT::i32),
15444 SDValue(Result.getNode(), 1) };
15445 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15446 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15449 // Return { result, isValid, chain }.
15450 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15451 SDValue(Result.getNode(), 2));
15454 //gather(v1, mask, index, base, scale);
15455 SDValue Chain = Op.getOperand(0);
15456 SDValue Src = Op.getOperand(2);
15457 SDValue Base = Op.getOperand(3);
15458 SDValue Index = Op.getOperand(4);
15459 SDValue Mask = Op.getOperand(5);
15460 SDValue Scale = Op.getOperand(6);
15461 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15465 //scatter(base, mask, index, v1, scale);
15466 SDValue Chain = Op.getOperand(0);
15467 SDValue Base = Op.getOperand(2);
15468 SDValue Mask = Op.getOperand(3);
15469 SDValue Index = Op.getOperand(4);
15470 SDValue Src = Op.getOperand(5);
15471 SDValue Scale = Op.getOperand(6);
15472 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15476 SDValue Hint = Op.getOperand(6);
15477 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15478 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15479 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15480 SDValue Chain = Op.getOperand(0);
15481 SDValue Mask = Op.getOperand(2);
15482 SDValue Index = Op.getOperand(3);
15483 SDValue Base = Op.getOperand(4);
15484 SDValue Scale = Op.getOperand(5);
15485 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15487 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15489 SmallVector<SDValue, 2> Results;
15490 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15492 return DAG.getMergeValues(Results, dl);
15494 // Read Performance Monitoring Counters.
15496 SmallVector<SDValue, 2> Results;
15497 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15498 return DAG.getMergeValues(Results, dl);
15500 // XTEST intrinsics.
15502 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15503 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15504 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15505 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15507 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15508 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15509 Ret, SDValue(InTrans.getNode(), 1));
15513 SmallVector<SDValue, 2> Results;
15514 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15515 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15516 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15517 DAG.getConstant(-1, dl, MVT::i8));
15518 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15519 Op.getOperand(4), GenCF.getValue(1));
15520 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15521 Op.getOperand(5), MachinePointerInfo(),
15523 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15524 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15526 Results.push_back(SetCC);
15527 Results.push_back(Store);
15528 return DAG.getMergeValues(Results, dl);
15530 case COMPRESS_TO_MEM: {
15532 SDValue Mask = Op.getOperand(4);
15533 SDValue DataToCompress = Op.getOperand(3);
15534 SDValue Addr = Op.getOperand(2);
15535 SDValue Chain = Op.getOperand(0);
15537 if (isAllOnes(Mask)) // return just a store
15538 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15539 MachinePointerInfo(), false, false, 0);
15541 EVT VT = DataToCompress.getValueType();
15542 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15543 VT.getVectorNumElements());
15544 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15545 Mask.getValueType().getSizeInBits());
15546 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15547 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15548 DAG.getIntPtrConstant(0, dl));
15550 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15551 DataToCompress, DAG.getUNDEF(VT));
15552 return DAG.getStore(Chain, dl, Compressed, Addr,
15553 MachinePointerInfo(), false, false, 0);
15555 case EXPAND_FROM_MEM: {
15557 SDValue Mask = Op.getOperand(4);
15558 SDValue PathThru = Op.getOperand(3);
15559 SDValue Addr = Op.getOperand(2);
15560 SDValue Chain = Op.getOperand(0);
15561 EVT VT = Op.getValueType();
15563 if (isAllOnes(Mask)) // return just a load
15564 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15566 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15567 VT.getVectorNumElements());
15568 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15569 Mask.getValueType().getSizeInBits());
15570 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15571 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15572 DAG.getIntPtrConstant(0, dl));
15574 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15575 false, false, false, 0);
15577 SDValue Results[] = {
15578 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15580 return DAG.getMergeValues(Results, dl);
15585 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15586 SelectionDAG &DAG) const {
15587 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15588 MFI->setReturnAddressIsTaken(true);
15590 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15593 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15595 EVT PtrVT = getPointerTy();
15598 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15599 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15600 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15601 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15602 DAG.getNode(ISD::ADD, dl, PtrVT,
15603 FrameAddr, Offset),
15604 MachinePointerInfo(), false, false, false, 0);
15607 // Just load the return address.
15608 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15609 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15610 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15613 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15614 MachineFunction &MF = DAG.getMachineFunction();
15615 MachineFrameInfo *MFI = MF.getFrameInfo();
15616 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15617 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15618 EVT VT = Op.getValueType();
15620 MFI->setFrameAddressIsTaken(true);
15622 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15623 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15624 // is not possible to crawl up the stack without looking at the unwind codes
15626 int FrameAddrIndex = FuncInfo->getFAIndex();
15627 if (!FrameAddrIndex) {
15628 // Set up a frame object for the return address.
15629 unsigned SlotSize = RegInfo->getSlotSize();
15630 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15631 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15632 FuncInfo->setFAIndex(FrameAddrIndex);
15634 return DAG.getFrameIndex(FrameAddrIndex, VT);
15637 unsigned FrameReg =
15638 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15639 SDLoc dl(Op); // FIXME probably not meaningful
15640 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15641 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15642 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15643 "Invalid Frame Register!");
15644 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15646 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15647 MachinePointerInfo(),
15648 false, false, false, 0);
15652 // FIXME? Maybe this could be a TableGen attribute on some registers and
15653 // this table could be generated automatically from RegInfo.
15654 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15656 unsigned Reg = StringSwitch<unsigned>(RegName)
15657 .Case("esp", X86::ESP)
15658 .Case("rsp", X86::RSP)
15662 report_fatal_error("Invalid register name global variable");
15665 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15666 SelectionDAG &DAG) const {
15667 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15668 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15671 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15672 SDValue Chain = Op.getOperand(0);
15673 SDValue Offset = Op.getOperand(1);
15674 SDValue Handler = Op.getOperand(2);
15677 EVT PtrVT = getPointerTy();
15678 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15679 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15680 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15681 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15682 "Invalid Frame Register!");
15683 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15684 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15686 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15687 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15689 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15690 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15692 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15694 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15695 DAG.getRegister(StoreAddrReg, PtrVT));
15698 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15699 SelectionDAG &DAG) const {
15701 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15702 DAG.getVTList(MVT::i32, MVT::Other),
15703 Op.getOperand(0), Op.getOperand(1));
15706 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15707 SelectionDAG &DAG) const {
15709 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15710 Op.getOperand(0), Op.getOperand(1));
15713 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15714 return Op.getOperand(0);
15717 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15718 SelectionDAG &DAG) const {
15719 SDValue Root = Op.getOperand(0);
15720 SDValue Trmp = Op.getOperand(1); // trampoline
15721 SDValue FPtr = Op.getOperand(2); // nested function
15722 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15725 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15726 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15728 if (Subtarget->is64Bit()) {
15729 SDValue OutChains[6];
15731 // Large code-model.
15732 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15733 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15735 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15736 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15738 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15740 // Load the pointer to the nested function into R11.
15741 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15742 SDValue Addr = Trmp;
15743 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15744 Addr, MachinePointerInfo(TrmpAddr),
15747 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15748 DAG.getConstant(2, dl, MVT::i64));
15749 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15750 MachinePointerInfo(TrmpAddr, 2),
15753 // Load the 'nest' parameter value into R10.
15754 // R10 is specified in X86CallingConv.td
15755 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15756 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15757 DAG.getConstant(10, dl, MVT::i64));
15758 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15759 Addr, MachinePointerInfo(TrmpAddr, 10),
15762 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15763 DAG.getConstant(12, dl, MVT::i64));
15764 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15765 MachinePointerInfo(TrmpAddr, 12),
15768 // Jump to the nested function.
15769 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15770 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15771 DAG.getConstant(20, dl, MVT::i64));
15772 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15773 Addr, MachinePointerInfo(TrmpAddr, 20),
15776 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15777 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15778 DAG.getConstant(22, dl, MVT::i64));
15779 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15780 Addr, MachinePointerInfo(TrmpAddr, 22),
15783 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15785 const Function *Func =
15786 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15787 CallingConv::ID CC = Func->getCallingConv();
15792 llvm_unreachable("Unsupported calling convention");
15793 case CallingConv::C:
15794 case CallingConv::X86_StdCall: {
15795 // Pass 'nest' parameter in ECX.
15796 // Must be kept in sync with X86CallingConv.td
15797 NestReg = X86::ECX;
15799 // Check that ECX wasn't needed by an 'inreg' parameter.
15800 FunctionType *FTy = Func->getFunctionType();
15801 const AttributeSet &Attrs = Func->getAttributes();
15803 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15804 unsigned InRegCount = 0;
15807 for (FunctionType::param_iterator I = FTy->param_begin(),
15808 E = FTy->param_end(); I != E; ++I, ++Idx)
15809 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15810 // FIXME: should only count parameters that are lowered to integers.
15811 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15813 if (InRegCount > 2) {
15814 report_fatal_error("Nest register in use - reduce number of inreg"
15820 case CallingConv::X86_FastCall:
15821 case CallingConv::X86_ThisCall:
15822 case CallingConv::Fast:
15823 // Pass 'nest' parameter in EAX.
15824 // Must be kept in sync with X86CallingConv.td
15825 NestReg = X86::EAX;
15829 SDValue OutChains[4];
15830 SDValue Addr, Disp;
15832 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15833 DAG.getConstant(10, dl, MVT::i32));
15834 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15836 // This is storing the opcode for MOV32ri.
15837 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15838 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15839 OutChains[0] = DAG.getStore(Root, dl,
15840 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15841 Trmp, MachinePointerInfo(TrmpAddr),
15844 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15845 DAG.getConstant(1, dl, MVT::i32));
15846 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15847 MachinePointerInfo(TrmpAddr, 1),
15850 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15851 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15852 DAG.getConstant(5, dl, MVT::i32));
15853 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15854 Addr, MachinePointerInfo(TrmpAddr, 5),
15857 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15858 DAG.getConstant(6, dl, MVT::i32));
15859 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15860 MachinePointerInfo(TrmpAddr, 6),
15863 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15867 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15868 SelectionDAG &DAG) const {
15870 The rounding mode is in bits 11:10 of FPSR, and has the following
15872 00 Round to nearest
15877 FLT_ROUNDS, on the other hand, expects the following:
15884 To perform the conversion, we do:
15885 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15888 MachineFunction &MF = DAG.getMachineFunction();
15889 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15890 unsigned StackAlignment = TFI.getStackAlignment();
15891 MVT VT = Op.getSimpleValueType();
15894 // Save FP Control Word to stack slot
15895 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15896 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15898 MachineMemOperand *MMO =
15899 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15900 MachineMemOperand::MOStore, 2, 2);
15902 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15903 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15904 DAG.getVTList(MVT::Other),
15905 Ops, MVT::i16, MMO);
15907 // Load FP Control Word from stack slot
15908 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15909 MachinePointerInfo(), false, false, false, 0);
15911 // Transform as necessary
15913 DAG.getNode(ISD::SRL, DL, MVT::i16,
15914 DAG.getNode(ISD::AND, DL, MVT::i16,
15915 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15916 DAG.getConstant(11, DL, MVT::i8));
15918 DAG.getNode(ISD::SRL, DL, MVT::i16,
15919 DAG.getNode(ISD::AND, DL, MVT::i16,
15920 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15921 DAG.getConstant(9, DL, MVT::i8));
15924 DAG.getNode(ISD::AND, DL, MVT::i16,
15925 DAG.getNode(ISD::ADD, DL, MVT::i16,
15926 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15927 DAG.getConstant(1, DL, MVT::i16)),
15928 DAG.getConstant(3, DL, MVT::i16));
15930 return DAG.getNode((VT.getSizeInBits() < 16 ?
15931 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15934 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15935 MVT VT = Op.getSimpleValueType();
15937 unsigned NumBits = VT.getSizeInBits();
15940 Op = Op.getOperand(0);
15941 if (VT == MVT::i8) {
15942 // Zero extend to i32 since there is not an i8 bsr.
15944 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15947 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15948 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15949 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15951 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15954 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15955 DAG.getConstant(X86::COND_E, dl, MVT::i8),
15958 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15960 // Finally 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 LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15970 MVT VT = Op.getSimpleValueType();
15972 unsigned NumBits = VT.getSizeInBits();
15975 Op = Op.getOperand(0);
15976 if (VT == MVT::i8) {
15977 // Zero extend to i32 since there is not an i8 bsr.
15979 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15982 // Issue a bsr (scan bits in reverse).
15983 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15984 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15986 // And xor with NumBits-1.
15987 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15988 DAG.getConstant(NumBits - 1, dl, OpVT));
15991 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15995 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15996 MVT VT = Op.getSimpleValueType();
15997 unsigned NumBits = VT.getSizeInBits();
15999 Op = Op.getOperand(0);
16001 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16002 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16003 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16005 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16008 DAG.getConstant(NumBits, dl, VT),
16009 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16012 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16015 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16016 // ones, and then concatenate the result back.
16017 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16018 MVT VT = Op.getSimpleValueType();
16020 assert(VT.is256BitVector() && VT.isInteger() &&
16021 "Unsupported value type for operation");
16023 unsigned NumElems = VT.getVectorNumElements();
16026 // Extract the LHS vectors
16027 SDValue LHS = Op.getOperand(0);
16028 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16029 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16031 // Extract the RHS vectors
16032 SDValue RHS = Op.getOperand(1);
16033 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16034 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16036 MVT EltVT = VT.getVectorElementType();
16037 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16039 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16040 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16041 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16044 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16045 assert(Op.getSimpleValueType().is256BitVector() &&
16046 Op.getSimpleValueType().isInteger() &&
16047 "Only handle AVX 256-bit vector integer operation");
16048 return Lower256IntArith(Op, DAG);
16051 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16052 assert(Op.getSimpleValueType().is256BitVector() &&
16053 Op.getSimpleValueType().isInteger() &&
16054 "Only handle AVX 256-bit vector integer operation");
16055 return Lower256IntArith(Op, DAG);
16058 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16059 SelectionDAG &DAG) {
16061 MVT VT = Op.getSimpleValueType();
16063 // Decompose 256-bit ops into smaller 128-bit ops.
16064 if (VT.is256BitVector() && !Subtarget->hasInt256())
16065 return Lower256IntArith(Op, DAG);
16067 SDValue A = Op.getOperand(0);
16068 SDValue B = Op.getOperand(1);
16070 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16071 // pairs, multiply and truncate.
16072 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16073 if (Subtarget->hasInt256()) {
16074 if (VT == MVT::v32i8) {
16075 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16076 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16077 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16078 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16079 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16080 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16081 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16082 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16083 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16084 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16087 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16088 return DAG.getNode(
16089 ISD::TRUNCATE, dl, VT,
16090 DAG.getNode(ISD::MUL, dl, ExVT,
16091 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16092 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16095 assert(VT == MVT::v16i8 &&
16096 "Pre-AVX2 support only supports v16i8 multiplication");
16097 MVT ExVT = MVT::v8i16;
16099 // Extract the lo parts and sign extend to i16
16101 if (Subtarget->hasSSE41()) {
16102 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16103 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16105 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16106 -1, 4, -1, 5, -1, 6, -1, 7};
16107 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16108 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16109 ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16110 BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16111 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16112 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16115 // Extract the hi parts and sign extend to i16
16117 if (Subtarget->hasSSE41()) {
16118 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16119 -1, -1, -1, -1, -1, -1, -1, -1};
16120 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16121 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16122 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16123 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16125 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16126 -1, 12, -1, 13, -1, 14, -1, 15};
16127 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16128 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16129 AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16130 BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16131 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16132 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16135 // Multiply, mask the lower 8bits of the lo/hi results and pack
16136 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16137 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16138 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16139 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16140 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16143 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16144 if (VT == MVT::v4i32) {
16145 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16146 "Should not custom lower when pmuldq is available!");
16148 // Extract the odd parts.
16149 static const int UnpackMask[] = { 1, -1, 3, -1 };
16150 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16151 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16153 // Multiply the even parts.
16154 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16155 // Now multiply odd parts.
16156 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16158 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16159 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16161 // Merge the two vectors back together with a shuffle. This expands into 2
16163 static const int ShufMask[] = { 0, 4, 2, 6 };
16164 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16167 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16168 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16170 // Ahi = psrlqi(a, 32);
16171 // Bhi = psrlqi(b, 32);
16173 // AloBlo = pmuludq(a, b);
16174 // AloBhi = pmuludq(a, Bhi);
16175 // AhiBlo = pmuludq(Ahi, b);
16177 // AloBhi = psllqi(AloBhi, 32);
16178 // AhiBlo = psllqi(AhiBlo, 32);
16179 // return AloBlo + AloBhi + AhiBlo;
16181 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16182 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16184 // Bit cast to 32-bit vectors for MULUDQ
16185 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16186 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16187 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16188 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16189 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16190 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16192 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16193 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16194 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16196 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16197 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16199 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16200 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16203 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16204 assert(Subtarget->isTargetWin64() && "Unexpected target");
16205 EVT VT = Op.getValueType();
16206 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16207 "Unexpected return type for lowering");
16211 switch (Op->getOpcode()) {
16212 default: llvm_unreachable("Unexpected request for libcall!");
16213 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16214 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16215 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16216 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16217 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16218 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16222 SDValue InChain = DAG.getEntryNode();
16224 TargetLowering::ArgListTy Args;
16225 TargetLowering::ArgListEntry Entry;
16226 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16227 EVT ArgVT = Op->getOperand(i).getValueType();
16228 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16229 "Unexpected argument type for lowering");
16230 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16231 Entry.Node = StackPtr;
16232 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16234 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16235 Entry.Ty = PointerType::get(ArgTy,0);
16236 Entry.isSExt = false;
16237 Entry.isZExt = false;
16238 Args.push_back(Entry);
16241 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16244 TargetLowering::CallLoweringInfo CLI(DAG);
16245 CLI.setDebugLoc(dl).setChain(InChain)
16246 .setCallee(getLibcallCallingConv(LC),
16247 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16248 Callee, std::move(Args), 0)
16249 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16251 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16252 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16255 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16256 SelectionDAG &DAG) {
16257 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16258 EVT VT = Op0.getValueType();
16261 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16262 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16264 // PMULxD operations multiply each even value (starting at 0) of LHS with
16265 // the related value of RHS and produce a widen result.
16266 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16267 // => <2 x i64> <ae|cg>
16269 // In other word, to have all the results, we need to perform two PMULxD:
16270 // 1. one with the even values.
16271 // 2. one with the odd values.
16272 // To achieve #2, with need to place the odd values at an even position.
16274 // Place the odd value at an even position (basically, shift all values 1
16275 // step to the left):
16276 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16277 // <a|b|c|d> => <b|undef|d|undef>
16278 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16279 // <e|f|g|h> => <f|undef|h|undef>
16280 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16282 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16284 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16285 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16287 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16288 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16289 // => <2 x i64> <ae|cg>
16290 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16291 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16292 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16293 // => <2 x i64> <bf|dh>
16294 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16295 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16297 // Shuffle it back into the right order.
16298 SDValue Highs, Lows;
16299 if (VT == MVT::v8i32) {
16300 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16301 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16302 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16303 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16305 const int HighMask[] = {1, 5, 3, 7};
16306 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16307 const int LowMask[] = {0, 4, 2, 6};
16308 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16311 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16312 // unsigned multiply.
16313 if (IsSigned && !Subtarget->hasSSE41()) {
16315 DAG.getConstant(31, dl,
16316 DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16317 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16318 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16319 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16320 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16322 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16323 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16326 // The first result of MUL_LOHI is actually the low value, followed by the
16328 SDValue Ops[] = {Lows, Highs};
16329 return DAG.getMergeValues(Ops, dl);
16332 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16333 const X86Subtarget *Subtarget) {
16334 MVT VT = Op.getSimpleValueType();
16336 SDValue R = Op.getOperand(0);
16337 SDValue Amt = Op.getOperand(1);
16339 // Optimize shl/srl/sra with constant shift amount.
16340 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16341 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16342 uint64_t ShiftAmt = ShiftConst->getZExtValue();
16344 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16345 (Subtarget->hasInt256() &&
16346 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16347 (Subtarget->hasAVX512() &&
16348 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16349 if (Op.getOpcode() == ISD::SHL)
16350 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16352 if (Op.getOpcode() == ISD::SRL)
16353 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16355 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16356 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16360 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16361 unsigned NumElts = VT.getVectorNumElements();
16362 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16364 if (Op.getOpcode() == ISD::SHL) {
16365 // Make a large shift.
16366 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16368 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16369 // Zero out the rightmost bits.
16370 SmallVector<SDValue, 32> V(
16371 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16372 return DAG.getNode(ISD::AND, dl, VT, SHL,
16373 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16375 if (Op.getOpcode() == ISD::SRL) {
16376 // Make a large shift.
16377 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16379 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16380 // Zero out the leftmost bits.
16381 SmallVector<SDValue, 32> V(
16382 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16383 return DAG.getNode(ISD::AND, dl, VT, SRL,
16384 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16386 if (Op.getOpcode() == ISD::SRA) {
16387 if (ShiftAmt == 7) {
16388 // R s>> 7 === R s< 0
16389 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16390 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16393 // R s>> a === ((R u>> a) ^ m) - m
16394 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16395 SmallVector<SDValue, 32> V(NumElts,
16396 DAG.getConstant(128 >> ShiftAmt, dl,
16398 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16399 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16400 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16403 llvm_unreachable("Unknown shift opcode.");
16408 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16409 if (!Subtarget->is64Bit() &&
16410 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16411 Amt.getOpcode() == ISD::BITCAST &&
16412 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16413 Amt = Amt.getOperand(0);
16414 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16415 VT.getVectorNumElements();
16416 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16417 uint64_t ShiftAmt = 0;
16418 for (unsigned i = 0; i != Ratio; ++i) {
16419 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16423 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16425 // Check remaining shift amounts.
16426 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16427 uint64_t ShAmt = 0;
16428 for (unsigned j = 0; j != Ratio; ++j) {
16429 ConstantSDNode *C =
16430 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16434 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16436 if (ShAmt != ShiftAmt)
16439 switch (Op.getOpcode()) {
16441 llvm_unreachable("Unknown shift opcode!");
16443 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16446 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16449 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16457 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16458 const X86Subtarget* Subtarget) {
16459 MVT VT = Op.getSimpleValueType();
16461 SDValue R = Op.getOperand(0);
16462 SDValue Amt = Op.getOperand(1);
16464 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16465 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16466 (Subtarget->hasInt256() &&
16467 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16468 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16469 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16471 EVT EltVT = VT.getVectorElementType();
16473 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16474 // Check if this build_vector node is doing a splat.
16475 // If so, then set BaseShAmt equal to the splat value.
16476 BaseShAmt = BV->getSplatValue();
16477 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16478 BaseShAmt = SDValue();
16480 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16481 Amt = Amt.getOperand(0);
16483 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16484 if (SVN && SVN->isSplat()) {
16485 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16486 SDValue InVec = Amt.getOperand(0);
16487 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16488 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16489 "Unexpected shuffle index found!");
16490 BaseShAmt = InVec.getOperand(SplatIdx);
16491 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16492 if (ConstantSDNode *C =
16493 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16494 if (C->getZExtValue() == SplatIdx)
16495 BaseShAmt = InVec.getOperand(1);
16500 // Avoid introducing an extract element from a shuffle.
16501 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16502 DAG.getIntPtrConstant(SplatIdx, dl));
16506 if (BaseShAmt.getNode()) {
16507 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16508 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16509 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16510 else if (EltVT.bitsLT(MVT::i32))
16511 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16513 switch (Op.getOpcode()) {
16515 llvm_unreachable("Unknown shift opcode!");
16517 switch (VT.SimpleTy) {
16518 default: return SDValue();
16527 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16530 switch (VT.SimpleTy) {
16531 default: return SDValue();
16538 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16541 switch (VT.SimpleTy) {
16542 default: return SDValue();
16551 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16557 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16558 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
16559 Amt.getOpcode() == ISD::BITCAST &&
16560 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16561 Amt = Amt.getOperand(0);
16562 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16563 VT.getVectorNumElements();
16564 std::vector<SDValue> Vals(Ratio);
16565 for (unsigned i = 0; i != Ratio; ++i)
16566 Vals[i] = Amt.getOperand(i);
16567 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16568 for (unsigned j = 0; j != Ratio; ++j)
16569 if (Vals[j] != Amt.getOperand(i + j))
16572 switch (Op.getOpcode()) {
16574 llvm_unreachable("Unknown shift opcode!");
16576 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16578 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16580 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16587 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16588 SelectionDAG &DAG) {
16589 MVT VT = Op.getSimpleValueType();
16591 SDValue R = Op.getOperand(0);
16592 SDValue Amt = Op.getOperand(1);
16594 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16595 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16597 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16600 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16603 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16606 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16607 if (Subtarget->hasInt256()) {
16608 if (Op.getOpcode() == ISD::SRL &&
16609 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16610 VT == MVT::v4i64 || VT == MVT::v8i32))
16612 if (Op.getOpcode() == ISD::SHL &&
16613 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16614 VT == MVT::v4i64 || VT == MVT::v8i32))
16616 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16620 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16621 // shifts per-lane and then shuffle the partial results back together.
16622 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16623 // Splat the shift amounts so the scalar shifts above will catch it.
16624 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16625 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16626 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16627 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16628 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16631 // If possible, lower this packed shift into a vector multiply instead of
16632 // expanding it into a sequence of scalar shifts.
16633 // Do this only if the vector shift count is a constant build_vector.
16634 if (Op.getOpcode() == ISD::SHL &&
16635 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16636 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16637 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16638 SmallVector<SDValue, 8> Elts;
16639 EVT SVT = VT.getScalarType();
16640 unsigned SVTBits = SVT.getSizeInBits();
16641 const APInt &One = APInt(SVTBits, 1);
16642 unsigned NumElems = VT.getVectorNumElements();
16644 for (unsigned i=0; i !=NumElems; ++i) {
16645 SDValue Op = Amt->getOperand(i);
16646 if (Op->getOpcode() == ISD::UNDEF) {
16647 Elts.push_back(Op);
16651 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16652 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16653 uint64_t ShAmt = C.getZExtValue();
16654 if (ShAmt >= SVTBits) {
16655 Elts.push_back(DAG.getUNDEF(SVT));
16658 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16660 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16661 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16664 // Lower SHL with variable shift amount.
16665 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16666 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16668 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16669 DAG.getConstant(0x3f800000U, dl, VT));
16670 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16671 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16672 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16675 // If possible, lower this shift as a sequence of two shifts by
16676 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16678 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16680 // Could be rewritten as:
16681 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16683 // The advantage is that the two shifts from the example would be
16684 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16685 // the vector shift into four scalar shifts plus four pairs of vector
16687 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16688 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16689 unsigned TargetOpcode = X86ISD::MOVSS;
16690 bool CanBeSimplified;
16691 // The splat value for the first packed shift (the 'X' from the example).
16692 SDValue Amt1 = Amt->getOperand(0);
16693 // The splat value for the second packed shift (the 'Y' from the example).
16694 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16695 Amt->getOperand(2);
16697 // See if it is possible to replace this node with a sequence of
16698 // two shifts followed by a MOVSS/MOVSD
16699 if (VT == MVT::v4i32) {
16700 // Check if it is legal to use a MOVSS.
16701 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16702 Amt2 == Amt->getOperand(3);
16703 if (!CanBeSimplified) {
16704 // Otherwise, check if we can still simplify this node using a MOVSD.
16705 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16706 Amt->getOperand(2) == Amt->getOperand(3);
16707 TargetOpcode = X86ISD::MOVSD;
16708 Amt2 = Amt->getOperand(2);
16711 // Do similar checks for the case where the machine value type
16713 CanBeSimplified = Amt1 == Amt->getOperand(1);
16714 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16715 CanBeSimplified = Amt2 == Amt->getOperand(i);
16717 if (!CanBeSimplified) {
16718 TargetOpcode = X86ISD::MOVSD;
16719 CanBeSimplified = true;
16720 Amt2 = Amt->getOperand(4);
16721 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16722 CanBeSimplified = Amt1 == Amt->getOperand(i);
16723 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16724 CanBeSimplified = Amt2 == Amt->getOperand(j);
16728 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16729 isa<ConstantSDNode>(Amt2)) {
16730 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16731 EVT CastVT = MVT::v4i32;
16733 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16734 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16736 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16737 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16738 if (TargetOpcode == X86ISD::MOVSD)
16739 CastVT = MVT::v2i64;
16740 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16741 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16742 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16744 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16748 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16749 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16750 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16752 SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16753 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16754 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16756 // r = VSELECT(r, shl(r, 4), a);
16757 SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16758 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16761 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16762 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16763 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16765 // r = VSELECT(r, shl(r, 2), a);
16766 M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16767 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16770 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16771 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16772 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16774 // return VSELECT(r, r+r, a);
16775 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16776 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16780 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16781 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16782 // solution better.
16783 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16784 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16786 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16787 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16788 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16789 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16790 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16793 // Decompose 256-bit shifts into smaller 128-bit shifts.
16794 if (VT.is256BitVector()) {
16795 unsigned NumElems = VT.getVectorNumElements();
16796 MVT EltVT = VT.getVectorElementType();
16797 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16799 // Extract the two vectors
16800 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16801 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16803 // Recreate the shift amount vectors
16804 SDValue Amt1, Amt2;
16805 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16806 // Constant shift amount
16807 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16808 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16809 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16811 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16812 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16814 // Variable shift amount
16815 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16816 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16819 // Issue new vector shifts for the smaller types
16820 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16821 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16823 // Concatenate the result back
16824 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16830 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16831 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16832 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16833 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16834 // has only one use.
16835 SDNode *N = Op.getNode();
16836 SDValue LHS = N->getOperand(0);
16837 SDValue RHS = N->getOperand(1);
16838 unsigned BaseOp = 0;
16841 switch (Op.getOpcode()) {
16842 default: llvm_unreachable("Unknown ovf instruction!");
16844 // A subtract of one will be selected as a INC. Note that INC doesn't
16845 // set CF, so we can't do this for UADDO.
16846 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16848 BaseOp = X86ISD::INC;
16849 Cond = X86::COND_O;
16852 BaseOp = X86ISD::ADD;
16853 Cond = X86::COND_O;
16856 BaseOp = X86ISD::ADD;
16857 Cond = X86::COND_B;
16860 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16861 // set CF, so we can't do this for USUBO.
16862 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16864 BaseOp = X86ISD::DEC;
16865 Cond = X86::COND_O;
16868 BaseOp = X86ISD::SUB;
16869 Cond = X86::COND_O;
16872 BaseOp = X86ISD::SUB;
16873 Cond = X86::COND_B;
16876 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16877 Cond = X86::COND_O;
16879 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16880 if (N->getValueType(0) == MVT::i8) {
16881 BaseOp = X86ISD::UMUL8;
16882 Cond = X86::COND_O;
16885 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16887 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16890 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16891 DAG.getConstant(X86::COND_O, DL, MVT::i32),
16892 SDValue(Sum.getNode(), 2));
16894 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16898 // Also sets EFLAGS.
16899 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16900 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16903 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16904 DAG.getConstant(Cond, DL, MVT::i32),
16905 SDValue(Sum.getNode(), 1));
16907 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16910 /// Returns true if the operand type is exactly twice the native width, and
16911 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16912 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16913 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16914 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16915 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16918 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16919 else if (OpWidth == 128)
16920 return Subtarget->hasCmpxchg16b();
16925 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16926 return needsCmpXchgNb(SI->getValueOperand()->getType());
16929 // Note: this turns large loads into lock cmpxchg8b/16b.
16930 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16931 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16932 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16933 return needsCmpXchgNb(PTy->getElementType());
16936 TargetLoweringBase::AtomicRMWExpansionKind
16937 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16938 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16939 const Type *MemType = AI->getType();
16941 // If the operand is too big, we must see if cmpxchg8/16b is available
16942 // and default to library calls otherwise.
16943 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16944 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16945 : AtomicRMWExpansionKind::None;
16948 AtomicRMWInst::BinOp Op = AI->getOperation();
16951 llvm_unreachable("Unknown atomic operation");
16952 case AtomicRMWInst::Xchg:
16953 case AtomicRMWInst::Add:
16954 case AtomicRMWInst::Sub:
16955 // It's better to use xadd, xsub or xchg for these in all cases.
16956 return AtomicRMWExpansionKind::None;
16957 case AtomicRMWInst::Or:
16958 case AtomicRMWInst::And:
16959 case AtomicRMWInst::Xor:
16960 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16961 // prefix to a normal instruction for these operations.
16962 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16963 : AtomicRMWExpansionKind::None;
16964 case AtomicRMWInst::Nand:
16965 case AtomicRMWInst::Max:
16966 case AtomicRMWInst::Min:
16967 case AtomicRMWInst::UMax:
16968 case AtomicRMWInst::UMin:
16969 // These always require a non-trivial set of data operations on x86. We must
16970 // use a cmpxchg loop.
16971 return AtomicRMWExpansionKind::CmpXChg;
16975 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16976 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16977 // no-sse2). There isn't any reason to disable it if the target processor
16979 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16983 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16984 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16985 const Type *MemType = AI->getType();
16986 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16987 // there is no benefit in turning such RMWs into loads, and it is actually
16988 // harmful as it introduces a mfence.
16989 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16992 auto Builder = IRBuilder<>(AI);
16993 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16994 auto SynchScope = AI->getSynchScope();
16995 // We must restrict the ordering to avoid generating loads with Release or
16996 // ReleaseAcquire orderings.
16997 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16998 auto Ptr = AI->getPointerOperand();
17000 // Before the load we need a fence. Here is an example lifted from
17001 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17004 // x.store(1, relaxed);
17005 // r1 = y.fetch_add(0, release);
17007 // y.fetch_add(42, acquire);
17008 // r2 = x.load(relaxed);
17009 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17010 // lowered to just a load without a fence. A mfence flushes the store buffer,
17011 // making the optimization clearly correct.
17012 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17013 // otherwise, we might be able to be more agressive on relaxed idempotent
17014 // rmw. In practice, they do not look useful, so we don't try to be
17015 // especially clever.
17016 if (SynchScope == SingleThread) {
17017 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17018 // the IR level, so we must wrap it in an intrinsic.
17020 } else if (hasMFENCE(*Subtarget)) {
17021 Function *MFence = llvm::Intrinsic::getDeclaration(M,
17022 Intrinsic::x86_sse2_mfence);
17023 Builder.CreateCall(MFence);
17025 // FIXME: it might make sense to use a locked operation here but on a
17026 // different cache-line to prevent cache-line bouncing. In practice it
17027 // is probably a small win, and x86 processors without mfence are rare
17028 // enough that we do not bother.
17032 // Finally we can emit the atomic load.
17033 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17034 AI->getType()->getPrimitiveSizeInBits());
17035 Loaded->setAtomic(Order, SynchScope);
17036 AI->replaceAllUsesWith(Loaded);
17037 AI->eraseFromParent();
17041 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17042 SelectionDAG &DAG) {
17044 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17045 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17046 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17047 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17049 // The only fence that needs an instruction is a sequentially-consistent
17050 // cross-thread fence.
17051 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17052 if (hasMFENCE(*Subtarget))
17053 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17055 SDValue Chain = Op.getOperand(0);
17056 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17058 DAG.getRegister(X86::ESP, MVT::i32), // Base
17059 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
17060 DAG.getRegister(0, MVT::i32), // Index
17061 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
17062 DAG.getRegister(0, MVT::i32), // Segment.
17066 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17067 return SDValue(Res, 0);
17070 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17071 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17074 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17075 SelectionDAG &DAG) {
17076 MVT T = Op.getSimpleValueType();
17080 switch(T.SimpleTy) {
17081 default: llvm_unreachable("Invalid value type!");
17082 case MVT::i8: Reg = X86::AL; size = 1; break;
17083 case MVT::i16: Reg = X86::AX; size = 2; break;
17084 case MVT::i32: Reg = X86::EAX; size = 4; break;
17086 assert(Subtarget->is64Bit() && "Node not type legal!");
17087 Reg = X86::RAX; size = 8;
17090 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17091 Op.getOperand(2), SDValue());
17092 SDValue Ops[] = { cpIn.getValue(0),
17095 DAG.getTargetConstant(size, DL, MVT::i8),
17096 cpIn.getValue(1) };
17097 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17098 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17099 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17103 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17104 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17105 MVT::i32, cpOut.getValue(2));
17106 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17107 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17110 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17111 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17112 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17116 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17117 SelectionDAG &DAG) {
17118 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17119 MVT DstVT = Op.getSimpleValueType();
17121 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17122 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17123 if (DstVT != MVT::f64)
17124 // This conversion needs to be expanded.
17127 SDValue InVec = Op->getOperand(0);
17129 unsigned NumElts = SrcVT.getVectorNumElements();
17130 EVT SVT = SrcVT.getVectorElementType();
17132 // Widen the vector in input in the case of MVT::v2i32.
17133 // Example: from MVT::v2i32 to MVT::v4i32.
17134 SmallVector<SDValue, 16> Elts;
17135 for (unsigned i = 0, e = NumElts; i != e; ++i)
17136 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17137 DAG.getIntPtrConstant(i, dl)));
17139 // Explicitly mark the extra elements as Undef.
17140 Elts.append(NumElts, DAG.getUNDEF(SVT));
17142 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17143 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17144 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17145 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17146 DAG.getIntPtrConstant(0, dl));
17149 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17150 Subtarget->hasMMX() && "Unexpected custom BITCAST");
17151 assert((DstVT == MVT::i64 ||
17152 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17153 "Unexpected custom BITCAST");
17154 // i64 <=> MMX conversions are Legal.
17155 if (SrcVT==MVT::i64 && DstVT.isVector())
17157 if (DstVT==MVT::i64 && SrcVT.isVector())
17159 // MMX <=> MMX conversions are Legal.
17160 if (SrcVT.isVector() && DstVT.isVector())
17162 // All other conversions need to be expanded.
17166 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17167 SelectionDAG &DAG) {
17168 SDNode *Node = Op.getNode();
17171 Op = Op.getOperand(0);
17172 EVT VT = Op.getValueType();
17173 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17174 "CTPOP lowering only implemented for 128/256-bit wide vector types");
17176 unsigned NumElts = VT.getVectorNumElements();
17177 EVT EltVT = VT.getVectorElementType();
17178 unsigned Len = EltVT.getSizeInBits();
17180 // This is the vectorized version of the "best" algorithm from
17181 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17182 // with a minor tweak to use a series of adds + shifts instead of vector
17183 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17185 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17186 // v8i32 => Always profitable
17188 // FIXME: There a couple of possible improvements:
17190 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17191 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17193 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17194 "CTPOP not implemented for this vector element type.");
17196 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17197 // extra legalization.
17198 bool NeedsBitcast = EltVT == MVT::i32;
17199 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17201 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17203 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17205 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17208 // v = v - ((v >> 1) & 0x55555555...)
17209 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17210 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17211 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17213 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17215 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17216 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17218 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17220 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17221 if (VT != And.getValueType())
17222 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17223 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17225 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17226 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17227 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17228 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17229 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17231 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17232 if (NeedsBitcast) {
17233 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17234 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17235 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17238 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17239 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17240 if (VT != AndRHS.getValueType()) {
17241 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17242 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17244 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17246 // v = (v + (v >> 4)) & 0x0F0F0F0F...
17247 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17248 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17249 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17250 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17252 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17253 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17254 if (NeedsBitcast) {
17255 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17256 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17258 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17259 if (VT != And.getValueType())
17260 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17262 // The algorithm mentioned above uses:
17263 // v = (v * 0x01010101...) >> (Len - 8)
17265 // Change it to use vector adds + vector shifts which yield faster results on
17266 // Haswell than using vector integer multiplication.
17268 // For i32 elements:
17269 // v = v + (v >> 8)
17270 // v = v + (v >> 16)
17272 // For i64 elements:
17273 // v = v + (v >> 8)
17274 // v = v + (v >> 16)
17275 // v = v + (v >> 32)
17278 SmallVector<SDValue, 8> Csts;
17279 for (unsigned i = 8; i <= Len/2; i *= 2) {
17280 Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17281 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17282 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17283 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17287 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17288 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17290 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17291 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17292 if (NeedsBitcast) {
17293 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17294 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17296 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17297 if (VT != And.getValueType())
17298 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17303 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17304 SDNode *Node = Op.getNode();
17306 EVT T = Node->getValueType(0);
17307 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17308 DAG.getConstant(0, dl, T), Node->getOperand(2));
17309 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17310 cast<AtomicSDNode>(Node)->getMemoryVT(),
17311 Node->getOperand(0),
17312 Node->getOperand(1), negOp,
17313 cast<AtomicSDNode>(Node)->getMemOperand(),
17314 cast<AtomicSDNode>(Node)->getOrdering(),
17315 cast<AtomicSDNode>(Node)->getSynchScope());
17318 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17319 SDNode *Node = Op.getNode();
17321 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17323 // Convert seq_cst store -> xchg
17324 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17325 // FIXME: On 32-bit, store -> fist or movq would be more efficient
17326 // (The only way to get a 16-byte store is cmpxchg16b)
17327 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17328 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17329 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17330 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17331 cast<AtomicSDNode>(Node)->getMemoryVT(),
17332 Node->getOperand(0),
17333 Node->getOperand(1), Node->getOperand(2),
17334 cast<AtomicSDNode>(Node)->getMemOperand(),
17335 cast<AtomicSDNode>(Node)->getOrdering(),
17336 cast<AtomicSDNode>(Node)->getSynchScope());
17337 return Swap.getValue(1);
17339 // Other atomic stores have a simple pattern.
17343 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17344 EVT VT = Op.getNode()->getSimpleValueType(0);
17346 // Let legalize expand this if it isn't a legal type yet.
17347 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17350 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17353 bool ExtraOp = false;
17354 switch (Op.getOpcode()) {
17355 default: llvm_unreachable("Invalid code");
17356 case ISD::ADDC: Opc = X86ISD::ADD; break;
17357 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17358 case ISD::SUBC: Opc = X86ISD::SUB; break;
17359 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17363 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17365 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17366 Op.getOperand(1), Op.getOperand(2));
17369 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17370 SelectionDAG &DAG) {
17371 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17373 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17374 // which returns the values as { float, float } (in XMM0) or
17375 // { double, double } (which is returned in XMM0, XMM1).
17377 SDValue Arg = Op.getOperand(0);
17378 EVT ArgVT = Arg.getValueType();
17379 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17381 TargetLowering::ArgListTy Args;
17382 TargetLowering::ArgListEntry Entry;
17386 Entry.isSExt = false;
17387 Entry.isZExt = false;
17388 Args.push_back(Entry);
17390 bool isF64 = ArgVT == MVT::f64;
17391 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17392 // the small struct {f32, f32} is returned in (eax, edx). For f64,
17393 // the results are returned via SRet in memory.
17394 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
17395 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17396 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17398 Type *RetTy = isF64
17399 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17400 : (Type*)VectorType::get(ArgTy, 4);
17402 TargetLowering::CallLoweringInfo CLI(DAG);
17403 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17404 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17406 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17409 // Returned in xmm0 and xmm1.
17410 return CallResult.first;
17412 // Returned in bits 0:31 and 32:64 xmm0.
17413 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17414 CallResult.first, DAG.getIntPtrConstant(0, dl));
17415 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17416 CallResult.first, DAG.getIntPtrConstant(1, dl));
17417 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17418 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17421 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17422 SelectionDAG &DAG) {
17423 assert(Subtarget->hasAVX512() &&
17424 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17426 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17427 EVT VT = N->getValue().getValueType();
17428 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17431 // X86 scatter kills mask register, so its type should be added to
17432 // the list of return values
17433 if (N->getNumValues() == 1) {
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);
17439 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17440 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17441 N->getOperand(3), Index };
17443 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17444 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17445 return SDValue(NewScatter.getNode(), 0);
17450 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17451 SelectionDAG &DAG) {
17452 assert(Subtarget->hasAVX512() &&
17453 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17455 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17456 EVT VT = Op.getValueType();
17457 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17460 SDValue Index = N->getIndex();
17461 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17462 !Index.getValueType().is512BitVector()) {
17463 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17464 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17465 N->getOperand(3), Index };
17466 DAG.UpdateNodeOperands(N, Ops);
17471 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17472 SelectionDAG &DAG) const {
17473 // TODO: Eventually, the lowering of these nodes should be informed by or
17474 // deferred to the GC strategy for the function in which they appear. For
17475 // now, however, they must be lowered to something. Since they are logically
17476 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17477 // require special handling for these nodes), lower them as literal NOOPs for
17479 SmallVector<SDValue, 2> Ops;
17481 Ops.push_back(Op.getOperand(0));
17482 if (Op->getGluedNode())
17483 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17486 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17487 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17492 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17493 SelectionDAG &DAG) const {
17494 // TODO: Eventually, the lowering of these nodes should be informed by or
17495 // deferred to the GC strategy for the function in which they appear. For
17496 // now, however, they must be lowered to something. Since they are logically
17497 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17498 // require special handling for these nodes), lower them as literal NOOPs for
17500 SmallVector<SDValue, 2> Ops;
17502 Ops.push_back(Op.getOperand(0));
17503 if (Op->getGluedNode())
17504 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17507 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17508 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17513 /// LowerOperation - Provide custom lowering hooks for some operations.
17515 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17516 switch (Op.getOpcode()) {
17517 default: llvm_unreachable("Should not custom lower this!");
17518 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17519 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17520 return LowerCMP_SWAP(Op, Subtarget, DAG);
17521 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
17522 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17523 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17524 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17525 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17526 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
17527 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17528 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17529 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17530 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17531 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17532 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17533 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17534 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17535 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17536 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17537 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17538 case ISD::SHL_PARTS:
17539 case ISD::SRA_PARTS:
17540 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17541 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17542 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17543 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17544 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17545 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17546 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17547 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17548 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17549 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17550 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17552 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17553 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17554 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17555 case ISD::SETCC: return LowerSETCC(Op, DAG);
17556 case ISD::SELECT: return LowerSELECT(Op, DAG);
17557 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17558 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17559 case ISD::VASTART: return LowerVASTART(Op, DAG);
17560 case ISD::VAARG: return LowerVAARG(Op, DAG);
17561 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17562 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17563 case ISD::INTRINSIC_VOID:
17564 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17565 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17566 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17567 case ISD::FRAME_TO_ARGS_OFFSET:
17568 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17569 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17570 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17571 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17572 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17573 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17574 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17575 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17576 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17577 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17578 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17579 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17580 case ISD::UMUL_LOHI:
17581 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17584 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17590 case ISD::UMULO: return LowerXALUO(Op, DAG);
17591 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17592 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17596 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17597 case ISD::ADD: return LowerADD(Op, DAG);
17598 case ISD::SUB: return LowerSUB(Op, DAG);
17599 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17600 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
17601 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
17602 case ISD::GC_TRANSITION_START:
17603 return LowerGC_TRANSITION_START(Op, DAG);
17604 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
17608 /// ReplaceNodeResults - Replace a node with an illegal result type
17609 /// with a new node built out of custom code.
17610 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17611 SmallVectorImpl<SDValue>&Results,
17612 SelectionDAG &DAG) const {
17614 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17615 switch (N->getOpcode()) {
17617 llvm_unreachable("Do not know how to custom type legalize this operation!");
17618 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17619 case X86ISD::FMINC:
17621 case X86ISD::FMAXC:
17622 case X86ISD::FMAX: {
17623 EVT VT = N->getValueType(0);
17624 if (VT != MVT::v2f32)
17625 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17626 SDValue UNDEF = DAG.getUNDEF(VT);
17627 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17628 N->getOperand(0), UNDEF);
17629 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17630 N->getOperand(1), UNDEF);
17631 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17634 case ISD::SIGN_EXTEND_INREG:
17639 // We don't want to expand or promote these.
17646 case ISD::UDIVREM: {
17647 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17648 Results.push_back(V);
17651 case ISD::FP_TO_SINT:
17652 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
17653 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17654 if (N->getOperand(0).getValueType() == MVT::f16)
17657 case ISD::FP_TO_UINT: {
17658 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17660 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17663 std::pair<SDValue,SDValue> Vals =
17664 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17665 SDValue FIST = Vals.first, StackSlot = Vals.second;
17666 if (FIST.getNode()) {
17667 EVT VT = N->getValueType(0);
17668 // Return a load from the stack slot.
17669 if (StackSlot.getNode())
17670 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17671 MachinePointerInfo(),
17672 false, false, false, 0));
17674 Results.push_back(FIST);
17678 case ISD::UINT_TO_FP: {
17679 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17680 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17681 N->getValueType(0) != MVT::v2f32)
17683 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17685 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17687 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17688 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17689 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17690 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17691 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17692 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17695 case ISD::FP_ROUND: {
17696 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17698 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17699 Results.push_back(V);
17702 case ISD::FP_EXTEND: {
17703 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17704 // No other ValueType for FP_EXTEND should reach this point.
17705 assert(N->getValueType(0) == MVT::v2f32 &&
17706 "Do not know how to legalize this Node");
17709 case ISD::INTRINSIC_W_CHAIN: {
17710 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17712 default : llvm_unreachable("Do not know how to custom type "
17713 "legalize this intrinsic operation!");
17714 case Intrinsic::x86_rdtsc:
17715 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17717 case Intrinsic::x86_rdtscp:
17718 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17720 case Intrinsic::x86_rdpmc:
17721 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17724 case ISD::READCYCLECOUNTER: {
17725 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17728 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17729 EVT T = N->getValueType(0);
17730 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17731 bool Regs64bit = T == MVT::i128;
17732 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17733 SDValue cpInL, cpInH;
17734 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17735 DAG.getConstant(0, dl, HalfT));
17736 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17737 DAG.getConstant(1, dl, HalfT));
17738 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17739 Regs64bit ? X86::RAX : X86::EAX,
17741 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17742 Regs64bit ? X86::RDX : X86::EDX,
17743 cpInH, cpInL.getValue(1));
17744 SDValue swapInL, swapInH;
17745 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17746 DAG.getConstant(0, dl, HalfT));
17747 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17748 DAG.getConstant(1, dl, HalfT));
17749 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17750 Regs64bit ? X86::RBX : X86::EBX,
17751 swapInL, cpInH.getValue(1));
17752 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17753 Regs64bit ? X86::RCX : X86::ECX,
17754 swapInH, swapInL.getValue(1));
17755 SDValue Ops[] = { swapInH.getValue(0),
17757 swapInH.getValue(1) };
17758 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17759 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17760 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17761 X86ISD::LCMPXCHG8_DAG;
17762 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17763 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17764 Regs64bit ? X86::RAX : X86::EAX,
17765 HalfT, Result.getValue(1));
17766 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17767 Regs64bit ? X86::RDX : X86::EDX,
17768 HalfT, cpOutL.getValue(2));
17769 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17771 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17772 MVT::i32, cpOutH.getValue(2));
17774 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17775 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17776 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17778 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17779 Results.push_back(Success);
17780 Results.push_back(EFLAGS.getValue(1));
17783 case ISD::ATOMIC_SWAP:
17784 case ISD::ATOMIC_LOAD_ADD:
17785 case ISD::ATOMIC_LOAD_SUB:
17786 case ISD::ATOMIC_LOAD_AND:
17787 case ISD::ATOMIC_LOAD_OR:
17788 case ISD::ATOMIC_LOAD_XOR:
17789 case ISD::ATOMIC_LOAD_NAND:
17790 case ISD::ATOMIC_LOAD_MIN:
17791 case ISD::ATOMIC_LOAD_MAX:
17792 case ISD::ATOMIC_LOAD_UMIN:
17793 case ISD::ATOMIC_LOAD_UMAX:
17794 case ISD::ATOMIC_LOAD: {
17795 // Delegate to generic TypeLegalization. Situations we can really handle
17796 // should have already been dealt with by AtomicExpandPass.cpp.
17799 case ISD::BITCAST: {
17800 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17801 EVT DstVT = N->getValueType(0);
17802 EVT SrcVT = N->getOperand(0)->getValueType(0);
17804 if (SrcVT != MVT::f64 ||
17805 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17808 unsigned NumElts = DstVT.getVectorNumElements();
17809 EVT SVT = DstVT.getVectorElementType();
17810 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17811 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17812 MVT::v2f64, N->getOperand(0));
17813 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17815 if (ExperimentalVectorWideningLegalization) {
17816 // If we are legalizing vectors by widening, we already have the desired
17817 // legal vector type, just return it.
17818 Results.push_back(ToVecInt);
17822 SmallVector<SDValue, 8> Elts;
17823 for (unsigned i = 0, e = NumElts; i != e; ++i)
17824 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17825 ToVecInt, DAG.getIntPtrConstant(i, dl)));
17827 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17832 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17833 switch ((X86ISD::NodeType)Opcode) {
17834 case X86ISD::FIRST_NUMBER: break;
17835 case X86ISD::BSF: return "X86ISD::BSF";
17836 case X86ISD::BSR: return "X86ISD::BSR";
17837 case X86ISD::SHLD: return "X86ISD::SHLD";
17838 case X86ISD::SHRD: return "X86ISD::SHRD";
17839 case X86ISD::FAND: return "X86ISD::FAND";
17840 case X86ISD::FANDN: return "X86ISD::FANDN";
17841 case X86ISD::FOR: return "X86ISD::FOR";
17842 case X86ISD::FXOR: return "X86ISD::FXOR";
17843 case X86ISD::FSRL: return "X86ISD::FSRL";
17844 case X86ISD::FILD: return "X86ISD::FILD";
17845 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17846 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17847 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17848 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17849 case X86ISD::FLD: return "X86ISD::FLD";
17850 case X86ISD::FST: return "X86ISD::FST";
17851 case X86ISD::CALL: return "X86ISD::CALL";
17852 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17853 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17854 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17855 case X86ISD::BT: return "X86ISD::BT";
17856 case X86ISD::CMP: return "X86ISD::CMP";
17857 case X86ISD::COMI: return "X86ISD::COMI";
17858 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17859 case X86ISD::CMPM: return "X86ISD::CMPM";
17860 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17861 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
17862 case X86ISD::SETCC: return "X86ISD::SETCC";
17863 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17864 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17865 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
17866 case X86ISD::CMOV: return "X86ISD::CMOV";
17867 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17868 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17869 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17870 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17871 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17872 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17873 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17874 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
17875 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
17876 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
17877 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17878 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17879 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17880 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17881 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17882 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
17883 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17884 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17885 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17886 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17887 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17888 case X86ISD::ADDUS: return "X86ISD::ADDUS";
17889 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17890 case X86ISD::HADD: return "X86ISD::HADD";
17891 case X86ISD::HSUB: return "X86ISD::HSUB";
17892 case X86ISD::FHADD: return "X86ISD::FHADD";
17893 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17894 case X86ISD::UMAX: return "X86ISD::UMAX";
17895 case X86ISD::UMIN: return "X86ISD::UMIN";
17896 case X86ISD::SMAX: return "X86ISD::SMAX";
17897 case X86ISD::SMIN: return "X86ISD::SMIN";
17898 case X86ISD::FMAX: return "X86ISD::FMAX";
17899 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
17900 case X86ISD::FMIN: return "X86ISD::FMIN";
17901 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
17902 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17903 case X86ISD::FMINC: return "X86ISD::FMINC";
17904 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17905 case X86ISD::FRCP: return "X86ISD::FRCP";
17906 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17907 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17908 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17909 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17910 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17911 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17912 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17913 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17914 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17915 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17916 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17917 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17918 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17919 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17920 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17921 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17922 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17923 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17924 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17925 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17926 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17927 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17928 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17929 case X86ISD::VSHL: return "X86ISD::VSHL";
17930 case X86ISD::VSRL: return "X86ISD::VSRL";
17931 case X86ISD::VSRA: return "X86ISD::VSRA";
17932 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17933 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17934 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17935 case X86ISD::CMPP: return "X86ISD::CMPP";
17936 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17937 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17938 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17939 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17940 case X86ISD::ADD: return "X86ISD::ADD";
17941 case X86ISD::SUB: return "X86ISD::SUB";
17942 case X86ISD::ADC: return "X86ISD::ADC";
17943 case X86ISD::SBB: return "X86ISD::SBB";
17944 case X86ISD::SMUL: return "X86ISD::SMUL";
17945 case X86ISD::UMUL: return "X86ISD::UMUL";
17946 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17947 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17948 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17949 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17950 case X86ISD::INC: return "X86ISD::INC";
17951 case X86ISD::DEC: return "X86ISD::DEC";
17952 case X86ISD::OR: return "X86ISD::OR";
17953 case X86ISD::XOR: return "X86ISD::XOR";
17954 case X86ISD::AND: return "X86ISD::AND";
17955 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17956 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17957 case X86ISD::PTEST: return "X86ISD::PTEST";
17958 case X86ISD::TESTP: return "X86ISD::TESTP";
17959 case X86ISD::TESTM: return "X86ISD::TESTM";
17960 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17961 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17962 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17963 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17964 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17965 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17966 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17967 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17968 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17969 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17970 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17971 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17972 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17973 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17974 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17975 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17976 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17977 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17978 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17979 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17980 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17981 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17982 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17983 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17984 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
17985 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17986 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17987 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17988 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17989 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17990 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17991 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17992 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17993 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17994 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17995 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17996 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17997 case X86ISD::MFENCE: return "X86ISD::MFENCE";
17998 case X86ISD::SFENCE: return "X86ISD::SFENCE";
17999 case X86ISD::LFENCE: return "X86ISD::LFENCE";
18000 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
18001 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
18002 case X86ISD::SAHF: return "X86ISD::SAHF";
18003 case X86ISD::RDRAND: return "X86ISD::RDRAND";
18004 case X86ISD::RDSEED: return "X86ISD::RDSEED";
18005 case X86ISD::FMADD: return "X86ISD::FMADD";
18006 case X86ISD::FMSUB: return "X86ISD::FMSUB";
18007 case X86ISD::FNMADD: return "X86ISD::FNMADD";
18008 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
18009 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
18010 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
18011 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
18012 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
18013 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
18014 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
18015 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
18016 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
18017 case X86ISD::RNDSCALE: return "X86ISD::RNDSCALE";
18018 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
18019 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
18020 case X86ISD::XTEST: return "X86ISD::XTEST";
18021 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
18022 case X86ISD::EXPAND: return "X86ISD::EXPAND";
18023 case X86ISD::SELECT: return "X86ISD::SELECT";
18024 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
18025 case X86ISD::RCP28: return "X86ISD::RCP28";
18026 case X86ISD::EXP2: return "X86ISD::EXP2";
18027 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
18028 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
18029 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
18030 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
18031 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
18032 case X86ISD::ADDS: return "X86ISD::ADDS";
18033 case X86ISD::SUBS: return "X86ISD::SUBS";
18038 // isLegalAddressingMode - Return true if the addressing mode represented
18039 // by AM is legal for this target, for a load/store of the specified type.
18040 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18042 // X86 supports extremely general addressing modes.
18043 CodeModel::Model M = getTargetMachine().getCodeModel();
18044 Reloc::Model R = getTargetMachine().getRelocationModel();
18046 // X86 allows a sign-extended 32-bit immediate field as a displacement.
18047 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18052 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18054 // If a reference to this global requires an extra load, we can't fold it.
18055 if (isGlobalStubReference(GVFlags))
18058 // If BaseGV requires a register for the PIC base, we cannot also have a
18059 // BaseReg specified.
18060 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18063 // If lower 4G is not available, then we must use rip-relative addressing.
18064 if ((M != CodeModel::Small || R != Reloc::Static) &&
18065 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18069 switch (AM.Scale) {
18075 // These scales always work.
18080 // These scales are formed with basereg+scalereg. Only accept if there is
18085 default: // Other stuff never works.
18092 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18093 unsigned Bits = Ty->getScalarSizeInBits();
18095 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18096 // particularly cheaper than those without.
18100 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18101 // variable shifts just as cheap as scalar ones.
18102 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18105 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18106 // fully general vector.
18110 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18111 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18113 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18114 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18115 return NumBits1 > NumBits2;
18118 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18119 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18122 if (!isTypeLegal(EVT::getEVT(Ty1)))
18125 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18127 // Assuming the caller doesn't have a zeroext or signext return parameter,
18128 // truncation all the way down to i1 is valid.
18132 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18133 return isInt<32>(Imm);
18136 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18137 // Can also use sub to handle negated immediates.
18138 return isInt<32>(Imm);
18141 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18142 if (!VT1.isInteger() || !VT2.isInteger())
18144 unsigned NumBits1 = VT1.getSizeInBits();
18145 unsigned NumBits2 = VT2.getSizeInBits();
18146 return NumBits1 > NumBits2;
18149 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18150 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18151 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18154 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18155 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18156 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18159 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18160 EVT VT1 = Val.getValueType();
18161 if (isZExtFree(VT1, VT2))
18164 if (Val.getOpcode() != ISD::LOAD)
18167 if (!VT1.isSimple() || !VT1.isInteger() ||
18168 !VT2.isSimple() || !VT2.isInteger())
18171 switch (VT1.getSimpleVT().SimpleTy) {
18176 // X86 has 8, 16, and 32-bit zero-extending loads.
18183 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18186 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18187 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18190 VT = VT.getScalarType();
18192 if (!VT.isSimple())
18195 switch (VT.getSimpleVT().SimpleTy) {
18206 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18207 // i16 instructions are longer (0x66 prefix) and potentially slower.
18208 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18211 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18212 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18213 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18214 /// are assumed to be legal.
18216 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18218 if (!VT.isSimple())
18221 // Not for i1 vectors
18222 if (VT.getScalarType() == MVT::i1)
18225 // Very little shuffling can be done for 64-bit vectors right now.
18226 if (VT.getSizeInBits() == 64)
18229 // We only care that the types being shuffled are legal. The lowering can
18230 // handle any possible shuffle mask that results.
18231 return isTypeLegal(VT.getSimpleVT());
18235 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18237 // Just delegate to the generic legality, clear masks aren't special.
18238 return isShuffleMaskLegal(Mask, VT);
18241 //===----------------------------------------------------------------------===//
18242 // X86 Scheduler Hooks
18243 //===----------------------------------------------------------------------===//
18245 /// Utility function to emit xbegin specifying the start of an RTM region.
18246 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18247 const TargetInstrInfo *TII) {
18248 DebugLoc DL = MI->getDebugLoc();
18250 const BasicBlock *BB = MBB->getBasicBlock();
18251 MachineFunction::iterator I = MBB;
18254 // For the v = xbegin(), we generate
18265 MachineBasicBlock *thisMBB = MBB;
18266 MachineFunction *MF = MBB->getParent();
18267 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18268 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18269 MF->insert(I, mainMBB);
18270 MF->insert(I, sinkMBB);
18272 // Transfer the remainder of BB and its successor edges to sinkMBB.
18273 sinkMBB->splice(sinkMBB->begin(), MBB,
18274 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18275 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18279 // # fallthrough to mainMBB
18280 // # abortion to sinkMBB
18281 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18282 thisMBB->addSuccessor(mainMBB);
18283 thisMBB->addSuccessor(sinkMBB);
18287 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18288 mainMBB->addSuccessor(sinkMBB);
18291 // EAX is live into the sinkMBB
18292 sinkMBB->addLiveIn(X86::EAX);
18293 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18294 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18297 MI->eraseFromParent();
18301 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18302 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18303 // in the .td file.
18304 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18305 const TargetInstrInfo *TII) {
18307 switch (MI->getOpcode()) {
18308 default: llvm_unreachable("illegal opcode!");
18309 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
18310 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18311 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
18312 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18313 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
18314 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18315 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
18316 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18319 DebugLoc dl = MI->getDebugLoc();
18320 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18322 unsigned NumArgs = MI->getNumOperands();
18323 for (unsigned i = 1; i < NumArgs; ++i) {
18324 MachineOperand &Op = MI->getOperand(i);
18325 if (!(Op.isReg() && Op.isImplicit()))
18326 MIB.addOperand(Op);
18328 if (MI->hasOneMemOperand())
18329 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18331 BuildMI(*BB, MI, dl,
18332 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18333 .addReg(X86::XMM0);
18335 MI->eraseFromParent();
18339 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18340 // defs in an instruction pattern
18341 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18342 const TargetInstrInfo *TII) {
18344 switch (MI->getOpcode()) {
18345 default: llvm_unreachable("illegal opcode!");
18346 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
18347 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18348 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
18349 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18350 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
18351 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18352 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
18353 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18356 DebugLoc dl = MI->getDebugLoc();
18357 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18359 unsigned NumArgs = MI->getNumOperands(); // remove the results
18360 for (unsigned i = 1; i < NumArgs; ++i) {
18361 MachineOperand &Op = MI->getOperand(i);
18362 if (!(Op.isReg() && Op.isImplicit()))
18363 MIB.addOperand(Op);
18365 if (MI->hasOneMemOperand())
18366 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18368 BuildMI(*BB, MI, dl,
18369 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18372 MI->eraseFromParent();
18376 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18377 const X86Subtarget *Subtarget) {
18378 DebugLoc dl = MI->getDebugLoc();
18379 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18380 // Address into RAX/EAX, other two args into ECX, EDX.
18381 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18382 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18383 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18384 for (int i = 0; i < X86::AddrNumOperands; ++i)
18385 MIB.addOperand(MI->getOperand(i));
18387 unsigned ValOps = X86::AddrNumOperands;
18388 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18389 .addReg(MI->getOperand(ValOps).getReg());
18390 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18391 .addReg(MI->getOperand(ValOps+1).getReg());
18393 // The instruction doesn't actually take any operands though.
18394 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18396 MI->eraseFromParent(); // The pseudo is gone now.
18400 MachineBasicBlock *
18401 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18402 MachineBasicBlock *MBB) const {
18403 // Emit va_arg instruction on X86-64.
18405 // Operands to this pseudo-instruction:
18406 // 0 ) Output : destination address (reg)
18407 // 1-5) Input : va_list address (addr, i64mem)
18408 // 6 ) ArgSize : Size (in bytes) of vararg type
18409 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18410 // 8 ) Align : Alignment of type
18411 // 9 ) EFLAGS (implicit-def)
18413 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18414 static_assert(X86::AddrNumOperands == 5,
18415 "VAARG_64 assumes 5 address operands");
18417 unsigned DestReg = MI->getOperand(0).getReg();
18418 MachineOperand &Base = MI->getOperand(1);
18419 MachineOperand &Scale = MI->getOperand(2);
18420 MachineOperand &Index = MI->getOperand(3);
18421 MachineOperand &Disp = MI->getOperand(4);
18422 MachineOperand &Segment = MI->getOperand(5);
18423 unsigned ArgSize = MI->getOperand(6).getImm();
18424 unsigned ArgMode = MI->getOperand(7).getImm();
18425 unsigned Align = MI->getOperand(8).getImm();
18427 // Memory Reference
18428 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18429 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18430 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18432 // Machine Information
18433 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18434 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18435 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18436 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18437 DebugLoc DL = MI->getDebugLoc();
18439 // struct va_list {
18442 // i64 overflow_area (address)
18443 // i64 reg_save_area (address)
18445 // sizeof(va_list) = 24
18446 // alignment(va_list) = 8
18448 unsigned TotalNumIntRegs = 6;
18449 unsigned TotalNumXMMRegs = 8;
18450 bool UseGPOffset = (ArgMode == 1);
18451 bool UseFPOffset = (ArgMode == 2);
18452 unsigned MaxOffset = TotalNumIntRegs * 8 +
18453 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18455 /* Align ArgSize to a multiple of 8 */
18456 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18457 bool NeedsAlign = (Align > 8);
18459 MachineBasicBlock *thisMBB = MBB;
18460 MachineBasicBlock *overflowMBB;
18461 MachineBasicBlock *offsetMBB;
18462 MachineBasicBlock *endMBB;
18464 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
18465 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
18466 unsigned OffsetReg = 0;
18468 if (!UseGPOffset && !UseFPOffset) {
18469 // If we only pull from the overflow region, we don't create a branch.
18470 // We don't need to alter control flow.
18471 OffsetDestReg = 0; // unused
18472 OverflowDestReg = DestReg;
18474 offsetMBB = nullptr;
18475 overflowMBB = thisMBB;
18478 // First emit code to check if gp_offset (or fp_offset) is below the bound.
18479 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18480 // If not, pull from overflow_area. (branch to overflowMBB)
18485 // offsetMBB overflowMBB
18490 // Registers for the PHI in endMBB
18491 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18492 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18494 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18495 MachineFunction *MF = MBB->getParent();
18496 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18497 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18498 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18500 MachineFunction::iterator MBBIter = MBB;
18503 // Insert the new basic blocks
18504 MF->insert(MBBIter, offsetMBB);
18505 MF->insert(MBBIter, overflowMBB);
18506 MF->insert(MBBIter, endMBB);
18508 // Transfer the remainder of MBB and its successor edges to endMBB.
18509 endMBB->splice(endMBB->begin(), thisMBB,
18510 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18511 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18513 // Make offsetMBB and overflowMBB successors of thisMBB
18514 thisMBB->addSuccessor(offsetMBB);
18515 thisMBB->addSuccessor(overflowMBB);
18517 // endMBB is a successor of both offsetMBB and overflowMBB
18518 offsetMBB->addSuccessor(endMBB);
18519 overflowMBB->addSuccessor(endMBB);
18521 // Load the offset value into a register
18522 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18523 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18527 .addDisp(Disp, UseFPOffset ? 4 : 0)
18528 .addOperand(Segment)
18529 .setMemRefs(MMOBegin, MMOEnd);
18531 // Check if there is enough room left to pull this argument.
18532 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18534 .addImm(MaxOffset + 8 - ArgSizeA8);
18536 // Branch to "overflowMBB" if offset >= max
18537 // Fall through to "offsetMBB" otherwise
18538 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18539 .addMBB(overflowMBB);
18542 // In offsetMBB, emit code to use the reg_save_area.
18544 assert(OffsetReg != 0);
18546 // Read the reg_save_area address.
18547 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18548 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18553 .addOperand(Segment)
18554 .setMemRefs(MMOBegin, MMOEnd);
18556 // Zero-extend the offset
18557 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18558 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18561 .addImm(X86::sub_32bit);
18563 // Add the offset to the reg_save_area to get the final address.
18564 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18565 .addReg(OffsetReg64)
18566 .addReg(RegSaveReg);
18568 // Compute the offset for the next argument
18569 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18570 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18572 .addImm(UseFPOffset ? 16 : 8);
18574 // Store it back into the va_list.
18575 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18579 .addDisp(Disp, UseFPOffset ? 4 : 0)
18580 .addOperand(Segment)
18581 .addReg(NextOffsetReg)
18582 .setMemRefs(MMOBegin, MMOEnd);
18585 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18590 // Emit code to use overflow area
18593 // Load the overflow_area address into a register.
18594 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18595 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18600 .addOperand(Segment)
18601 .setMemRefs(MMOBegin, MMOEnd);
18603 // If we need to align it, do so. Otherwise, just copy the address
18604 // to OverflowDestReg.
18606 // Align the overflow address
18607 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18608 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18610 // aligned_addr = (addr + (align-1)) & ~(align-1)
18611 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18612 .addReg(OverflowAddrReg)
18615 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18617 .addImm(~(uint64_t)(Align-1));
18619 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18620 .addReg(OverflowAddrReg);
18623 // Compute the next overflow address after this argument.
18624 // (the overflow address should be kept 8-byte aligned)
18625 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18626 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18627 .addReg(OverflowDestReg)
18628 .addImm(ArgSizeA8);
18630 // Store the new overflow address.
18631 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18636 .addOperand(Segment)
18637 .addReg(NextAddrReg)
18638 .setMemRefs(MMOBegin, MMOEnd);
18640 // If we branched, emit the PHI to the front of endMBB.
18642 BuildMI(*endMBB, endMBB->begin(), DL,
18643 TII->get(X86::PHI), DestReg)
18644 .addReg(OffsetDestReg).addMBB(offsetMBB)
18645 .addReg(OverflowDestReg).addMBB(overflowMBB);
18648 // Erase the pseudo instruction
18649 MI->eraseFromParent();
18654 MachineBasicBlock *
18655 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18657 MachineBasicBlock *MBB) const {
18658 // Emit code to save XMM registers to the stack. The ABI says that the
18659 // number of registers to save is given in %al, so it's theoretically
18660 // possible to do an indirect jump trick to avoid saving all of them,
18661 // however this code takes a simpler approach and just executes all
18662 // of the stores if %al is non-zero. It's less code, and it's probably
18663 // easier on the hardware branch predictor, and stores aren't all that
18664 // expensive anyway.
18666 // Create the new basic blocks. One block contains all the XMM stores,
18667 // and one block is the final destination regardless of whether any
18668 // stores were performed.
18669 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18670 MachineFunction *F = MBB->getParent();
18671 MachineFunction::iterator MBBIter = MBB;
18673 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18674 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18675 F->insert(MBBIter, XMMSaveMBB);
18676 F->insert(MBBIter, EndMBB);
18678 // Transfer the remainder of MBB and its successor edges to EndMBB.
18679 EndMBB->splice(EndMBB->begin(), MBB,
18680 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18681 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18683 // The original block will now fall through to the XMM save block.
18684 MBB->addSuccessor(XMMSaveMBB);
18685 // The XMMSaveMBB will fall through to the end block.
18686 XMMSaveMBB->addSuccessor(EndMBB);
18688 // Now add the instructions.
18689 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18690 DebugLoc DL = MI->getDebugLoc();
18692 unsigned CountReg = MI->getOperand(0).getReg();
18693 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18694 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18696 if (!Subtarget->isTargetWin64()) {
18697 // If %al is 0, branch around the XMM save block.
18698 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18699 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18700 MBB->addSuccessor(EndMBB);
18703 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18704 // that was just emitted, but clearly shouldn't be "saved".
18705 assert((MI->getNumOperands() <= 3 ||
18706 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18707 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18708 && "Expected last argument to be EFLAGS");
18709 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18710 // In the XMM save block, save all the XMM argument registers.
18711 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18712 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18713 MachineMemOperand *MMO =
18714 F->getMachineMemOperand(
18715 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18716 MachineMemOperand::MOStore,
18717 /*Size=*/16, /*Align=*/16);
18718 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18719 .addFrameIndex(RegSaveFrameIndex)
18720 .addImm(/*Scale=*/1)
18721 .addReg(/*IndexReg=*/0)
18722 .addImm(/*Disp=*/Offset)
18723 .addReg(/*Segment=*/0)
18724 .addReg(MI->getOperand(i).getReg())
18725 .addMemOperand(MMO);
18728 MI->eraseFromParent(); // The pseudo instruction is gone now.
18733 // The EFLAGS operand of SelectItr might be missing a kill marker
18734 // because there were multiple uses of EFLAGS, and ISel didn't know
18735 // which to mark. Figure out whether SelectItr should have had a
18736 // kill marker, and set it if it should. Returns the correct kill
18738 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18739 MachineBasicBlock* BB,
18740 const TargetRegisterInfo* TRI) {
18741 // Scan forward through BB for a use/def of EFLAGS.
18742 MachineBasicBlock::iterator miI(std::next(SelectItr));
18743 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18744 const MachineInstr& mi = *miI;
18745 if (mi.readsRegister(X86::EFLAGS))
18747 if (mi.definesRegister(X86::EFLAGS))
18748 break; // Should have kill-flag - update below.
18751 // If we hit the end of the block, check whether EFLAGS is live into a
18753 if (miI == BB->end()) {
18754 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18755 sEnd = BB->succ_end();
18756 sItr != sEnd; ++sItr) {
18757 MachineBasicBlock* succ = *sItr;
18758 if (succ->isLiveIn(X86::EFLAGS))
18763 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18764 // out. SelectMI should have a kill flag on EFLAGS.
18765 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18769 MachineBasicBlock *
18770 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18771 MachineBasicBlock *BB) const {
18772 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18773 DebugLoc DL = MI->getDebugLoc();
18775 // To "insert" a SELECT_CC instruction, we actually have to insert the
18776 // diamond control-flow pattern. The incoming instruction knows the
18777 // destination vreg to set, the condition code register to branch on, the
18778 // true/false values to select between, and a branch opcode to use.
18779 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18780 MachineFunction::iterator It = BB;
18786 // cmpTY ccX, r1, r2
18788 // fallthrough --> copy0MBB
18789 MachineBasicBlock *thisMBB = BB;
18790 MachineFunction *F = BB->getParent();
18792 // We also lower double CMOVs:
18793 // (CMOV (CMOV F, T, cc1), T, cc2)
18794 // to two successives branches. For that, we look for another CMOV as the
18795 // following instruction.
18797 // Without this, we would add a PHI between the two jumps, which ends up
18798 // creating a few copies all around. For instance, for
18800 // (sitofp (zext (fcmp une)))
18802 // we would generate:
18804 // ucomiss %xmm1, %xmm0
18805 // movss <1.0f>, %xmm0
18806 // movaps %xmm0, %xmm1
18808 // xorps %xmm1, %xmm1
18811 // movaps %xmm1, %xmm0
18815 // because this custom-inserter would have generated:
18827 // A: X = ...; Y = ...
18829 // C: Z = PHI [X, A], [Y, B]
18831 // E: PHI [X, C], [Z, D]
18833 // If we lower both CMOVs in a single step, we can instead generate:
18845 // A: X = ...; Y = ...
18847 // E: PHI [X, A], [X, C], [Y, D]
18849 // Which, in our sitofp/fcmp example, gives us something like:
18851 // ucomiss %xmm1, %xmm0
18852 // movss <1.0f>, %xmm0
18855 // xorps %xmm0, %xmm0
18859 MachineInstr *NextCMOV = nullptr;
18860 MachineBasicBlock::iterator NextMIIt =
18861 std::next(MachineBasicBlock::iterator(MI));
18862 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18863 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18864 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18865 NextCMOV = &*NextMIIt;
18867 MachineBasicBlock *jcc1MBB = nullptr;
18869 // If we have a double CMOV, we lower it to two successive branches to
18870 // the same block. EFLAGS is used by both, so mark it as live in the second.
18872 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18873 F->insert(It, jcc1MBB);
18874 jcc1MBB->addLiveIn(X86::EFLAGS);
18877 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18878 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18879 F->insert(It, copy0MBB);
18880 F->insert(It, sinkMBB);
18882 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18883 // live into the sink and copy blocks.
18884 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18886 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18887 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18888 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18889 copy0MBB->addLiveIn(X86::EFLAGS);
18890 sinkMBB->addLiveIn(X86::EFLAGS);
18893 // Transfer the remainder of BB and its successor edges to sinkMBB.
18894 sinkMBB->splice(sinkMBB->begin(), BB,
18895 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18896 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18898 // Add the true and fallthrough blocks as its successors.
18900 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18901 BB->addSuccessor(jcc1MBB);
18903 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18904 // jump to the sinkMBB.
18905 jcc1MBB->addSuccessor(copy0MBB);
18906 jcc1MBB->addSuccessor(sinkMBB);
18908 BB->addSuccessor(copy0MBB);
18911 // The true block target of the first (or only) branch is always sinkMBB.
18912 BB->addSuccessor(sinkMBB);
18914 // Create the conditional branch instruction.
18916 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18917 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18920 unsigned Opc2 = X86::GetCondBranchFromCond(
18921 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18922 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18926 // %FalseValue = ...
18927 // # fallthrough to sinkMBB
18928 copy0MBB->addSuccessor(sinkMBB);
18931 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18933 MachineInstrBuilder MIB =
18934 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18935 MI->getOperand(0).getReg())
18936 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18937 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18939 // If we have a double CMOV, the second Jcc provides the same incoming
18940 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18942 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18943 // Copy the PHI result to the register defined by the second CMOV.
18944 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18945 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18946 .addReg(MI->getOperand(0).getReg());
18947 NextCMOV->eraseFromParent();
18950 MI->eraseFromParent(); // The pseudo instruction is gone now.
18954 MachineBasicBlock *
18955 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18956 MachineBasicBlock *BB) const {
18957 MachineFunction *MF = BB->getParent();
18958 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18959 DebugLoc DL = MI->getDebugLoc();
18960 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18962 assert(MF->shouldSplitStack());
18964 const bool Is64Bit = Subtarget->is64Bit();
18965 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18967 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18968 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18971 // ... [Till the alloca]
18972 // If stacklet is not large enough, jump to mallocMBB
18975 // Allocate by subtracting from RSP
18976 // Jump to continueMBB
18979 // Allocate by call to runtime
18983 // [rest of original BB]
18986 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18987 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18988 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18990 MachineRegisterInfo &MRI = MF->getRegInfo();
18991 const TargetRegisterClass *AddrRegClass =
18992 getRegClassFor(getPointerTy());
18994 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18995 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18996 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18997 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18998 sizeVReg = MI->getOperand(1).getReg(),
18999 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19001 MachineFunction::iterator MBBIter = BB;
19004 MF->insert(MBBIter, bumpMBB);
19005 MF->insert(MBBIter, mallocMBB);
19006 MF->insert(MBBIter, continueMBB);
19008 continueMBB->splice(continueMBB->begin(), BB,
19009 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19010 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19012 // Add code to the main basic block to check if the stack limit has been hit,
19013 // and if so, jump to mallocMBB otherwise to bumpMBB.
19014 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19015 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19016 .addReg(tmpSPVReg).addReg(sizeVReg);
19017 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19018 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19019 .addReg(SPLimitVReg);
19020 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19022 // bumpMBB simply decreases the stack pointer, since we know the current
19023 // stacklet has enough space.
19024 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19025 .addReg(SPLimitVReg);
19026 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19027 .addReg(SPLimitVReg);
19028 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19030 // Calls into a routine in libgcc to allocate more space from the heap.
19031 const uint32_t *RegMask =
19032 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19034 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19036 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19037 .addExternalSymbol("__morestack_allocate_stack_space")
19038 .addRegMask(RegMask)
19039 .addReg(X86::RDI, RegState::Implicit)
19040 .addReg(X86::RAX, RegState::ImplicitDefine);
19041 } else if (Is64Bit) {
19042 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19044 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19045 .addExternalSymbol("__morestack_allocate_stack_space")
19046 .addRegMask(RegMask)
19047 .addReg(X86::EDI, RegState::Implicit)
19048 .addReg(X86::EAX, RegState::ImplicitDefine);
19050 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19052 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19053 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19054 .addExternalSymbol("__morestack_allocate_stack_space")
19055 .addRegMask(RegMask)
19056 .addReg(X86::EAX, RegState::ImplicitDefine);
19060 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19063 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19064 .addReg(IsLP64 ? X86::RAX : X86::EAX);
19065 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19067 // Set up the CFG correctly.
19068 BB->addSuccessor(bumpMBB);
19069 BB->addSuccessor(mallocMBB);
19070 mallocMBB->addSuccessor(continueMBB);
19071 bumpMBB->addSuccessor(continueMBB);
19073 // Take care of the PHI nodes.
19074 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19075 MI->getOperand(0).getReg())
19076 .addReg(mallocPtrVReg).addMBB(mallocMBB)
19077 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19079 // Delete the original pseudo instruction.
19080 MI->eraseFromParent();
19083 return continueMBB;
19086 MachineBasicBlock *
19087 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19088 MachineBasicBlock *BB) const {
19089 DebugLoc DL = MI->getDebugLoc();
19091 assert(!Subtarget->isTargetMachO());
19093 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19095 MI->eraseFromParent(); // The pseudo instruction is gone now.
19099 MachineBasicBlock *
19100 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19101 MachineBasicBlock *BB) const {
19102 // This is pretty easy. We're taking the value that we received from
19103 // our load from the relocation, sticking it in either RDI (x86-64)
19104 // or EAX and doing an indirect call. The return value will then
19105 // be in the normal return register.
19106 MachineFunction *F = BB->getParent();
19107 const X86InstrInfo *TII = Subtarget->getInstrInfo();
19108 DebugLoc DL = MI->getDebugLoc();
19110 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19111 assert(MI->getOperand(3).isGlobal() && "This should be a global");
19113 // Get a register mask for the lowered call.
19114 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19115 // proper register mask.
19116 const uint32_t *RegMask =
19117 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19118 if (Subtarget->is64Bit()) {
19119 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19120 TII->get(X86::MOV64rm), X86::RDI)
19122 .addImm(0).addReg(0)
19123 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19124 MI->getOperand(3).getTargetFlags())
19126 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19127 addDirectMem(MIB, X86::RDI);
19128 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19129 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19130 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19131 TII->get(X86::MOV32rm), X86::EAX)
19133 .addImm(0).addReg(0)
19134 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19135 MI->getOperand(3).getTargetFlags())
19137 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19138 addDirectMem(MIB, X86::EAX);
19139 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19141 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19142 TII->get(X86::MOV32rm), X86::EAX)
19143 .addReg(TII->getGlobalBaseReg(F))
19144 .addImm(0).addReg(0)
19145 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19146 MI->getOperand(3).getTargetFlags())
19148 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19149 addDirectMem(MIB, X86::EAX);
19150 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19153 MI->eraseFromParent(); // The pseudo instruction is gone now.
19157 MachineBasicBlock *
19158 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19159 MachineBasicBlock *MBB) const {
19160 DebugLoc DL = MI->getDebugLoc();
19161 MachineFunction *MF = MBB->getParent();
19162 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19163 MachineRegisterInfo &MRI = MF->getRegInfo();
19165 const BasicBlock *BB = MBB->getBasicBlock();
19166 MachineFunction::iterator I = MBB;
19169 // Memory Reference
19170 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19171 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19174 unsigned MemOpndSlot = 0;
19176 unsigned CurOp = 0;
19178 DstReg = MI->getOperand(CurOp++).getReg();
19179 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19180 assert(RC->hasType(MVT::i32) && "Invalid destination!");
19181 unsigned mainDstReg = MRI.createVirtualRegister(RC);
19182 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19184 MemOpndSlot = CurOp;
19186 MVT PVT = getPointerTy();
19187 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19188 "Invalid Pointer Size!");
19190 // For v = setjmp(buf), we generate
19193 // buf[LabelOffset] = restoreMBB
19194 // SjLjSetup restoreMBB
19200 // v = phi(main, restore)
19203 // if base pointer being used, load it from frame
19206 MachineBasicBlock *thisMBB = MBB;
19207 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19208 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19209 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19210 MF->insert(I, mainMBB);
19211 MF->insert(I, sinkMBB);
19212 MF->push_back(restoreMBB);
19214 MachineInstrBuilder MIB;
19216 // Transfer the remainder of BB and its successor edges to sinkMBB.
19217 sinkMBB->splice(sinkMBB->begin(), MBB,
19218 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19219 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19222 unsigned PtrStoreOpc = 0;
19223 unsigned LabelReg = 0;
19224 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19225 Reloc::Model RM = MF->getTarget().getRelocationModel();
19226 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19227 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19229 // Prepare IP either in reg or imm.
19230 if (!UseImmLabel) {
19231 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19232 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19233 LabelReg = MRI.createVirtualRegister(PtrRC);
19234 if (Subtarget->is64Bit()) {
19235 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19239 .addMBB(restoreMBB)
19242 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19243 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19244 .addReg(XII->getGlobalBaseReg(MF))
19247 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19251 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19253 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19254 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19255 if (i == X86::AddrDisp)
19256 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19258 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19261 MIB.addReg(LabelReg);
19263 MIB.addMBB(restoreMBB);
19264 MIB.setMemRefs(MMOBegin, MMOEnd);
19266 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19267 .addMBB(restoreMBB);
19269 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19270 MIB.addRegMask(RegInfo->getNoPreservedMask());
19271 thisMBB->addSuccessor(mainMBB);
19272 thisMBB->addSuccessor(restoreMBB);
19276 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19277 mainMBB->addSuccessor(sinkMBB);
19280 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19281 TII->get(X86::PHI), DstReg)
19282 .addReg(mainDstReg).addMBB(mainMBB)
19283 .addReg(restoreDstReg).addMBB(restoreMBB);
19286 if (RegInfo->hasBasePointer(*MF)) {
19287 const bool Uses64BitFramePtr =
19288 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19289 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19290 X86FI->setRestoreBasePointer(MF);
19291 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19292 unsigned BasePtr = RegInfo->getBaseRegister();
19293 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19294 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19295 FramePtr, true, X86FI->getRestoreBasePointerOffset())
19296 .setMIFlag(MachineInstr::FrameSetup);
19298 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19299 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19300 restoreMBB->addSuccessor(sinkMBB);
19302 MI->eraseFromParent();
19306 MachineBasicBlock *
19307 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19308 MachineBasicBlock *MBB) const {
19309 DebugLoc DL = MI->getDebugLoc();
19310 MachineFunction *MF = MBB->getParent();
19311 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19312 MachineRegisterInfo &MRI = MF->getRegInfo();
19314 // Memory Reference
19315 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19316 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19318 MVT PVT = getPointerTy();
19319 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19320 "Invalid Pointer Size!");
19322 const TargetRegisterClass *RC =
19323 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19324 unsigned Tmp = MRI.createVirtualRegister(RC);
19325 // Since FP is only updated here but NOT referenced, it's treated as GPR.
19326 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19327 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19328 unsigned SP = RegInfo->getStackRegister();
19330 MachineInstrBuilder MIB;
19332 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19333 const int64_t SPOffset = 2 * PVT.getStoreSize();
19335 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19336 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19339 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19340 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19341 MIB.addOperand(MI->getOperand(i));
19342 MIB.setMemRefs(MMOBegin, MMOEnd);
19344 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19345 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19346 if (i == X86::AddrDisp)
19347 MIB.addDisp(MI->getOperand(i), LabelOffset);
19349 MIB.addOperand(MI->getOperand(i));
19351 MIB.setMemRefs(MMOBegin, MMOEnd);
19353 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19354 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19355 if (i == X86::AddrDisp)
19356 MIB.addDisp(MI->getOperand(i), SPOffset);
19358 MIB.addOperand(MI->getOperand(i));
19360 MIB.setMemRefs(MMOBegin, MMOEnd);
19362 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19364 MI->eraseFromParent();
19368 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19369 // accumulator loops. Writing back to the accumulator allows the coalescer
19370 // to remove extra copies in the loop.
19371 MachineBasicBlock *
19372 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19373 MachineBasicBlock *MBB) const {
19374 MachineOperand &AddendOp = MI->getOperand(3);
19376 // Bail out early if the addend isn't a register - we can't switch these.
19377 if (!AddendOp.isReg())
19380 MachineFunction &MF = *MBB->getParent();
19381 MachineRegisterInfo &MRI = MF.getRegInfo();
19383 // Check whether the addend is defined by a PHI:
19384 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19385 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19386 if (!AddendDef.isPHI())
19389 // Look for the following pattern:
19391 // %addend = phi [%entry, 0], [%loop, %result]
19393 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19397 // %addend = phi [%entry, 0], [%loop, %result]
19399 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19401 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19402 assert(AddendDef.getOperand(i).isReg());
19403 MachineOperand PHISrcOp = AddendDef.getOperand(i);
19404 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19405 if (&PHISrcInst == MI) {
19406 // Found a matching instruction.
19407 unsigned NewFMAOpc = 0;
19408 switch (MI->getOpcode()) {
19409 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19410 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19411 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19412 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19413 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19414 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19415 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19416 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19417 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19418 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19419 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19420 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19421 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19422 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19423 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19424 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19425 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19426 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19427 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19428 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19430 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19431 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19432 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19433 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19434 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19435 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19436 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19437 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19438 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19439 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19440 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19441 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19442 default: llvm_unreachable("Unrecognized FMA variant.");
19445 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19446 MachineInstrBuilder MIB =
19447 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19448 .addOperand(MI->getOperand(0))
19449 .addOperand(MI->getOperand(3))
19450 .addOperand(MI->getOperand(2))
19451 .addOperand(MI->getOperand(1));
19452 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19453 MI->eraseFromParent();
19460 MachineBasicBlock *
19461 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19462 MachineBasicBlock *BB) const {
19463 switch (MI->getOpcode()) {
19464 default: llvm_unreachable("Unexpected instr type to insert");
19465 case X86::TAILJMPd64:
19466 case X86::TAILJMPr64:
19467 case X86::TAILJMPm64:
19468 case X86::TAILJMPd64_REX:
19469 case X86::TAILJMPr64_REX:
19470 case X86::TAILJMPm64_REX:
19471 llvm_unreachable("TAILJMP64 would not be touched here.");
19472 case X86::TCRETURNdi64:
19473 case X86::TCRETURNri64:
19474 case X86::TCRETURNmi64:
19476 case X86::WIN_ALLOCA:
19477 return EmitLoweredWinAlloca(MI, BB);
19478 case X86::SEG_ALLOCA_32:
19479 case X86::SEG_ALLOCA_64:
19480 return EmitLoweredSegAlloca(MI, BB);
19481 case X86::TLSCall_32:
19482 case X86::TLSCall_64:
19483 return EmitLoweredTLSCall(MI, BB);
19484 case X86::CMOV_GR8:
19485 case X86::CMOV_FR32:
19486 case X86::CMOV_FR64:
19487 case X86::CMOV_V4F32:
19488 case X86::CMOV_V2F64:
19489 case X86::CMOV_V2I64:
19490 case X86::CMOV_V8F32:
19491 case X86::CMOV_V4F64:
19492 case X86::CMOV_V4I64:
19493 case X86::CMOV_V16F32:
19494 case X86::CMOV_V8F64:
19495 case X86::CMOV_V8I64:
19496 case X86::CMOV_GR16:
19497 case X86::CMOV_GR32:
19498 case X86::CMOV_RFP32:
19499 case X86::CMOV_RFP64:
19500 case X86::CMOV_RFP80:
19501 case X86::CMOV_V8I1:
19502 case X86::CMOV_V16I1:
19503 case X86::CMOV_V32I1:
19504 case X86::CMOV_V64I1:
19505 return EmitLoweredSelect(MI, BB);
19507 case X86::FP32_TO_INT16_IN_MEM:
19508 case X86::FP32_TO_INT32_IN_MEM:
19509 case X86::FP32_TO_INT64_IN_MEM:
19510 case X86::FP64_TO_INT16_IN_MEM:
19511 case X86::FP64_TO_INT32_IN_MEM:
19512 case X86::FP64_TO_INT64_IN_MEM:
19513 case X86::FP80_TO_INT16_IN_MEM:
19514 case X86::FP80_TO_INT32_IN_MEM:
19515 case X86::FP80_TO_INT64_IN_MEM: {
19516 MachineFunction *F = BB->getParent();
19517 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19518 DebugLoc DL = MI->getDebugLoc();
19520 // Change the floating point control register to use "round towards zero"
19521 // mode when truncating to an integer value.
19522 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19523 addFrameReference(BuildMI(*BB, MI, DL,
19524 TII->get(X86::FNSTCW16m)), CWFrameIdx);
19526 // Load the old value of the high byte of the control word...
19528 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19529 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19532 // Set the high part to be round to zero...
19533 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19536 // Reload the modified control word now...
19537 addFrameReference(BuildMI(*BB, MI, DL,
19538 TII->get(X86::FLDCW16m)), CWFrameIdx);
19540 // Restore the memory image of control word to original value
19541 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19544 // Get the X86 opcode to use.
19546 switch (MI->getOpcode()) {
19547 default: llvm_unreachable("illegal opcode!");
19548 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19549 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19550 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19551 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19552 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19553 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19554 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19555 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19556 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19560 MachineOperand &Op = MI->getOperand(0);
19562 AM.BaseType = X86AddressMode::RegBase;
19563 AM.Base.Reg = Op.getReg();
19565 AM.BaseType = X86AddressMode::FrameIndexBase;
19566 AM.Base.FrameIndex = Op.getIndex();
19568 Op = MI->getOperand(1);
19570 AM.Scale = Op.getImm();
19571 Op = MI->getOperand(2);
19573 AM.IndexReg = Op.getImm();
19574 Op = MI->getOperand(3);
19575 if (Op.isGlobal()) {
19576 AM.GV = Op.getGlobal();
19578 AM.Disp = Op.getImm();
19580 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19581 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19583 // Reload the original control word now.
19584 addFrameReference(BuildMI(*BB, MI, DL,
19585 TII->get(X86::FLDCW16m)), CWFrameIdx);
19587 MI->eraseFromParent(); // The pseudo instruction is gone now.
19590 // String/text processing lowering.
19591 case X86::PCMPISTRM128REG:
19592 case X86::VPCMPISTRM128REG:
19593 case X86::PCMPISTRM128MEM:
19594 case X86::VPCMPISTRM128MEM:
19595 case X86::PCMPESTRM128REG:
19596 case X86::VPCMPESTRM128REG:
19597 case X86::PCMPESTRM128MEM:
19598 case X86::VPCMPESTRM128MEM:
19599 assert(Subtarget->hasSSE42() &&
19600 "Target must have SSE4.2 or AVX features enabled");
19601 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19603 // String/text processing lowering.
19604 case X86::PCMPISTRIREG:
19605 case X86::VPCMPISTRIREG:
19606 case X86::PCMPISTRIMEM:
19607 case X86::VPCMPISTRIMEM:
19608 case X86::PCMPESTRIREG:
19609 case X86::VPCMPESTRIREG:
19610 case X86::PCMPESTRIMEM:
19611 case X86::VPCMPESTRIMEM:
19612 assert(Subtarget->hasSSE42() &&
19613 "Target must have SSE4.2 or AVX features enabled");
19614 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19616 // Thread synchronization.
19618 return EmitMonitor(MI, BB, Subtarget);
19622 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19624 case X86::VASTART_SAVE_XMM_REGS:
19625 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19627 case X86::VAARG_64:
19628 return EmitVAARG64WithCustomInserter(MI, BB);
19630 case X86::EH_SjLj_SetJmp32:
19631 case X86::EH_SjLj_SetJmp64:
19632 return emitEHSjLjSetJmp(MI, BB);
19634 case X86::EH_SjLj_LongJmp32:
19635 case X86::EH_SjLj_LongJmp64:
19636 return emitEHSjLjLongJmp(MI, BB);
19638 case TargetOpcode::STATEPOINT:
19639 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19640 // this point in the process. We diverge later.
19641 return emitPatchPoint(MI, BB);
19643 case TargetOpcode::STACKMAP:
19644 case TargetOpcode::PATCHPOINT:
19645 return emitPatchPoint(MI, BB);
19647 case X86::VFMADDPDr213r:
19648 case X86::VFMADDPSr213r:
19649 case X86::VFMADDSDr213r:
19650 case X86::VFMADDSSr213r:
19651 case X86::VFMSUBPDr213r:
19652 case X86::VFMSUBPSr213r:
19653 case X86::VFMSUBSDr213r:
19654 case X86::VFMSUBSSr213r:
19655 case X86::VFNMADDPDr213r:
19656 case X86::VFNMADDPSr213r:
19657 case X86::VFNMADDSDr213r:
19658 case X86::VFNMADDSSr213r:
19659 case X86::VFNMSUBPDr213r:
19660 case X86::VFNMSUBPSr213r:
19661 case X86::VFNMSUBSDr213r:
19662 case X86::VFNMSUBSSr213r:
19663 case X86::VFMADDSUBPDr213r:
19664 case X86::VFMADDSUBPSr213r:
19665 case X86::VFMSUBADDPDr213r:
19666 case X86::VFMSUBADDPSr213r:
19667 case X86::VFMADDPDr213rY:
19668 case X86::VFMADDPSr213rY:
19669 case X86::VFMSUBPDr213rY:
19670 case X86::VFMSUBPSr213rY:
19671 case X86::VFNMADDPDr213rY:
19672 case X86::VFNMADDPSr213rY:
19673 case X86::VFNMSUBPDr213rY:
19674 case X86::VFNMSUBPSr213rY:
19675 case X86::VFMADDSUBPDr213rY:
19676 case X86::VFMADDSUBPSr213rY:
19677 case X86::VFMSUBADDPDr213rY:
19678 case X86::VFMSUBADDPSr213rY:
19679 return emitFMA3Instr(MI, BB);
19683 //===----------------------------------------------------------------------===//
19684 // X86 Optimization Hooks
19685 //===----------------------------------------------------------------------===//
19687 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19690 const SelectionDAG &DAG,
19691 unsigned Depth) const {
19692 unsigned BitWidth = KnownZero.getBitWidth();
19693 unsigned Opc = Op.getOpcode();
19694 assert((Opc >= ISD::BUILTIN_OP_END ||
19695 Opc == ISD::INTRINSIC_WO_CHAIN ||
19696 Opc == ISD::INTRINSIC_W_CHAIN ||
19697 Opc == ISD::INTRINSIC_VOID) &&
19698 "Should use MaskedValueIsZero if you don't know whether Op"
19699 " is a target node!");
19701 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19715 // These nodes' second result is a boolean.
19716 if (Op.getResNo() == 0)
19719 case X86ISD::SETCC:
19720 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19722 case ISD::INTRINSIC_WO_CHAIN: {
19723 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19724 unsigned NumLoBits = 0;
19727 case Intrinsic::x86_sse_movmsk_ps:
19728 case Intrinsic::x86_avx_movmsk_ps_256:
19729 case Intrinsic::x86_sse2_movmsk_pd:
19730 case Intrinsic::x86_avx_movmsk_pd_256:
19731 case Intrinsic::x86_mmx_pmovmskb:
19732 case Intrinsic::x86_sse2_pmovmskb_128:
19733 case Intrinsic::x86_avx2_pmovmskb: {
19734 // High bits of movmskp{s|d}, pmovmskb are known zero.
19736 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19737 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19738 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19739 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19740 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19741 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19742 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19743 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19745 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19754 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19756 const SelectionDAG &,
19757 unsigned Depth) const {
19758 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19759 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19760 return Op.getValueType().getScalarType().getSizeInBits();
19766 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19767 /// node is a GlobalAddress + offset.
19768 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19769 const GlobalValue* &GA,
19770 int64_t &Offset) const {
19771 if (N->getOpcode() == X86ISD::Wrapper) {
19772 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19773 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19774 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19778 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19781 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19782 /// same as extracting the high 128-bit part of 256-bit vector and then
19783 /// inserting the result into the low part of a new 256-bit vector
19784 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19785 EVT VT = SVOp->getValueType(0);
19786 unsigned NumElems = VT.getVectorNumElements();
19788 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19789 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19790 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19791 SVOp->getMaskElt(j) >= 0)
19797 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19798 /// same as extracting the low 128-bit part of 256-bit vector and then
19799 /// inserting the result into the high part of a new 256-bit vector
19800 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19801 EVT VT = SVOp->getValueType(0);
19802 unsigned NumElems = VT.getVectorNumElements();
19804 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19805 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19806 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19807 SVOp->getMaskElt(j) >= 0)
19813 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19814 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19815 TargetLowering::DAGCombinerInfo &DCI,
19816 const X86Subtarget* Subtarget) {
19818 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19819 SDValue V1 = SVOp->getOperand(0);
19820 SDValue V2 = SVOp->getOperand(1);
19821 EVT VT = SVOp->getValueType(0);
19822 unsigned NumElems = VT.getVectorNumElements();
19824 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19825 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19829 // V UNDEF BUILD_VECTOR UNDEF
19831 // CONCAT_VECTOR CONCAT_VECTOR
19834 // RESULT: V + zero extended
19836 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19837 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19838 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19841 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19844 // To match the shuffle mask, the first half of the mask should
19845 // be exactly the first vector, and all the rest a splat with the
19846 // first element of the second one.
19847 for (unsigned i = 0; i != NumElems/2; ++i)
19848 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19849 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19852 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19853 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19854 if (Ld->hasNUsesOfValue(1, 0)) {
19855 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19856 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19858 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19860 Ld->getPointerInfo(),
19861 Ld->getAlignment(),
19862 false/*isVolatile*/, true/*ReadMem*/,
19863 false/*WriteMem*/);
19865 // Make sure the newly-created LOAD is in the same position as Ld in
19866 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19867 // and update uses of Ld's output chain to use the TokenFactor.
19868 if (Ld->hasAnyUseOfValue(1)) {
19869 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19870 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19871 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19872 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19873 SDValue(ResNode.getNode(), 1));
19876 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19880 // Emit a zeroed vector and insert the desired subvector on its
19882 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19883 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19884 return DCI.CombineTo(N, InsV);
19887 //===--------------------------------------------------------------------===//
19888 // Combine some shuffles into subvector extracts and inserts:
19891 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19892 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19893 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19894 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19895 return DCI.CombineTo(N, InsV);
19898 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19899 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19900 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19901 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19902 return DCI.CombineTo(N, InsV);
19908 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19911 /// This is the leaf of the recursive combinine below. When we have found some
19912 /// chain of single-use x86 shuffle instructions and accumulated the combined
19913 /// shuffle mask represented by them, this will try to pattern match that mask
19914 /// into either a single instruction if there is a special purpose instruction
19915 /// for this operation, or into a PSHUFB instruction which is a fully general
19916 /// instruction but should only be used to replace chains over a certain depth.
19917 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19918 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19919 TargetLowering::DAGCombinerInfo &DCI,
19920 const X86Subtarget *Subtarget) {
19921 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19923 // Find the operand that enters the chain. Note that multiple uses are OK
19924 // here, we're not going to remove the operand we find.
19925 SDValue Input = Op.getOperand(0);
19926 while (Input.getOpcode() == ISD::BITCAST)
19927 Input = Input.getOperand(0);
19929 MVT VT = Input.getSimpleValueType();
19930 MVT RootVT = Root.getSimpleValueType();
19933 // Just remove no-op shuffle masks.
19934 if (Mask.size() == 1) {
19935 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19940 // Use the float domain if the operand type is a floating point type.
19941 bool FloatDomain = VT.isFloatingPoint();
19943 // For floating point shuffles, we don't have free copies in the shuffle
19944 // instructions or the ability to load as part of the instruction, so
19945 // canonicalize their shuffles to UNPCK or MOV variants.
19947 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19948 // vectors because it can have a load folded into it that UNPCK cannot. This
19949 // doesn't preclude something switching to the shorter encoding post-RA.
19951 // FIXME: Should teach these routines about AVX vector widths.
19952 if (FloatDomain && VT.getSizeInBits() == 128) {
19953 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19954 bool Lo = Mask.equals({0, 0});
19957 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19958 // is no slower than UNPCKLPD but has the option to fold the input operand
19959 // into even an unaligned memory load.
19960 if (Lo && Subtarget->hasSSE3()) {
19961 Shuffle = X86ISD::MOVDDUP;
19962 ShuffleVT = MVT::v2f64;
19964 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19965 // than the UNPCK variants.
19966 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19967 ShuffleVT = MVT::v4f32;
19969 if (Depth == 1 && Root->getOpcode() == Shuffle)
19970 return false; // Nothing to do!
19971 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19972 DCI.AddToWorklist(Op.getNode());
19973 if (Shuffle == X86ISD::MOVDDUP)
19974 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19976 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19977 DCI.AddToWorklist(Op.getNode());
19978 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19982 if (Subtarget->hasSSE3() &&
19983 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19984 bool Lo = Mask.equals({0, 0, 2, 2});
19985 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19986 MVT ShuffleVT = MVT::v4f32;
19987 if (Depth == 1 && Root->getOpcode() == Shuffle)
19988 return false; // Nothing to do!
19989 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19990 DCI.AddToWorklist(Op.getNode());
19991 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19992 DCI.AddToWorklist(Op.getNode());
19993 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19997 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19998 bool Lo = Mask.equals({0, 0, 1, 1});
19999 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20000 MVT ShuffleVT = MVT::v4f32;
20001 if (Depth == 1 && Root->getOpcode() == Shuffle)
20002 return false; // Nothing to do!
20003 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20004 DCI.AddToWorklist(Op.getNode());
20005 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20006 DCI.AddToWorklist(Op.getNode());
20007 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20013 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20014 // variants as none of these have single-instruction variants that are
20015 // superior to the UNPCK formulation.
20016 if (!FloatDomain && VT.getSizeInBits() == 128 &&
20017 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20018 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20019 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20021 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20022 bool Lo = Mask[0] == 0;
20023 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20024 if (Depth == 1 && Root->getOpcode() == Shuffle)
20025 return false; // Nothing to do!
20027 switch (Mask.size()) {
20029 ShuffleVT = MVT::v8i16;
20032 ShuffleVT = MVT::v16i8;
20035 llvm_unreachable("Impossible mask size!");
20037 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20038 DCI.AddToWorklist(Op.getNode());
20039 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20040 DCI.AddToWorklist(Op.getNode());
20041 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20046 // Don't try to re-form single instruction chains under any circumstances now
20047 // that we've done encoding canonicalization for them.
20051 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20052 // can replace them with a single PSHUFB instruction profitably. Intel's
20053 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20054 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20055 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20056 SmallVector<SDValue, 16> PSHUFBMask;
20057 int NumBytes = VT.getSizeInBits() / 8;
20058 int Ratio = NumBytes / Mask.size();
20059 for (int i = 0; i < NumBytes; ++i) {
20060 if (Mask[i / Ratio] == SM_SentinelUndef) {
20061 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20064 int M = Mask[i / Ratio] != SM_SentinelZero
20065 ? Ratio * Mask[i / Ratio] + i % Ratio
20067 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20069 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20070 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20071 DCI.AddToWorklist(Op.getNode());
20072 SDValue PSHUFBMaskOp =
20073 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20074 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20075 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20076 DCI.AddToWorklist(Op.getNode());
20077 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20082 // Failed to find any combines.
20086 /// \brief Fully generic combining of x86 shuffle instructions.
20088 /// This should be the last combine run over the x86 shuffle instructions. Once
20089 /// they have been fully optimized, this will recursively consider all chains
20090 /// of single-use shuffle instructions, build a generic model of the cumulative
20091 /// shuffle operation, and check for simpler instructions which implement this
20092 /// operation. We use this primarily for two purposes:
20094 /// 1) Collapse generic shuffles to specialized single instructions when
20095 /// equivalent. In most cases, this is just an encoding size win, but
20096 /// sometimes we will collapse multiple generic shuffles into a single
20097 /// special-purpose shuffle.
20098 /// 2) Look for sequences of shuffle instructions with 3 or more total
20099 /// instructions, and replace them with the slightly more expensive SSSE3
20100 /// PSHUFB instruction if available. We do this as the last combining step
20101 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
20102 /// a suitable short sequence of other instructions. The PHUFB will either
20103 /// use a register or have to read from memory and so is slightly (but only
20104 /// slightly) more expensive than the other shuffle instructions.
20106 /// Because this is inherently a quadratic operation (for each shuffle in
20107 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20108 /// This should never be an issue in practice as the shuffle lowering doesn't
20109 /// produce sequences of more than 8 instructions.
20111 /// FIXME: We will currently miss some cases where the redundant shuffling
20112 /// would simplify under the threshold for PSHUFB formation because of
20113 /// combine-ordering. To fix this, we should do the redundant instruction
20114 /// combining in this recursive walk.
20115 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20116 ArrayRef<int> RootMask,
20117 int Depth, bool HasPSHUFB,
20119 TargetLowering::DAGCombinerInfo &DCI,
20120 const X86Subtarget *Subtarget) {
20121 // Bound the depth of our recursive combine because this is ultimately
20122 // quadratic in nature.
20126 // Directly rip through bitcasts to find the underlying operand.
20127 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20128 Op = Op.getOperand(0);
20130 MVT VT = Op.getSimpleValueType();
20131 if (!VT.isVector())
20132 return false; // Bail if we hit a non-vector.
20134 assert(Root.getSimpleValueType().isVector() &&
20135 "Shuffles operate on vector types!");
20136 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20137 "Can only combine shuffles of the same vector register size.");
20139 if (!isTargetShuffle(Op.getOpcode()))
20141 SmallVector<int, 16> OpMask;
20143 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20144 // We only can combine unary shuffles which we can decode the mask for.
20145 if (!HaveMask || !IsUnary)
20148 assert(VT.getVectorNumElements() == OpMask.size() &&
20149 "Different mask size from vector size!");
20150 assert(((RootMask.size() > OpMask.size() &&
20151 RootMask.size() % OpMask.size() == 0) ||
20152 (OpMask.size() > RootMask.size() &&
20153 OpMask.size() % RootMask.size() == 0) ||
20154 OpMask.size() == RootMask.size()) &&
20155 "The smaller number of elements must divide the larger.");
20156 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20157 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20158 assert(((RootRatio == 1 && OpRatio == 1) ||
20159 (RootRatio == 1) != (OpRatio == 1)) &&
20160 "Must not have a ratio for both incoming and op masks!");
20162 SmallVector<int, 16> Mask;
20163 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20165 // Merge this shuffle operation's mask into our accumulated mask. Note that
20166 // this shuffle's mask will be the first applied to the input, followed by the
20167 // root mask to get us all the way to the root value arrangement. The reason
20168 // for this order is that we are recursing up the operation chain.
20169 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20170 int RootIdx = i / RootRatio;
20171 if (RootMask[RootIdx] < 0) {
20172 // This is a zero or undef lane, we're done.
20173 Mask.push_back(RootMask[RootIdx]);
20177 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20178 int OpIdx = RootMaskedIdx / OpRatio;
20179 if (OpMask[OpIdx] < 0) {
20180 // The incoming lanes are zero or undef, it doesn't matter which ones we
20182 Mask.push_back(OpMask[OpIdx]);
20186 // Ok, we have non-zero lanes, map them through.
20187 Mask.push_back(OpMask[OpIdx] * OpRatio +
20188 RootMaskedIdx % OpRatio);
20191 // See if we can recurse into the operand to combine more things.
20192 switch (Op.getOpcode()) {
20193 case X86ISD::PSHUFB:
20195 case X86ISD::PSHUFD:
20196 case X86ISD::PSHUFHW:
20197 case X86ISD::PSHUFLW:
20198 if (Op.getOperand(0).hasOneUse() &&
20199 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20200 HasPSHUFB, DAG, DCI, Subtarget))
20204 case X86ISD::UNPCKL:
20205 case X86ISD::UNPCKH:
20206 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20207 // We can't check for single use, we have to check that this shuffle is the only user.
20208 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20209 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20210 HasPSHUFB, DAG, DCI, Subtarget))
20215 // Minor canonicalization of the accumulated shuffle mask to make it easier
20216 // to match below. All this does is detect masks with squential pairs of
20217 // elements, and shrink them to the half-width mask. It does this in a loop
20218 // so it will reduce the size of the mask to the minimal width mask which
20219 // performs an equivalent shuffle.
20220 SmallVector<int, 16> WidenedMask;
20221 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20222 Mask = std::move(WidenedMask);
20223 WidenedMask.clear();
20226 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20230 /// \brief Get the PSHUF-style mask from PSHUF node.
20232 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20233 /// PSHUF-style masks that can be reused with such instructions.
20234 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20235 MVT VT = N.getSimpleValueType();
20236 SmallVector<int, 4> Mask;
20238 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20242 // If we have more than 128-bits, only the low 128-bits of shuffle mask
20243 // matter. Check that the upper masks are repeats and remove them.
20244 if (VT.getSizeInBits() > 128) {
20245 int LaneElts = 128 / VT.getScalarSizeInBits();
20247 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20248 for (int j = 0; j < LaneElts; ++j)
20249 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20250 "Mask doesn't repeat in high 128-bit lanes!");
20252 Mask.resize(LaneElts);
20255 switch (N.getOpcode()) {
20256 case X86ISD::PSHUFD:
20258 case X86ISD::PSHUFLW:
20261 case X86ISD::PSHUFHW:
20262 Mask.erase(Mask.begin(), Mask.begin() + 4);
20263 for (int &M : Mask)
20267 llvm_unreachable("No valid shuffle instruction found!");
20271 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20273 /// We walk up the chain and look for a combinable shuffle, skipping over
20274 /// shuffles that we could hoist this shuffle's transformation past without
20275 /// altering anything.
20277 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20279 TargetLowering::DAGCombinerInfo &DCI) {
20280 assert(N.getOpcode() == X86ISD::PSHUFD &&
20281 "Called with something other than an x86 128-bit half shuffle!");
20284 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20285 // of the shuffles in the chain so that we can form a fresh chain to replace
20287 SmallVector<SDValue, 8> Chain;
20288 SDValue V = N.getOperand(0);
20289 for (; V.hasOneUse(); V = V.getOperand(0)) {
20290 switch (V.getOpcode()) {
20292 return SDValue(); // Nothing combined!
20295 // Skip bitcasts as we always know the type for the target specific
20299 case X86ISD::PSHUFD:
20300 // Found another dword shuffle.
20303 case X86ISD::PSHUFLW:
20304 // Check that the low words (being shuffled) are the identity in the
20305 // dword shuffle, and the high words are self-contained.
20306 if (Mask[0] != 0 || Mask[1] != 1 ||
20307 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20310 Chain.push_back(V);
20313 case X86ISD::PSHUFHW:
20314 // Check that the high words (being shuffled) are the identity in the
20315 // dword shuffle, and the low words are self-contained.
20316 if (Mask[2] != 2 || Mask[3] != 3 ||
20317 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20320 Chain.push_back(V);
20323 case X86ISD::UNPCKL:
20324 case X86ISD::UNPCKH:
20325 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20326 // shuffle into a preceding word shuffle.
20327 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20328 V.getSimpleValueType().getScalarType() != MVT::i16)
20331 // Search for a half-shuffle which we can combine with.
20332 unsigned CombineOp =
20333 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20334 if (V.getOperand(0) != V.getOperand(1) ||
20335 !V->isOnlyUserOf(V.getOperand(0).getNode()))
20337 Chain.push_back(V);
20338 V = V.getOperand(0);
20340 switch (V.getOpcode()) {
20342 return SDValue(); // Nothing to combine.
20344 case X86ISD::PSHUFLW:
20345 case X86ISD::PSHUFHW:
20346 if (V.getOpcode() == CombineOp)
20349 Chain.push_back(V);
20353 V = V.getOperand(0);
20357 } while (V.hasOneUse());
20360 // Break out of the loop if we break out of the switch.
20364 if (!V.hasOneUse())
20365 // We fell out of the loop without finding a viable combining instruction.
20368 // Merge this node's mask and our incoming mask.
20369 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20370 for (int &M : Mask)
20372 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20373 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20375 // Rebuild the chain around this new shuffle.
20376 while (!Chain.empty()) {
20377 SDValue W = Chain.pop_back_val();
20379 if (V.getValueType() != W.getOperand(0).getValueType())
20380 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20382 switch (W.getOpcode()) {
20384 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20386 case X86ISD::UNPCKL:
20387 case X86ISD::UNPCKH:
20388 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20391 case X86ISD::PSHUFD:
20392 case X86ISD::PSHUFLW:
20393 case X86ISD::PSHUFHW:
20394 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20398 if (V.getValueType() != N.getValueType())
20399 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20401 // Return the new chain to replace N.
20405 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20407 /// We walk up the chain, skipping shuffles of the other half and looking
20408 /// through shuffles which switch halves trying to find a shuffle of the same
20409 /// pair of dwords.
20410 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20412 TargetLowering::DAGCombinerInfo &DCI) {
20414 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20415 "Called with something other than an x86 128-bit half shuffle!");
20417 unsigned CombineOpcode = N.getOpcode();
20419 // Walk up a single-use chain looking for a combinable shuffle.
20420 SDValue V = N.getOperand(0);
20421 for (; V.hasOneUse(); V = V.getOperand(0)) {
20422 switch (V.getOpcode()) {
20424 return false; // Nothing combined!
20427 // Skip bitcasts as we always know the type for the target specific
20431 case X86ISD::PSHUFLW:
20432 case X86ISD::PSHUFHW:
20433 if (V.getOpcode() == CombineOpcode)
20436 // Other-half shuffles are no-ops.
20439 // Break out of the loop if we break out of the switch.
20443 if (!V.hasOneUse())
20444 // We fell out of the loop without finding a viable combining instruction.
20447 // Combine away the bottom node as its shuffle will be accumulated into
20448 // a preceding shuffle.
20449 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20451 // Record the old value.
20454 // Merge this node's mask and our incoming mask (adjusted to account for all
20455 // the pshufd instructions encountered).
20456 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20457 for (int &M : Mask)
20459 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20460 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20462 // Check that the shuffles didn't cancel each other out. If not, we need to
20463 // combine to the new one.
20465 // Replace the combinable shuffle with the combined one, updating all users
20466 // so that we re-evaluate the chain here.
20467 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20472 /// \brief Try to combine x86 target specific shuffles.
20473 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20474 TargetLowering::DAGCombinerInfo &DCI,
20475 const X86Subtarget *Subtarget) {
20477 MVT VT = N.getSimpleValueType();
20478 SmallVector<int, 4> Mask;
20480 switch (N.getOpcode()) {
20481 case X86ISD::PSHUFD:
20482 case X86ISD::PSHUFLW:
20483 case X86ISD::PSHUFHW:
20484 Mask = getPSHUFShuffleMask(N);
20485 assert(Mask.size() == 4);
20491 // Nuke no-op shuffles that show up after combining.
20492 if (isNoopShuffleMask(Mask))
20493 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20495 // Look for simplifications involving one or two shuffle instructions.
20496 SDValue V = N.getOperand(0);
20497 switch (N.getOpcode()) {
20500 case X86ISD::PSHUFLW:
20501 case X86ISD::PSHUFHW:
20502 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20504 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20505 return SDValue(); // We combined away this shuffle, so we're done.
20507 // See if this reduces to a PSHUFD which is no more expensive and can
20508 // combine with more operations. Note that it has to at least flip the
20509 // dwords as otherwise it would have been removed as a no-op.
20510 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20511 int DMask[] = {0, 1, 2, 3};
20512 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20513 DMask[DOffset + 0] = DOffset + 1;
20514 DMask[DOffset + 1] = DOffset + 0;
20515 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20516 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20517 DCI.AddToWorklist(V.getNode());
20518 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20519 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20520 DCI.AddToWorklist(V.getNode());
20521 return DAG.getNode(ISD::BITCAST, DL, VT, V);
20524 // Look for shuffle patterns which can be implemented as a single unpack.
20525 // FIXME: This doesn't handle the location of the PSHUFD generically, and
20526 // only works when we have a PSHUFD followed by two half-shuffles.
20527 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20528 (V.getOpcode() == X86ISD::PSHUFLW ||
20529 V.getOpcode() == X86ISD::PSHUFHW) &&
20530 V.getOpcode() != N.getOpcode() &&
20532 SDValue D = V.getOperand(0);
20533 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20534 D = D.getOperand(0);
20535 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20536 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20537 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20538 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20539 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20541 for (int i = 0; i < 4; ++i) {
20542 WordMask[i + NOffset] = Mask[i] + NOffset;
20543 WordMask[i + VOffset] = VMask[i] + VOffset;
20545 // Map the word mask through the DWord mask.
20547 for (int i = 0; i < 8; ++i)
20548 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20549 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20550 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20551 // We can replace all three shuffles with an unpack.
20552 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20553 DCI.AddToWorklist(V.getNode());
20554 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20563 case X86ISD::PSHUFD:
20564 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20573 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20575 /// We combine this directly on the abstract vector shuffle nodes so it is
20576 /// easier to generically match. We also insert dummy vector shuffle nodes for
20577 /// the operands which explicitly discard the lanes which are unused by this
20578 /// operation to try to flow through the rest of the combiner the fact that
20579 /// they're unused.
20580 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20582 EVT VT = N->getValueType(0);
20584 // We only handle target-independent shuffles.
20585 // FIXME: It would be easy and harmless to use the target shuffle mask
20586 // extraction tool to support more.
20587 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20590 auto *SVN = cast<ShuffleVectorSDNode>(N);
20591 ArrayRef<int> Mask = SVN->getMask();
20592 SDValue V1 = N->getOperand(0);
20593 SDValue V2 = N->getOperand(1);
20595 // We require the first shuffle operand to be the SUB node, and the second to
20596 // be the ADD node.
20597 // FIXME: We should support the commuted patterns.
20598 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20601 // If there are other uses of these operations we can't fold them.
20602 if (!V1->hasOneUse() || !V2->hasOneUse())
20605 // Ensure that both operations have the same operands. Note that we can
20606 // commute the FADD operands.
20607 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20608 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20609 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20612 // We're looking for blends between FADD and FSUB nodes. We insist on these
20613 // nodes being lined up in a specific expected pattern.
20614 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20615 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20616 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20619 // Only specific types are legal at this point, assert so we notice if and
20620 // when these change.
20621 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20622 VT == MVT::v4f64) &&
20623 "Unknown vector type encountered!");
20625 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20628 /// PerformShuffleCombine - Performs several different shuffle combines.
20629 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20630 TargetLowering::DAGCombinerInfo &DCI,
20631 const X86Subtarget *Subtarget) {
20633 SDValue N0 = N->getOperand(0);
20634 SDValue N1 = N->getOperand(1);
20635 EVT VT = N->getValueType(0);
20637 // Don't create instructions with illegal types after legalize types has run.
20638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20639 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20642 // If we have legalized the vector types, look for blends of FADD and FSUB
20643 // nodes that we can fuse into an ADDSUB node.
20644 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20645 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20648 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20649 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20650 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20651 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20653 // During Type Legalization, when promoting illegal vector types,
20654 // the backend might introduce new shuffle dag nodes and bitcasts.
20656 // This code performs the following transformation:
20657 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20658 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20660 // We do this only if both the bitcast and the BINOP dag nodes have
20661 // one use. Also, perform this transformation only if the new binary
20662 // operation is legal. This is to avoid introducing dag nodes that
20663 // potentially need to be further expanded (or custom lowered) into a
20664 // less optimal sequence of dag nodes.
20665 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20666 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20667 N0.getOpcode() == ISD::BITCAST) {
20668 SDValue BC0 = N0.getOperand(0);
20669 EVT SVT = BC0.getValueType();
20670 unsigned Opcode = BC0.getOpcode();
20671 unsigned NumElts = VT.getVectorNumElements();
20673 if (BC0.hasOneUse() && SVT.isVector() &&
20674 SVT.getVectorNumElements() * 2 == NumElts &&
20675 TLI.isOperationLegal(Opcode, VT)) {
20676 bool CanFold = false;
20688 unsigned SVTNumElts = SVT.getVectorNumElements();
20689 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20690 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20691 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20692 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20693 CanFold = SVOp->getMaskElt(i) < 0;
20696 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20697 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20698 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20699 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20704 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20705 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20706 // consecutive, non-overlapping, and in the right order.
20707 SmallVector<SDValue, 16> Elts;
20708 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20709 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20711 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20715 if (isTargetShuffle(N->getOpcode())) {
20717 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20718 if (Shuffle.getNode())
20721 // Try recursively combining arbitrary sequences of x86 shuffle
20722 // instructions into higher-order shuffles. We do this after combining
20723 // specific PSHUF instruction sequences into their minimal form so that we
20724 // can evaluate how many specialized shuffle instructions are involved in
20725 // a particular chain.
20726 SmallVector<int, 1> NonceMask; // Just a placeholder.
20727 NonceMask.push_back(0);
20728 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20729 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20731 return SDValue(); // This routine will use CombineTo to replace N.
20737 /// PerformTruncateCombine - Converts truncate operation to
20738 /// a sequence of vector shuffle operations.
20739 /// It is possible when we truncate 256-bit vector to 128-bit vector
20740 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20741 TargetLowering::DAGCombinerInfo &DCI,
20742 const X86Subtarget *Subtarget) {
20746 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20747 /// specific shuffle of a load can be folded into a single element load.
20748 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20749 /// shuffles have been custom lowered so we need to handle those here.
20750 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20751 TargetLowering::DAGCombinerInfo &DCI) {
20752 if (DCI.isBeforeLegalizeOps())
20755 SDValue InVec = N->getOperand(0);
20756 SDValue EltNo = N->getOperand(1);
20758 if (!isa<ConstantSDNode>(EltNo))
20761 EVT OriginalVT = InVec.getValueType();
20763 if (InVec.getOpcode() == ISD::BITCAST) {
20764 // Don't duplicate a load with other uses.
20765 if (!InVec.hasOneUse())
20767 EVT BCVT = InVec.getOperand(0).getValueType();
20768 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20770 InVec = InVec.getOperand(0);
20773 EVT CurrentVT = InVec.getValueType();
20775 if (!isTargetShuffle(InVec.getOpcode()))
20778 // Don't duplicate a load with other uses.
20779 if (!InVec.hasOneUse())
20782 SmallVector<int, 16> ShuffleMask;
20784 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20785 ShuffleMask, UnaryShuffle))
20788 // Select the input vector, guarding against out of range extract vector.
20789 unsigned NumElems = CurrentVT.getVectorNumElements();
20790 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20791 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20792 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20793 : InVec.getOperand(1);
20795 // If inputs to shuffle are the same for both ops, then allow 2 uses
20796 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20797 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20799 if (LdNode.getOpcode() == ISD::BITCAST) {
20800 // Don't duplicate a load with other uses.
20801 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20804 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20805 LdNode = LdNode.getOperand(0);
20808 if (!ISD::isNormalLoad(LdNode.getNode()))
20811 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20813 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20816 EVT EltVT = N->getValueType(0);
20817 // If there's a bitcast before the shuffle, check if the load type and
20818 // alignment is valid.
20819 unsigned Align = LN0->getAlignment();
20820 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20821 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20822 EltVT.getTypeForEVT(*DAG.getContext()));
20824 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20827 // All checks match so transform back to vector_shuffle so that DAG combiner
20828 // can finish the job
20831 // Create shuffle node taking into account the case that its a unary shuffle
20832 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20833 : InVec.getOperand(1);
20834 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20835 InVec.getOperand(0), Shuffle,
20837 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20838 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20842 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20843 /// special and don't usually play with other vector types, it's better to
20844 /// handle them early to be sure we emit efficient code by avoiding
20845 /// store-load conversions.
20846 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20847 if (N->getValueType(0) != MVT::x86mmx ||
20848 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20849 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20852 SDValue V = N->getOperand(0);
20853 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20854 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20855 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20856 N->getValueType(0), V.getOperand(0));
20861 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20862 /// generation and convert it from being a bunch of shuffles and extracts
20863 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20864 /// storing the value and loading scalars back, while for x64 we should
20865 /// use 64-bit extracts and shifts.
20866 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20867 TargetLowering::DAGCombinerInfo &DCI) {
20868 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20869 if (NewOp.getNode())
20872 SDValue InputVector = N->getOperand(0);
20874 // Detect mmx to i32 conversion through a v2i32 elt extract.
20875 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20876 N->getValueType(0) == MVT::i32 &&
20877 InputVector.getValueType() == MVT::v2i32) {
20879 // The bitcast source is a direct mmx result.
20880 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20881 if (MMXSrc.getValueType() == MVT::x86mmx)
20882 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20883 N->getValueType(0),
20884 InputVector.getNode()->getOperand(0));
20886 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20887 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20888 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20889 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20890 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20891 MMXSrcOp.getValueType() == MVT::v1i64 &&
20892 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20893 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20894 N->getValueType(0),
20895 MMXSrcOp.getOperand(0));
20898 // Only operate on vectors of 4 elements, where the alternative shuffling
20899 // gets to be more expensive.
20900 if (InputVector.getValueType() != MVT::v4i32)
20903 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20904 // single use which is a sign-extend or zero-extend, and all elements are
20906 SmallVector<SDNode *, 4> Uses;
20907 unsigned ExtractedElements = 0;
20908 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20909 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20910 if (UI.getUse().getResNo() != InputVector.getResNo())
20913 SDNode *Extract = *UI;
20914 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20917 if (Extract->getValueType(0) != MVT::i32)
20919 if (!Extract->hasOneUse())
20921 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20922 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20924 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20927 // Record which element was extracted.
20928 ExtractedElements |=
20929 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20931 Uses.push_back(Extract);
20934 // If not all the elements were used, this may not be worthwhile.
20935 if (ExtractedElements != 15)
20938 // Ok, we've now decided to do the transformation.
20939 // If 64-bit shifts are legal, use the extract-shift sequence,
20940 // otherwise bounce the vector off the cache.
20941 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20943 SDLoc dl(InputVector);
20945 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20946 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20947 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20948 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20949 DAG.getConstant(0, dl, VecIdxTy));
20950 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20951 DAG.getConstant(1, dl, VecIdxTy));
20953 SDValue ShAmt = DAG.getConstant(32, dl,
20954 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20955 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20956 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20957 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20958 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20959 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20960 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20962 // Store the value to a temporary stack slot.
20963 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20964 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20965 MachinePointerInfo(), false, false, 0);
20967 EVT ElementType = InputVector.getValueType().getVectorElementType();
20968 unsigned EltSize = ElementType.getSizeInBits() / 8;
20970 // Replace each use (extract) with a load of the appropriate element.
20971 for (unsigned i = 0; i < 4; ++i) {
20972 uint64_t Offset = EltSize * i;
20973 SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20975 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20976 StackPtr, OffsetVal);
20978 // Load the scalar.
20979 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20980 ScalarAddr, MachinePointerInfo(),
20981 false, false, false, 0);
20986 // Replace the extracts
20987 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20988 UE = Uses.end(); UI != UE; ++UI) {
20989 SDNode *Extract = *UI;
20991 SDValue Idx = Extract->getOperand(1);
20992 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20993 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20996 // The replacement was made in place; don't return anything.
21000 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21001 static std::pair<unsigned, bool>
21002 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21003 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21004 if (!VT.isVector())
21005 return std::make_pair(0, false);
21007 bool NeedSplit = false;
21008 switch (VT.getSimpleVT().SimpleTy) {
21009 default: return std::make_pair(0, false);
21012 if (!Subtarget->hasVLX())
21013 return std::make_pair(0, false);
21017 if (!Subtarget->hasBWI())
21018 return std::make_pair(0, false);
21022 if (!Subtarget->hasAVX512())
21023 return std::make_pair(0, false);
21028 if (!Subtarget->hasAVX2())
21030 if (!Subtarget->hasAVX())
21031 return std::make_pair(0, false);
21036 if (!Subtarget->hasSSE2())
21037 return std::make_pair(0, false);
21040 // SSE2 has only a small subset of the operations.
21041 bool hasUnsigned = Subtarget->hasSSE41() ||
21042 (Subtarget->hasSSE2() && VT == MVT::v16i8);
21043 bool hasSigned = Subtarget->hasSSE41() ||
21044 (Subtarget->hasSSE2() && VT == MVT::v8i16);
21046 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21049 // Check for x CC y ? x : y.
21050 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21051 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21056 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21059 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21062 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21065 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21067 // Check for x CC y ? y : x -- a min/max with reversed arms.
21068 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21069 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21074 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21077 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21080 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21083 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21087 return std::make_pair(Opc, NeedSplit);
21091 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21092 const X86Subtarget *Subtarget) {
21094 SDValue Cond = N->getOperand(0);
21095 SDValue LHS = N->getOperand(1);
21096 SDValue RHS = N->getOperand(2);
21098 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21099 SDValue CondSrc = Cond->getOperand(0);
21100 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21101 Cond = CondSrc->getOperand(0);
21104 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21107 // A vselect where all conditions and data are constants can be optimized into
21108 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21109 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21110 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21113 unsigned MaskValue = 0;
21114 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21117 MVT VT = N->getSimpleValueType(0);
21118 unsigned NumElems = VT.getVectorNumElements();
21119 SmallVector<int, 8> ShuffleMask(NumElems, -1);
21120 for (unsigned i = 0; i < NumElems; ++i) {
21121 // Be sure we emit undef where we can.
21122 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21123 ShuffleMask[i] = -1;
21125 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21129 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21131 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21134 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21136 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21137 TargetLowering::DAGCombinerInfo &DCI,
21138 const X86Subtarget *Subtarget) {
21140 SDValue Cond = N->getOperand(0);
21141 // Get the LHS/RHS of the select.
21142 SDValue LHS = N->getOperand(1);
21143 SDValue RHS = N->getOperand(2);
21144 EVT VT = LHS.getValueType();
21145 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21147 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21148 // instructions match the semantics of the common C idiom x<y?x:y but not
21149 // x<=y?x:y, because of how they handle negative zero (which can be
21150 // ignored in unsafe-math mode).
21151 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21152 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21153 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21154 (Subtarget->hasSSE2() ||
21155 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21156 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21158 unsigned Opcode = 0;
21159 // Check for x CC y ? x : y.
21160 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21161 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21165 // Converting this to a min would handle NaNs incorrectly, and swapping
21166 // the operands would cause it to handle comparisons between positive
21167 // and negative zero incorrectly.
21168 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21169 if (!DAG.getTarget().Options.UnsafeFPMath &&
21170 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21172 std::swap(LHS, RHS);
21174 Opcode = X86ISD::FMIN;
21177 // Converting this to a min would handle comparisons between positive
21178 // and negative zero incorrectly.
21179 if (!DAG.getTarget().Options.UnsafeFPMath &&
21180 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21182 Opcode = X86ISD::FMIN;
21185 // Converting this to a min would handle both negative zeros and NaNs
21186 // incorrectly, but we can swap the operands to fix both.
21187 std::swap(LHS, RHS);
21191 Opcode = X86ISD::FMIN;
21195 // Converting this to a max would handle comparisons between positive
21196 // and negative zero incorrectly.
21197 if (!DAG.getTarget().Options.UnsafeFPMath &&
21198 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21200 Opcode = X86ISD::FMAX;
21203 // Converting this to a max would handle NaNs incorrectly, and swapping
21204 // the operands would cause it to handle comparisons between positive
21205 // and negative zero incorrectly.
21206 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21207 if (!DAG.getTarget().Options.UnsafeFPMath &&
21208 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21210 std::swap(LHS, RHS);
21212 Opcode = X86ISD::FMAX;
21215 // Converting this to a max would handle both negative zeros and NaNs
21216 // incorrectly, but we can swap the operands to fix both.
21217 std::swap(LHS, RHS);
21221 Opcode = X86ISD::FMAX;
21224 // Check for x CC y ? y : x -- a min/max with reversed arms.
21225 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21226 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21230 // Converting this to a min would handle comparisons between positive
21231 // and negative zero incorrectly, and swapping the operands would
21232 // cause it to handle NaNs incorrectly.
21233 if (!DAG.getTarget().Options.UnsafeFPMath &&
21234 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21235 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21237 std::swap(LHS, RHS);
21239 Opcode = X86ISD::FMIN;
21242 // Converting this to a min would handle NaNs incorrectly.
21243 if (!DAG.getTarget().Options.UnsafeFPMath &&
21244 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21246 Opcode = X86ISD::FMIN;
21249 // Converting this to a min would handle both negative zeros and NaNs
21250 // incorrectly, but we can swap the operands to fix both.
21251 std::swap(LHS, RHS);
21255 Opcode = X86ISD::FMIN;
21259 // Converting this to a max would handle NaNs incorrectly.
21260 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21262 Opcode = X86ISD::FMAX;
21265 // Converting this to a max would handle comparisons between positive
21266 // and negative zero incorrectly, and swapping the operands would
21267 // cause it to handle NaNs incorrectly.
21268 if (!DAG.getTarget().Options.UnsafeFPMath &&
21269 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21270 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21272 std::swap(LHS, RHS);
21274 Opcode = X86ISD::FMAX;
21277 // Converting this to a max would handle both negative zeros and NaNs
21278 // incorrectly, but we can swap the operands to fix both.
21279 std::swap(LHS, RHS);
21283 Opcode = X86ISD::FMAX;
21289 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21292 EVT CondVT = Cond.getValueType();
21293 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21294 CondVT.getVectorElementType() == MVT::i1) {
21295 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21296 // lowering on KNL. In this case we convert it to
21297 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21298 // The same situation for all 128 and 256-bit vectors of i8 and i16.
21299 // Since SKX these selects have a proper lowering.
21300 EVT OpVT = LHS.getValueType();
21301 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21302 (OpVT.getVectorElementType() == MVT::i8 ||
21303 OpVT.getVectorElementType() == MVT::i16) &&
21304 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21305 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21306 DCI.AddToWorklist(Cond.getNode());
21307 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21310 // If this is a select between two integer constants, try to do some
21312 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21313 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21314 // Don't do this for crazy integer types.
21315 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21316 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21317 // so that TrueC (the true value) is larger than FalseC.
21318 bool NeedsCondInvert = false;
21320 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21321 // Efficiently invertible.
21322 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
21323 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
21324 isa<ConstantSDNode>(Cond.getOperand(1))))) {
21325 NeedsCondInvert = true;
21326 std::swap(TrueC, FalseC);
21329 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
21330 if (FalseC->getAPIntValue() == 0 &&
21331 TrueC->getAPIntValue().isPowerOf2()) {
21332 if (NeedsCondInvert) // Invert the condition if needed.
21333 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21334 DAG.getConstant(1, DL, Cond.getValueType()));
21336 // Zero extend the condition if needed.
21337 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21339 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21340 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21341 DAG.getConstant(ShAmt, DL, MVT::i8));
21344 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21345 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21346 if (NeedsCondInvert) // Invert the condition if needed.
21347 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21348 DAG.getConstant(1, DL, Cond.getValueType()));
21350 // Zero extend the condition if needed.
21351 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21352 FalseC->getValueType(0), Cond);
21353 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21354 SDValue(FalseC, 0));
21357 // Optimize cases that will turn into an LEA instruction. This requires
21358 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21359 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21360 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21361 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21363 bool isFastMultiplier = false;
21365 switch ((unsigned char)Diff) {
21367 case 1: // result = add base, cond
21368 case 2: // result = lea base( , cond*2)
21369 case 3: // result = lea base(cond, cond*2)
21370 case 4: // result = lea base( , cond*4)
21371 case 5: // result = lea base(cond, cond*4)
21372 case 8: // result = lea base( , cond*8)
21373 case 9: // result = lea base(cond, cond*8)
21374 isFastMultiplier = true;
21379 if (isFastMultiplier) {
21380 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21381 if (NeedsCondInvert) // Invert the condition if needed.
21382 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21383 DAG.getConstant(1, DL, Cond.getValueType()));
21385 // Zero extend the condition if needed.
21386 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21388 // Scale the condition by the difference.
21390 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21391 DAG.getConstant(Diff, DL,
21392 Cond.getValueType()));
21394 // Add the base if non-zero.
21395 if (FalseC->getAPIntValue() != 0)
21396 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21397 SDValue(FalseC, 0));
21404 // Canonicalize max and min:
21405 // (x > y) ? x : y -> (x >= y) ? x : y
21406 // (x < y) ? x : y -> (x <= y) ? x : y
21407 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21408 // the need for an extra compare
21409 // against zero. e.g.
21410 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21412 // testl %edi, %edi
21414 // cmovgl %edi, %eax
21418 // cmovsl %eax, %edi
21419 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21420 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21421 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21422 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21427 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21428 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21429 Cond.getOperand(0), Cond.getOperand(1), NewCC);
21430 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21435 // Early exit check
21436 if (!TLI.isTypeLegal(VT))
21439 // Match VSELECTs into subs with unsigned saturation.
21440 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21441 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21442 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21443 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21444 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21446 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21447 // left side invert the predicate to simplify logic below.
21449 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21451 CC = ISD::getSetCCInverse(CC, true);
21452 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21456 if (Other.getNode() && Other->getNumOperands() == 2 &&
21457 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21458 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21459 SDValue CondRHS = Cond->getOperand(1);
21461 // Look for a general sub with unsigned saturation first.
21462 // x >= y ? x-y : 0 --> subus x, y
21463 // x > y ? x-y : 0 --> subus x, y
21464 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21465 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21466 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21468 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21469 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21470 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21471 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21472 // If the RHS is a constant we have to reverse the const
21473 // canonicalization.
21474 // x > C-1 ? x+-C : 0 --> subus x, C
21475 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21476 CondRHSConst->getAPIntValue() ==
21477 (-OpRHSConst->getAPIntValue() - 1))
21478 return DAG.getNode(
21479 X86ISD::SUBUS, DL, VT, OpLHS,
21480 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21482 // Another special case: If C was a sign bit, the sub has been
21483 // canonicalized into a xor.
21484 // FIXME: Would it be better to use computeKnownBits to determine
21485 // whether it's safe to decanonicalize the xor?
21486 // x s< 0 ? x^C : 0 --> subus x, C
21487 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21488 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21489 OpRHSConst->getAPIntValue().isSignBit())
21490 // Note that we have to rebuild the RHS constant here to ensure we
21491 // don't rely on particular values of undef lanes.
21492 return DAG.getNode(
21493 X86ISD::SUBUS, DL, VT, OpLHS,
21494 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21499 // Try to match a min/max vector operation.
21500 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21501 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21502 unsigned Opc = ret.first;
21503 bool NeedSplit = ret.second;
21505 if (Opc && NeedSplit) {
21506 unsigned NumElems = VT.getVectorNumElements();
21507 // Extract the LHS vectors
21508 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21509 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21511 // Extract the RHS vectors
21512 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21513 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21515 // Create min/max for each subvector
21516 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21517 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21519 // Merge the result
21520 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21522 return DAG.getNode(Opc, DL, VT, LHS, RHS);
21525 // Simplify vector selection if condition value type matches vselect
21527 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21528 assert(Cond.getValueType().isVector() &&
21529 "vector select expects a vector selector!");
21531 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21532 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21534 // Try invert the condition if true value is not all 1s and false value
21536 if (!TValIsAllOnes && !FValIsAllZeros &&
21537 // Check if the selector will be produced by CMPP*/PCMP*
21538 Cond.getOpcode() == ISD::SETCC &&
21539 // Check if SETCC has already been promoted
21540 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21541 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21542 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21544 if (TValIsAllZeros || FValIsAllOnes) {
21545 SDValue CC = Cond.getOperand(2);
21546 ISD::CondCode NewCC =
21547 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21548 Cond.getOperand(0).getValueType().isInteger());
21549 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21550 std::swap(LHS, RHS);
21551 TValIsAllOnes = FValIsAllOnes;
21552 FValIsAllZeros = TValIsAllZeros;
21556 if (TValIsAllOnes || FValIsAllZeros) {
21559 if (TValIsAllOnes && FValIsAllZeros)
21561 else if (TValIsAllOnes)
21562 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21563 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21564 else if (FValIsAllZeros)
21565 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21566 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21568 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21572 // We should generate an X86ISD::BLENDI from a vselect if its argument
21573 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21574 // constants. This specific pattern gets generated when we split a
21575 // selector for a 512 bit vector in a machine without AVX512 (but with
21576 // 256-bit vectors), during legalization:
21578 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21580 // Iff we find this pattern and the build_vectors are built from
21581 // constants, we translate the vselect into a shuffle_vector that we
21582 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21583 if ((N->getOpcode() == ISD::VSELECT ||
21584 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21585 !DCI.isBeforeLegalize()) {
21586 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21587 if (Shuffle.getNode())
21591 // If this is a *dynamic* select (non-constant condition) and we can match
21592 // this node with one of the variable blend instructions, restructure the
21593 // condition so that the blends can use the high bit of each element and use
21594 // SimplifyDemandedBits to simplify the condition operand.
21595 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21596 !DCI.isBeforeLegalize() &&
21597 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21598 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21600 // Don't optimize vector selects that map to mask-registers.
21604 // We can only handle the cases where VSELECT is directly legal on the
21605 // subtarget. We custom lower VSELECT nodes with constant conditions and
21606 // this makes it hard to see whether a dynamic VSELECT will correctly
21607 // lower, so we both check the operation's status and explicitly handle the
21608 // cases where a *dynamic* blend will fail even though a constant-condition
21609 // blend could be custom lowered.
21610 // FIXME: We should find a better way to handle this class of problems.
21611 // Potentially, we should combine constant-condition vselect nodes
21612 // pre-legalization into shuffles and not mark as many types as custom
21614 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21616 // FIXME: We don't support i16-element blends currently. We could and
21617 // should support them by making *all* the bits in the condition be set
21618 // rather than just the high bit and using an i8-element blend.
21619 if (VT.getScalarType() == MVT::i16)
21621 // Dynamic blending was only available from SSE4.1 onward.
21622 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21624 // Byte blends are only available in AVX2
21625 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21626 !Subtarget->hasAVX2())
21629 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21630 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21632 APInt KnownZero, KnownOne;
21633 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21634 DCI.isBeforeLegalizeOps());
21635 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21636 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21638 // If we changed the computation somewhere in the DAG, this change
21639 // will affect all users of Cond.
21640 // Make sure it is fine and update all the nodes so that we do not
21641 // use the generic VSELECT anymore. Otherwise, we may perform
21642 // wrong optimizations as we messed up with the actual expectation
21643 // for the vector boolean values.
21644 if (Cond != TLO.Old) {
21645 // Check all uses of that condition operand to check whether it will be
21646 // consumed by non-BLEND instructions, which may depend on all bits are
21648 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21650 if (I->getOpcode() != ISD::VSELECT)
21651 // TODO: Add other opcodes eventually lowered into BLEND.
21654 // Update all the users of the condition, before committing the change,
21655 // so that the VSELECT optimizations that expect the correct vector
21656 // boolean value will not be triggered.
21657 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21659 DAG.ReplaceAllUsesOfValueWith(
21661 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21662 Cond, I->getOperand(1), I->getOperand(2)));
21663 DCI.CommitTargetLoweringOpt(TLO);
21666 // At this point, only Cond is changed. Change the condition
21667 // just for N to keep the opportunity to optimize all other
21668 // users their own way.
21669 DAG.ReplaceAllUsesOfValueWith(
21671 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21672 TLO.New, N->getOperand(1), N->getOperand(2)));
21680 // Check whether a boolean test is testing a boolean value generated by
21681 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21684 // Simplify the following patterns:
21685 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21686 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21687 // to (Op EFLAGS Cond)
21689 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21690 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21691 // to (Op EFLAGS !Cond)
21693 // where Op could be BRCOND or CMOV.
21695 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21696 // Quit if not CMP and SUB with its value result used.
21697 if (Cmp.getOpcode() != X86ISD::CMP &&
21698 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21701 // Quit if not used as a boolean value.
21702 if (CC != X86::COND_E && CC != X86::COND_NE)
21705 // Check CMP operands. One of them should be 0 or 1 and the other should be
21706 // an SetCC or extended from it.
21707 SDValue Op1 = Cmp.getOperand(0);
21708 SDValue Op2 = Cmp.getOperand(1);
21711 const ConstantSDNode* C = nullptr;
21712 bool needOppositeCond = (CC == X86::COND_E);
21713 bool checkAgainstTrue = false; // Is it a comparison against 1?
21715 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21717 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21719 else // Quit if all operands are not constants.
21722 if (C->getZExtValue() == 1) {
21723 needOppositeCond = !needOppositeCond;
21724 checkAgainstTrue = true;
21725 } else if (C->getZExtValue() != 0)
21726 // Quit if the constant is neither 0 or 1.
21729 bool truncatedToBoolWithAnd = false;
21730 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21731 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21732 SetCC.getOpcode() == ISD::TRUNCATE ||
21733 SetCC.getOpcode() == ISD::AND) {
21734 if (SetCC.getOpcode() == ISD::AND) {
21736 ConstantSDNode *CS;
21737 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21738 CS->getZExtValue() == 1)
21740 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21741 CS->getZExtValue() == 1)
21745 SetCC = SetCC.getOperand(OpIdx);
21746 truncatedToBoolWithAnd = true;
21748 SetCC = SetCC.getOperand(0);
21751 switch (SetCC.getOpcode()) {
21752 case X86ISD::SETCC_CARRY:
21753 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21754 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21755 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21756 // truncated to i1 using 'and'.
21757 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21759 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21760 "Invalid use of SETCC_CARRY!");
21762 case X86ISD::SETCC:
21763 // Set the condition code or opposite one if necessary.
21764 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21765 if (needOppositeCond)
21766 CC = X86::GetOppositeBranchCondition(CC);
21767 return SetCC.getOperand(1);
21768 case X86ISD::CMOV: {
21769 // Check whether false/true value has canonical one, i.e. 0 or 1.
21770 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21771 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21772 // Quit if true value is not a constant.
21775 // Quit if false value is not a constant.
21777 SDValue Op = SetCC.getOperand(0);
21778 // Skip 'zext' or 'trunc' node.
21779 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21780 Op.getOpcode() == ISD::TRUNCATE)
21781 Op = Op.getOperand(0);
21782 // A special case for rdrand/rdseed, where 0 is set if false cond is
21784 if ((Op.getOpcode() != X86ISD::RDRAND &&
21785 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21788 // Quit if false value is not the constant 0 or 1.
21789 bool FValIsFalse = true;
21790 if (FVal && FVal->getZExtValue() != 0) {
21791 if (FVal->getZExtValue() != 1)
21793 // If FVal is 1, opposite cond is needed.
21794 needOppositeCond = !needOppositeCond;
21795 FValIsFalse = false;
21797 // Quit if TVal is not the constant opposite of FVal.
21798 if (FValIsFalse && TVal->getZExtValue() != 1)
21800 if (!FValIsFalse && TVal->getZExtValue() != 0)
21802 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21803 if (needOppositeCond)
21804 CC = X86::GetOppositeBranchCondition(CC);
21805 return SetCC.getOperand(3);
21812 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21814 /// (X86or (X86setcc) (X86setcc))
21815 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21816 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21817 X86::CondCode &CC1, SDValue &Flags,
21819 if (Cond->getOpcode() == X86ISD::CMP) {
21820 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21821 if (!CondOp1C || !CondOp1C->isNullValue())
21824 Cond = Cond->getOperand(0);
21829 SDValue SetCC0, SetCC1;
21830 switch (Cond->getOpcode()) {
21831 default: return false;
21838 SetCC0 = Cond->getOperand(0);
21839 SetCC1 = Cond->getOperand(1);
21843 // Make sure we have SETCC nodes, using the same flags value.
21844 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21845 SetCC1.getOpcode() != X86ISD::SETCC ||
21846 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21849 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21850 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21851 Flags = SetCC0->getOperand(1);
21855 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21856 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21857 TargetLowering::DAGCombinerInfo &DCI,
21858 const X86Subtarget *Subtarget) {
21861 // If the flag operand isn't dead, don't touch this CMOV.
21862 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21865 SDValue FalseOp = N->getOperand(0);
21866 SDValue TrueOp = N->getOperand(1);
21867 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21868 SDValue Cond = N->getOperand(3);
21870 if (CC == X86::COND_E || CC == X86::COND_NE) {
21871 switch (Cond.getOpcode()) {
21875 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21876 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21877 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21883 Flags = checkBoolTestSetCCCombine(Cond, CC);
21884 if (Flags.getNode() &&
21885 // Extra check as FCMOV only supports a subset of X86 cond.
21886 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21887 SDValue Ops[] = { FalseOp, TrueOp,
21888 DAG.getConstant(CC, DL, MVT::i8), Flags };
21889 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21892 // If this is a select between two integer constants, try to do some
21893 // optimizations. Note that the operands are ordered the opposite of SELECT
21895 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21896 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21897 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21898 // larger than FalseC (the false value).
21899 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21900 CC = X86::GetOppositeBranchCondition(CC);
21901 std::swap(TrueC, FalseC);
21902 std::swap(TrueOp, FalseOp);
21905 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21906 // This is efficient for any integer data type (including i8/i16) and
21908 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21909 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21910 DAG.getConstant(CC, DL, MVT::i8), Cond);
21912 // Zero extend the condition if needed.
21913 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21915 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21916 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21917 DAG.getConstant(ShAmt, DL, MVT::i8));
21918 if (N->getNumValues() == 2) // Dead flag value?
21919 return DCI.CombineTo(N, Cond, SDValue());
21923 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21924 // for any integer data type, including i8/i16.
21925 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21926 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21927 DAG.getConstant(CC, DL, MVT::i8), Cond);
21929 // Zero extend the condition if needed.
21930 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21931 FalseC->getValueType(0), Cond);
21932 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21933 SDValue(FalseC, 0));
21935 if (N->getNumValues() == 2) // Dead flag value?
21936 return DCI.CombineTo(N, Cond, SDValue());
21940 // Optimize cases that will turn into an LEA instruction. This requires
21941 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21942 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21943 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21944 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21946 bool isFastMultiplier = false;
21948 switch ((unsigned char)Diff) {
21950 case 1: // result = add base, cond
21951 case 2: // result = lea base( , cond*2)
21952 case 3: // result = lea base(cond, cond*2)
21953 case 4: // result = lea base( , cond*4)
21954 case 5: // result = lea base(cond, cond*4)
21955 case 8: // result = lea base( , cond*8)
21956 case 9: // result = lea base(cond, cond*8)
21957 isFastMultiplier = true;
21962 if (isFastMultiplier) {
21963 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21964 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21965 DAG.getConstant(CC, DL, MVT::i8), Cond);
21966 // Zero extend the condition if needed.
21967 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21969 // Scale the condition by the difference.
21971 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21972 DAG.getConstant(Diff, DL, Cond.getValueType()));
21974 // Add the base if non-zero.
21975 if (FalseC->getAPIntValue() != 0)
21976 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21977 SDValue(FalseC, 0));
21978 if (N->getNumValues() == 2) // Dead flag value?
21979 return DCI.CombineTo(N, Cond, SDValue());
21986 // Handle these cases:
21987 // (select (x != c), e, c) -> select (x != c), e, x),
21988 // (select (x == c), c, e) -> select (x == c), x, e)
21989 // where the c is an integer constant, and the "select" is the combination
21990 // of CMOV and CMP.
21992 // The rationale for this change is that the conditional-move from a constant
21993 // needs two instructions, however, conditional-move from a register needs
21994 // only one instruction.
21996 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21997 // some instruction-combining opportunities. This opt needs to be
21998 // postponed as late as possible.
22000 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22001 // the DCI.xxxx conditions are provided to postpone the optimization as
22002 // late as possible.
22004 ConstantSDNode *CmpAgainst = nullptr;
22005 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22006 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22007 !isa<ConstantSDNode>(Cond.getOperand(0))) {
22009 if (CC == X86::COND_NE &&
22010 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22011 CC = X86::GetOppositeBranchCondition(CC);
22012 std::swap(TrueOp, FalseOp);
22015 if (CC == X86::COND_E &&
22016 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22017 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22018 DAG.getConstant(CC, DL, MVT::i8), Cond };
22019 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22024 // Fold and/or of setcc's to double CMOV:
22025 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22026 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22028 // This combine lets us generate:
22029 // cmovcc1 (jcc1 if we don't have CMOV)
22035 // cmovne (jne if we don't have CMOV)
22036 // When we can't use the CMOV instruction, it might increase branch
22038 // When we can use CMOV, or when there is no mispredict, this improves
22039 // throughput and reduces register pressure.
22041 if (CC == X86::COND_NE) {
22043 X86::CondCode CC0, CC1;
22045 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22047 std::swap(FalseOp, TrueOp);
22048 CC0 = X86::GetOppositeBranchCondition(CC0);
22049 CC1 = X86::GetOppositeBranchCondition(CC1);
22052 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22054 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22055 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22056 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22057 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22065 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22066 const X86Subtarget *Subtarget) {
22067 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22069 default: return SDValue();
22070 // SSE/AVX/AVX2 blend intrinsics.
22071 case Intrinsic::x86_avx2_pblendvb:
22072 // Don't try to simplify this intrinsic if we don't have AVX2.
22073 if (!Subtarget->hasAVX2())
22076 case Intrinsic::x86_avx_blendv_pd_256:
22077 case Intrinsic::x86_avx_blendv_ps_256:
22078 // Don't try to simplify this intrinsic if we don't have AVX.
22079 if (!Subtarget->hasAVX())
22082 case Intrinsic::x86_sse41_blendvps:
22083 case Intrinsic::x86_sse41_blendvpd:
22084 case Intrinsic::x86_sse41_pblendvb: {
22085 SDValue Op0 = N->getOperand(1);
22086 SDValue Op1 = N->getOperand(2);
22087 SDValue Mask = N->getOperand(3);
22089 // Don't try to simplify this intrinsic if we don't have SSE4.1.
22090 if (!Subtarget->hasSSE41())
22093 // fold (blend A, A, Mask) -> A
22096 // fold (blend A, B, allZeros) -> A
22097 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22099 // fold (blend A, B, allOnes) -> B
22100 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22103 // Simplify the case where the mask is a constant i32 value.
22104 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22105 if (C->isNullValue())
22107 if (C->isAllOnesValue())
22114 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22115 case Intrinsic::x86_sse2_psrai_w:
22116 case Intrinsic::x86_sse2_psrai_d:
22117 case Intrinsic::x86_avx2_psrai_w:
22118 case Intrinsic::x86_avx2_psrai_d:
22119 case Intrinsic::x86_sse2_psra_w:
22120 case Intrinsic::x86_sse2_psra_d:
22121 case Intrinsic::x86_avx2_psra_w:
22122 case Intrinsic::x86_avx2_psra_d: {
22123 SDValue Op0 = N->getOperand(1);
22124 SDValue Op1 = N->getOperand(2);
22125 EVT VT = Op0.getValueType();
22126 assert(VT.isVector() && "Expected a vector type!");
22128 if (isa<BuildVectorSDNode>(Op1))
22129 Op1 = Op1.getOperand(0);
22131 if (!isa<ConstantSDNode>(Op1))
22134 EVT SVT = VT.getVectorElementType();
22135 unsigned SVTBits = SVT.getSizeInBits();
22137 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22138 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22139 uint64_t ShAmt = C.getZExtValue();
22141 // Don't try to convert this shift into a ISD::SRA if the shift
22142 // count is bigger than or equal to the element size.
22143 if (ShAmt >= SVTBits)
22146 // Trivial case: if the shift count is zero, then fold this
22147 // into the first operand.
22151 // Replace this packed shift intrinsic with a target independent
22154 SDValue Splat = DAG.getConstant(C, DL, VT);
22155 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22160 /// PerformMulCombine - Optimize a single multiply with constant into two
22161 /// in order to implement it with two cheaper instructions, e.g.
22162 /// LEA + SHL, LEA + LEA.
22163 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22164 TargetLowering::DAGCombinerInfo &DCI) {
22165 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22168 EVT VT = N->getValueType(0);
22169 if (VT != MVT::i64 && VT != MVT::i32)
22172 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22175 uint64_t MulAmt = C->getZExtValue();
22176 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22179 uint64_t MulAmt1 = 0;
22180 uint64_t MulAmt2 = 0;
22181 if ((MulAmt % 9) == 0) {
22183 MulAmt2 = MulAmt / 9;
22184 } else if ((MulAmt % 5) == 0) {
22186 MulAmt2 = MulAmt / 5;
22187 } else if ((MulAmt % 3) == 0) {
22189 MulAmt2 = MulAmt / 3;
22192 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22195 if (isPowerOf2_64(MulAmt2) &&
22196 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22197 // If second multiplifer is pow2, issue it first. We want the multiply by
22198 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22200 std::swap(MulAmt1, MulAmt2);
22203 if (isPowerOf2_64(MulAmt1))
22204 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22205 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22207 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22208 DAG.getConstant(MulAmt1, DL, VT));
22210 if (isPowerOf2_64(MulAmt2))
22211 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22212 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22214 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22215 DAG.getConstant(MulAmt2, DL, VT));
22217 // Do not add new nodes to DAG combiner worklist.
22218 DCI.CombineTo(N, NewMul, false);
22223 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22224 SDValue N0 = N->getOperand(0);
22225 SDValue N1 = N->getOperand(1);
22226 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22227 EVT VT = N0.getValueType();
22229 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22230 // since the result of setcc_c is all zero's or all ones.
22231 if (VT.isInteger() && !VT.isVector() &&
22232 N1C && N0.getOpcode() == ISD::AND &&
22233 N0.getOperand(1).getOpcode() == ISD::Constant) {
22234 SDValue N00 = N0.getOperand(0);
22235 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22236 ((N00.getOpcode() == ISD::ANY_EXTEND ||
22237 N00.getOpcode() == ISD::ZERO_EXTEND) &&
22238 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22239 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22240 APInt ShAmt = N1C->getAPIntValue();
22241 Mask = Mask.shl(ShAmt);
22244 return DAG.getNode(ISD::AND, DL, VT,
22245 N00, DAG.getConstant(Mask, DL, VT));
22250 // Hardware support for vector shifts is sparse which makes us scalarize the
22251 // vector operations in many cases. Also, on sandybridge ADD is faster than
22253 // (shl V, 1) -> add V,V
22254 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22255 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22256 assert(N0.getValueType().isVector() && "Invalid vector shift type");
22257 // We shift all of the values by one. In many cases we do not have
22258 // hardware support for this operation. This is better expressed as an ADD
22260 if (N1SplatC->getZExtValue() == 1)
22261 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22267 /// \brief Returns a vector of 0s if the node in input is a vector logical
22268 /// shift by a constant amount which is known to be bigger than or equal
22269 /// to the vector element size in bits.
22270 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22271 const X86Subtarget *Subtarget) {
22272 EVT VT = N->getValueType(0);
22274 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22275 (!Subtarget->hasInt256() ||
22276 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22279 SDValue Amt = N->getOperand(1);
22281 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22282 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22283 APInt ShiftAmt = AmtSplat->getAPIntValue();
22284 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22286 // SSE2/AVX2 logical shifts always return a vector of 0s
22287 // if the shift amount is bigger than or equal to
22288 // the element size. The constant shift amount will be
22289 // encoded as a 8-bit immediate.
22290 if (ShiftAmt.trunc(8).uge(MaxAmount))
22291 return getZeroVector(VT, Subtarget, DAG, DL);
22297 /// PerformShiftCombine - Combine shifts.
22298 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22299 TargetLowering::DAGCombinerInfo &DCI,
22300 const X86Subtarget *Subtarget) {
22301 if (N->getOpcode() == ISD::SHL) {
22302 SDValue V = PerformSHLCombine(N, DAG);
22303 if (V.getNode()) return V;
22306 if (N->getOpcode() != ISD::SRA) {
22307 // Try to fold this logical shift into a zero vector.
22308 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22309 if (V.getNode()) return V;
22315 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
22316 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22317 // and friends. Likewise for OR -> CMPNEQSS.
22318 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22319 TargetLowering::DAGCombinerInfo &DCI,
22320 const X86Subtarget *Subtarget) {
22323 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22324 // we're requiring SSE2 for both.
22325 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22326 SDValue N0 = N->getOperand(0);
22327 SDValue N1 = N->getOperand(1);
22328 SDValue CMP0 = N0->getOperand(1);
22329 SDValue CMP1 = N1->getOperand(1);
22332 // The SETCCs should both refer to the same CMP.
22333 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22336 SDValue CMP00 = CMP0->getOperand(0);
22337 SDValue CMP01 = CMP0->getOperand(1);
22338 EVT VT = CMP00.getValueType();
22340 if (VT == MVT::f32 || VT == MVT::f64) {
22341 bool ExpectingFlags = false;
22342 // Check for any users that want flags:
22343 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22344 !ExpectingFlags && UI != UE; ++UI)
22345 switch (UI->getOpcode()) {
22350 ExpectingFlags = true;
22352 case ISD::CopyToReg:
22353 case ISD::SIGN_EXTEND:
22354 case ISD::ZERO_EXTEND:
22355 case ISD::ANY_EXTEND:
22359 if (!ExpectingFlags) {
22360 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22361 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22363 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22364 X86::CondCode tmp = cc0;
22369 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
22370 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22371 // FIXME: need symbolic constants for these magic numbers.
22372 // See X86ATTInstPrinter.cpp:printSSECC().
22373 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22374 if (Subtarget->hasAVX512()) {
22375 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22377 DAG.getConstant(x86cc, DL, MVT::i8));
22378 if (N->getValueType(0) != MVT::i1)
22379 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22383 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22384 CMP00.getValueType(), CMP00, CMP01,
22385 DAG.getConstant(x86cc, DL,
22388 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22389 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22391 if (is64BitFP && !Subtarget->is64Bit()) {
22392 // On a 32-bit target, we cannot bitcast the 64-bit float to a
22393 // 64-bit integer, since that's not a legal type. Since
22394 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22395 // bits, but can do this little dance to extract the lowest 32 bits
22396 // and work with those going forward.
22397 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22399 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22401 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22402 Vector32, DAG.getIntPtrConstant(0, DL));
22406 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22408 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22409 DAG.getConstant(1, DL, IntVT));
22410 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22412 return OneBitOfTruth;
22420 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22421 /// so it can be folded inside ANDNP.
22422 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22423 EVT VT = N->getValueType(0);
22425 // Match direct AllOnes for 128 and 256-bit vectors
22426 if (ISD::isBuildVectorAllOnes(N))
22429 // Look through a bit convert.
22430 if (N->getOpcode() == ISD::BITCAST)
22431 N = N->getOperand(0).getNode();
22433 // Sometimes the operand may come from a insert_subvector building a 256-bit
22435 if (VT.is256BitVector() &&
22436 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22437 SDValue V1 = N->getOperand(0);
22438 SDValue V2 = N->getOperand(1);
22440 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22441 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22442 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22443 ISD::isBuildVectorAllOnes(V2.getNode()))
22450 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22451 // register. In most cases we actually compare or select YMM-sized registers
22452 // and mixing the two types creates horrible code. This method optimizes
22453 // some of the transition sequences.
22454 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22455 TargetLowering::DAGCombinerInfo &DCI,
22456 const X86Subtarget *Subtarget) {
22457 EVT VT = N->getValueType(0);
22458 if (!VT.is256BitVector())
22461 assert((N->getOpcode() == ISD::ANY_EXTEND ||
22462 N->getOpcode() == ISD::ZERO_EXTEND ||
22463 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22465 SDValue Narrow = N->getOperand(0);
22466 EVT NarrowVT = Narrow->getValueType(0);
22467 if (!NarrowVT.is128BitVector())
22470 if (Narrow->getOpcode() != ISD::XOR &&
22471 Narrow->getOpcode() != ISD::AND &&
22472 Narrow->getOpcode() != ISD::OR)
22475 SDValue N0 = Narrow->getOperand(0);
22476 SDValue N1 = Narrow->getOperand(1);
22479 // The Left side has to be a trunc.
22480 if (N0.getOpcode() != ISD::TRUNCATE)
22483 // The type of the truncated inputs.
22484 EVT WideVT = N0->getOperand(0)->getValueType(0);
22488 // The right side has to be a 'trunc' or a constant vector.
22489 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22490 ConstantSDNode *RHSConstSplat = nullptr;
22491 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22492 RHSConstSplat = RHSBV->getConstantSplatNode();
22493 if (!RHSTrunc && !RHSConstSplat)
22496 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22498 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22501 // Set N0 and N1 to hold the inputs to the new wide operation.
22502 N0 = N0->getOperand(0);
22503 if (RHSConstSplat) {
22504 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22505 SDValue(RHSConstSplat, 0));
22506 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22507 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22508 } else if (RHSTrunc) {
22509 N1 = N1->getOperand(0);
22512 // Generate the wide operation.
22513 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22514 unsigned Opcode = N->getOpcode();
22516 case ISD::ANY_EXTEND:
22518 case ISD::ZERO_EXTEND: {
22519 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22520 APInt Mask = APInt::getAllOnesValue(InBits);
22521 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22522 return DAG.getNode(ISD::AND, DL, VT,
22523 Op, DAG.getConstant(Mask, DL, VT));
22525 case ISD::SIGN_EXTEND:
22526 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22527 Op, DAG.getValueType(NarrowVT));
22529 llvm_unreachable("Unexpected opcode");
22533 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22534 TargetLowering::DAGCombinerInfo &DCI,
22535 const X86Subtarget *Subtarget) {
22536 SDValue N0 = N->getOperand(0);
22537 SDValue N1 = N->getOperand(1);
22540 // A vector zext_in_reg may be represented as a shuffle,
22541 // feeding into a bitcast (this represents anyext) feeding into
22542 // an and with a mask.
22543 // We'd like to try to combine that into a shuffle with zero
22544 // plus a bitcast, removing the and.
22545 if (N0.getOpcode() != ISD::BITCAST ||
22546 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22549 // The other side of the AND should be a splat of 2^C, where C
22550 // is the number of bits in the source type.
22551 if (N1.getOpcode() == ISD::BITCAST)
22552 N1 = N1.getOperand(0);
22553 if (N1.getOpcode() != ISD::BUILD_VECTOR)
22555 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22557 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22558 EVT SrcType = Shuffle->getValueType(0);
22560 // We expect a single-source shuffle
22561 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22564 unsigned SrcSize = SrcType.getScalarSizeInBits();
22566 APInt SplatValue, SplatUndef;
22567 unsigned SplatBitSize;
22569 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22570 SplatBitSize, HasAnyUndefs))
22573 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22574 // Make sure the splat matches the mask we expect
22575 if (SplatBitSize > ResSize ||
22576 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22579 // Make sure the input and output size make sense
22580 if (SrcSize >= ResSize || ResSize % SrcSize)
22583 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22584 // The number of u's between each two values depends on the ratio between
22585 // the source and dest type.
22586 unsigned ZextRatio = ResSize / SrcSize;
22587 bool IsZext = true;
22588 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22589 if (i % ZextRatio) {
22590 if (Shuffle->getMaskElt(i) > 0) {
22596 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22597 // Expected element number
22607 // Ok, perform the transformation - replace the shuffle with
22608 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22609 // (instead of undef) where the k elements come from the zero vector.
22610 SmallVector<int, 8> Mask;
22611 unsigned NumElems = SrcType.getVectorNumElements();
22612 for (unsigned i = 0; i < NumElems; ++i)
22614 Mask.push_back(NumElems);
22616 Mask.push_back(i / ZextRatio);
22618 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22619 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22620 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22623 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22624 TargetLowering::DAGCombinerInfo &DCI,
22625 const X86Subtarget *Subtarget) {
22626 if (DCI.isBeforeLegalizeOps())
22629 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22632 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22635 EVT VT = N->getValueType(0);
22636 SDValue N0 = N->getOperand(0);
22637 SDValue N1 = N->getOperand(1);
22640 // Create BEXTR instructions
22641 // BEXTR is ((X >> imm) & (2**size-1))
22642 if (VT == MVT::i32 || VT == MVT::i64) {
22643 // Check for BEXTR.
22644 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22645 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22646 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22647 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22648 if (MaskNode && ShiftNode) {
22649 uint64_t Mask = MaskNode->getZExtValue();
22650 uint64_t Shift = ShiftNode->getZExtValue();
22651 if (isMask_64(Mask)) {
22652 uint64_t MaskSize = countPopulation(Mask);
22653 if (Shift + MaskSize <= VT.getSizeInBits())
22654 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22655 DAG.getConstant(Shift | (MaskSize << 8), DL,
22664 // Want to form ANDNP nodes:
22665 // 1) In the hopes of then easily combining them with OR and AND nodes
22666 // to form PBLEND/PSIGN.
22667 // 2) To match ANDN packed intrinsics
22668 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22671 // Check LHS for vnot
22672 if (N0.getOpcode() == ISD::XOR &&
22673 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22674 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22675 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22677 // Check RHS for vnot
22678 if (N1.getOpcode() == ISD::XOR &&
22679 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22680 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22681 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22686 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22687 TargetLowering::DAGCombinerInfo &DCI,
22688 const X86Subtarget *Subtarget) {
22689 if (DCI.isBeforeLegalizeOps())
22692 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22696 SDValue N0 = N->getOperand(0);
22697 SDValue N1 = N->getOperand(1);
22698 EVT VT = N->getValueType(0);
22700 // look for psign/blend
22701 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22702 if (!Subtarget->hasSSSE3() ||
22703 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22706 // Canonicalize pandn to RHS
22707 if (N0.getOpcode() == X86ISD::ANDNP)
22709 // or (and (m, y), (pandn m, x))
22710 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22711 SDValue Mask = N1.getOperand(0);
22712 SDValue X = N1.getOperand(1);
22714 if (N0.getOperand(0) == Mask)
22715 Y = N0.getOperand(1);
22716 if (N0.getOperand(1) == Mask)
22717 Y = N0.getOperand(0);
22719 // Check to see if the mask appeared in both the AND and ANDNP and
22723 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22724 // Look through mask bitcast.
22725 if (Mask.getOpcode() == ISD::BITCAST)
22726 Mask = Mask.getOperand(0);
22727 if (X.getOpcode() == ISD::BITCAST)
22728 X = X.getOperand(0);
22729 if (Y.getOpcode() == ISD::BITCAST)
22730 Y = Y.getOperand(0);
22732 EVT MaskVT = Mask.getValueType();
22734 // Validate that the Mask operand is a vector sra node.
22735 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22736 // there is no psrai.b
22737 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22738 unsigned SraAmt = ~0;
22739 if (Mask.getOpcode() == ISD::SRA) {
22740 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22741 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22742 SraAmt = AmtConst->getZExtValue();
22743 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22744 SDValue SraC = Mask.getOperand(1);
22745 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22747 if ((SraAmt + 1) != EltBits)
22752 // Now we know we at least have a plendvb with the mask val. See if
22753 // we can form a psignb/w/d.
22754 // psign = x.type == y.type == mask.type && y = sub(0, x);
22755 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22756 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22757 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22758 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22759 "Unsupported VT for PSIGN");
22760 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22761 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22763 // PBLENDVB only available on SSE 4.1
22764 if (!Subtarget->hasSSE41())
22767 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22769 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22770 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22771 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22772 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22773 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22777 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22780 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22781 MachineFunction &MF = DAG.getMachineFunction();
22783 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22785 // SHLD/SHRD instructions have lower register pressure, but on some
22786 // platforms they have higher latency than the equivalent
22787 // series of shifts/or that would otherwise be generated.
22788 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22789 // have higher latencies and we are not optimizing for size.
22790 if (!OptForSize && Subtarget->isSHLDSlow())
22793 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22795 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22797 if (!N0.hasOneUse() || !N1.hasOneUse())
22800 SDValue ShAmt0 = N0.getOperand(1);
22801 if (ShAmt0.getValueType() != MVT::i8)
22803 SDValue ShAmt1 = N1.getOperand(1);
22804 if (ShAmt1.getValueType() != MVT::i8)
22806 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22807 ShAmt0 = ShAmt0.getOperand(0);
22808 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22809 ShAmt1 = ShAmt1.getOperand(0);
22812 unsigned Opc = X86ISD::SHLD;
22813 SDValue Op0 = N0.getOperand(0);
22814 SDValue Op1 = N1.getOperand(0);
22815 if (ShAmt0.getOpcode() == ISD::SUB) {
22816 Opc = X86ISD::SHRD;
22817 std::swap(Op0, Op1);
22818 std::swap(ShAmt0, ShAmt1);
22821 unsigned Bits = VT.getSizeInBits();
22822 if (ShAmt1.getOpcode() == ISD::SUB) {
22823 SDValue Sum = ShAmt1.getOperand(0);
22824 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22825 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22826 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22827 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22828 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22829 return DAG.getNode(Opc, DL, VT,
22831 DAG.getNode(ISD::TRUNCATE, DL,
22834 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22835 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22837 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22838 return DAG.getNode(Opc, DL, VT,
22839 N0.getOperand(0), N1.getOperand(0),
22840 DAG.getNode(ISD::TRUNCATE, DL,
22847 // Generate NEG and CMOV for integer abs.
22848 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22849 EVT VT = N->getValueType(0);
22851 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22852 // 8-bit integer abs to NEG and CMOV.
22853 if (VT.isInteger() && VT.getSizeInBits() == 8)
22856 SDValue N0 = N->getOperand(0);
22857 SDValue N1 = N->getOperand(1);
22860 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22861 // and change it to SUB and CMOV.
22862 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22863 N0.getOpcode() == ISD::ADD &&
22864 N0.getOperand(1) == N1 &&
22865 N1.getOpcode() == ISD::SRA &&
22866 N1.getOperand(0) == N0.getOperand(0))
22867 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22868 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22869 // Generate SUB & CMOV.
22870 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22871 DAG.getConstant(0, DL, VT), N0.getOperand(0));
22873 SDValue Ops[] = { N0.getOperand(0), Neg,
22874 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22875 SDValue(Neg.getNode(), 1) };
22876 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22881 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22882 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22883 TargetLowering::DAGCombinerInfo &DCI,
22884 const X86Subtarget *Subtarget) {
22885 if (DCI.isBeforeLegalizeOps())
22888 if (Subtarget->hasCMov()) {
22889 SDValue RV = performIntegerAbsCombine(N, DAG);
22897 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22898 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22899 TargetLowering::DAGCombinerInfo &DCI,
22900 const X86Subtarget *Subtarget) {
22901 LoadSDNode *Ld = cast<LoadSDNode>(N);
22902 EVT RegVT = Ld->getValueType(0);
22903 EVT MemVT = Ld->getMemoryVT();
22905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22907 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22908 // into two 16-byte operations.
22909 ISD::LoadExtType Ext = Ld->getExtensionType();
22910 unsigned Alignment = Ld->getAlignment();
22911 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22912 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22913 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22914 unsigned NumElems = RegVT.getVectorNumElements();
22918 SDValue Ptr = Ld->getBasePtr();
22919 SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22921 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22923 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22924 Ld->getPointerInfo(), Ld->isVolatile(),
22925 Ld->isNonTemporal(), Ld->isInvariant(),
22927 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22928 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22929 Ld->getPointerInfo(), Ld->isVolatile(),
22930 Ld->isNonTemporal(), Ld->isInvariant(),
22931 std::min(16U, Alignment));
22932 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22934 Load2.getValue(1));
22936 SDValue NewVec = DAG.getUNDEF(RegVT);
22937 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22938 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22939 return DCI.CombineTo(N, NewVec, TF, true);
22945 /// PerformMLOADCombine - Resolve extending loads
22946 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22947 TargetLowering::DAGCombinerInfo &DCI,
22948 const X86Subtarget *Subtarget) {
22949 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22950 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22953 EVT VT = Mld->getValueType(0);
22954 unsigned NumElems = VT.getVectorNumElements();
22955 EVT LdVT = Mld->getMemoryVT();
22958 assert(LdVT != VT && "Cannot extend to the same type");
22959 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22960 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22961 // From, To sizes and ElemCount must be pow of two
22962 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22963 "Unexpected size for extending masked load");
22965 unsigned SizeRatio = ToSz / FromSz;
22966 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22968 // Create a type on which we perform the shuffle
22969 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22970 LdVT.getScalarType(), NumElems*SizeRatio);
22971 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22973 // Convert Src0 value
22974 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22975 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22976 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22977 for (unsigned i = 0; i != NumElems; ++i)
22978 ShuffleVec[i] = i * SizeRatio;
22980 // Can't shuffle using an illegal type.
22981 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22982 && "WideVecVT should be legal");
22983 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22984 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22986 // Prepare the new mask
22988 SDValue Mask = Mld->getMask();
22989 if (Mask.getValueType() == VT) {
22990 // Mask and original value have the same type
22991 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22992 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22993 for (unsigned i = 0; i != NumElems; ++i)
22994 ShuffleVec[i] = i * SizeRatio;
22995 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22996 ShuffleVec[i] = NumElems*SizeRatio;
22997 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22998 DAG.getConstant(0, dl, WideVecVT),
23002 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23003 unsigned WidenNumElts = NumElems*SizeRatio;
23004 unsigned MaskNumElts = VT.getVectorNumElements();
23005 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23008 unsigned NumConcat = WidenNumElts / MaskNumElts;
23009 SmallVector<SDValue, 16> Ops(NumConcat);
23010 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23012 for (unsigned i = 1; i != NumConcat; ++i)
23015 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23018 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23019 Mld->getBasePtr(), NewMask, WideSrc0,
23020 Mld->getMemoryVT(), Mld->getMemOperand(),
23022 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23023 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23026 /// PerformMSTORECombine - Resolve truncating stores
23027 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23028 const X86Subtarget *Subtarget) {
23029 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23030 if (!Mst->isTruncatingStore())
23033 EVT VT = Mst->getValue().getValueType();
23034 unsigned NumElems = VT.getVectorNumElements();
23035 EVT StVT = Mst->getMemoryVT();
23038 assert(StVT != VT && "Cannot truncate to the same type");
23039 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23040 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23042 // From, To sizes and ElemCount must be pow of two
23043 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23044 "Unexpected size for truncating masked store");
23045 // We are going to use the original vector elt for storing.
23046 // Accumulated smaller vector elements must be a multiple of the store size.
23047 assert (((NumElems * FromSz) % ToSz) == 0 &&
23048 "Unexpected ratio for truncating masked store");
23050 unsigned SizeRatio = FromSz / ToSz;
23051 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23053 // Create a type on which we perform the shuffle
23054 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23055 StVT.getScalarType(), NumElems*SizeRatio);
23057 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23059 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23060 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23061 for (unsigned i = 0; i != NumElems; ++i)
23062 ShuffleVec[i] = i * SizeRatio;
23064 // Can't shuffle using an illegal type.
23065 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23066 && "WideVecVT should be legal");
23068 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23069 DAG.getUNDEF(WideVecVT),
23073 SDValue Mask = Mst->getMask();
23074 if (Mask.getValueType() == VT) {
23075 // Mask and original value have the same type
23076 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23077 for (unsigned i = 0; i != NumElems; ++i)
23078 ShuffleVec[i] = i * SizeRatio;
23079 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23080 ShuffleVec[i] = NumElems*SizeRatio;
23081 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23082 DAG.getConstant(0, dl, WideVecVT),
23086 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23087 unsigned WidenNumElts = NumElems*SizeRatio;
23088 unsigned MaskNumElts = VT.getVectorNumElements();
23089 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23092 unsigned NumConcat = WidenNumElts / MaskNumElts;
23093 SmallVector<SDValue, 16> Ops(NumConcat);
23094 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23096 for (unsigned i = 1; i != NumConcat; ++i)
23099 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23102 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23103 NewMask, StVT, Mst->getMemOperand(), false);
23105 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23106 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23107 const X86Subtarget *Subtarget) {
23108 StoreSDNode *St = cast<StoreSDNode>(N);
23109 EVT VT = St->getValue().getValueType();
23110 EVT StVT = St->getMemoryVT();
23112 SDValue StoredVal = St->getOperand(1);
23113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23115 // If we are saving a concatenation of two XMM registers and 32-byte stores
23116 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23117 unsigned Alignment = St->getAlignment();
23118 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23119 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23120 StVT == VT && !IsAligned) {
23121 unsigned NumElems = VT.getVectorNumElements();
23125 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23126 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23128 SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23129 SDValue Ptr0 = St->getBasePtr();
23130 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23132 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23133 St->getPointerInfo(), St->isVolatile(),
23134 St->isNonTemporal(), Alignment);
23135 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23136 St->getPointerInfo(), St->isVolatile(),
23137 St->isNonTemporal(),
23138 std::min(16U, Alignment));
23139 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23142 // Optimize trunc store (of multiple scalars) to shuffle and store.
23143 // First, pack all of the elements in one place. Next, store to memory
23144 // in fewer chunks.
23145 if (St->isTruncatingStore() && VT.isVector()) {
23146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23147 unsigned NumElems = VT.getVectorNumElements();
23148 assert(StVT != VT && "Cannot truncate to the same type");
23149 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23150 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23152 // From, To sizes and ElemCount must be pow of two
23153 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23154 // We are going to use the original vector elt for storing.
23155 // Accumulated smaller vector elements must be a multiple of the store size.
23156 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23158 unsigned SizeRatio = FromSz / ToSz;
23160 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23162 // Create a type on which we perform the shuffle
23163 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23164 StVT.getScalarType(), NumElems*SizeRatio);
23166 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23168 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23169 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23170 for (unsigned i = 0; i != NumElems; ++i)
23171 ShuffleVec[i] = i * SizeRatio;
23173 // Can't shuffle using an illegal type.
23174 if (!TLI.isTypeLegal(WideVecVT))
23177 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23178 DAG.getUNDEF(WideVecVT),
23180 // At this point all of the data is stored at the bottom of the
23181 // register. We now need to save it to mem.
23183 // Find the largest store unit
23184 MVT StoreType = MVT::i8;
23185 for (MVT Tp : MVT::integer_valuetypes()) {
23186 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23190 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23191 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23192 (64 <= NumElems * ToSz))
23193 StoreType = MVT::f64;
23195 // Bitcast the original vector into a vector of store-size units
23196 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23197 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23198 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23199 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23200 SmallVector<SDValue, 8> Chains;
23201 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23202 TLI.getPointerTy());
23203 SDValue Ptr = St->getBasePtr();
23205 // Perform one or more big stores into memory.
23206 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23207 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23208 StoreType, ShuffWide,
23209 DAG.getIntPtrConstant(i, dl));
23210 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23211 St->getPointerInfo(), St->isVolatile(),
23212 St->isNonTemporal(), St->getAlignment());
23213 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23214 Chains.push_back(Ch);
23217 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23220 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
23221 // the FP state in cases where an emms may be missing.
23222 // A preferable solution to the general problem is to figure out the right
23223 // places to insert EMMS. This qualifies as a quick hack.
23225 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23226 if (VT.getSizeInBits() != 64)
23229 const Function *F = DAG.getMachineFunction().getFunction();
23230 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23232 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23233 if ((VT.isVector() ||
23234 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23235 isa<LoadSDNode>(St->getValue()) &&
23236 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23237 St->getChain().hasOneUse() && !St->isVolatile()) {
23238 SDNode* LdVal = St->getValue().getNode();
23239 LoadSDNode *Ld = nullptr;
23240 int TokenFactorIndex = -1;
23241 SmallVector<SDValue, 8> Ops;
23242 SDNode* ChainVal = St->getChain().getNode();
23243 // Must be a store of a load. We currently handle two cases: the load
23244 // is a direct child, and it's under an intervening TokenFactor. It is
23245 // possible to dig deeper under nested TokenFactors.
23246 if (ChainVal == LdVal)
23247 Ld = cast<LoadSDNode>(St->getChain());
23248 else if (St->getValue().hasOneUse() &&
23249 ChainVal->getOpcode() == ISD::TokenFactor) {
23250 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23251 if (ChainVal->getOperand(i).getNode() == LdVal) {
23252 TokenFactorIndex = i;
23253 Ld = cast<LoadSDNode>(St->getValue());
23255 Ops.push_back(ChainVal->getOperand(i));
23259 if (!Ld || !ISD::isNormalLoad(Ld))
23262 // If this is not the MMX case, i.e. we are just turning i64 load/store
23263 // into f64 load/store, avoid the transformation if there are multiple
23264 // uses of the loaded value.
23265 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23270 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23271 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23273 if (Subtarget->is64Bit() || F64IsLegal) {
23274 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23275 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23276 Ld->getPointerInfo(), Ld->isVolatile(),
23277 Ld->isNonTemporal(), Ld->isInvariant(),
23278 Ld->getAlignment());
23279 SDValue NewChain = NewLd.getValue(1);
23280 if (TokenFactorIndex != -1) {
23281 Ops.push_back(NewChain);
23282 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23284 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23285 St->getPointerInfo(),
23286 St->isVolatile(), St->isNonTemporal(),
23287 St->getAlignment());
23290 // Otherwise, lower to two pairs of 32-bit loads / stores.
23291 SDValue LoAddr = Ld->getBasePtr();
23292 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23293 DAG.getConstant(4, LdDL, MVT::i32));
23295 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23296 Ld->getPointerInfo(),
23297 Ld->isVolatile(), Ld->isNonTemporal(),
23298 Ld->isInvariant(), Ld->getAlignment());
23299 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23300 Ld->getPointerInfo().getWithOffset(4),
23301 Ld->isVolatile(), Ld->isNonTemporal(),
23303 MinAlign(Ld->getAlignment(), 4));
23305 SDValue NewChain = LoLd.getValue(1);
23306 if (TokenFactorIndex != -1) {
23307 Ops.push_back(LoLd);
23308 Ops.push_back(HiLd);
23309 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23312 LoAddr = St->getBasePtr();
23313 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23314 DAG.getConstant(4, StDL, MVT::i32));
23316 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23317 St->getPointerInfo(),
23318 St->isVolatile(), St->isNonTemporal(),
23319 St->getAlignment());
23320 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23321 St->getPointerInfo().getWithOffset(4),
23323 St->isNonTemporal(),
23324 MinAlign(St->getAlignment(), 4));
23325 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23328 // This is similar to the above case, but here we handle a scalar 64-bit
23329 // integer store that is extracted from a vector on a 32-bit target.
23330 // If we have SSE2, then we can treat it like a floating-point double
23331 // to get past legalization. The execution dependencies fixup pass will
23332 // choose the optimal machine instruction for the store if this really is
23333 // an integer or v2f32 rather than an f64.
23334 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23335 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23336 SDValue OldExtract = St->getOperand(1);
23337 SDValue ExtOp0 = OldExtract.getOperand(0);
23338 unsigned VecSize = ExtOp0.getValueSizeInBits();
23339 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23340 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23341 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23342 BitCast, OldExtract.getOperand(1));
23343 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23344 St->getPointerInfo(), St->isVolatile(),
23345 St->isNonTemporal(), St->getAlignment());
23351 /// Return 'true' if this vector operation is "horizontal"
23352 /// and return the operands for the horizontal operation in LHS and RHS. A
23353 /// horizontal operation performs the binary operation on successive elements
23354 /// of its first operand, then on successive elements of its second operand,
23355 /// returning the resulting values in a vector. For example, if
23356 /// A = < float a0, float a1, float a2, float a3 >
23358 /// B = < float b0, float b1, float b2, float b3 >
23359 /// then the result of doing a horizontal operation on A and B is
23360 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23361 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23362 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23363 /// set to A, RHS to B, and the routine returns 'true'.
23364 /// Note that the binary operation should have the property that if one of the
23365 /// operands is UNDEF then the result is UNDEF.
23366 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23367 // Look for the following pattern: if
23368 // A = < float a0, float a1, float a2, float a3 >
23369 // B = < float b0, float b1, float b2, float b3 >
23371 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23372 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23373 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23374 // which is A horizontal-op B.
23376 // At least one of the operands should be a vector shuffle.
23377 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23378 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23381 MVT VT = LHS.getSimpleValueType();
23383 assert((VT.is128BitVector() || VT.is256BitVector()) &&
23384 "Unsupported vector type for horizontal add/sub");
23386 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23387 // operate independently on 128-bit lanes.
23388 unsigned NumElts = VT.getVectorNumElements();
23389 unsigned NumLanes = VT.getSizeInBits()/128;
23390 unsigned NumLaneElts = NumElts / NumLanes;
23391 assert((NumLaneElts % 2 == 0) &&
23392 "Vector type should have an even number of elements in each lane");
23393 unsigned HalfLaneElts = NumLaneElts/2;
23395 // View LHS in the form
23396 // LHS = VECTOR_SHUFFLE A, B, LMask
23397 // If LHS is not a shuffle then pretend it is the shuffle
23398 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23399 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23402 SmallVector<int, 16> LMask(NumElts);
23403 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23404 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23405 A = LHS.getOperand(0);
23406 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23407 B = LHS.getOperand(1);
23408 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23409 std::copy(Mask.begin(), Mask.end(), LMask.begin());
23411 if (LHS.getOpcode() != ISD::UNDEF)
23413 for (unsigned i = 0; i != NumElts; ++i)
23417 // Likewise, view RHS in the form
23418 // RHS = VECTOR_SHUFFLE C, D, RMask
23420 SmallVector<int, 16> RMask(NumElts);
23421 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23422 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23423 C = RHS.getOperand(0);
23424 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23425 D = RHS.getOperand(1);
23426 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23427 std::copy(Mask.begin(), Mask.end(), RMask.begin());
23429 if (RHS.getOpcode() != ISD::UNDEF)
23431 for (unsigned i = 0; i != NumElts; ++i)
23435 // Check that the shuffles are both shuffling the same vectors.
23436 if (!(A == C && B == D) && !(A == D && B == C))
23439 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23440 if (!A.getNode() && !B.getNode())
23443 // If A and B occur in reverse order in RHS, then "swap" them (which means
23444 // rewriting the mask).
23446 ShuffleVectorSDNode::commuteMask(RMask);
23448 // At this point LHS and RHS are equivalent to
23449 // LHS = VECTOR_SHUFFLE A, B, LMask
23450 // RHS = VECTOR_SHUFFLE A, B, RMask
23451 // Check that the masks correspond to performing a horizontal operation.
23452 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23453 for (unsigned i = 0; i != NumLaneElts; ++i) {
23454 int LIdx = LMask[i+l], RIdx = RMask[i+l];
23456 // Ignore any UNDEF components.
23457 if (LIdx < 0 || RIdx < 0 ||
23458 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23459 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23462 // Check that successive elements are being operated on. If not, this is
23463 // not a horizontal operation.
23464 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23465 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23466 if (!(LIdx == Index && RIdx == Index + 1) &&
23467 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23472 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23473 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23477 /// Do target-specific dag combines on floating point adds.
23478 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23479 const X86Subtarget *Subtarget) {
23480 EVT VT = N->getValueType(0);
23481 SDValue LHS = N->getOperand(0);
23482 SDValue RHS = N->getOperand(1);
23484 // Try to synthesize horizontal adds from adds of shuffles.
23485 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23486 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23487 isHorizontalBinOp(LHS, RHS, true))
23488 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23492 /// Do target-specific dag combines on floating point subs.
23493 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23494 const X86Subtarget *Subtarget) {
23495 EVT VT = N->getValueType(0);
23496 SDValue LHS = N->getOperand(0);
23497 SDValue RHS = N->getOperand(1);
23499 // Try to synthesize horizontal subs from subs of shuffles.
23500 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23501 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23502 isHorizontalBinOp(LHS, RHS, false))
23503 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23507 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23508 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23509 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23511 // F[X]OR(0.0, x) -> x
23512 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23513 if (C->getValueAPF().isPosZero())
23514 return N->getOperand(1);
23516 // F[X]OR(x, 0.0) -> x
23517 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23518 if (C->getValueAPF().isPosZero())
23519 return N->getOperand(0);
23523 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23524 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23525 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23527 // Only perform optimizations if UnsafeMath is used.
23528 if (!DAG.getTarget().Options.UnsafeFPMath)
23531 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23532 // into FMINC and FMAXC, which are Commutative operations.
23533 unsigned NewOp = 0;
23534 switch (N->getOpcode()) {
23535 default: llvm_unreachable("unknown opcode");
23536 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
23537 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
23540 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23541 N->getOperand(0), N->getOperand(1));
23544 /// Do target-specific dag combines on X86ISD::FAND nodes.
23545 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23546 // FAND(0.0, x) -> 0.0
23547 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23548 if (C->getValueAPF().isPosZero())
23549 return N->getOperand(0);
23551 // FAND(x, 0.0) -> 0.0
23552 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23553 if (C->getValueAPF().isPosZero())
23554 return N->getOperand(1);
23559 /// Do target-specific dag combines on X86ISD::FANDN nodes
23560 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23561 // FANDN(0.0, x) -> x
23562 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23563 if (C->getValueAPF().isPosZero())
23564 return N->getOperand(1);
23566 // FANDN(x, 0.0) -> 0.0
23567 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23568 if (C->getValueAPF().isPosZero())
23569 return N->getOperand(1);
23574 static SDValue PerformBTCombine(SDNode *N,
23576 TargetLowering::DAGCombinerInfo &DCI) {
23577 // BT ignores high bits in the bit index operand.
23578 SDValue Op1 = N->getOperand(1);
23579 if (Op1.hasOneUse()) {
23580 unsigned BitWidth = Op1.getValueSizeInBits();
23581 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23582 APInt KnownZero, KnownOne;
23583 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23584 !DCI.isBeforeLegalizeOps());
23585 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23586 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23587 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23588 DCI.CommitTargetLoweringOpt(TLO);
23593 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23594 SDValue Op = N->getOperand(0);
23595 if (Op.getOpcode() == ISD::BITCAST)
23596 Op = Op.getOperand(0);
23597 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23598 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23599 VT.getVectorElementType().getSizeInBits() ==
23600 OpVT.getVectorElementType().getSizeInBits()) {
23601 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23606 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23607 const X86Subtarget *Subtarget) {
23608 EVT VT = N->getValueType(0);
23609 if (!VT.isVector())
23612 SDValue N0 = N->getOperand(0);
23613 SDValue N1 = N->getOperand(1);
23614 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23617 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23618 // both SSE and AVX2 since there is no sign-extended shift right
23619 // operation on a vector with 64-bit elements.
23620 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23621 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23622 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23623 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23624 SDValue N00 = N0.getOperand(0);
23626 // EXTLOAD has a better solution on AVX2,
23627 // it may be replaced with X86ISD::VSEXT node.
23628 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23629 if (!ISD::isNormalLoad(N00.getNode()))
23632 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23633 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23635 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23641 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23642 TargetLowering::DAGCombinerInfo &DCI,
23643 const X86Subtarget *Subtarget) {
23644 SDValue N0 = N->getOperand(0);
23645 EVT VT = N->getValueType(0);
23647 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23648 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23649 // This exposes the sext to the sdivrem lowering, so that it directly extends
23650 // from AH (which we otherwise need to do contortions to access).
23651 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23652 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23654 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23655 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23656 N0.getOperand(0), N0.getOperand(1));
23657 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23658 return R.getValue(1);
23661 if (!DCI.isBeforeLegalizeOps())
23664 if (!Subtarget->hasFp256())
23667 if (VT.isVector() && VT.getSizeInBits() == 256) {
23668 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23676 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23677 const X86Subtarget* Subtarget) {
23679 EVT VT = N->getValueType(0);
23681 // Let legalize expand this if it isn't a legal type yet.
23682 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23685 EVT ScalarVT = VT.getScalarType();
23686 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23687 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23690 SDValue A = N->getOperand(0);
23691 SDValue B = N->getOperand(1);
23692 SDValue C = N->getOperand(2);
23694 bool NegA = (A.getOpcode() == ISD::FNEG);
23695 bool NegB = (B.getOpcode() == ISD::FNEG);
23696 bool NegC = (C.getOpcode() == ISD::FNEG);
23698 // Negative multiplication when NegA xor NegB
23699 bool NegMul = (NegA != NegB);
23701 A = A.getOperand(0);
23703 B = B.getOperand(0);
23705 C = C.getOperand(0);
23709 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23711 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23713 return DAG.getNode(Opcode, dl, VT, A, B, C);
23716 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23717 TargetLowering::DAGCombinerInfo &DCI,
23718 const X86Subtarget *Subtarget) {
23719 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23720 // (and (i32 x86isd::setcc_carry), 1)
23721 // This eliminates the zext. This transformation is necessary because
23722 // ISD::SETCC is always legalized to i8.
23724 SDValue N0 = N->getOperand(0);
23725 EVT VT = N->getValueType(0);
23727 if (N0.getOpcode() == ISD::AND &&
23729 N0.getOperand(0).hasOneUse()) {
23730 SDValue N00 = N0.getOperand(0);
23731 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23732 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23733 if (!C || C->getZExtValue() != 1)
23735 return DAG.getNode(ISD::AND, dl, VT,
23736 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23737 N00.getOperand(0), N00.getOperand(1)),
23738 DAG.getConstant(1, dl, VT));
23742 if (N0.getOpcode() == ISD::TRUNCATE &&
23744 N0.getOperand(0).hasOneUse()) {
23745 SDValue N00 = N0.getOperand(0);
23746 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23747 return DAG.getNode(ISD::AND, dl, VT,
23748 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23749 N00.getOperand(0), N00.getOperand(1)),
23750 DAG.getConstant(1, dl, VT));
23753 if (VT.is256BitVector()) {
23754 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23759 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23760 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23761 // This exposes the zext to the udivrem lowering, so that it directly extends
23762 // from AH (which we otherwise need to do contortions to access).
23763 if (N0.getOpcode() == ISD::UDIVREM &&
23764 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23765 (VT == MVT::i32 || VT == MVT::i64)) {
23766 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23767 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23768 N0.getOperand(0), N0.getOperand(1));
23769 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23770 return R.getValue(1);
23776 // Optimize x == -y --> x+y == 0
23777 // x != -y --> x+y != 0
23778 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23779 const X86Subtarget* Subtarget) {
23780 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23781 SDValue LHS = N->getOperand(0);
23782 SDValue RHS = N->getOperand(1);
23783 EVT VT = N->getValueType(0);
23786 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23787 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23788 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23789 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23790 LHS.getOperand(1));
23791 return DAG.getSetCC(DL, N->getValueType(0), addV,
23792 DAG.getConstant(0, DL, addV.getValueType()), CC);
23794 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23795 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23796 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23797 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23798 RHS.getOperand(1));
23799 return DAG.getSetCC(DL, N->getValueType(0), addV,
23800 DAG.getConstant(0, DL, addV.getValueType()), CC);
23803 if (VT.getScalarType() == MVT::i1 &&
23804 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23806 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23807 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23808 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23810 if (!IsSEXT0 || !IsVZero1) {
23811 // Swap the operands and update the condition code.
23812 std::swap(LHS, RHS);
23813 CC = ISD::getSetCCSwappedOperands(CC);
23815 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23816 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23817 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23820 if (IsSEXT0 && IsVZero1) {
23821 assert(VT == LHS.getOperand(0).getValueType() &&
23822 "Uexpected operand type");
23823 if (CC == ISD::SETGT)
23824 return DAG.getConstant(0, DL, VT);
23825 if (CC == ISD::SETLE)
23826 return DAG.getConstant(1, DL, VT);
23827 if (CC == ISD::SETEQ || CC == ISD::SETGE)
23828 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23830 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23831 "Unexpected condition code!");
23832 return LHS.getOperand(0);
23839 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23840 SelectionDAG &DAG) {
23842 MVT VT = Load->getSimpleValueType(0);
23843 MVT EVT = VT.getVectorElementType();
23844 SDValue Addr = Load->getOperand(1);
23845 SDValue NewAddr = DAG.getNode(
23846 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23847 DAG.getConstant(Index * EVT.getStoreSize(), dl,
23848 Addr.getSimpleValueType()));
23851 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23852 DAG.getMachineFunction().getMachineMemOperand(
23853 Load->getMemOperand(), 0, EVT.getStoreSize()));
23857 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23858 const X86Subtarget *Subtarget) {
23860 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23861 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23862 "X86insertps is only defined for v4x32");
23864 SDValue Ld = N->getOperand(1);
23865 if (MayFoldLoad(Ld)) {
23866 // Extract the countS bits from the immediate so we can get the proper
23867 // address when narrowing the vector load to a specific element.
23868 // When the second source op is a memory address, insertps doesn't use
23869 // countS and just gets an f32 from that address.
23870 unsigned DestIndex =
23871 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23873 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23875 // Create this as a scalar to vector to match the instruction pattern.
23876 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23877 // countS bits are ignored when loading from memory on insertps, which
23878 // means we don't need to explicitly set them to 0.
23879 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23880 LoadScalarToVector, N->getOperand(2));
23885 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23886 SDValue V0 = N->getOperand(0);
23887 SDValue V1 = N->getOperand(1);
23889 EVT VT = N->getValueType(0);
23891 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23892 // operands and changing the mask to 1. This saves us a bunch of
23893 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23894 // x86InstrInfo knows how to commute this back after instruction selection
23895 // if it would help register allocation.
23897 // TODO: If optimizing for size or a processor that doesn't suffer from
23898 // partial register update stalls, this should be transformed into a MOVSD
23899 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23901 if (VT == MVT::v2f64)
23902 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23903 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23904 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23905 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23911 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23912 // as "sbb reg,reg", since it can be extended without zext and produces
23913 // an all-ones bit which is more useful than 0/1 in some cases.
23914 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23917 return DAG.getNode(ISD::AND, DL, VT,
23918 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23919 DAG.getConstant(X86::COND_B, DL, MVT::i8),
23921 DAG.getConstant(1, DL, VT));
23922 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23923 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23924 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23925 DAG.getConstant(X86::COND_B, DL, MVT::i8),
23929 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23930 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23931 TargetLowering::DAGCombinerInfo &DCI,
23932 const X86Subtarget *Subtarget) {
23934 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23935 SDValue EFLAGS = N->getOperand(1);
23937 if (CC == X86::COND_A) {
23938 // Try to convert COND_A into COND_B in an attempt to facilitate
23939 // materializing "setb reg".
23941 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23942 // cannot take an immediate as its first operand.
23944 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23945 EFLAGS.getValueType().isInteger() &&
23946 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23947 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23948 EFLAGS.getNode()->getVTList(),
23949 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23950 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23951 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23955 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23956 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23958 if (CC == X86::COND_B)
23959 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23963 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23964 if (Flags.getNode()) {
23965 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23966 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23972 // Optimize branch condition evaluation.
23974 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23975 TargetLowering::DAGCombinerInfo &DCI,
23976 const X86Subtarget *Subtarget) {
23978 SDValue Chain = N->getOperand(0);
23979 SDValue Dest = N->getOperand(1);
23980 SDValue EFLAGS = N->getOperand(3);
23981 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23985 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23986 if (Flags.getNode()) {
23987 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23988 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23995 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23996 SelectionDAG &DAG) {
23997 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23998 // optimize away operation when it's from a constant.
24000 // The general transformation is:
24001 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24002 // AND(VECTOR_CMP(x,y), constant2)
24003 // constant2 = UNARYOP(constant)
24005 // Early exit if this isn't a vector operation, the operand of the
24006 // unary operation isn't a bitwise AND, or if the sizes of the operations
24007 // aren't the same.
24008 EVT VT = N->getValueType(0);
24009 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24010 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24011 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24014 // Now check that the other operand of the AND is a constant. We could
24015 // make the transformation for non-constant splats as well, but it's unclear
24016 // that would be a benefit as it would not eliminate any operations, just
24017 // perform one more step in scalar code before moving to the vector unit.
24018 if (BuildVectorSDNode *BV =
24019 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24020 // Bail out if the vector isn't a constant.
24021 if (!BV->isConstant())
24024 // Everything checks out. Build up the new and improved node.
24026 EVT IntVT = BV->getValueType(0);
24027 // Create a new constant of the appropriate type for the transformed
24029 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24030 // The AND node needs bitcasts to/from an integer vector type around it.
24031 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24032 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24033 N->getOperand(0)->getOperand(0), MaskConst);
24034 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24041 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24042 const X86Subtarget *Subtarget) {
24043 // First try to optimize away the conversion entirely when it's
24044 // conditionally from a constant. Vectors only.
24045 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24046 if (Res != SDValue())
24049 // Now move on to more general possibilities.
24050 SDValue Op0 = N->getOperand(0);
24051 EVT InVT = Op0->getValueType(0);
24053 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24054 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24056 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24057 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24058 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24061 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24062 // a 32-bit target where SSE doesn't support i64->FP operations.
24063 if (Op0.getOpcode() == ISD::LOAD) {
24064 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24065 EVT VT = Ld->getValueType(0);
24067 // This transformation is not supported if the result type is f16
24068 if (N->getValueType(0) == MVT::f16)
24071 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24072 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24073 !Subtarget->is64Bit() && VT == MVT::i64) {
24074 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24075 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24076 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24083 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24084 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24085 X86TargetLowering::DAGCombinerInfo &DCI) {
24086 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24087 // the result is either zero or one (depending on the input carry bit).
24088 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24089 if (X86::isZeroNode(N->getOperand(0)) &&
24090 X86::isZeroNode(N->getOperand(1)) &&
24091 // We don't have a good way to replace an EFLAGS use, so only do this when
24093 SDValue(N, 1).use_empty()) {
24095 EVT VT = N->getValueType(0);
24096 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24097 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24098 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24099 DAG.getConstant(X86::COND_B, DL,
24102 DAG.getConstant(1, DL, VT));
24103 return DCI.CombineTo(N, Res1, CarryOut);
24109 // fold (add Y, (sete X, 0)) -> adc 0, Y
24110 // (add Y, (setne X, 0)) -> sbb -1, Y
24111 // (sub (sete X, 0), Y) -> sbb 0, Y
24112 // (sub (setne X, 0), Y) -> adc -1, Y
24113 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24116 // Look through ZExts.
24117 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24118 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24121 SDValue SetCC = Ext.getOperand(0);
24122 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24125 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24126 if (CC != X86::COND_E && CC != X86::COND_NE)
24129 SDValue Cmp = SetCC.getOperand(1);
24130 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24131 !X86::isZeroNode(Cmp.getOperand(1)) ||
24132 !Cmp.getOperand(0).getValueType().isInteger())
24135 SDValue CmpOp0 = Cmp.getOperand(0);
24136 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24137 DAG.getConstant(1, DL, CmpOp0.getValueType()));
24139 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24140 if (CC == X86::COND_NE)
24141 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24142 DL, OtherVal.getValueType(), OtherVal,
24143 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24145 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24146 DL, OtherVal.getValueType(), OtherVal,
24147 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24150 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24151 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24152 const X86Subtarget *Subtarget) {
24153 EVT VT = N->getValueType(0);
24154 SDValue Op0 = N->getOperand(0);
24155 SDValue Op1 = N->getOperand(1);
24157 // Try to synthesize horizontal adds from adds of shuffles.
24158 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24159 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24160 isHorizontalBinOp(Op0, Op1, true))
24161 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24163 return OptimizeConditionalInDecrement(N, DAG);
24166 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24167 const X86Subtarget *Subtarget) {
24168 SDValue Op0 = N->getOperand(0);
24169 SDValue Op1 = N->getOperand(1);
24171 // X86 can't encode an immediate LHS of a sub. See if we can push the
24172 // negation into a preceding instruction.
24173 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24174 // If the RHS of the sub is a XOR with one use and a constant, invert the
24175 // immediate. Then add one to the LHS of the sub so we can turn
24176 // X-Y -> X+~Y+1, saving one register.
24177 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24178 isa<ConstantSDNode>(Op1.getOperand(1))) {
24179 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24180 EVT VT = Op0.getValueType();
24181 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24183 DAG.getConstant(~XorC, SDLoc(Op1), VT));
24184 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24185 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24189 // Try to synthesize horizontal adds from adds of shuffles.
24190 EVT VT = N->getValueType(0);
24191 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24192 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24193 isHorizontalBinOp(Op0, Op1, true))
24194 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24196 return OptimizeConditionalInDecrement(N, DAG);
24199 /// performVZEXTCombine - Performs build vector combines
24200 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24201 TargetLowering::DAGCombinerInfo &DCI,
24202 const X86Subtarget *Subtarget) {
24204 MVT VT = N->getSimpleValueType(0);
24205 SDValue Op = N->getOperand(0);
24206 MVT OpVT = Op.getSimpleValueType();
24207 MVT OpEltVT = OpVT.getVectorElementType();
24208 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24210 // (vzext (bitcast (vzext (x)) -> (vzext x)
24212 while (V.getOpcode() == ISD::BITCAST)
24213 V = V.getOperand(0);
24215 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24216 MVT InnerVT = V.getSimpleValueType();
24217 MVT InnerEltVT = InnerVT.getVectorElementType();
24219 // If the element sizes match exactly, we can just do one larger vzext. This
24220 // is always an exact type match as vzext operates on integer types.
24221 if (OpEltVT == InnerEltVT) {
24222 assert(OpVT == InnerVT && "Types must match for vzext!");
24223 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24226 // The only other way we can combine them is if only a single element of the
24227 // inner vzext is used in the input to the outer vzext.
24228 if (InnerEltVT.getSizeInBits() < InputBits)
24231 // In this case, the inner vzext is completely dead because we're going to
24232 // only look at bits inside of the low element. Just do the outer vzext on
24233 // a bitcast of the input to the inner.
24234 return DAG.getNode(X86ISD::VZEXT, DL, VT,
24235 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24238 // Check if we can bypass extracting and re-inserting an element of an input
24239 // vector. Essentialy:
24240 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24241 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24242 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24243 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24244 SDValue ExtractedV = V.getOperand(0);
24245 SDValue OrigV = ExtractedV.getOperand(0);
24246 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24247 if (ExtractIdx->getZExtValue() == 0) {
24248 MVT OrigVT = OrigV.getSimpleValueType();
24249 // Extract a subvector if necessary...
24250 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24251 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24252 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24253 OrigVT.getVectorNumElements() / Ratio);
24254 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24255 DAG.getIntPtrConstant(0, DL));
24257 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24258 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24265 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24266 DAGCombinerInfo &DCI) const {
24267 SelectionDAG &DAG = DCI.DAG;
24268 switch (N->getOpcode()) {
24270 case ISD::EXTRACT_VECTOR_ELT:
24271 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24274 case X86ISD::SHRUNKBLEND:
24275 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24276 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
24277 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24278 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
24279 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
24280 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
24281 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
24284 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
24285 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
24286 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
24287 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
24288 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
24289 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24290 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
24291 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
24292 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24293 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
24294 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
24296 case X86ISD::FOR: return PerformFORCombine(N, DAG);
24298 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
24299 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
24300 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
24301 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
24302 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
24303 case ISD::ANY_EXTEND:
24304 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
24305 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
24306 case ISD::SIGN_EXTEND_INREG:
24307 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24308 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24309 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
24310 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24311 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24312 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
24313 case X86ISD::SHUFP: // Handle all target specific shuffles
24314 case X86ISD::PALIGNR:
24315 case X86ISD::UNPCKH:
24316 case X86ISD::UNPCKL:
24317 case X86ISD::MOVHLPS:
24318 case X86ISD::MOVLHPS:
24319 case X86ISD::PSHUFB:
24320 case X86ISD::PSHUFD:
24321 case X86ISD::PSHUFHW:
24322 case X86ISD::PSHUFLW:
24323 case X86ISD::MOVSS:
24324 case X86ISD::MOVSD:
24325 case X86ISD::VPERMILPI:
24326 case X86ISD::VPERM2X128:
24327 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24328 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
24329 case ISD::INTRINSIC_WO_CHAIN:
24330 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24331 case X86ISD::INSERTPS: {
24332 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24333 return PerformINSERTPSCombine(N, DAG, Subtarget);
24336 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
24342 /// isTypeDesirableForOp - Return true if the target has native support for
24343 /// the specified value type and it is 'desirable' to use the type for the
24344 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24345 /// instruction encodings are longer and some i16 instructions are slow.
24346 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24347 if (!isTypeLegal(VT))
24349 if (VT != MVT::i16)
24356 case ISD::SIGN_EXTEND:
24357 case ISD::ZERO_EXTEND:
24358 case ISD::ANY_EXTEND:
24371 /// IsDesirableToPromoteOp - This method query the target whether it is
24372 /// beneficial for dag combiner to promote the specified node. If true, it
24373 /// should return the desired promotion type by reference.
24374 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24375 EVT VT = Op.getValueType();
24376 if (VT != MVT::i16)
24379 bool Promote = false;
24380 bool Commute = false;
24381 switch (Op.getOpcode()) {
24384 LoadSDNode *LD = cast<LoadSDNode>(Op);
24385 // If the non-extending load has a single use and it's not live out, then it
24386 // might be folded.
24387 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24388 Op.hasOneUse()*/) {
24389 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24390 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24391 // The only case where we'd want to promote LOAD (rather then it being
24392 // promoted as an operand is when it's only use is liveout.
24393 if (UI->getOpcode() != ISD::CopyToReg)
24400 case ISD::SIGN_EXTEND:
24401 case ISD::ZERO_EXTEND:
24402 case ISD::ANY_EXTEND:
24407 SDValue N0 = Op.getOperand(0);
24408 // Look out for (store (shl (load), x)).
24409 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24422 SDValue N0 = Op.getOperand(0);
24423 SDValue N1 = Op.getOperand(1);
24424 if (!Commute && MayFoldLoad(N1))
24426 // Avoid disabling potential load folding opportunities.
24427 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24429 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24439 //===----------------------------------------------------------------------===//
24440 // X86 Inline Assembly Support
24441 //===----------------------------------------------------------------------===//
24443 // Helper to match a string separated by whitespace.
24444 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24445 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24447 for (StringRef Piece : Pieces) {
24448 if (!S.startswith(Piece)) // Check if the piece matches.
24451 S = S.substr(Piece.size());
24452 StringRef::size_type Pos = S.find_first_not_of(" \t");
24453 if (Pos == 0) // We matched a prefix.
24462 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24464 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24465 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24466 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24467 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24469 if (AsmPieces.size() == 3)
24471 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24478 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24479 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24481 std::string AsmStr = IA->getAsmString();
24483 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24484 if (!Ty || Ty->getBitWidth() % 16 != 0)
24487 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24488 SmallVector<StringRef, 4> AsmPieces;
24489 SplitString(AsmStr, AsmPieces, ";\n");
24491 switch (AsmPieces.size()) {
24492 default: return false;
24494 // FIXME: this should verify that we are targeting a 486 or better. If not,
24495 // we will turn this bswap into something that will be lowered to logical
24496 // ops instead of emitting the bswap asm. For now, we don't support 486 or
24497 // lower so don't worry about this.
24499 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24500 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24501 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24502 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24503 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24504 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24505 // No need to check constraints, nothing other than the equivalent of
24506 // "=r,0" would be valid here.
24507 return IntrinsicLowering::LowerToByteSwap(CI);
24510 // rorw $$8, ${0:w} --> llvm.bswap.i16
24511 if (CI->getType()->isIntegerTy(16) &&
24512 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24513 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24514 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24516 const std::string &ConstraintsStr = IA->getConstraintString();
24517 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24518 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24519 if (clobbersFlagRegisters(AsmPieces))
24520 return IntrinsicLowering::LowerToByteSwap(CI);
24524 if (CI->getType()->isIntegerTy(32) &&
24525 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24526 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24527 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24528 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24530 const std::string &ConstraintsStr = IA->getConstraintString();
24531 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24532 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24533 if (clobbersFlagRegisters(AsmPieces))
24534 return IntrinsicLowering::LowerToByteSwap(CI);
24537 if (CI->getType()->isIntegerTy(64)) {
24538 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24539 if (Constraints.size() >= 2 &&
24540 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24541 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24542 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
24543 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24544 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24545 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24546 return IntrinsicLowering::LowerToByteSwap(CI);
24554 /// getConstraintType - Given a constraint letter, return the type of
24555 /// constraint it is for this target.
24556 X86TargetLowering::ConstraintType
24557 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24558 if (Constraint.size() == 1) {
24559 switch (Constraint[0]) {
24570 return C_RegisterClass;
24594 return TargetLowering::getConstraintType(Constraint);
24597 /// Examine constraint type and operand type and determine a weight value.
24598 /// This object must already have been set up with the operand type
24599 /// and the current alternative constraint selected.
24600 TargetLowering::ConstraintWeight
24601 X86TargetLowering::getSingleConstraintMatchWeight(
24602 AsmOperandInfo &info, const char *constraint) const {
24603 ConstraintWeight weight = CW_Invalid;
24604 Value *CallOperandVal = info.CallOperandVal;
24605 // If we don't have a value, we can't do a match,
24606 // but allow it at the lowest weight.
24607 if (!CallOperandVal)
24609 Type *type = CallOperandVal->getType();
24610 // Look at the constraint type.
24611 switch (*constraint) {
24613 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24624 if (CallOperandVal->getType()->isIntegerTy())
24625 weight = CW_SpecificReg;
24630 if (type->isFloatingPointTy())
24631 weight = CW_SpecificReg;
24634 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24635 weight = CW_SpecificReg;
24639 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24640 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24641 weight = CW_Register;
24644 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24645 if (C->getZExtValue() <= 31)
24646 weight = CW_Constant;
24650 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24651 if (C->getZExtValue() <= 63)
24652 weight = CW_Constant;
24656 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24657 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24658 weight = CW_Constant;
24662 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24663 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24664 weight = CW_Constant;
24668 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24669 if (C->getZExtValue() <= 3)
24670 weight = CW_Constant;
24674 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24675 if (C->getZExtValue() <= 0xff)
24676 weight = CW_Constant;
24681 if (isa<ConstantFP>(CallOperandVal)) {
24682 weight = CW_Constant;
24686 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24687 if ((C->getSExtValue() >= -0x80000000LL) &&
24688 (C->getSExtValue() <= 0x7fffffffLL))
24689 weight = CW_Constant;
24693 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24694 if (C->getZExtValue() <= 0xffffffff)
24695 weight = CW_Constant;
24702 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24703 /// with another that has more specific requirements based on the type of the
24704 /// corresponding operand.
24705 const char *X86TargetLowering::
24706 LowerXConstraint(EVT ConstraintVT) const {
24707 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24708 // 'f' like normal targets.
24709 if (ConstraintVT.isFloatingPoint()) {
24710 if (Subtarget->hasSSE2())
24712 if (Subtarget->hasSSE1())
24716 return TargetLowering::LowerXConstraint(ConstraintVT);
24719 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24720 /// vector. If it is invalid, don't add anything to Ops.
24721 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24722 std::string &Constraint,
24723 std::vector<SDValue>&Ops,
24724 SelectionDAG &DAG) const {
24727 // Only support length 1 constraints for now.
24728 if (Constraint.length() > 1) return;
24730 char ConstraintLetter = Constraint[0];
24731 switch (ConstraintLetter) {
24734 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24735 if (C->getZExtValue() <= 31) {
24736 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24737 Op.getValueType());
24743 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24744 if (C->getZExtValue() <= 63) {
24745 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24746 Op.getValueType());
24752 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24753 if (isInt<8>(C->getSExtValue())) {
24754 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24755 Op.getValueType());
24761 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24762 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24763 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24764 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24765 Op.getValueType());
24771 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24772 if (C->getZExtValue() <= 3) {
24773 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24774 Op.getValueType());
24780 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24781 if (C->getZExtValue() <= 255) {
24782 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24783 Op.getValueType());
24789 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24790 if (C->getZExtValue() <= 127) {
24791 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24792 Op.getValueType());
24798 // 32-bit signed value
24799 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24800 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24801 C->getSExtValue())) {
24802 // Widen to 64 bits here to get it sign extended.
24803 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24806 // FIXME gcc accepts some relocatable values here too, but only in certain
24807 // memory models; it's complicated.
24812 // 32-bit unsigned value
24813 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24814 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24815 C->getZExtValue())) {
24816 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24817 Op.getValueType());
24821 // FIXME gcc accepts some relocatable values here too, but only in certain
24822 // memory models; it's complicated.
24826 // Literal immediates are always ok.
24827 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24828 // Widen to 64 bits here to get it sign extended.
24829 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24833 // In any sort of PIC mode addresses need to be computed at runtime by
24834 // adding in a register or some sort of table lookup. These can't
24835 // be used as immediates.
24836 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24839 // If we are in non-pic codegen mode, we allow the address of a global (with
24840 // an optional displacement) to be used with 'i'.
24841 GlobalAddressSDNode *GA = nullptr;
24842 int64_t Offset = 0;
24844 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24846 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24847 Offset += GA->getOffset();
24849 } else if (Op.getOpcode() == ISD::ADD) {
24850 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24851 Offset += C->getZExtValue();
24852 Op = Op.getOperand(0);
24855 } else if (Op.getOpcode() == ISD::SUB) {
24856 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24857 Offset += -C->getZExtValue();
24858 Op = Op.getOperand(0);
24863 // Otherwise, this isn't something we can handle, reject it.
24867 const GlobalValue *GV = GA->getGlobal();
24868 // If we require an extra load to get this address, as in PIC mode, we
24869 // can't accept it.
24870 if (isGlobalStubReference(
24871 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24874 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24875 GA->getValueType(0), Offset);
24880 if (Result.getNode()) {
24881 Ops.push_back(Result);
24884 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24887 std::pair<unsigned, const TargetRegisterClass *>
24888 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24889 const std::string &Constraint,
24891 // First, see if this is a constraint that directly corresponds to an LLVM
24893 if (Constraint.size() == 1) {
24894 // GCC Constraint Letters
24895 switch (Constraint[0]) {
24897 // TODO: Slight differences here in allocation order and leaving
24898 // RIP in the class. Do they matter any more here than they do
24899 // in the normal allocation?
24900 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24901 if (Subtarget->is64Bit()) {
24902 if (VT == MVT::i32 || VT == MVT::f32)
24903 return std::make_pair(0U, &X86::GR32RegClass);
24904 if (VT == MVT::i16)
24905 return std::make_pair(0U, &X86::GR16RegClass);
24906 if (VT == MVT::i8 || VT == MVT::i1)
24907 return std::make_pair(0U, &X86::GR8RegClass);
24908 if (VT == MVT::i64 || VT == MVT::f64)
24909 return std::make_pair(0U, &X86::GR64RegClass);
24912 // 32-bit fallthrough
24913 case 'Q': // Q_REGS
24914 if (VT == MVT::i32 || VT == MVT::f32)
24915 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24916 if (VT == MVT::i16)
24917 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24918 if (VT == MVT::i8 || VT == MVT::i1)
24919 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24920 if (VT == MVT::i64)
24921 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24923 case 'r': // GENERAL_REGS
24924 case 'l': // INDEX_REGS
24925 if (VT == MVT::i8 || VT == MVT::i1)
24926 return std::make_pair(0U, &X86::GR8RegClass);
24927 if (VT == MVT::i16)
24928 return std::make_pair(0U, &X86::GR16RegClass);
24929 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24930 return std::make_pair(0U, &X86::GR32RegClass);
24931 return std::make_pair(0U, &X86::GR64RegClass);
24932 case 'R': // LEGACY_REGS
24933 if (VT == MVT::i8 || VT == MVT::i1)
24934 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24935 if (VT == MVT::i16)
24936 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24937 if (VT == MVT::i32 || !Subtarget->is64Bit())
24938 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24939 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24940 case 'f': // FP Stack registers.
24941 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24942 // value to the correct fpstack register class.
24943 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24944 return std::make_pair(0U, &X86::RFP32RegClass);
24945 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24946 return std::make_pair(0U, &X86::RFP64RegClass);
24947 return std::make_pair(0U, &X86::RFP80RegClass);
24948 case 'y': // MMX_REGS if MMX allowed.
24949 if (!Subtarget->hasMMX()) break;
24950 return std::make_pair(0U, &X86::VR64RegClass);
24951 case 'Y': // SSE_REGS if SSE2 allowed
24952 if (!Subtarget->hasSSE2()) break;
24954 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24955 if (!Subtarget->hasSSE1()) break;
24957 switch (VT.SimpleTy) {
24959 // Scalar SSE types.
24962 return std::make_pair(0U, &X86::FR32RegClass);
24965 return std::make_pair(0U, &X86::FR64RegClass);
24973 return std::make_pair(0U, &X86::VR128RegClass);
24981 return std::make_pair(0U, &X86::VR256RegClass);
24986 return std::make_pair(0U, &X86::VR512RegClass);
24992 // Use the default implementation in TargetLowering to convert the register
24993 // constraint into a member of a register class.
24994 std::pair<unsigned, const TargetRegisterClass*> Res;
24995 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24997 // Not found as a standard register?
24999 // Map st(0) -> st(7) -> ST0
25000 if (Constraint.size() == 7 && Constraint[0] == '{' &&
25001 tolower(Constraint[1]) == 's' &&
25002 tolower(Constraint[2]) == 't' &&
25003 Constraint[3] == '(' &&
25004 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25005 Constraint[5] == ')' &&
25006 Constraint[6] == '}') {
25008 Res.first = X86::FP0+Constraint[4]-'0';
25009 Res.second = &X86::RFP80RegClass;
25013 // GCC allows "st(0)" to be called just plain "st".
25014 if (StringRef("{st}").equals_lower(Constraint)) {
25015 Res.first = X86::FP0;
25016 Res.second = &X86::RFP80RegClass;
25021 if (StringRef("{flags}").equals_lower(Constraint)) {
25022 Res.first = X86::EFLAGS;
25023 Res.second = &X86::CCRRegClass;
25027 // 'A' means EAX + EDX.
25028 if (Constraint == "A") {
25029 Res.first = X86::EAX;
25030 Res.second = &X86::GR32_ADRegClass;
25036 // Otherwise, check to see if this is a register class of the wrong value
25037 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25038 // turn into {ax},{dx}.
25039 if (Res.second->hasType(VT))
25040 return Res; // Correct type already, nothing to do.
25042 // All of the single-register GCC register classes map their values onto
25043 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
25044 // really want an 8-bit or 32-bit register, map to the appropriate register
25045 // class and return the appropriate register.
25046 if (Res.second == &X86::GR16RegClass) {
25047 if (VT == MVT::i8 || VT == MVT::i1) {
25048 unsigned DestReg = 0;
25049 switch (Res.first) {
25051 case X86::AX: DestReg = X86::AL; break;
25052 case X86::DX: DestReg = X86::DL; break;
25053 case X86::CX: DestReg = X86::CL; break;
25054 case X86::BX: DestReg = X86::BL; break;
25057 Res.first = DestReg;
25058 Res.second = &X86::GR8RegClass;
25060 } else if (VT == MVT::i32 || VT == MVT::f32) {
25061 unsigned DestReg = 0;
25062 switch (Res.first) {
25064 case X86::AX: DestReg = X86::EAX; break;
25065 case X86::DX: DestReg = X86::EDX; break;
25066 case X86::CX: DestReg = X86::ECX; break;
25067 case X86::BX: DestReg = X86::EBX; break;
25068 case X86::SI: DestReg = X86::ESI; break;
25069 case X86::DI: DestReg = X86::EDI; break;
25070 case X86::BP: DestReg = X86::EBP; break;
25071 case X86::SP: DestReg = X86::ESP; break;
25074 Res.first = DestReg;
25075 Res.second = &X86::GR32RegClass;
25077 } else if (VT == MVT::i64 || VT == MVT::f64) {
25078 unsigned DestReg = 0;
25079 switch (Res.first) {
25081 case X86::AX: DestReg = X86::RAX; break;
25082 case X86::DX: DestReg = X86::RDX; break;
25083 case X86::CX: DestReg = X86::RCX; break;
25084 case X86::BX: DestReg = X86::RBX; break;
25085 case X86::SI: DestReg = X86::RSI; break;
25086 case X86::DI: DestReg = X86::RDI; break;
25087 case X86::BP: DestReg = X86::RBP; break;
25088 case X86::SP: DestReg = X86::RSP; break;
25091 Res.first = DestReg;
25092 Res.second = &X86::GR64RegClass;
25095 } else if (Res.second == &X86::FR32RegClass ||
25096 Res.second == &X86::FR64RegClass ||
25097 Res.second == &X86::VR128RegClass ||
25098 Res.second == &X86::VR256RegClass ||
25099 Res.second == &X86::FR32XRegClass ||
25100 Res.second == &X86::FR64XRegClass ||
25101 Res.second == &X86::VR128XRegClass ||
25102 Res.second == &X86::VR256XRegClass ||
25103 Res.second == &X86::VR512RegClass) {
25104 // Handle references to XMM physical registers that got mapped into the
25105 // wrong class. This can happen with constraints like {xmm0} where the
25106 // target independent register mapper will just pick the first match it can
25107 // find, ignoring the required type.
25109 if (VT == MVT::f32 || VT == MVT::i32)
25110 Res.second = &X86::FR32RegClass;
25111 else if (VT == MVT::f64 || VT == MVT::i64)
25112 Res.second = &X86::FR64RegClass;
25113 else if (X86::VR128RegClass.hasType(VT))
25114 Res.second = &X86::VR128RegClass;
25115 else if (X86::VR256RegClass.hasType(VT))
25116 Res.second = &X86::VR256RegClass;
25117 else if (X86::VR512RegClass.hasType(VT))
25118 Res.second = &X86::VR512RegClass;
25124 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25126 // Scaling factors are not free at all.
25127 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25128 // will take 2 allocations in the out of order engine instead of 1
25129 // for plain addressing mode, i.e. inst (reg1).
25131 // vaddps (%rsi,%drx), %ymm0, %ymm1
25132 // Requires two allocations (one for the load, one for the computation)
25134 // vaddps (%rsi), %ymm0, %ymm1
25135 // Requires just 1 allocation, i.e., freeing allocations for other operations
25136 // and having less micro operations to execute.
25138 // For some X86 architectures, this is even worse because for instance for
25139 // stores, the complex addressing mode forces the instruction to use the
25140 // "load" ports instead of the dedicated "store" port.
25141 // E.g., on Haswell:
25142 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25143 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25144 if (isLegalAddressingMode(AM, Ty))
25145 // Scale represents reg2 * scale, thus account for 1
25146 // as soon as we use a second register.
25147 return AM.Scale != 0;
25151 bool X86TargetLowering::isTargetFTOL() const {
25152 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();