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 "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/VariadicFunction.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/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
59 #define DEBUG_TYPE "x86-isel"
61 STATISTIC(NumTailCalls, "Number of tail calls");
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64 "x86-experimental-vector-widening-legalization", cl::init(false),
65 cl::desc("Enable an experimental vector type legalization through widening "
66 "rather than promotion."),
69 static cl::opt<bool> ExperimentalVectorShuffleLowering(
70 "x86-experimental-vector-shuffle-lowering", cl::init(true),
71 cl::desc("Enable an experimental vector shuffle lowering code path."),
74 static cl::opt<int> ReciprocalEstimateRefinementSteps(
75 "x86-recip-refinement-steps", cl::init(1),
76 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
77 "result of the hardware reciprocal estimate instruction."),
80 // Forward declarations.
81 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
84 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
85 SelectionDAG &DAG, SDLoc dl,
86 unsigned vectorWidth) {
87 assert((vectorWidth == 128 || vectorWidth == 256) &&
88 "Unsupported vector width");
89 EVT VT = Vec.getValueType();
90 EVT ElVT = VT.getVectorElementType();
91 unsigned Factor = VT.getSizeInBits()/vectorWidth;
92 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
93 VT.getVectorNumElements()/Factor);
95 // Extract from UNDEF is UNDEF.
96 if (Vec.getOpcode() == ISD::UNDEF)
97 return DAG.getUNDEF(ResultVT);
99 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
100 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
102 // This is the index of the first element of the vectorWidth-bit chunk
104 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
107 // If the input is a buildvector just emit a smaller one.
108 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
109 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
110 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
113 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
114 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
117 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
118 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
119 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
120 /// instructions or a simple subregister reference. Idx is an index in the
121 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
122 /// lowering EXTRACT_VECTOR_ELT operations easier.
123 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
124 SelectionDAG &DAG, SDLoc dl) {
125 assert((Vec.getValueType().is256BitVector() ||
126 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
127 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
130 /// Generate a DAG to grab 256-bits from a 512-bit vector.
131 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
132 SelectionDAG &DAG, SDLoc dl) {
133 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
134 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
137 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
138 unsigned IdxVal, SelectionDAG &DAG,
139 SDLoc dl, unsigned vectorWidth) {
140 assert((vectorWidth == 128 || vectorWidth == 256) &&
141 "Unsupported vector width");
142 // Inserting UNDEF is Result
143 if (Vec.getOpcode() == ISD::UNDEF)
145 EVT VT = Vec.getValueType();
146 EVT ElVT = VT.getVectorElementType();
147 EVT ResultVT = Result.getValueType();
149 // Insert the relevant vectorWidth bits.
150 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
152 // This is the index of the first element of the vectorWidth-bit chunk
154 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
157 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
158 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
161 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
162 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
163 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
164 /// simple superregister reference. Idx is an index in the 128 bits
165 /// we want. It need not be aligned to a 128-bit boundary. That makes
166 /// lowering INSERT_VECTOR_ELT operations easier.
167 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
168 SelectionDAG &DAG,SDLoc dl) {
169 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
170 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
173 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
174 SelectionDAG &DAG, SDLoc dl) {
175 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
176 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
179 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
180 /// instructions. This is used because creating CONCAT_VECTOR nodes of
181 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
182 /// large BUILD_VECTORS.
183 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
184 unsigned NumElems, SelectionDAG &DAG,
186 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
187 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
190 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
191 unsigned NumElems, SelectionDAG &DAG,
193 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
194 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
197 // FIXME: This should stop caching the target machine as soon as
198 // we can remove resetOperationActions et al.
199 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM)
200 : TargetLowering(TM) {
201 Subtarget = &TM.getSubtarget<X86Subtarget>();
202 X86ScalarSSEf64 = Subtarget->hasSSE2();
203 X86ScalarSSEf32 = Subtarget->hasSSE1();
204 TD = getDataLayout();
206 resetOperationActions();
209 void X86TargetLowering::resetOperationActions() {
210 const TargetMachine &TM = getTargetMachine();
211 static bool FirstTimeThrough = true;
213 // If none of the target options have changed, then we don't need to reset the
214 // operation actions.
215 if (!FirstTimeThrough && TO == TM.Options) return;
217 if (!FirstTimeThrough) {
218 // Reinitialize the actions.
220 FirstTimeThrough = false;
225 // Set up the TargetLowering object.
226 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228 // X86 is weird. It always uses i8 for shift amounts and setcc results.
229 setBooleanContents(ZeroOrOneBooleanContent);
230 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233 // For 64-bit, since we have so many registers, use the ILP scheduler.
234 // For 32-bit, use the register pressure specific scheduling.
235 // For Atom, always use ILP scheduling.
236 if (Subtarget->isAtom())
237 setSchedulingPreference(Sched::ILP);
238 else if (Subtarget->is64Bit())
239 setSchedulingPreference(Sched::ILP);
241 setSchedulingPreference(Sched::RegPressure);
242 const X86RegisterInfo *RegInfo =
243 TM.getSubtarget<X86Subtarget>().getRegisterInfo();
244 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246 // Bypass expensive divides on Atom when compiling with O2.
247 if (TM.getOptLevel() >= CodeGenOpt::Default) {
248 if (Subtarget->hasSlowDivide32())
249 addBypassSlowDiv(32, 8);
250 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
251 addBypassSlowDiv(64, 16);
254 if (Subtarget->isTargetKnownWindowsMSVC()) {
255 // Setup Windows compiler runtime calls.
256 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258 setLibcallName(RTLIB::SREM_I64, "_allrem");
259 setLibcallName(RTLIB::UREM_I64, "_aullrem");
260 setLibcallName(RTLIB::MUL_I64, "_allmul");
261 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
267 // The _ftol2 runtime function has an unusual calling conv, which
268 // is modeled by a special pseudo-instruction.
269 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
275 if (Subtarget->isTargetDarwin()) {
276 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277 setUseUnderscoreSetJmp(false);
278 setUseUnderscoreLongJmp(false);
279 } else if (Subtarget->isTargetWindowsGNU()) {
280 // MS runtime is weird: it exports _setjmp, but longjmp!
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(false);
284 setUseUnderscoreSetJmp(true);
285 setUseUnderscoreLongJmp(true);
288 // Set up the register classes.
289 addRegisterClass(MVT::i8, &X86::GR8RegClass);
290 addRegisterClass(MVT::i16, &X86::GR16RegClass);
291 addRegisterClass(MVT::i32, &X86::GR32RegClass);
292 if (Subtarget->is64Bit())
293 addRegisterClass(MVT::i64, &X86::GR64RegClass);
295 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297 // We don't accept any truncstore of integer registers.
298 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
305 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
307 // SETOEQ and SETUNE require checking two conditions.
308 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
315 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
317 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
319 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
323 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
324 } else if (!TM.Options.UseSoftFloat) {
325 // We have an algorithm for SSE2->double, and we turn this into a
326 // 64-bit FILD followed by conditional FADD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
328 // We have an algorithm for SSE2, and we turn this into a 64-bit
329 // FILD for other targets.
330 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
333 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
335 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
336 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
338 if (!TM.Options.UseSoftFloat) {
339 // SSE has no i16 to fp conversion, only i32
340 if (X86ScalarSSEf32) {
341 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
342 // f32 and f64 cases are Legal, f80 case is not
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
350 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
353 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
354 // are Legal, f80 is custom lowered.
355 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
356 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
358 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
360 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
361 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
363 if (X86ScalarSSEf32) {
364 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
365 // f32 and f64 cases are Legal, f80 case is not
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
369 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
372 // Handle FP_TO_UINT by promoting the destination to a larger signed
374 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
376 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
378 if (Subtarget->is64Bit()) {
379 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
380 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
381 } else if (!TM.Options.UseSoftFloat) {
382 // Since AVX is a superset of SSE3, only check for SSE here.
383 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384 // Expand FP_TO_UINT into a select.
385 // FIXME: We would like to use a Custom expander here eventually to do
386 // the optimal thing for SSE vs. the default expansion in the legalizer.
387 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
389 // With SSE3 we can use fisttpll to convert to a signed i64; without
390 // SSE, we're stuck with a fistpll.
391 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
394 if (isTargetFTOL()) {
395 // Use the _ftol2 runtime function, which has a pseudo-instruction
396 // to handle its weird calling convention.
397 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
400 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401 if (!X86ScalarSSEf64) {
402 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
403 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
404 if (Subtarget->is64Bit()) {
405 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
406 // Without SSE, i64->f64 goes through memory.
407 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
411 // Scalar integer divide and remainder are lowered to use operations that
412 // produce two results, to match the available instructions. This exposes
413 // the two-result form to trivial CSE, which is able to combine x/y and x%y
414 // into a single instruction.
416 // Scalar integer multiply-high is also lowered to use two-result
417 // operations, to match the available instructions. However, plain multiply
418 // (low) operations are left as Legal, as there are single-result
419 // instructions for this in x86. Using the two-result multiply instructions
420 // when both high and low results are needed must be arranged by dagcombine.
421 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
423 setOperationAction(ISD::MULHS, VT, Expand);
424 setOperationAction(ISD::MULHU, VT, Expand);
425 setOperationAction(ISD::SDIV, VT, Expand);
426 setOperationAction(ISD::UDIV, VT, Expand);
427 setOperationAction(ISD::SREM, VT, Expand);
428 setOperationAction(ISD::UREM, VT, Expand);
430 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431 setOperationAction(ISD::ADDC, VT, Custom);
432 setOperationAction(ISD::ADDE, VT, Custom);
433 setOperationAction(ISD::SUBC, VT, Custom);
434 setOperationAction(ISD::SUBE, VT, Custom);
437 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
438 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
439 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
441 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
445 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
447 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
448 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
449 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
450 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
451 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
452 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
453 if (Subtarget->is64Bit())
454 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
455 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
456 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
457 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
458 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
459 setOperationAction(ISD::FREM , MVT::f32 , Expand);
460 setOperationAction(ISD::FREM , MVT::f64 , Expand);
461 setOperationAction(ISD::FREM , MVT::f80 , Expand);
462 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
464 // Promote the i8 variants and force them on up to i32 which has a shorter
466 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
467 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
468 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
469 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
470 if (Subtarget->hasBMI()) {
471 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
472 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
473 if (Subtarget->is64Bit())
474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
476 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
477 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
478 if (Subtarget->is64Bit())
479 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
482 if (Subtarget->hasLZCNT()) {
483 // When promoting the i8 variants, force them to i32 for a shorter
485 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
486 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
487 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
488 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
491 if (Subtarget->is64Bit())
492 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
494 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
495 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
496 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
497 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
498 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
500 if (Subtarget->is64Bit()) {
501 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
506 // Special handling for half-precision floating point conversions.
507 // If we don't have F16C support, then lower half float conversions
508 // into library calls.
509 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
510 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
511 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
514 // There's never any support for operations beyond MVT::f32.
515 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
516 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
517 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
518 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
520 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
521 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
522 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
523 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
525 if (Subtarget->hasPOPCNT()) {
526 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
528 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
529 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
530 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
531 if (Subtarget->is64Bit())
532 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
535 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
537 if (!Subtarget->hasMOVBE())
538 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
540 // These should be promoted to a larger select which is supported.
541 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
542 // X86 wants to expand cmov itself.
543 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
544 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
545 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
546 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
547 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
548 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
549 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
550 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
551 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
552 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
553 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
554 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
555 if (Subtarget->is64Bit()) {
556 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
557 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
559 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
560 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
561 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
562 // support continuation, user-level threading, and etc.. As a result, no
563 // other SjLj exception interfaces are implemented and please don't build
564 // your own exception handling based on them.
565 // LLVM/Clang supports zero-cost DWARF exception handling.
566 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
567 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
570 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
571 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
572 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
573 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
574 if (Subtarget->is64Bit())
575 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
576 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
577 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
578 if (Subtarget->is64Bit()) {
579 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
580 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
581 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
582 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
583 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
585 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
586 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
587 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
588 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
589 if (Subtarget->is64Bit()) {
590 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
591 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
592 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
595 if (Subtarget->hasSSE1())
596 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
598 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
600 // Expand certain atomics
601 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
603 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
604 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
605 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
608 if (Subtarget->hasCmpxchg16b()) {
609 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
612 // FIXME - use subtarget debug flags
613 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
614 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
615 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
618 if (Subtarget->is64Bit()) {
619 setExceptionPointerRegister(X86::RAX);
620 setExceptionSelectorRegister(X86::RDX);
622 setExceptionPointerRegister(X86::EAX);
623 setExceptionSelectorRegister(X86::EDX);
625 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
626 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
628 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
629 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
631 setOperationAction(ISD::TRAP, MVT::Other, Legal);
632 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
634 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
635 setOperationAction(ISD::VASTART , MVT::Other, Custom);
636 setOperationAction(ISD::VAEND , MVT::Other, Expand);
637 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
638 // TargetInfo::X86_64ABIBuiltinVaList
639 setOperationAction(ISD::VAARG , MVT::Other, Custom);
640 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
642 // TargetInfo::CharPtrBuiltinVaList
643 setOperationAction(ISD::VAARG , MVT::Other, Expand);
644 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
647 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
648 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
650 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
652 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
653 // f32 and f64 use SSE.
654 // Set up the FP register classes.
655 addRegisterClass(MVT::f32, &X86::FR32RegClass);
656 addRegisterClass(MVT::f64, &X86::FR64RegClass);
658 // Use ANDPD to simulate FABS.
659 setOperationAction(ISD::FABS , MVT::f64, Custom);
660 setOperationAction(ISD::FABS , MVT::f32, Custom);
662 // Use XORP to simulate FNEG.
663 setOperationAction(ISD::FNEG , MVT::f64, Custom);
664 setOperationAction(ISD::FNEG , MVT::f32, Custom);
666 // Use ANDPD and ORPD to simulate FCOPYSIGN.
667 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
668 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
670 // Lower this to FGETSIGNx86 plus an AND.
671 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
672 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
674 // We don't support sin/cos/fmod
675 setOperationAction(ISD::FSIN , MVT::f64, Expand);
676 setOperationAction(ISD::FCOS , MVT::f64, Expand);
677 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
678 setOperationAction(ISD::FSIN , MVT::f32, Expand);
679 setOperationAction(ISD::FCOS , MVT::f32, Expand);
680 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
682 // Expand FP immediates into loads from the stack, except for the special
684 addLegalFPImmediate(APFloat(+0.0)); // xorpd
685 addLegalFPImmediate(APFloat(+0.0f)); // xorps
686 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
687 // Use SSE for f32, x87 for f64.
688 // Set up the FP register classes.
689 addRegisterClass(MVT::f32, &X86::FR32RegClass);
690 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
692 // Use ANDPS to simulate FABS.
693 setOperationAction(ISD::FABS , MVT::f32, Custom);
695 // Use XORP to simulate FNEG.
696 setOperationAction(ISD::FNEG , MVT::f32, Custom);
698 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
700 // Use ANDPS and ORPS to simulate FCOPYSIGN.
701 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
702 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
704 // We don't support sin/cos/fmod
705 setOperationAction(ISD::FSIN , MVT::f32, Expand);
706 setOperationAction(ISD::FCOS , MVT::f32, Expand);
707 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
709 // Special cases we handle for FP constants.
710 addLegalFPImmediate(APFloat(+0.0f)); // xorps
711 addLegalFPImmediate(APFloat(+0.0)); // FLD0
712 addLegalFPImmediate(APFloat(+1.0)); // FLD1
713 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
714 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
716 if (!TM.Options.UnsafeFPMath) {
717 setOperationAction(ISD::FSIN , MVT::f64, Expand);
718 setOperationAction(ISD::FCOS , MVT::f64, Expand);
719 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
721 } else if (!TM.Options.UseSoftFloat) {
722 // f32 and f64 in x87.
723 // Set up the FP register classes.
724 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
725 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
727 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
728 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
729 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
730 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
732 if (!TM.Options.UnsafeFPMath) {
733 setOperationAction(ISD::FSIN , MVT::f64, Expand);
734 setOperationAction(ISD::FSIN , MVT::f32, Expand);
735 setOperationAction(ISD::FCOS , MVT::f64, Expand);
736 setOperationAction(ISD::FCOS , MVT::f32, Expand);
737 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
738 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
740 addLegalFPImmediate(APFloat(+0.0)); // FLD0
741 addLegalFPImmediate(APFloat(+1.0)); // FLD1
742 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
743 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
744 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
745 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
746 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
747 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
750 // We don't support FMA.
751 setOperationAction(ISD::FMA, MVT::f64, Expand);
752 setOperationAction(ISD::FMA, MVT::f32, Expand);
754 // Long double always uses X87.
755 if (!TM.Options.UseSoftFloat) {
756 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
757 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
758 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
760 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
761 addLegalFPImmediate(TmpFlt); // FLD0
763 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
766 APFloat TmpFlt2(+1.0);
767 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
769 addLegalFPImmediate(TmpFlt2); // FLD1
770 TmpFlt2.changeSign();
771 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
774 if (!TM.Options.UnsafeFPMath) {
775 setOperationAction(ISD::FSIN , MVT::f80, Expand);
776 setOperationAction(ISD::FCOS , MVT::f80, Expand);
777 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
780 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
781 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
782 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
783 setOperationAction(ISD::FRINT, MVT::f80, Expand);
784 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
785 setOperationAction(ISD::FMA, MVT::f80, Expand);
788 // Always use a library call for pow.
789 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
790 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
791 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
793 setOperationAction(ISD::FLOG, MVT::f80, Expand);
794 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
795 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
796 setOperationAction(ISD::FEXP, MVT::f80, Expand);
797 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
798 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
799 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
801 // First set operation action for all vector types to either promote
802 // (for widening) or expand (for scalarization). Then we will selectively
803 // turn on ones that can be effectively codegen'd.
804 for (MVT VT : MVT::vector_valuetypes()) {
805 setOperationAction(ISD::ADD , VT, Expand);
806 setOperationAction(ISD::SUB , VT, Expand);
807 setOperationAction(ISD::FADD, VT, Expand);
808 setOperationAction(ISD::FNEG, VT, Expand);
809 setOperationAction(ISD::FSUB, VT, Expand);
810 setOperationAction(ISD::MUL , VT, Expand);
811 setOperationAction(ISD::FMUL, VT, Expand);
812 setOperationAction(ISD::SDIV, VT, Expand);
813 setOperationAction(ISD::UDIV, VT, Expand);
814 setOperationAction(ISD::FDIV, VT, Expand);
815 setOperationAction(ISD::SREM, VT, Expand);
816 setOperationAction(ISD::UREM, VT, Expand);
817 setOperationAction(ISD::LOAD, VT, Expand);
818 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
819 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
820 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
821 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
822 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
823 setOperationAction(ISD::FABS, VT, Expand);
824 setOperationAction(ISD::FSIN, VT, Expand);
825 setOperationAction(ISD::FSINCOS, VT, Expand);
826 setOperationAction(ISD::FCOS, VT, Expand);
827 setOperationAction(ISD::FSINCOS, VT, Expand);
828 setOperationAction(ISD::FREM, VT, Expand);
829 setOperationAction(ISD::FMA, VT, Expand);
830 setOperationAction(ISD::FPOWI, VT, Expand);
831 setOperationAction(ISD::FSQRT, VT, Expand);
832 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
833 setOperationAction(ISD::FFLOOR, VT, Expand);
834 setOperationAction(ISD::FCEIL, VT, Expand);
835 setOperationAction(ISD::FTRUNC, VT, Expand);
836 setOperationAction(ISD::FRINT, VT, Expand);
837 setOperationAction(ISD::FNEARBYINT, VT, Expand);
838 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
839 setOperationAction(ISD::MULHS, VT, Expand);
840 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
841 setOperationAction(ISD::MULHU, VT, Expand);
842 setOperationAction(ISD::SDIVREM, VT, Expand);
843 setOperationAction(ISD::UDIVREM, VT, Expand);
844 setOperationAction(ISD::FPOW, VT, Expand);
845 setOperationAction(ISD::CTPOP, VT, Expand);
846 setOperationAction(ISD::CTTZ, VT, Expand);
847 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
848 setOperationAction(ISD::CTLZ, VT, Expand);
849 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
850 setOperationAction(ISD::SHL, VT, Expand);
851 setOperationAction(ISD::SRA, VT, Expand);
852 setOperationAction(ISD::SRL, VT, Expand);
853 setOperationAction(ISD::ROTL, VT, Expand);
854 setOperationAction(ISD::ROTR, VT, Expand);
855 setOperationAction(ISD::BSWAP, VT, Expand);
856 setOperationAction(ISD::SETCC, VT, Expand);
857 setOperationAction(ISD::FLOG, VT, Expand);
858 setOperationAction(ISD::FLOG2, VT, Expand);
859 setOperationAction(ISD::FLOG10, VT, Expand);
860 setOperationAction(ISD::FEXP, VT, Expand);
861 setOperationAction(ISD::FEXP2, VT, Expand);
862 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
863 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
864 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
865 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
866 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
867 setOperationAction(ISD::TRUNCATE, VT, Expand);
868 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
869 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
870 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
871 setOperationAction(ISD::VSELECT, VT, Expand);
872 setOperationAction(ISD::SELECT_CC, VT, Expand);
873 for (MVT InnerVT : MVT::vector_valuetypes())
874 setTruncStoreAction(VT, InnerVT, Expand);
875 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
876 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
878 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
879 // we have to deal with them whether we ask for Expansion or not. Setting
880 // Expand causes its own optimisation problems though, so leave them legal.
881 if (VT.getVectorElementType() == MVT::i1)
882 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
885 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
886 // with -msoft-float, disable use of MMX as well.
887 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
888 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
889 // No operations on x86mmx supported, everything uses intrinsics.
892 // MMX-sized vectors (other than x86mmx) are expected to be expanded
893 // into smaller operations.
894 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
895 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
896 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
897 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
898 setOperationAction(ISD::AND, MVT::v8i8, Expand);
899 setOperationAction(ISD::AND, MVT::v4i16, Expand);
900 setOperationAction(ISD::AND, MVT::v2i32, Expand);
901 setOperationAction(ISD::AND, MVT::v1i64, Expand);
902 setOperationAction(ISD::OR, MVT::v8i8, Expand);
903 setOperationAction(ISD::OR, MVT::v4i16, Expand);
904 setOperationAction(ISD::OR, MVT::v2i32, Expand);
905 setOperationAction(ISD::OR, MVT::v1i64, Expand);
906 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
907 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
908 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
909 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
910 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
911 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
912 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
914 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
915 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
916 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
917 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
918 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
919 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
920 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
921 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
922 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
924 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
925 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
927 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
928 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
929 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
930 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
931 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
932 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
933 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
934 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
935 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
936 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
938 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
939 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
942 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
943 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
945 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
946 // registers cannot be used even for integer operations.
947 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
948 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
949 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
950 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
952 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
953 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
954 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
955 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
956 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
957 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
958 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
959 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
960 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
961 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
962 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
963 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
964 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
965 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
966 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
967 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
968 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
969 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
970 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
971 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
972 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
973 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
975 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
976 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
977 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
978 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
980 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
981 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
982 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
984 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
986 // Only provide customized ctpop vector bit twiddling for vector types we
987 // know to perform better than using the popcnt instructions on each vector
988 // element. If popcnt isn't supported, always provide the custom version.
989 if (!Subtarget->hasPOPCNT()) {
990 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
991 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
994 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
995 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996 MVT VT = (MVT::SimpleValueType)i;
997 // Do not attempt to custom lower non-power-of-2 vectors
998 if (!isPowerOf2_32(VT.getVectorNumElements()))
1000 // Do not attempt to custom lower non-128-bit vectors
1001 if (!VT.is128BitVector())
1003 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1004 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1005 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1008 // We support custom legalizing of sext and anyext loads for specific
1009 // memory vector types which we can load as a scalar (or sequence of
1010 // scalars) and extend in-register to a legal 128-bit vector type. For sext
1011 // loads these must work with a single scalar load.
1012 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1013 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1014 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1015 setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1016 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1017 setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1018 setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1019 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1020 setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1022 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1023 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1024 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1025 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1026 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1027 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1029 if (Subtarget->is64Bit()) {
1030 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1031 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1034 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1035 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1036 MVT VT = (MVT::SimpleValueType)i;
1038 // Do not attempt to promote non-128-bit vectors
1039 if (!VT.is128BitVector())
1042 setOperationAction(ISD::AND, VT, Promote);
1043 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1044 setOperationAction(ISD::OR, VT, Promote);
1045 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1046 setOperationAction(ISD::XOR, VT, Promote);
1047 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1048 setOperationAction(ISD::LOAD, VT, Promote);
1049 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1050 setOperationAction(ISD::SELECT, VT, Promote);
1051 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1054 // Custom lower v2i64 and v2f64 selects.
1055 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1056 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1057 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1058 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1060 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1061 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1063 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1064 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1065 // As there is no 64-bit GPR available, we need build a special custom
1066 // sequence to convert from v2i32 to v2f32.
1067 if (!Subtarget->is64Bit())
1068 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1070 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1071 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1073 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1075 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1076 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1077 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1080 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1081 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1082 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1083 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1084 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1085 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1086 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1087 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1088 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1089 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1090 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1092 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1093 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1094 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1095 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1096 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1097 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1098 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1099 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1100 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1101 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1103 // FIXME: Do we need to handle scalar-to-vector here?
1104 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1106 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1107 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1108 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1109 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1110 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1111 // There is no BLENDI for byte vectors. We don't need to custom lower
1112 // some vselects for now.
1113 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1115 // SSE41 brings specific instructions for doing vector sign extend even in
1116 // cases where we don't have SRA.
1117 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1118 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1119 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1121 // i8 and i16 vectors are custom because the source register and source
1122 // source memory operand types are not the same width. f32 vectors are
1123 // custom since the immediate controlling the insert encodes additional
1125 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1126 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1127 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1128 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1130 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1131 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1132 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1133 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1135 // FIXME: these should be Legal, but that's only for the case where
1136 // the index is constant. For now custom expand to deal with that.
1137 if (Subtarget->is64Bit()) {
1138 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1139 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1143 if (Subtarget->hasSSE2()) {
1144 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1145 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1147 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1148 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1150 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1151 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1153 // In the customized shift lowering, the legal cases in AVX2 will be
1155 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1156 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1158 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1159 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1161 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1164 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1165 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1166 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1167 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1168 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1169 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1170 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1172 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1173 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1174 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1176 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1177 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1178 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1179 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1180 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1181 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1182 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1183 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1184 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1185 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1186 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1187 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1189 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1190 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1191 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1192 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1193 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1194 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1195 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1196 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1197 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1198 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1199 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1200 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1202 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1203 // even though v8i16 is a legal type.
1204 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1205 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1206 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1208 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1209 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1210 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1212 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1213 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1215 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1217 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1218 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1220 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1221 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1223 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1224 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1226 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1227 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1228 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1229 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1231 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1232 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1233 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1235 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1236 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1237 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1238 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1240 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1241 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1242 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1243 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1244 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1245 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1246 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1247 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1248 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1249 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1250 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1251 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1253 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1254 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1255 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1256 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1257 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1258 setOperationAction(ISD::FMA, MVT::f32, Legal);
1259 setOperationAction(ISD::FMA, MVT::f64, Legal);
1262 if (Subtarget->hasInt256()) {
1263 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1264 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1265 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1266 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1268 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1269 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1270 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1271 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1273 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1274 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1275 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1276 // Don't lower v32i8 because there is no 128-bit byte mul
1278 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1279 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1280 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1281 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1283 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1284 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1286 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1287 // when we have a 256bit-wide blend with immediate.
1288 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1290 // Only provide customized ctpop vector bit twiddling for vector types we
1291 // know to perform better than using the popcnt instructions on each
1292 // vector element. If popcnt isn't supported, always provide the custom
1294 if (!Subtarget->hasPOPCNT())
1295 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1297 // Custom CTPOP always performs better on natively supported v8i32
1298 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1300 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1301 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1302 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1303 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1305 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1306 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1307 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1308 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1310 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1311 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1312 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1313 // Don't lower v32i8 because there is no 128-bit byte mul
1316 // In the customized shift lowering, the legal cases in AVX2 will be
1318 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1319 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1321 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1322 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1324 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1326 // Custom lower several nodes for 256-bit types.
1327 for (MVT VT : MVT::vector_valuetypes()) {
1328 if (VT.getScalarSizeInBits() >= 32) {
1329 setOperationAction(ISD::MLOAD, VT, Legal);
1330 setOperationAction(ISD::MSTORE, VT, Legal);
1332 // Extract subvector is special because the value type
1333 // (result) is 128-bit but the source is 256-bit wide.
1334 if (VT.is128BitVector()) {
1335 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1337 // Do not attempt to custom lower other non-256-bit vectors
1338 if (!VT.is256BitVector())
1341 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1342 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1343 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1344 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1345 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1346 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1347 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1350 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1351 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1352 MVT VT = (MVT::SimpleValueType)i;
1354 // Do not attempt to promote non-256-bit vectors
1355 if (!VT.is256BitVector())
1358 setOperationAction(ISD::AND, VT, Promote);
1359 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1360 setOperationAction(ISD::OR, VT, Promote);
1361 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1362 setOperationAction(ISD::XOR, VT, Promote);
1363 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1364 setOperationAction(ISD::LOAD, VT, Promote);
1365 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1366 setOperationAction(ISD::SELECT, VT, Promote);
1367 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1371 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1372 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1373 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1374 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1375 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1377 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1378 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1379 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1381 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1382 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1383 setOperationAction(ISD::XOR, MVT::i1, Legal);
1384 setOperationAction(ISD::OR, MVT::i1, Legal);
1385 setOperationAction(ISD::AND, MVT::i1, Legal);
1386 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1387 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1388 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1389 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1390 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1391 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1393 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1394 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1395 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1396 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1397 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1398 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1400 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1401 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1402 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1403 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1404 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1405 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1406 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1407 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1409 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1410 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1411 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1412 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1413 if (Subtarget->is64Bit()) {
1414 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1415 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1416 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1417 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1419 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1420 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1421 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1422 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1423 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1424 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1425 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1426 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1427 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1428 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1429 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1430 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1431 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1432 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1434 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1435 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1436 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1437 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1438 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1439 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1440 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1441 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1442 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1443 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1444 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1445 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1446 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1448 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1449 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1450 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1451 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1452 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1453 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1455 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1456 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1458 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1461 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1462 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1463 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1464 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1465 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1466 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1467 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1468 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1470 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1471 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1473 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1474 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1476 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1478 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1479 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1481 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1482 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1484 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1485 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1487 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1488 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1489 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1490 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1491 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1492 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1494 if (Subtarget->hasCDI()) {
1495 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1496 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1499 // Custom lower several nodes.
1500 for (MVT VT : MVT::vector_valuetypes()) {
1501 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1502 // Extract subvector is special because the value type
1503 // (result) is 256/128-bit but the source is 512-bit wide.
1504 if (VT.is128BitVector() || VT.is256BitVector()) {
1505 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1507 if (VT.getVectorElementType() == MVT::i1)
1508 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1510 // Do not attempt to custom lower other non-512-bit vectors
1511 if (!VT.is512BitVector())
1514 if ( EltSize >= 32) {
1515 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1516 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1517 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1518 setOperationAction(ISD::VSELECT, VT, Legal);
1519 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1520 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1521 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1522 setOperationAction(ISD::MLOAD, VT, Legal);
1523 setOperationAction(ISD::MSTORE, VT, Legal);
1526 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1527 MVT VT = (MVT::SimpleValueType)i;
1529 // Do not attempt to promote non-512-bit vectors.
1530 if (!VT.is512BitVector())
1533 setOperationAction(ISD::SELECT, VT, Promote);
1534 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1538 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1539 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1540 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1542 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1543 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1545 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1546 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1547 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1548 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1549 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1550 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1551 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1552 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1553 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1555 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1556 const MVT VT = (MVT::SimpleValueType)i;
1558 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1560 // Do not attempt to promote non-512-bit vectors.
1561 if (!VT.is512BitVector())
1565 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1566 setOperationAction(ISD::VSELECT, VT, Legal);
1571 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1572 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1573 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1575 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1576 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1577 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Legal);
1579 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1580 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1581 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1582 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1583 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1584 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1587 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1588 // of this type with custom code.
1589 for (MVT VT : MVT::vector_valuetypes())
1590 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1592 // We want to custom lower some of our intrinsics.
1593 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1594 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1595 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1596 if (!Subtarget->is64Bit())
1597 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1599 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1600 // handle type legalization for these operations here.
1602 // FIXME: We really should do custom legalization for addition and
1603 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1604 // than generic legalization for 64-bit multiplication-with-overflow, though.
1605 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1606 // Add/Sub/Mul with overflow operations are custom lowered.
1608 setOperationAction(ISD::SADDO, VT, Custom);
1609 setOperationAction(ISD::UADDO, VT, Custom);
1610 setOperationAction(ISD::SSUBO, VT, Custom);
1611 setOperationAction(ISD::USUBO, VT, Custom);
1612 setOperationAction(ISD::SMULO, VT, Custom);
1613 setOperationAction(ISD::UMULO, VT, Custom);
1617 if (!Subtarget->is64Bit()) {
1618 // These libcalls are not available in 32-bit.
1619 setLibcallName(RTLIB::SHL_I128, nullptr);
1620 setLibcallName(RTLIB::SRL_I128, nullptr);
1621 setLibcallName(RTLIB::SRA_I128, nullptr);
1624 // Combine sin / cos into one node or libcall if possible.
1625 if (Subtarget->hasSinCos()) {
1626 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1627 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1628 if (Subtarget->isTargetDarwin()) {
1629 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1630 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1631 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1632 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1636 if (Subtarget->isTargetWin64()) {
1637 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1638 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1639 setOperationAction(ISD::SREM, MVT::i128, Custom);
1640 setOperationAction(ISD::UREM, MVT::i128, Custom);
1641 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1642 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1645 // We have target-specific dag combine patterns for the following nodes:
1646 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1647 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1648 setTargetDAGCombine(ISD::VSELECT);
1649 setTargetDAGCombine(ISD::SELECT);
1650 setTargetDAGCombine(ISD::SHL);
1651 setTargetDAGCombine(ISD::SRA);
1652 setTargetDAGCombine(ISD::SRL);
1653 setTargetDAGCombine(ISD::OR);
1654 setTargetDAGCombine(ISD::AND);
1655 setTargetDAGCombine(ISD::ADD);
1656 setTargetDAGCombine(ISD::FADD);
1657 setTargetDAGCombine(ISD::FSUB);
1658 setTargetDAGCombine(ISD::FMA);
1659 setTargetDAGCombine(ISD::SUB);
1660 setTargetDAGCombine(ISD::LOAD);
1661 setTargetDAGCombine(ISD::STORE);
1662 setTargetDAGCombine(ISD::ZERO_EXTEND);
1663 setTargetDAGCombine(ISD::ANY_EXTEND);
1664 setTargetDAGCombine(ISD::SIGN_EXTEND);
1665 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1666 setTargetDAGCombine(ISD::TRUNCATE);
1667 setTargetDAGCombine(ISD::SINT_TO_FP);
1668 setTargetDAGCombine(ISD::SETCC);
1669 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1670 setTargetDAGCombine(ISD::BUILD_VECTOR);
1671 if (Subtarget->is64Bit())
1672 setTargetDAGCombine(ISD::MUL);
1673 setTargetDAGCombine(ISD::XOR);
1675 computeRegisterProperties();
1677 // On Darwin, -Os means optimize for size without hurting performance,
1678 // do not reduce the limit.
1679 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1680 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1681 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1682 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1683 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1684 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1685 setPrefLoopAlignment(4); // 2^4 bytes.
1687 // Predictable cmov don't hurt on atom because it's in-order.
1688 PredictableSelectIsExpensive = !Subtarget->isAtom();
1689 EnableExtLdPromotion = true;
1690 setPrefFunctionAlignment(4); // 2^4 bytes.
1692 verifyIntrinsicTables();
1695 // This has so far only been implemented for 64-bit MachO.
1696 bool X86TargetLowering::useLoadStackGuardNode() const {
1697 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1700 TargetLoweringBase::LegalizeTypeAction
1701 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1702 if (ExperimentalVectorWideningLegalization &&
1703 VT.getVectorNumElements() != 1 &&
1704 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1705 return TypeWidenVector;
1707 return TargetLoweringBase::getPreferredVectorAction(VT);
1710 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1712 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1714 const unsigned NumElts = VT.getVectorNumElements();
1715 const EVT EltVT = VT.getVectorElementType();
1716 if (VT.is512BitVector()) {
1717 if (Subtarget->hasAVX512())
1718 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1719 EltVT == MVT::f32 || EltVT == MVT::f64)
1721 case 8: return MVT::v8i1;
1722 case 16: return MVT::v16i1;
1724 if (Subtarget->hasBWI())
1725 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1727 case 32: return MVT::v32i1;
1728 case 64: return MVT::v64i1;
1732 if (VT.is256BitVector() || VT.is128BitVector()) {
1733 if (Subtarget->hasVLX())
1734 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1735 EltVT == MVT::f32 || EltVT == MVT::f64)
1737 case 2: return MVT::v2i1;
1738 case 4: return MVT::v4i1;
1739 case 8: return MVT::v8i1;
1741 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1742 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1744 case 8: return MVT::v8i1;
1745 case 16: return MVT::v16i1;
1746 case 32: return MVT::v32i1;
1750 return VT.changeVectorElementTypeToInteger();
1753 /// Helper for getByValTypeAlignment to determine
1754 /// the desired ByVal argument alignment.
1755 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1758 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1759 if (VTy->getBitWidth() == 128)
1761 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1762 unsigned EltAlign = 0;
1763 getMaxByValAlign(ATy->getElementType(), EltAlign);
1764 if (EltAlign > MaxAlign)
1765 MaxAlign = EltAlign;
1766 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1767 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1768 unsigned EltAlign = 0;
1769 getMaxByValAlign(STy->getElementType(i), EltAlign);
1770 if (EltAlign > MaxAlign)
1771 MaxAlign = EltAlign;
1778 /// Return the desired alignment for ByVal aggregate
1779 /// function arguments in the caller parameter area. For X86, aggregates
1780 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1781 /// are at 4-byte boundaries.
1782 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1783 if (Subtarget->is64Bit()) {
1784 // Max of 8 and alignment of type.
1785 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1792 if (Subtarget->hasSSE1())
1793 getMaxByValAlign(Ty, Align);
1797 /// Returns the target specific optimal type for load
1798 /// and store operations as a result of memset, memcpy, and memmove
1799 /// lowering. If DstAlign is zero that means it's safe to destination
1800 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1801 /// means there isn't a need to check it against alignment requirement,
1802 /// probably because the source does not need to be loaded. If 'IsMemset' is
1803 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1804 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1805 /// source is constant so it does not need to be loaded.
1806 /// It returns EVT::Other if the type should be determined using generic
1807 /// target-independent logic.
1809 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1810 unsigned DstAlign, unsigned SrcAlign,
1811 bool IsMemset, bool ZeroMemset,
1813 MachineFunction &MF) const {
1814 const Function *F = MF.getFunction();
1815 if ((!IsMemset || ZeroMemset) &&
1816 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1817 Attribute::NoImplicitFloat)) {
1819 (Subtarget->isUnalignedMemAccessFast() ||
1820 ((DstAlign == 0 || DstAlign >= 16) &&
1821 (SrcAlign == 0 || SrcAlign >= 16)))) {
1823 if (Subtarget->hasInt256())
1825 if (Subtarget->hasFp256())
1828 if (Subtarget->hasSSE2())
1830 if (Subtarget->hasSSE1())
1832 } else if (!MemcpyStrSrc && Size >= 8 &&
1833 !Subtarget->is64Bit() &&
1834 Subtarget->hasSSE2()) {
1835 // Do not use f64 to lower memcpy if source is string constant. It's
1836 // better to use i32 to avoid the loads.
1840 if (Subtarget->is64Bit() && Size >= 8)
1845 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1847 return X86ScalarSSEf32;
1848 else if (VT == MVT::f64)
1849 return X86ScalarSSEf64;
1854 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1859 *Fast = Subtarget->isUnalignedMemAccessFast();
1863 /// Return the entry encoding for a jump table in the
1864 /// current function. The returned value is a member of the
1865 /// MachineJumpTableInfo::JTEntryKind enum.
1866 unsigned X86TargetLowering::getJumpTableEncoding() const {
1867 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1869 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1870 Subtarget->isPICStyleGOT())
1871 return MachineJumpTableInfo::EK_Custom32;
1873 // Otherwise, use the normal jump table encoding heuristics.
1874 return TargetLowering::getJumpTableEncoding();
1878 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1879 const MachineBasicBlock *MBB,
1880 unsigned uid,MCContext &Ctx) const{
1881 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1882 Subtarget->isPICStyleGOT());
1883 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1885 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1886 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1889 /// Returns relocation base for the given PIC jumptable.
1890 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1891 SelectionDAG &DAG) const {
1892 if (!Subtarget->is64Bit())
1893 // This doesn't have SDLoc associated with it, but is not really the
1894 // same as a Register.
1895 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1899 /// This returns the relocation base for the given PIC jumptable,
1900 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1901 const MCExpr *X86TargetLowering::
1902 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1903 MCContext &Ctx) const {
1904 // X86-64 uses RIP relative addressing based on the jump table label.
1905 if (Subtarget->isPICStyleRIPRel())
1906 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1908 // Otherwise, the reference is relative to the PIC base.
1909 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1912 // FIXME: Why this routine is here? Move to RegInfo!
1913 std::pair<const TargetRegisterClass*, uint8_t>
1914 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1915 const TargetRegisterClass *RRC = nullptr;
1917 switch (VT.SimpleTy) {
1919 return TargetLowering::findRepresentativeClass(VT);
1920 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1921 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1924 RRC = &X86::VR64RegClass;
1926 case MVT::f32: case MVT::f64:
1927 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1928 case MVT::v4f32: case MVT::v2f64:
1929 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1931 RRC = &X86::VR128RegClass;
1934 return std::make_pair(RRC, Cost);
1937 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1938 unsigned &Offset) const {
1939 if (!Subtarget->isTargetLinux())
1942 if (Subtarget->is64Bit()) {
1943 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1945 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1957 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1958 unsigned DestAS) const {
1959 assert(SrcAS != DestAS && "Expected different address spaces!");
1961 return SrcAS < 256 && DestAS < 256;
1964 //===----------------------------------------------------------------------===//
1965 // Return Value Calling Convention Implementation
1966 //===----------------------------------------------------------------------===//
1968 #include "X86GenCallingConv.inc"
1971 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1972 MachineFunction &MF, bool isVarArg,
1973 const SmallVectorImpl<ISD::OutputArg> &Outs,
1974 LLVMContext &Context) const {
1975 SmallVector<CCValAssign, 16> RVLocs;
1976 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1977 return CCInfo.CheckReturn(Outs, RetCC_X86);
1980 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1981 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1986 X86TargetLowering::LowerReturn(SDValue Chain,
1987 CallingConv::ID CallConv, bool isVarArg,
1988 const SmallVectorImpl<ISD::OutputArg> &Outs,
1989 const SmallVectorImpl<SDValue> &OutVals,
1990 SDLoc dl, SelectionDAG &DAG) const {
1991 MachineFunction &MF = DAG.getMachineFunction();
1992 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1994 SmallVector<CCValAssign, 16> RVLocs;
1995 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1996 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1999 SmallVector<SDValue, 6> RetOps;
2000 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2001 // Operand #1 = Bytes To Pop
2002 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2005 // Copy the result values into the output registers.
2006 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2007 CCValAssign &VA = RVLocs[i];
2008 assert(VA.isRegLoc() && "Can only return in registers!");
2009 SDValue ValToCopy = OutVals[i];
2010 EVT ValVT = ValToCopy.getValueType();
2012 // Promote values to the appropriate types.
2013 if (VA.getLocInfo() == CCValAssign::SExt)
2014 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2015 else if (VA.getLocInfo() == CCValAssign::ZExt)
2016 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2017 else if (VA.getLocInfo() == CCValAssign::AExt)
2018 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2019 else if (VA.getLocInfo() == CCValAssign::BCvt)
2020 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2022 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2023 "Unexpected FP-extend for return value.");
2025 // If this is x86-64, and we disabled SSE, we can't return FP values,
2026 // or SSE or MMX vectors.
2027 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2028 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2029 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2030 report_fatal_error("SSE register return with SSE disabled");
2032 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2033 // llvm-gcc has never done it right and no one has noticed, so this
2034 // should be OK for now.
2035 if (ValVT == MVT::f64 &&
2036 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2037 report_fatal_error("SSE2 register return with SSE2 disabled");
2039 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2040 // the RET instruction and handled by the FP Stackifier.
2041 if (VA.getLocReg() == X86::FP0 ||
2042 VA.getLocReg() == X86::FP1) {
2043 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2044 // change the value to the FP stack register class.
2045 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2046 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2047 RetOps.push_back(ValToCopy);
2048 // Don't emit a copytoreg.
2052 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2053 // which is returned in RAX / RDX.
2054 if (Subtarget->is64Bit()) {
2055 if (ValVT == MVT::x86mmx) {
2056 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2057 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2058 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2060 // If we don't have SSE2 available, convert to v4f32 so the generated
2061 // register is legal.
2062 if (!Subtarget->hasSSE2())
2063 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2068 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2069 Flag = Chain.getValue(1);
2070 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2073 // The x86-64 ABIs require that for returning structs by value we copy
2074 // the sret argument into %rax/%eax (depending on ABI) for the return.
2075 // Win32 requires us to put the sret argument to %eax as well.
2076 // We saved the argument into a virtual register in the entry block,
2077 // so now we copy the value out and into %rax/%eax.
2078 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2079 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2080 MachineFunction &MF = DAG.getMachineFunction();
2081 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2082 unsigned Reg = FuncInfo->getSRetReturnReg();
2084 "SRetReturnReg should have been set in LowerFormalArguments().");
2085 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2088 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2089 X86::RAX : X86::EAX;
2090 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2091 Flag = Chain.getValue(1);
2093 // RAX/EAX now acts like a return value.
2094 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2097 RetOps[0] = Chain; // Update chain.
2099 // Add the flag if we have it.
2101 RetOps.push_back(Flag);
2103 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2106 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2107 if (N->getNumValues() != 1)
2109 if (!N->hasNUsesOfValue(1, 0))
2112 SDValue TCChain = Chain;
2113 SDNode *Copy = *N->use_begin();
2114 if (Copy->getOpcode() == ISD::CopyToReg) {
2115 // If the copy has a glue operand, we conservatively assume it isn't safe to
2116 // perform a tail call.
2117 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2119 TCChain = Copy->getOperand(0);
2120 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2123 bool HasRet = false;
2124 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2126 if (UI->getOpcode() != X86ISD::RET_FLAG)
2128 // If we are returning more than one value, we can definitely
2129 // not make a tail call see PR19530
2130 if (UI->getNumOperands() > 4)
2132 if (UI->getNumOperands() == 4 &&
2133 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2146 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2147 ISD::NodeType ExtendKind) const {
2149 // TODO: Is this also valid on 32-bit?
2150 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2151 ReturnMVT = MVT::i8;
2153 ReturnMVT = MVT::i32;
2155 EVT MinVT = getRegisterType(Context, ReturnMVT);
2156 return VT.bitsLT(MinVT) ? MinVT : VT;
2159 /// Lower the result values of a call into the
2160 /// appropriate copies out of appropriate physical registers.
2163 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2164 CallingConv::ID CallConv, bool isVarArg,
2165 const SmallVectorImpl<ISD::InputArg> &Ins,
2166 SDLoc dl, SelectionDAG &DAG,
2167 SmallVectorImpl<SDValue> &InVals) const {
2169 // Assign locations to each value returned by this call.
2170 SmallVector<CCValAssign, 16> RVLocs;
2171 bool Is64Bit = Subtarget->is64Bit();
2172 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2174 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2176 // Copy all of the result registers out of their specified physreg.
2177 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2178 CCValAssign &VA = RVLocs[i];
2179 EVT CopyVT = VA.getValVT();
2181 // If this is x86-64, and we disabled SSE, we can't return FP values
2182 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2183 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2184 report_fatal_error("SSE register return with SSE disabled");
2187 // If we prefer to use the value in xmm registers, copy it out as f80 and
2188 // use a truncate to move it from fp stack reg to xmm reg.
2189 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2190 isScalarFPTypeInSSEReg(VA.getValVT()))
2193 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2194 CopyVT, InFlag).getValue(1);
2195 SDValue Val = Chain.getValue(0);
2197 if (CopyVT != VA.getValVT())
2198 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2199 // This truncation won't change the value.
2200 DAG.getIntPtrConstant(1));
2202 InFlag = Chain.getValue(2);
2203 InVals.push_back(Val);
2209 //===----------------------------------------------------------------------===//
2210 // C & StdCall & Fast Calling Convention implementation
2211 //===----------------------------------------------------------------------===//
2212 // StdCall calling convention seems to be standard for many Windows' API
2213 // routines and around. It differs from C calling convention just a little:
2214 // callee should clean up the stack, not caller. Symbols should be also
2215 // decorated in some fancy way :) It doesn't support any vector arguments.
2216 // For info on fast calling convention see Fast Calling Convention (tail call)
2217 // implementation LowerX86_32FastCCCallTo.
2219 /// CallIsStructReturn - Determines whether a call uses struct return
2221 enum StructReturnType {
2226 static StructReturnType
2227 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2229 return NotStructReturn;
2231 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2232 if (!Flags.isSRet())
2233 return NotStructReturn;
2234 if (Flags.isInReg())
2235 return RegStructReturn;
2236 return StackStructReturn;
2239 /// Determines whether a function uses struct return semantics.
2240 static StructReturnType
2241 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2243 return NotStructReturn;
2245 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2246 if (!Flags.isSRet())
2247 return NotStructReturn;
2248 if (Flags.isInReg())
2249 return RegStructReturn;
2250 return StackStructReturn;
2253 /// Make a copy of an aggregate at address specified by "Src" to address
2254 /// "Dst" with size and alignment information specified by the specific
2255 /// parameter attribute. The copy will be passed as a byval function parameter.
2257 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2258 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2260 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2262 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2263 /*isVolatile*/false, /*AlwaysInline=*/true,
2264 MachinePointerInfo(), MachinePointerInfo());
2267 /// Return true if the calling convention is one that
2268 /// supports tail call optimization.
2269 static bool IsTailCallConvention(CallingConv::ID CC) {
2270 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2271 CC == CallingConv::HiPE);
2274 /// \brief Return true if the calling convention is a C calling convention.
2275 static bool IsCCallConvention(CallingConv::ID CC) {
2276 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2277 CC == CallingConv::X86_64_SysV);
2280 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2281 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2285 CallingConv::ID CalleeCC = CS.getCallingConv();
2286 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2292 /// Return true if the function is being made into
2293 /// a tailcall target by changing its ABI.
2294 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2295 bool GuaranteedTailCallOpt) {
2296 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2300 X86TargetLowering::LowerMemArgument(SDValue Chain,
2301 CallingConv::ID CallConv,
2302 const SmallVectorImpl<ISD::InputArg> &Ins,
2303 SDLoc dl, SelectionDAG &DAG,
2304 const CCValAssign &VA,
2305 MachineFrameInfo *MFI,
2307 // Create the nodes corresponding to a load from this parameter slot.
2308 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2309 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2310 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2311 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2314 // If value is passed by pointer we have address passed instead of the value
2316 if (VA.getLocInfo() == CCValAssign::Indirect)
2317 ValVT = VA.getLocVT();
2319 ValVT = VA.getValVT();
2321 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2322 // changed with more analysis.
2323 // In case of tail call optimization mark all arguments mutable. Since they
2324 // could be overwritten by lowering of arguments in case of a tail call.
2325 if (Flags.isByVal()) {
2326 unsigned Bytes = Flags.getByValSize();
2327 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2328 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2329 return DAG.getFrameIndex(FI, getPointerTy());
2331 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2332 VA.getLocMemOffset(), isImmutable);
2333 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2334 return DAG.getLoad(ValVT, dl, Chain, FIN,
2335 MachinePointerInfo::getFixedStack(FI),
2336 false, false, false, 0);
2340 // FIXME: Get this from tablegen.
2341 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2342 const X86Subtarget *Subtarget) {
2343 assert(Subtarget->is64Bit());
2345 if (Subtarget->isCallingConvWin64(CallConv)) {
2346 static const MCPhysReg GPR64ArgRegsWin64[] = {
2347 X86::RCX, X86::RDX, X86::R8, X86::R9
2349 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2352 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2353 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2355 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2358 // FIXME: Get this from tablegen.
2359 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2360 CallingConv::ID CallConv,
2361 const X86Subtarget *Subtarget) {
2362 assert(Subtarget->is64Bit());
2363 if (Subtarget->isCallingConvWin64(CallConv)) {
2364 // The XMM registers which might contain var arg parameters are shadowed
2365 // in their paired GPR. So we only need to save the GPR to their home
2367 // TODO: __vectorcall will change this.
2371 const Function *Fn = MF.getFunction();
2372 bool NoImplicitFloatOps = Fn->getAttributes().
2373 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2374 assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2375 "SSE register cannot be used when SSE is disabled!");
2376 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2377 !Subtarget->hasSSE1())
2378 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2382 static const MCPhysReg XMMArgRegs64Bit[] = {
2383 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2384 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2386 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2390 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2391 CallingConv::ID CallConv,
2393 const SmallVectorImpl<ISD::InputArg> &Ins,
2396 SmallVectorImpl<SDValue> &InVals)
2398 MachineFunction &MF = DAG.getMachineFunction();
2399 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2401 const Function* Fn = MF.getFunction();
2402 if (Fn->hasExternalLinkage() &&
2403 Subtarget->isTargetCygMing() &&
2404 Fn->getName() == "main")
2405 FuncInfo->setForceFramePointer(true);
2407 MachineFrameInfo *MFI = MF.getFrameInfo();
2408 bool Is64Bit = Subtarget->is64Bit();
2409 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2411 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2412 "Var args not supported with calling convention fastcc, ghc or hipe");
2414 // Assign locations to all of the incoming arguments.
2415 SmallVector<CCValAssign, 16> ArgLocs;
2416 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2418 // Allocate shadow area for Win64
2420 CCInfo.AllocateStack(32, 8);
2422 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2424 unsigned LastVal = ~0U;
2426 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2427 CCValAssign &VA = ArgLocs[i];
2428 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2430 assert(VA.getValNo() != LastVal &&
2431 "Don't support value assigned to multiple locs yet");
2433 LastVal = VA.getValNo();
2435 if (VA.isRegLoc()) {
2436 EVT RegVT = VA.getLocVT();
2437 const TargetRegisterClass *RC;
2438 if (RegVT == MVT::i32)
2439 RC = &X86::GR32RegClass;
2440 else if (Is64Bit && RegVT == MVT::i64)
2441 RC = &X86::GR64RegClass;
2442 else if (RegVT == MVT::f32)
2443 RC = &X86::FR32RegClass;
2444 else if (RegVT == MVT::f64)
2445 RC = &X86::FR64RegClass;
2446 else if (RegVT.is512BitVector())
2447 RC = &X86::VR512RegClass;
2448 else if (RegVT.is256BitVector())
2449 RC = &X86::VR256RegClass;
2450 else if (RegVT.is128BitVector())
2451 RC = &X86::VR128RegClass;
2452 else if (RegVT == MVT::x86mmx)
2453 RC = &X86::VR64RegClass;
2454 else if (RegVT == MVT::i1)
2455 RC = &X86::VK1RegClass;
2456 else if (RegVT == MVT::v8i1)
2457 RC = &X86::VK8RegClass;
2458 else if (RegVT == MVT::v16i1)
2459 RC = &X86::VK16RegClass;
2460 else if (RegVT == MVT::v32i1)
2461 RC = &X86::VK32RegClass;
2462 else if (RegVT == MVT::v64i1)
2463 RC = &X86::VK64RegClass;
2465 llvm_unreachable("Unknown argument type!");
2467 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2468 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2470 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2471 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2473 if (VA.getLocInfo() == CCValAssign::SExt)
2474 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2475 DAG.getValueType(VA.getValVT()));
2476 else if (VA.getLocInfo() == CCValAssign::ZExt)
2477 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2478 DAG.getValueType(VA.getValVT()));
2479 else if (VA.getLocInfo() == CCValAssign::BCvt)
2480 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2482 if (VA.isExtInLoc()) {
2483 // Handle MMX values passed in XMM regs.
2484 if (RegVT.isVector())
2485 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2487 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2490 assert(VA.isMemLoc());
2491 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2494 // If value is passed via pointer - do a load.
2495 if (VA.getLocInfo() == CCValAssign::Indirect)
2496 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2497 MachinePointerInfo(), false, false, false, 0);
2499 InVals.push_back(ArgValue);
2502 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2503 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504 // The x86-64 ABIs require that for returning structs by value we copy
2505 // the sret argument into %rax/%eax (depending on ABI) for the return.
2506 // Win32 requires us to put the sret argument to %eax as well.
2507 // Save the argument into a virtual register so that we can access it
2508 // from the return points.
2509 if (Ins[i].Flags.isSRet()) {
2510 unsigned Reg = FuncInfo->getSRetReturnReg();
2512 MVT PtrTy = getPointerTy();
2513 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2514 FuncInfo->setSRetReturnReg(Reg);
2516 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2517 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2523 unsigned StackSize = CCInfo.getNextStackOffset();
2524 // Align stack specially for tail calls.
2525 if (FuncIsMadeTailCallSafe(CallConv,
2526 MF.getTarget().Options.GuaranteedTailCallOpt))
2527 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2529 // If the function takes variable number of arguments, make a frame index for
2530 // the start of the first vararg value... for expansion of llvm.va_start. We
2531 // can skip this if there are no va_start calls.
2532 if (MFI->hasVAStart() &&
2533 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2534 CallConv != CallingConv::X86_ThisCall))) {
2535 FuncInfo->setVarArgsFrameIndex(
2536 MFI->CreateFixedObject(1, StackSize, true));
2539 // Figure out if XMM registers are in use.
2540 assert(!(MF.getTarget().Options.UseSoftFloat &&
2541 Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2542 Attribute::NoImplicitFloat)) &&
2543 "SSE register cannot be used when SSE is disabled!");
2545 // 64-bit calling conventions support varargs and register parameters, so we
2546 // have to do extra work to spill them in the prologue.
2547 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2548 // Find the first unallocated argument registers.
2549 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2550 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2551 unsigned NumIntRegs =
2552 CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2553 unsigned NumXMMRegs =
2554 CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2555 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2556 "SSE register cannot be used when SSE is disabled!");
2558 // Gather all the live in physical registers.
2559 SmallVector<SDValue, 6> LiveGPRs;
2560 SmallVector<SDValue, 8> LiveXMMRegs;
2562 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2563 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2565 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2567 if (!ArgXMMs.empty()) {
2568 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2569 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2570 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2571 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2572 LiveXMMRegs.push_back(
2573 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2578 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2579 // Get to the caller-allocated home save location. Add 8 to account
2580 // for the return address.
2581 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2582 FuncInfo->setRegSaveFrameIndex(
2583 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2584 // Fixup to set vararg frame on shadow area (4 x i64).
2586 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2588 // For X86-64, if there are vararg parameters that are passed via
2589 // registers, then we must store them to their spots on the stack so
2590 // they may be loaded by deferencing the result of va_next.
2591 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2592 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2593 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2594 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2597 // Store the integer parameter registers.
2598 SmallVector<SDValue, 8> MemOps;
2599 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2601 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2602 for (SDValue Val : LiveGPRs) {
2603 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2604 DAG.getIntPtrConstant(Offset));
2606 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2607 MachinePointerInfo::getFixedStack(
2608 FuncInfo->getRegSaveFrameIndex(), Offset),
2610 MemOps.push_back(Store);
2614 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2615 // Now store the XMM (fp + vector) parameter registers.
2616 SmallVector<SDValue, 12> SaveXMMOps;
2617 SaveXMMOps.push_back(Chain);
2618 SaveXMMOps.push_back(ALVal);
2619 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2620 FuncInfo->getRegSaveFrameIndex()));
2621 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2622 FuncInfo->getVarArgsFPOffset()));
2623 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2625 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2626 MVT::Other, SaveXMMOps));
2629 if (!MemOps.empty())
2630 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2633 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2634 // Find the largest legal vector type.
2635 MVT VecVT = MVT::Other;
2636 // FIXME: Only some x86_32 calling conventions support AVX512.
2637 if (Subtarget->hasAVX512() &&
2638 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2639 CallConv == CallingConv::Intel_OCL_BI)))
2640 VecVT = MVT::v16f32;
2641 else if (Subtarget->hasAVX())
2643 else if (Subtarget->hasSSE2())
2646 // We forward some GPRs and some vector types.
2647 SmallVector<MVT, 2> RegParmTypes;
2648 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2649 RegParmTypes.push_back(IntVT);
2650 if (VecVT != MVT::Other)
2651 RegParmTypes.push_back(VecVT);
2653 // Compute the set of forwarded registers. The rest are scratch.
2654 SmallVectorImpl<ForwardedRegister> &Forwards =
2655 FuncInfo->getForwardedMustTailRegParms();
2656 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2658 // Conservatively forward AL on x86_64, since it might be used for varargs.
2659 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2660 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2661 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2664 // Copy all forwards from physical to virtual registers.
2665 for (ForwardedRegister &F : Forwards) {
2666 // FIXME: Can we use a less constrained schedule?
2667 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2668 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2669 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2673 // Some CCs need callee pop.
2674 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2675 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2676 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2678 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2679 // If this is an sret function, the return should pop the hidden pointer.
2680 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2681 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2682 argsAreStructReturn(Ins) == StackStructReturn)
2683 FuncInfo->setBytesToPopOnReturn(4);
2687 // RegSaveFrameIndex is X86-64 only.
2688 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2689 if (CallConv == CallingConv::X86_FastCall ||
2690 CallConv == CallingConv::X86_ThisCall)
2691 // fastcc functions can't have varargs.
2692 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2695 FuncInfo->setArgumentStackSize(StackSize);
2701 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2702 SDValue StackPtr, SDValue Arg,
2703 SDLoc dl, SelectionDAG &DAG,
2704 const CCValAssign &VA,
2705 ISD::ArgFlagsTy Flags) const {
2706 unsigned LocMemOffset = VA.getLocMemOffset();
2707 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2708 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2709 if (Flags.isByVal())
2710 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2712 return DAG.getStore(Chain, dl, Arg, PtrOff,
2713 MachinePointerInfo::getStack(LocMemOffset),
2717 /// Emit a load of return address if tail call
2718 /// optimization is performed and it is required.
2720 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2721 SDValue &OutRetAddr, SDValue Chain,
2722 bool IsTailCall, bool Is64Bit,
2723 int FPDiff, SDLoc dl) const {
2724 // Adjust the Return address stack slot.
2725 EVT VT = getPointerTy();
2726 OutRetAddr = getReturnAddressFrameIndex(DAG);
2728 // Load the "old" Return address.
2729 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2730 false, false, false, 0);
2731 return SDValue(OutRetAddr.getNode(), 1);
2734 /// Emit a store of the return address if tail call
2735 /// optimization is performed and it is required (FPDiff!=0).
2736 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2737 SDValue Chain, SDValue RetAddrFrIdx,
2738 EVT PtrVT, unsigned SlotSize,
2739 int FPDiff, SDLoc dl) {
2740 // Store the return address to the appropriate stack slot.
2741 if (!FPDiff) return Chain;
2742 // Calculate the new stack slot for the return address.
2743 int NewReturnAddrFI =
2744 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2746 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2747 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2748 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2754 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2755 SmallVectorImpl<SDValue> &InVals) const {
2756 SelectionDAG &DAG = CLI.DAG;
2758 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2759 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2760 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2761 SDValue Chain = CLI.Chain;
2762 SDValue Callee = CLI.Callee;
2763 CallingConv::ID CallConv = CLI.CallConv;
2764 bool &isTailCall = CLI.IsTailCall;
2765 bool isVarArg = CLI.IsVarArg;
2767 MachineFunction &MF = DAG.getMachineFunction();
2768 bool Is64Bit = Subtarget->is64Bit();
2769 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2770 StructReturnType SR = callIsStructReturn(Outs);
2771 bool IsSibcall = false;
2772 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2774 if (MF.getTarget().Options.DisableTailCalls)
2777 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2779 // Force this to be a tail call. The verifier rules are enough to ensure
2780 // that we can lower this successfully without moving the return address
2783 } else if (isTailCall) {
2784 // Check if it's really possible to do a tail call.
2785 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2786 isVarArg, SR != NotStructReturn,
2787 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2788 Outs, OutVals, Ins, DAG);
2790 // Sibcalls are automatically detected tailcalls which do not require
2792 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2799 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2800 "Var args not supported with calling convention fastcc, ghc or hipe");
2802 // Analyze operands of the call, assigning locations to each operand.
2803 SmallVector<CCValAssign, 16> ArgLocs;
2804 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2806 // Allocate shadow area for Win64
2808 CCInfo.AllocateStack(32, 8);
2810 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2812 // Get a count of how many bytes are to be pushed on the stack.
2813 unsigned NumBytes = CCInfo.getNextStackOffset();
2815 // This is a sibcall. The memory operands are available in caller's
2816 // own caller's stack.
2818 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2819 IsTailCallConvention(CallConv))
2820 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2823 if (isTailCall && !IsSibcall && !IsMustTail) {
2824 // Lower arguments at fp - stackoffset + fpdiff.
2825 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2827 FPDiff = NumBytesCallerPushed - NumBytes;
2829 // Set the delta of movement of the returnaddr stackslot.
2830 // But only set if delta is greater than previous delta.
2831 if (FPDiff < X86Info->getTCReturnAddrDelta())
2832 X86Info->setTCReturnAddrDelta(FPDiff);
2835 unsigned NumBytesToPush = NumBytes;
2836 unsigned NumBytesToPop = NumBytes;
2838 // If we have an inalloca argument, all stack space has already been allocated
2839 // for us and be right at the top of the stack. We don't support multiple
2840 // arguments passed in memory when using inalloca.
2841 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2843 if (!ArgLocs.back().isMemLoc())
2844 report_fatal_error("cannot use inalloca attribute on a register "
2846 if (ArgLocs.back().getLocMemOffset() != 0)
2847 report_fatal_error("any parameter with the inalloca attribute must be "
2848 "the only memory argument");
2852 Chain = DAG.getCALLSEQ_START(
2853 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2855 SDValue RetAddrFrIdx;
2856 // Load return address for tail calls.
2857 if (isTailCall && FPDiff)
2858 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2859 Is64Bit, FPDiff, dl);
2861 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2862 SmallVector<SDValue, 8> MemOpChains;
2865 // Walk the register/memloc assignments, inserting copies/loads. In the case
2866 // of tail call optimization arguments are handle later.
2867 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2868 DAG.getSubtarget().getRegisterInfo());
2869 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2870 // Skip inalloca arguments, they have already been written.
2871 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2872 if (Flags.isInAlloca())
2875 CCValAssign &VA = ArgLocs[i];
2876 EVT RegVT = VA.getLocVT();
2877 SDValue Arg = OutVals[i];
2878 bool isByVal = Flags.isByVal();
2880 // Promote the value if needed.
2881 switch (VA.getLocInfo()) {
2882 default: llvm_unreachable("Unknown loc info!");
2883 case CCValAssign::Full: break;
2884 case CCValAssign::SExt:
2885 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2887 case CCValAssign::ZExt:
2888 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2890 case CCValAssign::AExt:
2891 if (RegVT.is128BitVector()) {
2892 // Special case: passing MMX values in XMM registers.
2893 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2894 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2895 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2897 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2899 case CCValAssign::BCvt:
2900 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2902 case CCValAssign::Indirect: {
2903 // Store the argument.
2904 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2905 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2906 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2907 MachinePointerInfo::getFixedStack(FI),
2914 if (VA.isRegLoc()) {
2915 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2916 if (isVarArg && IsWin64) {
2917 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2918 // shadow reg if callee is a varargs function.
2919 unsigned ShadowReg = 0;
2920 switch (VA.getLocReg()) {
2921 case X86::XMM0: ShadowReg = X86::RCX; break;
2922 case X86::XMM1: ShadowReg = X86::RDX; break;
2923 case X86::XMM2: ShadowReg = X86::R8; break;
2924 case X86::XMM3: ShadowReg = X86::R9; break;
2927 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2929 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2930 assert(VA.isMemLoc());
2931 if (!StackPtr.getNode())
2932 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2934 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2935 dl, DAG, VA, Flags));
2939 if (!MemOpChains.empty())
2940 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2942 if (Subtarget->isPICStyleGOT()) {
2943 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2946 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2947 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2949 // If we are tail calling and generating PIC/GOT style code load the
2950 // address of the callee into ECX. The value in ecx is used as target of
2951 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2952 // for tail calls on PIC/GOT architectures. Normally we would just put the
2953 // address of GOT into ebx and then call target@PLT. But for tail calls
2954 // ebx would be restored (since ebx is callee saved) before jumping to the
2957 // Note: The actual moving to ECX is done further down.
2958 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2959 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2960 !G->getGlobal()->hasProtectedVisibility())
2961 Callee = LowerGlobalAddress(Callee, DAG);
2962 else if (isa<ExternalSymbolSDNode>(Callee))
2963 Callee = LowerExternalSymbol(Callee, DAG);
2967 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2968 // From AMD64 ABI document:
2969 // For calls that may call functions that use varargs or stdargs
2970 // (prototype-less calls or calls to functions containing ellipsis (...) in
2971 // the declaration) %al is used as hidden argument to specify the number
2972 // of SSE registers used. The contents of %al do not need to match exactly
2973 // the number of registers, but must be an ubound on the number of SSE
2974 // registers used and is in the range 0 - 8 inclusive.
2976 // Count the number of XMM registers allocated.
2977 static const MCPhysReg XMMArgRegs[] = {
2978 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2979 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2981 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2982 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2983 && "SSE registers cannot be used when SSE is disabled");
2985 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2986 DAG.getConstant(NumXMMRegs, MVT::i8)));
2989 if (isVarArg && IsMustTail) {
2990 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2991 for (const auto &F : Forwards) {
2992 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2993 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2997 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2998 // don't need this because the eligibility check rejects calls that require
2999 // shuffling arguments passed in memory.
3000 if (!IsSibcall && isTailCall) {
3001 // Force all the incoming stack arguments to be loaded from the stack
3002 // before any new outgoing arguments are stored to the stack, because the
3003 // outgoing stack slots may alias the incoming argument stack slots, and
3004 // the alias isn't otherwise explicit. This is slightly more conservative
3005 // than necessary, because it means that each store effectively depends
3006 // on every argument instead of just those arguments it would clobber.
3007 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3009 SmallVector<SDValue, 8> MemOpChains2;
3012 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3013 CCValAssign &VA = ArgLocs[i];
3016 assert(VA.isMemLoc());
3017 SDValue Arg = OutVals[i];
3018 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3019 // Skip inalloca arguments. They don't require any work.
3020 if (Flags.isInAlloca())
3022 // Create frame index.
3023 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3024 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3025 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3026 FIN = DAG.getFrameIndex(FI, getPointerTy());
3028 if (Flags.isByVal()) {
3029 // Copy relative to framepointer.
3030 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3031 if (!StackPtr.getNode())
3032 StackPtr = DAG.getCopyFromReg(Chain, dl,
3033 RegInfo->getStackRegister(),
3035 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3037 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3041 // Store relative to framepointer.
3042 MemOpChains2.push_back(
3043 DAG.getStore(ArgChain, dl, Arg, FIN,
3044 MachinePointerInfo::getFixedStack(FI),
3049 if (!MemOpChains2.empty())
3050 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3052 // Store the return address to the appropriate stack slot.
3053 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3054 getPointerTy(), RegInfo->getSlotSize(),
3058 // Build a sequence of copy-to-reg nodes chained together with token chain
3059 // and flag operands which copy the outgoing args into registers.
3061 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3062 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3063 RegsToPass[i].second, InFlag);
3064 InFlag = Chain.getValue(1);
3067 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3068 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3069 // In the 64-bit large code model, we have to make all calls
3070 // through a register, since the call instruction's 32-bit
3071 // pc-relative offset may not be large enough to hold the whole
3073 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3074 // If the callee is a GlobalAddress node (quite common, every direct call
3075 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3078 // We should use extra load for direct calls to dllimported functions in
3080 const GlobalValue *GV = G->getGlobal();
3081 if (!GV->hasDLLImportStorageClass()) {
3082 unsigned char OpFlags = 0;
3083 bool ExtraLoad = false;
3084 unsigned WrapperKind = ISD::DELETED_NODE;
3086 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3087 // external symbols most go through the PLT in PIC mode. If the symbol
3088 // has hidden or protected visibility, or if it is static or local, then
3089 // we don't need to use the PLT - we can directly call it.
3090 if (Subtarget->isTargetELF() &&
3091 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3092 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3093 OpFlags = X86II::MO_PLT;
3094 } else if (Subtarget->isPICStyleStubAny() &&
3095 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3096 (!Subtarget->getTargetTriple().isMacOSX() ||
3097 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3098 // PC-relative references to external symbols should go through $stub,
3099 // unless we're building with the leopard linker or later, which
3100 // automatically synthesizes these stubs.
3101 OpFlags = X86II::MO_DARWIN_STUB;
3102 } else if (Subtarget->isPICStyleRIPRel() &&
3103 isa<Function>(GV) &&
3104 cast<Function>(GV)->getAttributes().
3105 hasAttribute(AttributeSet::FunctionIndex,
3106 Attribute::NonLazyBind)) {
3107 // If the function is marked as non-lazy, generate an indirect call
3108 // which loads from the GOT directly. This avoids runtime overhead
3109 // at the cost of eager binding (and one extra byte of encoding).
3110 OpFlags = X86II::MO_GOTPCREL;
3111 WrapperKind = X86ISD::WrapperRIP;
3115 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3116 G->getOffset(), OpFlags);
3118 // Add a wrapper if needed.
3119 if (WrapperKind != ISD::DELETED_NODE)
3120 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3121 // Add extra indirection if needed.
3123 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3124 MachinePointerInfo::getGOT(),
3125 false, false, false, 0);
3127 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3128 unsigned char OpFlags = 0;
3130 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3131 // external symbols should go through the PLT.
3132 if (Subtarget->isTargetELF() &&
3133 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3134 OpFlags = X86II::MO_PLT;
3135 } else if (Subtarget->isPICStyleStubAny() &&
3136 (!Subtarget->getTargetTriple().isMacOSX() ||
3137 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3138 // PC-relative references to external symbols should go through $stub,
3139 // unless we're building with the leopard linker or later, which
3140 // automatically synthesizes these stubs.
3141 OpFlags = X86II::MO_DARWIN_STUB;
3144 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3146 } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3147 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3148 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3151 // Returns a chain & a flag for retval copy to use.
3152 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3153 SmallVector<SDValue, 8> Ops;
3155 if (!IsSibcall && isTailCall) {
3156 Chain = DAG.getCALLSEQ_END(Chain,
3157 DAG.getIntPtrConstant(NumBytesToPop, true),
3158 DAG.getIntPtrConstant(0, true), InFlag, dl);
3159 InFlag = Chain.getValue(1);
3162 Ops.push_back(Chain);
3163 Ops.push_back(Callee);
3166 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3168 // Add argument registers to the end of the list so that they are known live
3170 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3171 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3172 RegsToPass[i].second.getValueType()));
3174 // Add a register mask operand representing the call-preserved registers.
3175 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3176 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3177 assert(Mask && "Missing call preserved mask for calling convention");
3178 Ops.push_back(DAG.getRegisterMask(Mask));
3180 if (InFlag.getNode())
3181 Ops.push_back(InFlag);
3185 //// If this is the first return lowered for this function, add the regs
3186 //// to the liveout set for the function.
3187 // This isn't right, although it's probably harmless on x86; liveouts
3188 // should be computed from returns not tail calls. Consider a void
3189 // function making a tail call to a function returning int.
3190 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3193 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3194 InFlag = Chain.getValue(1);
3196 // Create the CALLSEQ_END node.
3197 unsigned NumBytesForCalleeToPop;
3198 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3199 DAG.getTarget().Options.GuaranteedTailCallOpt))
3200 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3201 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3202 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3203 SR == StackStructReturn)
3204 // If this is a call to a struct-return function, the callee
3205 // pops the hidden struct pointer, so we have to push it back.
3206 // This is common for Darwin/X86, Linux & Mingw32 targets.
3207 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3208 NumBytesForCalleeToPop = 4;
3210 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3212 // Returns a flag for retval copy to use.
3214 Chain = DAG.getCALLSEQ_END(Chain,
3215 DAG.getIntPtrConstant(NumBytesToPop, true),
3216 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3219 InFlag = Chain.getValue(1);
3222 // Handle result values, copying them out of physregs into vregs that we
3224 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3225 Ins, dl, DAG, InVals);
3228 //===----------------------------------------------------------------------===//
3229 // Fast Calling Convention (tail call) implementation
3230 //===----------------------------------------------------------------------===//
3232 // Like std call, callee cleans arguments, convention except that ECX is
3233 // reserved for storing the tail called function address. Only 2 registers are
3234 // free for argument passing (inreg). Tail call optimization is performed
3236 // * tailcallopt is enabled
3237 // * caller/callee are fastcc
3238 // On X86_64 architecture with GOT-style position independent code only local
3239 // (within module) calls are supported at the moment.
3240 // To keep the stack aligned according to platform abi the function
3241 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3242 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3243 // If a tail called function callee has more arguments than the caller the
3244 // caller needs to make sure that there is room to move the RETADDR to. This is
3245 // achieved by reserving an area the size of the argument delta right after the
3246 // original RETADDR, but before the saved framepointer or the spilled registers
3247 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3259 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3260 /// for a 16 byte align requirement.
3262 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3263 SelectionDAG& DAG) const {
3264 MachineFunction &MF = DAG.getMachineFunction();
3265 const TargetMachine &TM = MF.getTarget();
3266 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3267 TM.getSubtargetImpl()->getRegisterInfo());
3268 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3269 unsigned StackAlignment = TFI.getStackAlignment();
3270 uint64_t AlignMask = StackAlignment - 1;
3271 int64_t Offset = StackSize;
3272 unsigned SlotSize = RegInfo->getSlotSize();
3273 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3274 // Number smaller than 12 so just add the difference.
3275 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3277 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3278 Offset = ((~AlignMask) & Offset) + StackAlignment +
3279 (StackAlignment-SlotSize);
3284 /// MatchingStackOffset - Return true if the given stack call argument is
3285 /// already available in the same position (relatively) of the caller's
3286 /// incoming argument stack.
3288 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3289 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3290 const X86InstrInfo *TII) {
3291 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3293 if (Arg.getOpcode() == ISD::CopyFromReg) {
3294 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3295 if (!TargetRegisterInfo::isVirtualRegister(VR))
3297 MachineInstr *Def = MRI->getVRegDef(VR);
3300 if (!Flags.isByVal()) {
3301 if (!TII->isLoadFromStackSlot(Def, FI))
3304 unsigned Opcode = Def->getOpcode();
3305 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3306 Def->getOperand(1).isFI()) {
3307 FI = Def->getOperand(1).getIndex();
3308 Bytes = Flags.getByValSize();
3312 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3313 if (Flags.isByVal())
3314 // ByVal argument is passed in as a pointer but it's now being
3315 // dereferenced. e.g.
3316 // define @foo(%struct.X* %A) {
3317 // tail call @bar(%struct.X* byval %A)
3320 SDValue Ptr = Ld->getBasePtr();
3321 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3324 FI = FINode->getIndex();
3325 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3326 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3327 FI = FINode->getIndex();
3328 Bytes = Flags.getByValSize();
3332 assert(FI != INT_MAX);
3333 if (!MFI->isFixedObjectIndex(FI))
3335 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3338 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3339 /// for tail call optimization. Targets which want to do tail call
3340 /// optimization should implement this function.
3342 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3343 CallingConv::ID CalleeCC,
3345 bool isCalleeStructRet,
3346 bool isCallerStructRet,
3348 const SmallVectorImpl<ISD::OutputArg> &Outs,
3349 const SmallVectorImpl<SDValue> &OutVals,
3350 const SmallVectorImpl<ISD::InputArg> &Ins,
3351 SelectionDAG &DAG) const {
3352 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3355 // If -tailcallopt is specified, make fastcc functions tail-callable.
3356 const MachineFunction &MF = DAG.getMachineFunction();
3357 const Function *CallerF = MF.getFunction();
3359 // If the function return type is x86_fp80 and the callee return type is not,
3360 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3361 // perform a tailcall optimization here.
3362 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3365 CallingConv::ID CallerCC = CallerF->getCallingConv();
3366 bool CCMatch = CallerCC == CalleeCC;
3367 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3368 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3370 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3371 if (IsTailCallConvention(CalleeCC) && CCMatch)
3376 // Look for obvious safe cases to perform tail call optimization that do not
3377 // require ABI changes. This is what gcc calls sibcall.
3379 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3380 // emit a special epilogue.
3381 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3382 DAG.getSubtarget().getRegisterInfo());
3383 if (RegInfo->needsStackRealignment(MF))
3386 // Also avoid sibcall optimization if either caller or callee uses struct
3387 // return semantics.
3388 if (isCalleeStructRet || isCallerStructRet)
3391 // An stdcall/thiscall caller is expected to clean up its arguments; the
3392 // callee isn't going to do that.
3393 // FIXME: this is more restrictive than needed. We could produce a tailcall
3394 // when the stack adjustment matches. For example, with a thiscall that takes
3395 // only one argument.
3396 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3397 CallerCC == CallingConv::X86_ThisCall))
3400 // Do not sibcall optimize vararg calls unless all arguments are passed via
3402 if (isVarArg && !Outs.empty()) {
3404 // Optimizing for varargs on Win64 is unlikely to be safe without
3405 // additional testing.
3406 if (IsCalleeWin64 || IsCallerWin64)
3409 SmallVector<CCValAssign, 16> ArgLocs;
3410 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3413 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3414 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3415 if (!ArgLocs[i].isRegLoc())
3419 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3420 // stack. Therefore, if it's not used by the call it is not safe to optimize
3421 // this into a sibcall.
3422 bool Unused = false;
3423 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3430 SmallVector<CCValAssign, 16> RVLocs;
3431 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3433 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3434 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3435 CCValAssign &VA = RVLocs[i];
3436 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3441 // If the calling conventions do not match, then we'd better make sure the
3442 // results are returned in the same way as what the caller expects.
3444 SmallVector<CCValAssign, 16> RVLocs1;
3445 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3447 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3449 SmallVector<CCValAssign, 16> RVLocs2;
3450 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3452 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3454 if (RVLocs1.size() != RVLocs2.size())
3456 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3457 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3459 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3461 if (RVLocs1[i].isRegLoc()) {
3462 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3465 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3471 // If the callee takes no arguments then go on to check the results of the
3473 if (!Outs.empty()) {
3474 // Check if stack adjustment is needed. For now, do not do this if any
3475 // argument is passed on the stack.
3476 SmallVector<CCValAssign, 16> ArgLocs;
3477 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3480 // Allocate shadow area for Win64
3482 CCInfo.AllocateStack(32, 8);
3484 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3485 if (CCInfo.getNextStackOffset()) {
3486 MachineFunction &MF = DAG.getMachineFunction();
3487 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3490 // Check if the arguments are already laid out in the right way as
3491 // the caller's fixed stack objects.
3492 MachineFrameInfo *MFI = MF.getFrameInfo();
3493 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3494 const X86InstrInfo *TII =
3495 static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3497 CCValAssign &VA = ArgLocs[i];
3498 SDValue Arg = OutVals[i];
3499 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3500 if (VA.getLocInfo() == CCValAssign::Indirect)
3502 if (!VA.isRegLoc()) {
3503 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3510 // If the tailcall address may be in a register, then make sure it's
3511 // possible to register allocate for it. In 32-bit, the call address can
3512 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3513 // callee-saved registers are restored. These happen to be the same
3514 // registers used to pass 'inreg' arguments so watch out for those.
3515 if (!Subtarget->is64Bit() &&
3516 ((!isa<GlobalAddressSDNode>(Callee) &&
3517 !isa<ExternalSymbolSDNode>(Callee)) ||
3518 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3519 unsigned NumInRegs = 0;
3520 // In PIC we need an extra register to formulate the address computation
3522 unsigned MaxInRegs =
3523 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3525 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3526 CCValAssign &VA = ArgLocs[i];
3529 unsigned Reg = VA.getLocReg();
3532 case X86::EAX: case X86::EDX: case X86::ECX:
3533 if (++NumInRegs == MaxInRegs)
3545 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3546 const TargetLibraryInfo *libInfo) const {
3547 return X86::createFastISel(funcInfo, libInfo);
3550 //===----------------------------------------------------------------------===//
3551 // Other Lowering Hooks
3552 //===----------------------------------------------------------------------===//
3554 static bool MayFoldLoad(SDValue Op) {
3555 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3558 static bool MayFoldIntoStore(SDValue Op) {
3559 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3562 static bool isTargetShuffle(unsigned Opcode) {
3564 default: return false;
3565 case X86ISD::BLENDI:
3566 case X86ISD::PSHUFB:
3567 case X86ISD::PSHUFD:
3568 case X86ISD::PSHUFHW:
3569 case X86ISD::PSHUFLW:
3571 case X86ISD::PALIGNR:
3572 case X86ISD::MOVLHPS:
3573 case X86ISD::MOVLHPD:
3574 case X86ISD::MOVHLPS:
3575 case X86ISD::MOVLPS:
3576 case X86ISD::MOVLPD:
3577 case X86ISD::MOVSHDUP:
3578 case X86ISD::MOVSLDUP:
3579 case X86ISD::MOVDDUP:
3582 case X86ISD::UNPCKL:
3583 case X86ISD::UNPCKH:
3584 case X86ISD::VPERMILPI:
3585 case X86ISD::VPERM2X128:
3586 case X86ISD::VPERMI:
3591 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3592 SDValue V1, SelectionDAG &DAG) {
3594 default: llvm_unreachable("Unknown x86 shuffle node");
3595 case X86ISD::MOVSHDUP:
3596 case X86ISD::MOVSLDUP:
3597 case X86ISD::MOVDDUP:
3598 return DAG.getNode(Opc, dl, VT, V1);
3602 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3603 SDValue V1, unsigned TargetMask,
3604 SelectionDAG &DAG) {
3606 default: llvm_unreachable("Unknown x86 shuffle node");
3607 case X86ISD::PSHUFD:
3608 case X86ISD::PSHUFHW:
3609 case X86ISD::PSHUFLW:
3610 case X86ISD::VPERMILPI:
3611 case X86ISD::VPERMI:
3612 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3616 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3617 SDValue V1, SDValue V2, unsigned TargetMask,
3618 SelectionDAG &DAG) {
3620 default: llvm_unreachable("Unknown x86 shuffle node");
3621 case X86ISD::PALIGNR:
3622 case X86ISD::VALIGN:
3624 case X86ISD::VPERM2X128:
3625 return DAG.getNode(Opc, dl, VT, V1, V2,
3626 DAG.getConstant(TargetMask, MVT::i8));
3630 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3631 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3633 default: llvm_unreachable("Unknown x86 shuffle node");
3634 case X86ISD::MOVLHPS:
3635 case X86ISD::MOVLHPD:
3636 case X86ISD::MOVHLPS:
3637 case X86ISD::MOVLPS:
3638 case X86ISD::MOVLPD:
3641 case X86ISD::UNPCKL:
3642 case X86ISD::UNPCKH:
3643 return DAG.getNode(Opc, dl, VT, V1, V2);
3647 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3648 MachineFunction &MF = DAG.getMachineFunction();
3649 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3650 DAG.getSubtarget().getRegisterInfo());
3651 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3652 int ReturnAddrIndex = FuncInfo->getRAIndex();
3654 if (ReturnAddrIndex == 0) {
3655 // Set up a frame object for the return address.
3656 unsigned SlotSize = RegInfo->getSlotSize();
3657 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3660 FuncInfo->setRAIndex(ReturnAddrIndex);
3663 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3666 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3667 bool hasSymbolicDisplacement) {
3668 // Offset should fit into 32 bit immediate field.
3669 if (!isInt<32>(Offset))
3672 // If we don't have a symbolic displacement - we don't have any extra
3674 if (!hasSymbolicDisplacement)
3677 // FIXME: Some tweaks might be needed for medium code model.
3678 if (M != CodeModel::Small && M != CodeModel::Kernel)
3681 // For small code model we assume that latest object is 16MB before end of 31
3682 // bits boundary. We may also accept pretty large negative constants knowing
3683 // that all objects are in the positive half of address space.
3684 if (M == CodeModel::Small && Offset < 16*1024*1024)
3687 // For kernel code model we know that all object resist in the negative half
3688 // of 32bits address space. We may not accept negative offsets, since they may
3689 // be just off and we may accept pretty large positive ones.
3690 if (M == CodeModel::Kernel && Offset >= 0)
3696 /// isCalleePop - Determines whether the callee is required to pop its
3697 /// own arguments. Callee pop is necessary to support tail calls.
3698 bool X86::isCalleePop(CallingConv::ID CallingConv,
3699 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3700 switch (CallingConv) {
3703 case CallingConv::X86_StdCall:
3704 case CallingConv::X86_FastCall:
3705 case CallingConv::X86_ThisCall:
3707 case CallingConv::Fast:
3708 case CallingConv::GHC:
3709 case CallingConv::HiPE:
3716 /// \brief Return true if the condition is an unsigned comparison operation.
3717 static bool isX86CCUnsigned(unsigned X86CC) {
3719 default: llvm_unreachable("Invalid integer condition!");
3720 case X86::COND_E: return true;
3721 case X86::COND_G: return false;
3722 case X86::COND_GE: return false;
3723 case X86::COND_L: return false;
3724 case X86::COND_LE: return false;
3725 case X86::COND_NE: return true;
3726 case X86::COND_B: return true;
3727 case X86::COND_A: return true;
3728 case X86::COND_BE: return true;
3729 case X86::COND_AE: return true;
3731 llvm_unreachable("covered switch fell through?!");
3734 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3735 /// specific condition code, returning the condition code and the LHS/RHS of the
3736 /// comparison to make.
3737 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3738 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3740 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3741 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3742 // X > -1 -> X == 0, jump !sign.
3743 RHS = DAG.getConstant(0, RHS.getValueType());
3744 return X86::COND_NS;
3746 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3747 // X < 0 -> X == 0, jump on sign.
3750 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3752 RHS = DAG.getConstant(0, RHS.getValueType());
3753 return X86::COND_LE;
3757 switch (SetCCOpcode) {
3758 default: llvm_unreachable("Invalid integer condition!");
3759 case ISD::SETEQ: return X86::COND_E;
3760 case ISD::SETGT: return X86::COND_G;
3761 case ISD::SETGE: return X86::COND_GE;
3762 case ISD::SETLT: return X86::COND_L;
3763 case ISD::SETLE: return X86::COND_LE;
3764 case ISD::SETNE: return X86::COND_NE;
3765 case ISD::SETULT: return X86::COND_B;
3766 case ISD::SETUGT: return X86::COND_A;
3767 case ISD::SETULE: return X86::COND_BE;
3768 case ISD::SETUGE: return X86::COND_AE;
3772 // First determine if it is required or is profitable to flip the operands.
3774 // If LHS is a foldable load, but RHS is not, flip the condition.
3775 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3776 !ISD::isNON_EXTLoad(RHS.getNode())) {
3777 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3778 std::swap(LHS, RHS);
3781 switch (SetCCOpcode) {
3787 std::swap(LHS, RHS);
3791 // On a floating point condition, the flags are set as follows:
3793 // 0 | 0 | 0 | X > Y
3794 // 0 | 0 | 1 | X < Y
3795 // 1 | 0 | 0 | X == Y
3796 // 1 | 1 | 1 | unordered
3797 switch (SetCCOpcode) {
3798 default: llvm_unreachable("Condcode should be pre-legalized away");
3800 case ISD::SETEQ: return X86::COND_E;
3801 case ISD::SETOLT: // flipped
3803 case ISD::SETGT: return X86::COND_A;
3804 case ISD::SETOLE: // flipped
3806 case ISD::SETGE: return X86::COND_AE;
3807 case ISD::SETUGT: // flipped
3809 case ISD::SETLT: return X86::COND_B;
3810 case ISD::SETUGE: // flipped
3812 case ISD::SETLE: return X86::COND_BE;
3814 case ISD::SETNE: return X86::COND_NE;
3815 case ISD::SETUO: return X86::COND_P;
3816 case ISD::SETO: return X86::COND_NP;
3818 case ISD::SETUNE: return X86::COND_INVALID;
3822 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3823 /// code. Current x86 isa includes the following FP cmov instructions:
3824 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3825 static bool hasFPCMov(unsigned X86CC) {
3841 /// isFPImmLegal - Returns true if the target can instruction select the
3842 /// specified FP immediate natively. If false, the legalizer will
3843 /// materialize the FP immediate as a load from a constant pool.
3844 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3845 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3846 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3852 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3853 ISD::LoadExtType ExtTy,
3855 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3856 // relocation target a movq or addq instruction: don't let the load shrink.
3857 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3858 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3859 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3860 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3864 /// \brief Returns true if it is beneficial to convert a load of a constant
3865 /// to just the constant itself.
3866 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3868 assert(Ty->isIntegerTy());
3870 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3871 if (BitSize == 0 || BitSize > 64)
3876 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3877 unsigned Index) const {
3878 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3881 return (Index == 0 || Index == ResVT.getVectorNumElements());
3884 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3885 // Speculate cttz only if we can directly use TZCNT.
3886 return Subtarget->hasBMI();
3889 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3890 // Speculate ctlz only if we can directly use LZCNT.
3891 return Subtarget->hasLZCNT();
3894 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3895 /// the specified range (L, H].
3896 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3897 return (Val < 0) || (Val >= Low && Val < Hi);
3900 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3901 /// specified value.
3902 static bool isUndefOrEqual(int Val, int CmpVal) {
3903 return (Val < 0 || Val == CmpVal);
3906 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3907 /// from position Pos and ending in Pos+Size, falls within the specified
3908 /// sequential range (Low, Low+Size]. or is undef.
3909 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3910 unsigned Pos, unsigned Size, int Low) {
3911 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3912 if (!isUndefOrEqual(Mask[i], Low))
3917 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3918 /// is suitable for input to PSHUFD. That is, it doesn't reference the other
3919 /// operand - by default will match for first operand.
3920 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT,
3921 bool TestSecondOperand = false) {
3922 if (VT != MVT::v4f32 && VT != MVT::v4i32 &&
3923 VT != MVT::v2f64 && VT != MVT::v2i64)
3926 unsigned NumElems = VT.getVectorNumElements();
3927 unsigned Lo = TestSecondOperand ? NumElems : 0;
3928 unsigned Hi = Lo + NumElems;
3930 for (unsigned i = 0; i < NumElems; ++i)
3931 if (!isUndefOrInRange(Mask[i], (int)Lo, (int)Hi))
3937 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3938 /// is suitable for input to PSHUFHW.
3939 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3940 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3943 // Lower quadword copied in order or undef.
3944 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3947 // Upper quadword shuffled.
3948 for (unsigned i = 4; i != 8; ++i)
3949 if (!isUndefOrInRange(Mask[i], 4, 8))
3952 if (VT == MVT::v16i16) {
3953 // Lower quadword copied in order or undef.
3954 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3957 // Upper quadword shuffled.
3958 for (unsigned i = 12; i != 16; ++i)
3959 if (!isUndefOrInRange(Mask[i], 12, 16))
3966 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3967 /// is suitable for input to PSHUFLW.
3968 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3969 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3972 // Upper quadword copied in order.
3973 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3976 // Lower quadword shuffled.
3977 for (unsigned i = 0; i != 4; ++i)
3978 if (!isUndefOrInRange(Mask[i], 0, 4))
3981 if (VT == MVT::v16i16) {
3982 // Upper quadword copied in order.
3983 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3986 // Lower quadword shuffled.
3987 for (unsigned i = 8; i != 12; ++i)
3988 if (!isUndefOrInRange(Mask[i], 8, 12))
3995 /// \brief Return true if the mask specifies a shuffle of elements that is
3996 /// suitable for input to intralane (palignr) or interlane (valign) vector
3998 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3999 unsigned NumElts = VT.getVectorNumElements();
4000 unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
4001 unsigned NumLaneElts = NumElts/NumLanes;
4003 // Do not handle 64-bit element shuffles with palignr.
4004 if (NumLaneElts == 2)
4007 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
4009 for (i = 0; i != NumLaneElts; ++i) {
4014 // Lane is all undef, go to next lane
4015 if (i == NumLaneElts)
4018 int Start = Mask[i+l];
4020 // Make sure its in this lane in one of the sources
4021 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
4022 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
4025 // If not lane 0, then we must match lane 0
4026 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
4029 // Correct second source to be contiguous with first source
4030 if (Start >= (int)NumElts)
4031 Start -= NumElts - NumLaneElts;
4033 // Make sure we're shifting in the right direction.
4034 if (Start <= (int)(i+l))
4039 // Check the rest of the elements to see if they are consecutive.
4040 for (++i; i != NumLaneElts; ++i) {
4041 int Idx = Mask[i+l];
4043 // Make sure its in this lane
4044 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
4045 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
4048 // If not lane 0, then we must match lane 0
4049 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
4052 if (Idx >= (int)NumElts)
4053 Idx -= NumElts - NumLaneElts;
4055 if (!isUndefOrEqual(Idx, Start+i))
4064 /// \brief Return true if the node specifies a shuffle of elements that is
4065 /// suitable for input to PALIGNR.
4066 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4067 const X86Subtarget *Subtarget) {
4068 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4069 (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4070 VT.is512BitVector())
4071 // FIXME: Add AVX512BW.
4074 return isAlignrMask(Mask, VT, false);
4077 /// \brief Return true if the node specifies a shuffle of elements that is
4078 /// suitable for input to VALIGN.
4079 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4080 const X86Subtarget *Subtarget) {
4081 // FIXME: Add AVX512VL.
4082 if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4084 return isAlignrMask(Mask, VT, true);
4087 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4088 /// the two vector operands have swapped position.
4089 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4090 unsigned NumElems) {
4091 for (unsigned i = 0; i != NumElems; ++i) {
4095 else if (idx < (int)NumElems)
4096 Mask[i] = idx + NumElems;
4098 Mask[i] = idx - NumElems;
4102 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4103 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4104 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4105 /// reverse of what x86 shuffles want.
4106 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4108 unsigned NumElems = VT.getVectorNumElements();
4109 unsigned NumLanes = VT.getSizeInBits()/128;
4110 unsigned NumLaneElems = NumElems/NumLanes;
4112 if (NumLaneElems != 2 && NumLaneElems != 4)
4115 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4116 bool symetricMaskRequired =
4117 (VT.getSizeInBits() >= 256) && (EltSize == 32);
4119 // VSHUFPSY divides the resulting vector into 4 chunks.
4120 // The sources are also splitted into 4 chunks, and each destination
4121 // chunk must come from a different source chunk.
4123 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
4124 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
4126 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
4127 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
4129 // VSHUFPDY divides the resulting vector into 4 chunks.
4130 // The sources are also splitted into 4 chunks, and each destination
4131 // chunk must come from a different source chunk.
4133 // SRC1 => X3 X2 X1 X0
4134 // SRC2 => Y3 Y2 Y1 Y0
4136 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
4138 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4139 unsigned HalfLaneElems = NumLaneElems/2;
4140 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4141 for (unsigned i = 0; i != NumLaneElems; ++i) {
4142 int Idx = Mask[i+l];
4143 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4144 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4146 // For VSHUFPSY, the mask of the second half must be the same as the
4147 // first but with the appropriate offsets. This works in the same way as
4148 // VPERMILPS works with masks.
4149 if (!symetricMaskRequired || Idx < 0)
4151 if (MaskVal[i] < 0) {
4152 MaskVal[i] = Idx - l;
4155 if ((signed)(Idx - l) != MaskVal[i])
4163 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4164 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4165 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4166 if (!VT.is128BitVector())
4169 unsigned NumElems = VT.getVectorNumElements();
4174 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4175 return isUndefOrEqual(Mask[0], 6) &&
4176 isUndefOrEqual(Mask[1], 7) &&
4177 isUndefOrEqual(Mask[2], 2) &&
4178 isUndefOrEqual(Mask[3], 3);
4181 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4182 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4184 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4185 if (!VT.is128BitVector())
4188 unsigned NumElems = VT.getVectorNumElements();
4193 return isUndefOrEqual(Mask[0], 2) &&
4194 isUndefOrEqual(Mask[1], 3) &&
4195 isUndefOrEqual(Mask[2], 2) &&
4196 isUndefOrEqual(Mask[3], 3);
4199 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4200 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4201 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4202 if (!VT.is128BitVector())
4205 unsigned NumElems = VT.getVectorNumElements();
4207 if (NumElems != 2 && NumElems != 4)
4210 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4211 if (!isUndefOrEqual(Mask[i], i + NumElems))
4214 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4215 if (!isUndefOrEqual(Mask[i], i))
4221 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4222 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4223 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4224 if (!VT.is128BitVector())
4227 unsigned NumElems = VT.getVectorNumElements();
4229 if (NumElems != 2 && NumElems != 4)
4232 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4233 if (!isUndefOrEqual(Mask[i], i))
4236 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4237 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4243 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4244 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4245 /// i. e: If all but one element come from the same vector.
4246 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4247 // TODO: Deal with AVX's VINSERTPS
4248 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4251 unsigned CorrectPosV1 = 0;
4252 unsigned CorrectPosV2 = 0;
4253 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4254 if (Mask[i] == -1) {
4262 else if (Mask[i] == i + 4)
4266 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4267 // We have 3 elements (undefs count as elements from any vector) from one
4268 // vector, and one from another.
4275 // Some special combinations that can be optimized.
4278 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4279 SelectionDAG &DAG) {
4280 MVT VT = SVOp->getSimpleValueType(0);
4283 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4286 ArrayRef<int> Mask = SVOp->getMask();
4288 // These are the special masks that may be optimized.
4289 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4290 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4291 bool MatchEvenMask = true;
4292 bool MatchOddMask = true;
4293 for (int i=0; i<8; ++i) {
4294 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4295 MatchEvenMask = false;
4296 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4297 MatchOddMask = false;
4300 if (!MatchEvenMask && !MatchOddMask)
4303 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4305 SDValue Op0 = SVOp->getOperand(0);
4306 SDValue Op1 = SVOp->getOperand(1);
4308 if (MatchEvenMask) {
4309 // Shift the second operand right to 32 bits.
4310 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4311 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4313 // Shift the first operand left to 32 bits.
4314 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4315 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4317 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4318 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4321 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4322 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4323 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4324 bool HasInt256, bool V2IsSplat = false) {
4326 assert(VT.getSizeInBits() >= 128 &&
4327 "Unsupported vector type for unpckl");
4329 unsigned NumElts = VT.getVectorNumElements();
4330 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4331 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4334 assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4335 "Unsupported vector type for unpckh");
4337 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4338 unsigned NumLanes = VT.getSizeInBits()/128;
4339 unsigned NumLaneElts = NumElts/NumLanes;
4341 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4342 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4343 int BitI = Mask[l+i];
4344 int BitI1 = Mask[l+i+1];
4345 if (!isUndefOrEqual(BitI, j))
4348 if (!isUndefOrEqual(BitI1, NumElts))
4351 if (!isUndefOrEqual(BitI1, j + NumElts))
4360 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4361 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4362 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4363 bool HasInt256, bool V2IsSplat = false) {
4364 assert(VT.getSizeInBits() >= 128 &&
4365 "Unsupported vector type for unpckh");
4367 unsigned NumElts = VT.getVectorNumElements();
4368 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4369 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4372 assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4373 "Unsupported vector type for unpckh");
4375 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4376 unsigned NumLanes = VT.getSizeInBits()/128;
4377 unsigned NumLaneElts = NumElts/NumLanes;
4379 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4380 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4381 int BitI = Mask[l+i];
4382 int BitI1 = Mask[l+i+1];
4383 if (!isUndefOrEqual(BitI, j))
4386 if (isUndefOrEqual(BitI1, NumElts))
4389 if (!isUndefOrEqual(BitI1, j+NumElts))
4397 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4398 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4400 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4401 unsigned NumElts = VT.getVectorNumElements();
4402 bool Is256BitVec = VT.is256BitVector();
4404 if (VT.is512BitVector())
4406 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4407 "Unsupported vector type for unpckh");
4409 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4410 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4413 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4414 // FIXME: Need a better way to get rid of this, there's no latency difference
4415 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4416 // the former later. We should also remove the "_undef" special mask.
4417 if (NumElts == 4 && Is256BitVec)
4420 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4421 // independently on 128-bit lanes.
4422 unsigned NumLanes = VT.getSizeInBits()/128;
4423 unsigned NumLaneElts = NumElts/NumLanes;
4425 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4426 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4427 int BitI = Mask[l+i];
4428 int BitI1 = Mask[l+i+1];
4430 if (!isUndefOrEqual(BitI, j))
4432 if (!isUndefOrEqual(BitI1, j))
4440 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4441 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4443 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4444 unsigned NumElts = VT.getVectorNumElements();
4446 if (VT.is512BitVector())
4449 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4450 "Unsupported vector type for unpckh");
4452 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4453 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4456 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4457 // independently on 128-bit lanes.
4458 unsigned NumLanes = VT.getSizeInBits()/128;
4459 unsigned NumLaneElts = NumElts/NumLanes;
4461 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4462 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4463 int BitI = Mask[l+i];
4464 int BitI1 = Mask[l+i+1];
4465 if (!isUndefOrEqual(BitI, j))
4467 if (!isUndefOrEqual(BitI1, j))
4474 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4475 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4476 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4477 if (!VT.is512BitVector())
4480 unsigned NumElts = VT.getVectorNumElements();
4481 unsigned HalfSize = NumElts/2;
4482 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4483 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4488 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4489 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4497 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4498 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4499 /// MOVSD, and MOVD, i.e. setting the lowest element.
4500 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4501 if (VT.getVectorElementType().getSizeInBits() < 32)
4503 if (!VT.is128BitVector())
4506 unsigned NumElts = VT.getVectorNumElements();
4508 if (!isUndefOrEqual(Mask[0], NumElts))
4511 for (unsigned i = 1; i != NumElts; ++i)
4512 if (!isUndefOrEqual(Mask[i], i))
4518 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4519 /// as permutations between 128-bit chunks or halves. As an example: this
4521 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4522 /// The first half comes from the second half of V1 and the second half from the
4523 /// the second half of V2.
4524 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4525 if (!HasFp256 || !VT.is256BitVector())
4528 // The shuffle result is divided into half A and half B. In total the two
4529 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4530 // B must come from C, D, E or F.
4531 unsigned HalfSize = VT.getVectorNumElements()/2;
4532 bool MatchA = false, MatchB = false;
4534 // Check if A comes from one of C, D, E, F.
4535 for (unsigned Half = 0; Half != 4; ++Half) {
4536 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4542 // Check if B comes from one of C, D, E, F.
4543 for (unsigned Half = 0; Half != 4; ++Half) {
4544 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4550 return MatchA && MatchB;
4553 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4554 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4555 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4556 MVT VT = SVOp->getSimpleValueType(0);
4558 unsigned HalfSize = VT.getVectorNumElements()/2;
4560 unsigned FstHalf = 0, SndHalf = 0;
4561 for (unsigned i = 0; i < HalfSize; ++i) {
4562 if (SVOp->getMaskElt(i) > 0) {
4563 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4567 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4568 if (SVOp->getMaskElt(i) > 0) {
4569 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4574 return (FstHalf | (SndHalf << 4));
4577 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4578 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4579 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4583 unsigned NumElts = VT.getVectorNumElements();
4585 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4586 for (unsigned i = 0; i != NumElts; ++i) {
4589 Imm8 |= Mask[i] << (i*2);
4594 unsigned LaneSize = 4;
4595 SmallVector<int, 4> MaskVal(LaneSize, -1);
4597 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4598 for (unsigned i = 0; i != LaneSize; ++i) {
4599 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4603 if (MaskVal[i] < 0) {
4604 MaskVal[i] = Mask[i+l] - l;
4605 Imm8 |= MaskVal[i] << (i*2);
4608 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4615 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4616 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4617 /// Note that VPERMIL mask matching is different depending whether theunderlying
4618 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4619 /// to the same elements of the low, but to the higher half of the source.
4620 /// In VPERMILPD the two lanes could be shuffled independently of each other
4621 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4622 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4623 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4624 if (VT.getSizeInBits() < 256 || EltSize < 32)
4626 bool symetricMaskRequired = (EltSize == 32);
4627 unsigned NumElts = VT.getVectorNumElements();
4629 unsigned NumLanes = VT.getSizeInBits()/128;
4630 unsigned LaneSize = NumElts/NumLanes;
4631 // 2 or 4 elements in one lane
4633 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4634 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4635 for (unsigned i = 0; i != LaneSize; ++i) {
4636 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4638 if (symetricMaskRequired) {
4639 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4640 ExpectedMaskVal[i] = Mask[i+l] - l;
4643 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4651 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4652 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4653 /// element of vector 2 and the other elements to come from vector 1 in order.
4654 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4655 bool V2IsSplat = false, bool V2IsUndef = false) {
4656 if (!VT.is128BitVector())
4659 unsigned NumOps = VT.getVectorNumElements();
4660 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4663 if (!isUndefOrEqual(Mask[0], 0))
4666 for (unsigned i = 1; i != NumOps; ++i)
4667 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4668 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4669 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4675 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4676 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4677 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4678 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4679 const X86Subtarget *Subtarget) {
4680 if (!Subtarget->hasSSE3())
4683 unsigned NumElems = VT.getVectorNumElements();
4685 if ((VT.is128BitVector() && NumElems != 4) ||
4686 (VT.is256BitVector() && NumElems != 8) ||
4687 (VT.is512BitVector() && NumElems != 16))
4690 // "i+1" is the value the indexed mask element must have
4691 for (unsigned i = 0; i != NumElems; i += 2)
4692 if (!isUndefOrEqual(Mask[i], i+1) ||
4693 !isUndefOrEqual(Mask[i+1], i+1))
4699 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4700 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4701 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4702 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4703 const X86Subtarget *Subtarget) {
4704 if (!Subtarget->hasSSE3())
4707 unsigned NumElems = VT.getVectorNumElements();
4709 if ((VT.is128BitVector() && NumElems != 4) ||
4710 (VT.is256BitVector() && NumElems != 8) ||
4711 (VT.is512BitVector() && NumElems != 16))
4714 // "i" is the value the indexed mask element must have
4715 for (unsigned i = 0; i != NumElems; i += 2)
4716 if (!isUndefOrEqual(Mask[i], i) ||
4717 !isUndefOrEqual(Mask[i+1], i))
4723 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4724 /// specifies a shuffle of elements that is suitable for input to 256-bit
4725 /// version of MOVDDUP.
4726 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4727 if (!HasFp256 || !VT.is256BitVector())
4730 unsigned NumElts = VT.getVectorNumElements();
4734 for (unsigned i = 0; i != NumElts/2; ++i)
4735 if (!isUndefOrEqual(Mask[i], 0))
4737 for (unsigned i = NumElts/2; i != NumElts; ++i)
4738 if (!isUndefOrEqual(Mask[i], NumElts/2))
4743 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4744 /// specifies a shuffle of elements that is suitable for input to 128-bit
4745 /// version of MOVDDUP.
4746 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4747 if (!VT.is128BitVector())
4750 unsigned e = VT.getVectorNumElements() / 2;
4751 for (unsigned i = 0; i != e; ++i)
4752 if (!isUndefOrEqual(Mask[i], i))
4754 for (unsigned i = 0; i != e; ++i)
4755 if (!isUndefOrEqual(Mask[e+i], i))
4760 /// isVEXTRACTIndex - Return true if the specified
4761 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4762 /// suitable for instruction that extract 128 or 256 bit vectors
4763 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4764 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4765 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4768 // The index should be aligned on a vecWidth-bit boundary.
4770 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4772 MVT VT = N->getSimpleValueType(0);
4773 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4774 bool Result = (Index * ElSize) % vecWidth == 0;
4779 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4780 /// operand specifies a subvector insert that is suitable for input to
4781 /// insertion of 128 or 256-bit subvectors
4782 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4783 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4784 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4786 // The index should be aligned on a vecWidth-bit boundary.
4788 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4790 MVT VT = N->getSimpleValueType(0);
4791 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4792 bool Result = (Index * ElSize) % vecWidth == 0;
4797 bool X86::isVINSERT128Index(SDNode *N) {
4798 return isVINSERTIndex(N, 128);
4801 bool X86::isVINSERT256Index(SDNode *N) {
4802 return isVINSERTIndex(N, 256);
4805 bool X86::isVEXTRACT128Index(SDNode *N) {
4806 return isVEXTRACTIndex(N, 128);
4809 bool X86::isVEXTRACT256Index(SDNode *N) {
4810 return isVEXTRACTIndex(N, 256);
4813 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4814 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4815 /// Handles 128-bit and 256-bit.
4816 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4817 MVT VT = N->getSimpleValueType(0);
4819 assert((VT.getSizeInBits() >= 128) &&
4820 "Unsupported vector type for PSHUF/SHUFP");
4822 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4823 // independently on 128-bit lanes.
4824 unsigned NumElts = VT.getVectorNumElements();
4825 unsigned NumLanes = VT.getSizeInBits()/128;
4826 unsigned NumLaneElts = NumElts/NumLanes;
4828 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4829 "Only supports 2, 4 or 8 elements per lane");
4831 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4833 for (unsigned i = 0; i != NumElts; ++i) {
4834 int Elt = N->getMaskElt(i);
4835 if (Elt < 0) continue;
4836 Elt &= NumLaneElts - 1;
4837 unsigned ShAmt = (i << Shift) % 8;
4838 Mask |= Elt << ShAmt;
4844 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4845 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4846 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4847 MVT VT = N->getSimpleValueType(0);
4849 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4850 "Unsupported vector type for PSHUFHW");
4852 unsigned NumElts = VT.getVectorNumElements();
4855 for (unsigned l = 0; l != NumElts; l += 8) {
4856 // 8 nodes per lane, but we only care about the last 4.
4857 for (unsigned i = 0; i < 4; ++i) {
4858 int Elt = N->getMaskElt(l+i+4);
4859 if (Elt < 0) continue;
4860 Elt &= 0x3; // only 2-bits.
4861 Mask |= Elt << (i * 2);
4868 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4869 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4870 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4871 MVT VT = N->getSimpleValueType(0);
4873 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4874 "Unsupported vector type for PSHUFHW");
4876 unsigned NumElts = VT.getVectorNumElements();
4879 for (unsigned l = 0; l != NumElts; l += 8) {
4880 // 8 nodes per lane, but we only care about the first 4.
4881 for (unsigned i = 0; i < 4; ++i) {
4882 int Elt = N->getMaskElt(l+i);
4883 if (Elt < 0) continue;
4884 Elt &= 0x3; // only 2-bits
4885 Mask |= Elt << (i * 2);
4892 /// \brief Return the appropriate immediate to shuffle the specified
4893 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4894 /// VALIGN (if Interlane is true) instructions.
4895 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4897 MVT VT = SVOp->getSimpleValueType(0);
4898 unsigned EltSize = InterLane ? 1 :
4899 VT.getVectorElementType().getSizeInBits() >> 3;
4901 unsigned NumElts = VT.getVectorNumElements();
4902 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4903 unsigned NumLaneElts = NumElts/NumLanes;
4907 for (i = 0; i != NumElts; ++i) {
4908 Val = SVOp->getMaskElt(i);
4912 if (Val >= (int)NumElts)
4913 Val -= NumElts - NumLaneElts;
4915 assert(Val - i > 0 && "PALIGNR imm should be positive");
4916 return (Val - i) * EltSize;
4919 /// \brief Return the appropriate immediate to shuffle the specified
4920 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4921 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4922 return getShuffleAlignrImmediate(SVOp, false);
4925 /// \brief Return the appropriate immediate to shuffle the specified
4926 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4927 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4928 return getShuffleAlignrImmediate(SVOp, true);
4932 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4933 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4934 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4935 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4938 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4940 MVT VecVT = N->getOperand(0).getSimpleValueType();
4941 MVT ElVT = VecVT.getVectorElementType();
4943 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4944 return Index / NumElemsPerChunk;
4947 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4948 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4949 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4950 llvm_unreachable("Illegal insert subvector for VINSERT");
4953 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4955 MVT VecVT = N->getSimpleValueType(0);
4956 MVT ElVT = VecVT.getVectorElementType();
4958 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4959 return Index / NumElemsPerChunk;
4962 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4963 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4964 /// and VINSERTI128 instructions.
4965 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4966 return getExtractVEXTRACTImmediate(N, 128);
4969 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4970 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4971 /// and VINSERTI64x4 instructions.
4972 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4973 return getExtractVEXTRACTImmediate(N, 256);
4976 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4977 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4978 /// and VINSERTI128 instructions.
4979 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4980 return getInsertVINSERTImmediate(N, 128);
4983 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4984 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4985 /// and VINSERTI64x4 instructions.
4986 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4987 return getInsertVINSERTImmediate(N, 256);
4990 /// isZero - Returns true if Elt is a constant integer zero
4991 static bool isZero(SDValue V) {
4992 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4993 return C && C->isNullValue();
4996 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4998 bool X86::isZeroNode(SDValue Elt) {
5001 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
5002 return CFP->getValueAPF().isPosZero();
5006 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
5007 /// match movhlps. The lower half elements should come from upper half of
5008 /// V1 (and in order), and the upper half elements should come from the upper
5009 /// half of V2 (and in order).
5010 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
5011 if (!VT.is128BitVector())
5013 if (VT.getVectorNumElements() != 4)
5015 for (unsigned i = 0, e = 2; i != e; ++i)
5016 if (!isUndefOrEqual(Mask[i], i+2))
5018 for (unsigned i = 2; i != 4; ++i)
5019 if (!isUndefOrEqual(Mask[i], i+4))
5024 /// isScalarLoadToVector - Returns true if the node is a scalar load that
5025 /// is promoted to a vector. It also returns the LoadSDNode by reference if
5027 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
5028 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
5030 N = N->getOperand(0).getNode();
5031 if (!ISD::isNON_EXTLoad(N))
5034 *LD = cast<LoadSDNode>(N);
5038 // Test whether the given value is a vector value which will be legalized
5040 static bool WillBeConstantPoolLoad(SDNode *N) {
5041 if (N->getOpcode() != ISD::BUILD_VECTOR)
5044 // Check for any non-constant elements.
5045 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5046 switch (N->getOperand(i).getNode()->getOpcode()) {
5048 case ISD::ConstantFP:
5055 // Vectors of all-zeros and all-ones are materialized with special
5056 // instructions rather than being loaded.
5057 return !ISD::isBuildVectorAllZeros(N) &&
5058 !ISD::isBuildVectorAllOnes(N);
5061 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5062 /// match movlp{s|d}. The lower half elements should come from lower half of
5063 /// V1 (and in order), and the upper half elements should come from the upper
5064 /// half of V2 (and in order). And since V1 will become the source of the
5065 /// MOVLP, it must be either a vector load or a scalar load to vector.
5066 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5067 ArrayRef<int> Mask, MVT VT) {
5068 if (!VT.is128BitVector())
5071 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5073 // Is V2 is a vector load, don't do this transformation. We will try to use
5074 // load folding shufps op.
5075 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5078 unsigned NumElems = VT.getVectorNumElements();
5080 if (NumElems != 2 && NumElems != 4)
5082 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5083 if (!isUndefOrEqual(Mask[i], i))
5085 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5086 if (!isUndefOrEqual(Mask[i], i+NumElems))
5091 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5092 /// to an zero vector.
5093 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5094 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5095 SDValue V1 = N->getOperand(0);
5096 SDValue V2 = N->getOperand(1);
5097 unsigned NumElems = N->getValueType(0).getVectorNumElements();
5098 for (unsigned i = 0; i != NumElems; ++i) {
5099 int Idx = N->getMaskElt(i);
5100 if (Idx >= (int)NumElems) {
5101 unsigned Opc = V2.getOpcode();
5102 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5104 if (Opc != ISD::BUILD_VECTOR ||
5105 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5107 } else if (Idx >= 0) {
5108 unsigned Opc = V1.getOpcode();
5109 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5111 if (Opc != ISD::BUILD_VECTOR ||
5112 !X86::isZeroNode(V1.getOperand(Idx)))
5119 /// getZeroVector - Returns a vector of specified type with all zero elements.
5121 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5122 SelectionDAG &DAG, SDLoc dl) {
5123 assert(VT.isVector() && "Expected a vector type");
5125 // Always build SSE zero vectors as <4 x i32> bitcasted
5126 // to their dest type. This ensures they get CSE'd.
5128 if (VT.is128BitVector()) { // SSE
5129 if (Subtarget->hasSSE2()) { // SSE2
5130 SDValue Cst = DAG.getConstant(0, MVT::i32);
5131 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5133 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5134 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5136 } else if (VT.is256BitVector()) { // AVX
5137 if (Subtarget->hasInt256()) { // AVX2
5138 SDValue Cst = DAG.getConstant(0, MVT::i32);
5139 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5140 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5142 // 256-bit logic and arithmetic instructions in AVX are all
5143 // floating-point, no support for integer ops. Emit fp zeroed vectors.
5144 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5145 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5146 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5148 } else if (VT.is512BitVector()) { // AVX-512
5149 SDValue Cst = DAG.getConstant(0, MVT::i32);
5150 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5151 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5152 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5153 } else if (VT.getScalarType() == MVT::i1) {
5154 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5155 SDValue Cst = DAG.getConstant(0, MVT::i1);
5156 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5157 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5159 llvm_unreachable("Unexpected vector type");
5161 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5164 /// getOnesVector - Returns a vector of specified type with all bits set.
5165 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5166 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5167 /// Then bitcast to their original type, ensuring they get CSE'd.
5168 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5170 assert(VT.isVector() && "Expected a vector type");
5172 SDValue Cst = DAG.getConstant(~0U, MVT::i32);
5174 if (VT.is256BitVector()) {
5175 if (HasInt256) { // AVX2
5176 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5177 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5179 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5180 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5182 } else if (VT.is128BitVector()) {
5183 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5185 llvm_unreachable("Unexpected vector type");
5187 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5190 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5191 /// that point to V2 points to its first element.
5192 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5193 for (unsigned i = 0; i != NumElems; ++i) {
5194 if (Mask[i] > (int)NumElems) {
5200 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5201 /// operation of specified width.
5202 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5204 unsigned NumElems = VT.getVectorNumElements();
5205 SmallVector<int, 8> Mask;
5206 Mask.push_back(NumElems);
5207 for (unsigned i = 1; i != NumElems; ++i)
5209 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5212 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5213 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5215 unsigned NumElems = VT.getVectorNumElements();
5216 SmallVector<int, 8> Mask;
5217 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5219 Mask.push_back(i + NumElems);
5221 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5224 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5225 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5227 unsigned NumElems = VT.getVectorNumElements();
5228 SmallVector<int, 8> Mask;
5229 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5230 Mask.push_back(i + Half);
5231 Mask.push_back(i + NumElems + Half);
5233 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5236 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5237 // a generic shuffle instruction because the target has no such instructions.
5238 // Generate shuffles which repeat i16 and i8 several times until they can be
5239 // represented by v4f32 and then be manipulated by target suported shuffles.
5240 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5241 MVT VT = V.getSimpleValueType();
5242 int NumElems = VT.getVectorNumElements();
5245 while (NumElems > 4) {
5246 if (EltNo < NumElems/2) {
5247 V = getUnpackl(DAG, dl, VT, V, V);
5249 V = getUnpackh(DAG, dl, VT, V, V);
5250 EltNo -= NumElems/2;
5257 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5258 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5259 MVT VT = V.getSimpleValueType();
5262 if (VT.is128BitVector()) {
5263 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5264 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5265 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5267 } else if (VT.is256BitVector()) {
5268 // To use VPERMILPS to splat scalars, the second half of indicies must
5269 // refer to the higher part, which is a duplication of the lower one,
5270 // because VPERMILPS can only handle in-lane permutations.
5271 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5272 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5274 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5275 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5278 llvm_unreachable("Vector size not supported");
5280 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5283 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5284 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5285 MVT SrcVT = SV->getSimpleValueType(0);
5286 SDValue V1 = SV->getOperand(0);
5289 int EltNo = SV->getSplatIndex();
5290 int NumElems = SrcVT.getVectorNumElements();
5291 bool Is256BitVec = SrcVT.is256BitVector();
5293 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5294 "Unknown how to promote splat for type");
5296 // Extract the 128-bit part containing the splat element and update
5297 // the splat element index when it refers to the higher register.
5299 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5300 if (EltNo >= NumElems/2)
5301 EltNo -= NumElems/2;
5304 // All i16 and i8 vector types can't be used directly by a generic shuffle
5305 // instruction because the target has no such instruction. Generate shuffles
5306 // which repeat i16 and i8 several times until they fit in i32, and then can
5307 // be manipulated by target suported shuffles.
5308 MVT EltVT = SrcVT.getVectorElementType();
5309 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5310 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5312 // Recreate the 256-bit vector and place the same 128-bit vector
5313 // into the low and high part. This is necessary because we want
5314 // to use VPERM* to shuffle the vectors
5316 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5319 return getLegalSplat(DAG, V1, EltNo);
5322 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5323 /// vector of zero or undef vector. This produces a shuffle where the low
5324 /// element of V2 is swizzled into the zero/undef vector, landing at element
5325 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5326 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5328 const X86Subtarget *Subtarget,
5329 SelectionDAG &DAG) {
5330 MVT VT = V2.getSimpleValueType();
5332 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5333 unsigned NumElems = VT.getVectorNumElements();
5334 SmallVector<int, 16> MaskVec;
5335 for (unsigned i = 0; i != NumElems; ++i)
5336 // If this is the insertion idx, put the low elt of V2 here.
5337 MaskVec.push_back(i == Idx ? NumElems : i);
5338 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5341 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5342 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5343 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5344 /// shuffles which use a single input multiple times, and in those cases it will
5345 /// adjust the mask to only have indices within that single input.
5346 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5347 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5348 unsigned NumElems = VT.getVectorNumElements();
5352 bool IsFakeUnary = false;
5353 switch(N->getOpcode()) {
5354 case X86ISD::BLENDI:
5355 ImmN = N->getOperand(N->getNumOperands()-1);
5356 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5359 ImmN = N->getOperand(N->getNumOperands()-1);
5360 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5361 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5363 case X86ISD::UNPCKH:
5364 DecodeUNPCKHMask(VT, Mask);
5365 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5367 case X86ISD::UNPCKL:
5368 DecodeUNPCKLMask(VT, Mask);
5369 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5371 case X86ISD::MOVHLPS:
5372 DecodeMOVHLPSMask(NumElems, Mask);
5373 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5375 case X86ISD::MOVLHPS:
5376 DecodeMOVLHPSMask(NumElems, Mask);
5377 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5379 case X86ISD::PALIGNR:
5380 ImmN = N->getOperand(N->getNumOperands()-1);
5381 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5383 case X86ISD::PSHUFD:
5384 case X86ISD::VPERMILPI:
5385 ImmN = N->getOperand(N->getNumOperands()-1);
5386 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5389 case X86ISD::PSHUFHW:
5390 ImmN = N->getOperand(N->getNumOperands()-1);
5391 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5394 case X86ISD::PSHUFLW:
5395 ImmN = N->getOperand(N->getNumOperands()-1);
5396 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5399 case X86ISD::PSHUFB: {
5401 SDValue MaskNode = N->getOperand(1);
5402 while (MaskNode->getOpcode() == ISD::BITCAST)
5403 MaskNode = MaskNode->getOperand(0);
5405 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5406 // If we have a build-vector, then things are easy.
5407 EVT VT = MaskNode.getValueType();
5408 assert(VT.isVector() &&
5409 "Can't produce a non-vector with a build_vector!");
5410 if (!VT.isInteger())
5413 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5415 SmallVector<uint64_t, 32> RawMask;
5416 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5417 SDValue Op = MaskNode->getOperand(i);
5418 if (Op->getOpcode() == ISD::UNDEF) {
5419 RawMask.push_back((uint64_t)SM_SentinelUndef);
5422 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5425 APInt MaskElement = CN->getAPIntValue();
5427 // We now have to decode the element which could be any integer size and
5428 // extract each byte of it.
5429 for (int j = 0; j < NumBytesPerElement; ++j) {
5430 // Note that this is x86 and so always little endian: the low byte is
5431 // the first byte of the mask.
5432 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5433 MaskElement = MaskElement.lshr(8);
5436 DecodePSHUFBMask(RawMask, Mask);
5440 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5444 SDValue Ptr = MaskLoad->getBasePtr();
5445 if (Ptr->getOpcode() == X86ISD::Wrapper)
5446 Ptr = Ptr->getOperand(0);
5448 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5449 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5452 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5453 // FIXME: Support AVX-512 here.
5454 Type *Ty = C->getType();
5455 if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5456 Ty->getVectorNumElements() != 32))
5459 DecodePSHUFBMask(C, Mask);
5465 case X86ISD::VPERMI:
5466 ImmN = N->getOperand(N->getNumOperands()-1);
5467 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5471 case X86ISD::MOVSD: {
5472 // The index 0 always comes from the first element of the second source,
5473 // this is why MOVSS and MOVSD are used in the first place. The other
5474 // elements come from the other positions of the first source vector
5475 Mask.push_back(NumElems);
5476 for (unsigned i = 1; i != NumElems; ++i) {
5481 case X86ISD::VPERM2X128:
5482 ImmN = N->getOperand(N->getNumOperands()-1);
5483 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5484 if (Mask.empty()) return false;
5486 case X86ISD::MOVSLDUP:
5487 DecodeMOVSLDUPMask(VT, Mask);
5489 case X86ISD::MOVSHDUP:
5490 DecodeMOVSHDUPMask(VT, Mask);
5492 case X86ISD::MOVDDUP:
5493 case X86ISD::MOVLHPD:
5494 case X86ISD::MOVLPD:
5495 case X86ISD::MOVLPS:
5496 // Not yet implemented
5498 default: llvm_unreachable("unknown target shuffle node");
5501 // If we have a fake unary shuffle, the shuffle mask is spread across two
5502 // inputs that are actually the same node. Re-map the mask to always point
5503 // into the first input.
5506 if (M >= (int)Mask.size())
5512 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5513 /// element of the result of the vector shuffle.
5514 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5517 return SDValue(); // Limit search depth.
5519 SDValue V = SDValue(N, 0);
5520 EVT VT = V.getValueType();
5521 unsigned Opcode = V.getOpcode();
5523 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5524 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5525 int Elt = SV->getMaskElt(Index);
5528 return DAG.getUNDEF(VT.getVectorElementType());
5530 unsigned NumElems = VT.getVectorNumElements();
5531 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5532 : SV->getOperand(1);
5533 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5536 // Recurse into target specific vector shuffles to find scalars.
5537 if (isTargetShuffle(Opcode)) {
5538 MVT ShufVT = V.getSimpleValueType();
5539 unsigned NumElems = ShufVT.getVectorNumElements();
5540 SmallVector<int, 16> ShuffleMask;
5543 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5546 int Elt = ShuffleMask[Index];
5548 return DAG.getUNDEF(ShufVT.getVectorElementType());
5550 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5552 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5556 // Actual nodes that may contain scalar elements
5557 if (Opcode == ISD::BITCAST) {
5558 V = V.getOperand(0);
5559 EVT SrcVT = V.getValueType();
5560 unsigned NumElems = VT.getVectorNumElements();
5562 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5566 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5567 return (Index == 0) ? V.getOperand(0)
5568 : DAG.getUNDEF(VT.getVectorElementType());
5570 if (V.getOpcode() == ISD::BUILD_VECTOR)
5571 return V.getOperand(Index);
5576 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5577 /// shuffle operation which come from a consecutively from a zero. The
5578 /// search can start in two different directions, from left or right.
5579 /// We count undefs as zeros until PreferredNum is reached.
5580 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5581 unsigned NumElems, bool ZerosFromLeft,
5583 unsigned PreferredNum = -1U) {
5584 unsigned NumZeros = 0;
5585 for (unsigned i = 0; i != NumElems; ++i) {
5586 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5587 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5591 if (X86::isZeroNode(Elt))
5593 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5594 NumZeros = std::min(NumZeros + 1, PreferredNum);
5602 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5603 /// correspond consecutively to elements from one of the vector operands,
5604 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5606 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5607 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5608 unsigned NumElems, unsigned &OpNum) {
5609 bool SeenV1 = false;
5610 bool SeenV2 = false;
5612 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5613 int Idx = SVOp->getMaskElt(i);
5614 // Ignore undef indicies
5618 if (Idx < (int)NumElems)
5623 // Only accept consecutive elements from the same vector
5624 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5628 OpNum = SeenV1 ? 0 : 1;
5632 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5633 /// logical left shift of a vector.
5634 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5635 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5637 SVOp->getSimpleValueType(0).getVectorNumElements();
5638 unsigned NumZeros = getNumOfConsecutiveZeros(
5639 SVOp, NumElems, false /* check zeros from right */, DAG,
5640 SVOp->getMaskElt(0));
5646 // Considering the elements in the mask that are not consecutive zeros,
5647 // check if they consecutively come from only one of the source vectors.
5649 // V1 = {X, A, B, C} 0
5651 // vector_shuffle V1, V2 <1, 2, 3, X>
5653 if (!isShuffleMaskConsecutive(SVOp,
5654 0, // Mask Start Index
5655 NumElems-NumZeros, // Mask End Index(exclusive)
5656 NumZeros, // Where to start looking in the src vector
5657 NumElems, // Number of elements in vector
5658 OpSrc)) // Which source operand ?
5663 ShVal = SVOp->getOperand(OpSrc);
5667 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5668 /// logical left shift of a vector.
5669 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5670 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5672 SVOp->getSimpleValueType(0).getVectorNumElements();
5673 unsigned NumZeros = getNumOfConsecutiveZeros(
5674 SVOp, NumElems, true /* check zeros from left */, DAG,
5675 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5681 // Considering the elements in the mask that are not consecutive zeros,
5682 // check if they consecutively come from only one of the source vectors.
5684 // 0 { A, B, X, X } = V2
5686 // vector_shuffle V1, V2 <X, X, 4, 5>
5688 if (!isShuffleMaskConsecutive(SVOp,
5689 NumZeros, // Mask Start Index
5690 NumElems, // Mask End Index(exclusive)
5691 0, // Where to start looking in the src vector
5692 NumElems, // Number of elements in vector
5693 OpSrc)) // Which source operand ?
5698 ShVal = SVOp->getOperand(OpSrc);
5702 /// isVectorShift - Returns true if the shuffle can be implemented as a
5703 /// logical left or right shift of a vector.
5704 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5705 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5706 // Although the logic below support any bitwidth size, there are no
5707 // shift instructions which handle more than 128-bit vectors.
5708 if (!SVOp->getSimpleValueType(0).is128BitVector())
5711 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5712 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5718 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5720 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5721 unsigned NumNonZero, unsigned NumZero,
5723 const X86Subtarget* Subtarget,
5724 const TargetLowering &TLI) {
5731 for (unsigned i = 0; i < 16; ++i) {
5732 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5733 if (ThisIsNonZero && First) {
5735 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5737 V = DAG.getUNDEF(MVT::v8i16);
5742 SDValue ThisElt, LastElt;
5743 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5744 if (LastIsNonZero) {
5745 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5746 MVT::i16, Op.getOperand(i-1));
5748 if (ThisIsNonZero) {
5749 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5750 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5751 ThisElt, DAG.getConstant(8, MVT::i8));
5753 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5757 if (ThisElt.getNode())
5758 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5759 DAG.getIntPtrConstant(i/2));
5763 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5766 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5768 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5769 unsigned NumNonZero, unsigned NumZero,
5771 const X86Subtarget* Subtarget,
5772 const TargetLowering &TLI) {
5779 for (unsigned i = 0; i < 8; ++i) {
5780 bool isNonZero = (NonZeros & (1 << i)) != 0;
5784 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5786 V = DAG.getUNDEF(MVT::v8i16);
5789 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5790 MVT::v8i16, V, Op.getOperand(i),
5791 DAG.getIntPtrConstant(i));
5798 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5799 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5800 const X86Subtarget *Subtarget,
5801 const TargetLowering &TLI) {
5802 // Find all zeroable elements.
5804 for (int i=0; i < 4; ++i) {
5805 SDValue Elt = Op->getOperand(i);
5806 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5808 assert(std::count_if(&Zeroable[0], &Zeroable[4],
5809 [](bool M) { return !M; }) > 1 &&
5810 "We expect at least two non-zero elements!");
5812 // We only know how to deal with build_vector nodes where elements are either
5813 // zeroable or extract_vector_elt with constant index.
5814 SDValue FirstNonZero;
5815 unsigned FirstNonZeroIdx;
5816 for (unsigned i=0; i < 4; ++i) {
5819 SDValue Elt = Op->getOperand(i);
5820 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5821 !isa<ConstantSDNode>(Elt.getOperand(1)))
5823 // Make sure that this node is extracting from a 128-bit vector.
5824 MVT VT = Elt.getOperand(0).getSimpleValueType();
5825 if (!VT.is128BitVector())
5827 if (!FirstNonZero.getNode()) {
5829 FirstNonZeroIdx = i;
5833 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5834 SDValue V1 = FirstNonZero.getOperand(0);
5835 MVT VT = V1.getSimpleValueType();
5837 // See if this build_vector can be lowered as a blend with zero.
5839 unsigned EltMaskIdx, EltIdx;
5841 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5842 if (Zeroable[EltIdx]) {
5843 // The zero vector will be on the right hand side.
5844 Mask[EltIdx] = EltIdx+4;
5848 Elt = Op->getOperand(EltIdx);
5849 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5850 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5851 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5853 Mask[EltIdx] = EltIdx;
5857 // Let the shuffle legalizer deal with blend operations.
5858 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5859 if (V1.getSimpleValueType() != VT)
5860 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5861 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5864 // See if we can lower this build_vector to a INSERTPS.
5865 if (!Subtarget->hasSSE41())
5868 SDValue V2 = Elt.getOperand(0);
5869 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5872 bool CanFold = true;
5873 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5877 SDValue Current = Op->getOperand(i);
5878 SDValue SrcVector = Current->getOperand(0);
5881 CanFold = SrcVector == V1 &&
5882 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5888 assert(V1.getNode() && "Expected at least two non-zero elements!");
5889 if (V1.getSimpleValueType() != MVT::v4f32)
5890 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5891 if (V2.getSimpleValueType() != MVT::v4f32)
5892 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5894 // Ok, we can emit an INSERTPS instruction.
5896 for (int i = 0; i < 4; ++i)
5900 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5901 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5902 SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
5903 DAG.getIntPtrConstant(InsertPSMask));
5904 return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
5907 /// getVShift - Return a vector logical shift node.
5909 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5910 unsigned NumBits, SelectionDAG &DAG,
5911 const TargetLowering &TLI, SDLoc dl) {
5912 assert(VT.is128BitVector() && "Unknown type for VShift");
5913 EVT ShVT = MVT::v2i64;
5914 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5915 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5916 return DAG.getNode(ISD::BITCAST, dl, VT,
5917 DAG.getNode(Opc, dl, ShVT, SrcOp,
5918 DAG.getConstant(NumBits,
5919 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5923 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5925 // Check if the scalar load can be widened into a vector load. And if
5926 // the address is "base + cst" see if the cst can be "absorbed" into
5927 // the shuffle mask.
5928 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5929 SDValue Ptr = LD->getBasePtr();
5930 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5932 EVT PVT = LD->getValueType(0);
5933 if (PVT != MVT::i32 && PVT != MVT::f32)
5938 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5939 FI = FINode->getIndex();
5941 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5942 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5943 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5944 Offset = Ptr.getConstantOperandVal(1);
5945 Ptr = Ptr.getOperand(0);
5950 // FIXME: 256-bit vector instructions don't require a strict alignment,
5951 // improve this code to support it better.
5952 unsigned RequiredAlign = VT.getSizeInBits()/8;
5953 SDValue Chain = LD->getChain();
5954 // Make sure the stack object alignment is at least 16 or 32.
5955 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5956 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5957 if (MFI->isFixedObjectIndex(FI)) {
5958 // Can't change the alignment. FIXME: It's possible to compute
5959 // the exact stack offset and reference FI + adjust offset instead.
5960 // If someone *really* cares about this. That's the way to implement it.
5963 MFI->setObjectAlignment(FI, RequiredAlign);
5967 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5968 // Ptr + (Offset & ~15).
5971 if ((Offset % RequiredAlign) & 3)
5973 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5975 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5976 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5978 int EltNo = (Offset - StartOffset) >> 2;
5979 unsigned NumElems = VT.getVectorNumElements();
5981 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5982 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5983 LD->getPointerInfo().getWithOffset(StartOffset),
5984 false, false, false, 0);
5986 SmallVector<int, 8> Mask;
5987 for (unsigned i = 0; i != NumElems; ++i)
5988 Mask.push_back(EltNo);
5990 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5996 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5997 /// vector of type 'VT', see if the elements can be replaced by a single large
5998 /// load which has the same value as a build_vector whose operands are 'elts'.
6000 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
6002 /// FIXME: we'd also like to handle the case where the last elements are zero
6003 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
6004 /// There's even a handy isZeroNode for that purpose.
6005 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
6006 SDLoc &DL, SelectionDAG &DAG,
6007 bool isAfterLegalize) {
6008 EVT EltVT = VT.getVectorElementType();
6009 unsigned NumElems = Elts.size();
6011 LoadSDNode *LDBase = nullptr;
6012 unsigned LastLoadedElt = -1U;
6014 // For each element in the initializer, see if we've found a load or an undef.
6015 // If we don't find an initial load element, or later load elements are
6016 // non-consecutive, bail out.
6017 for (unsigned i = 0; i < NumElems; ++i) {
6018 SDValue Elt = Elts[i];
6020 if (!Elt.getNode() ||
6021 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
6024 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
6026 LDBase = cast<LoadSDNode>(Elt.getNode());
6030 if (Elt.getOpcode() == ISD::UNDEF)
6033 LoadSDNode *LD = cast<LoadSDNode>(Elt);
6034 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
6039 // If we have found an entire vector of loads and undefs, then return a large
6040 // load of the entire vector width starting at the base pointer. If we found
6041 // consecutive loads for the low half, generate a vzext_load node.
6042 if (LastLoadedElt == NumElems - 1) {
6044 if (isAfterLegalize &&
6045 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
6048 SDValue NewLd = SDValue();
6050 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6051 LDBase->getPointerInfo(), LDBase->isVolatile(),
6052 LDBase->isNonTemporal(), LDBase->isInvariant(),
6053 LDBase->getAlignment());
6055 if (LDBase->hasAnyUseOfValue(1)) {
6056 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6058 SDValue(NewLd.getNode(), 1));
6059 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6060 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6061 SDValue(NewLd.getNode(), 1));
6067 //TODO: The code below fires only for for loading the low v2i32 / v2f32
6068 //of a v4i32 / v4f32. It's probably worth generalizing.
6069 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
6070 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
6071 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
6072 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6074 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
6075 LDBase->getPointerInfo(),
6076 LDBase->getAlignment(),
6077 false/*isVolatile*/, true/*ReadMem*/,
6080 // Make sure the newly-created LOAD is in the same position as LDBase in
6081 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
6082 // update uses of LDBase's output chain to use the TokenFactor.
6083 if (LDBase->hasAnyUseOfValue(1)) {
6084 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6085 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
6086 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6087 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6088 SDValue(ResNode.getNode(), 1));
6091 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
6096 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6097 /// to generate a splat value for the following cases:
6098 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6099 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6100 /// a scalar load, or a constant.
6101 /// The VBROADCAST node is returned when a pattern is found,
6102 /// or SDValue() otherwise.
6103 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6104 SelectionDAG &DAG) {
6105 // VBROADCAST requires AVX.
6106 // TODO: Splats could be generated for non-AVX CPUs using SSE
6107 // instructions, but there's less potential gain for only 128-bit vectors.
6108 if (!Subtarget->hasAVX())
6111 MVT VT = Op.getSimpleValueType();
6114 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6115 "Unsupported vector type for broadcast.");
6120 switch (Op.getOpcode()) {
6122 // Unknown pattern found.
6125 case ISD::BUILD_VECTOR: {
6126 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6127 BitVector UndefElements;
6128 SDValue Splat = BVOp->getSplatValue(&UndefElements);
6130 // We need a splat of a single value to use broadcast, and it doesn't
6131 // make any sense if the value is only in one element of the vector.
6132 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6136 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6137 Ld.getOpcode() == ISD::ConstantFP);
6139 // Make sure that all of the users of a non-constant load are from the
6140 // BUILD_VECTOR node.
6141 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6146 case ISD::VECTOR_SHUFFLE: {
6147 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6149 // Shuffles must have a splat mask where the first element is
6151 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6154 SDValue Sc = Op.getOperand(0);
6155 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6156 Sc.getOpcode() != ISD::BUILD_VECTOR) {
6158 if (!Subtarget->hasInt256())
6161 // Use the register form of the broadcast instruction available on AVX2.
6162 if (VT.getSizeInBits() >= 256)
6163 Sc = Extract128BitVector(Sc, 0, DAG, dl);
6164 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6167 Ld = Sc.getOperand(0);
6168 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6169 Ld.getOpcode() == ISD::ConstantFP);
6171 // The scalar_to_vector node and the suspected
6172 // load node must have exactly one user.
6173 // Constants may have multiple users.
6175 // AVX-512 has register version of the broadcast
6176 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6177 Ld.getValueType().getSizeInBits() >= 32;
6178 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6185 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6186 bool IsGE256 = (VT.getSizeInBits() >= 256);
6188 // When optimizing for size, generate up to 5 extra bytes for a broadcast
6189 // instruction to save 8 or more bytes of constant pool data.
6190 // TODO: If multiple splats are generated to load the same constant,
6191 // it may be detrimental to overall size. There needs to be a way to detect
6192 // that condition to know if this is truly a size win.
6193 const Function *F = DAG.getMachineFunction().getFunction();
6194 bool OptForSize = F->getAttributes().
6195 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6197 // Handle broadcasting a single constant scalar from the constant pool
6199 // On Sandybridge (no AVX2), it is still better to load a constant vector
6200 // from the constant pool and not to broadcast it from a scalar.
6201 // But override that restriction when optimizing for size.
6202 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6203 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6204 EVT CVT = Ld.getValueType();
6205 assert(!CVT.isVector() && "Must not broadcast a vector type");
6207 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6208 // For size optimization, also splat v2f64 and v2i64, and for size opt
6209 // with AVX2, also splat i8 and i16.
6210 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6211 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6212 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6213 const Constant *C = nullptr;
6214 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6215 C = CI->getConstantIntValue();
6216 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6217 C = CF->getConstantFPValue();
6219 assert(C && "Invalid constant type");
6221 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6222 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6223 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6224 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6225 MachinePointerInfo::getConstantPool(),
6226 false, false, false, Alignment);
6228 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6232 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6234 // Handle AVX2 in-register broadcasts.
6235 if (!IsLoad && Subtarget->hasInt256() &&
6236 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6237 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6239 // The scalar source must be a normal load.
6243 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6244 (Subtarget->hasVLX() && ScalarSize == 64))
6245 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6247 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6248 // double since there is no vbroadcastsd xmm
6249 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6250 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6251 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6254 // Unsupported broadcast.
6258 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6259 /// underlying vector and index.
6261 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6263 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6265 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6266 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6269 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6271 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6273 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6274 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6277 // In this case the vector is the extract_subvector expression and the index
6278 // is 2, as specified by the shuffle.
6279 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6280 SDValue ShuffleVec = SVOp->getOperand(0);
6281 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6282 assert(ShuffleVecVT.getVectorElementType() ==
6283 ExtractedFromVec.getSimpleValueType().getVectorElementType());
6285 int ShuffleIdx = SVOp->getMaskElt(Idx);
6286 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6287 ExtractedFromVec = ShuffleVec;
6293 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6294 MVT VT = Op.getSimpleValueType();
6296 // Skip if insert_vec_elt is not supported.
6297 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6298 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6302 unsigned NumElems = Op.getNumOperands();
6306 SmallVector<unsigned, 4> InsertIndices;
6307 SmallVector<int, 8> Mask(NumElems, -1);
6309 for (unsigned i = 0; i != NumElems; ++i) {
6310 unsigned Opc = Op.getOperand(i).getOpcode();
6312 if (Opc == ISD::UNDEF)
6315 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6316 // Quit if more than 1 elements need inserting.
6317 if (InsertIndices.size() > 1)
6320 InsertIndices.push_back(i);
6324 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6325 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6326 // Quit if non-constant index.
6327 if (!isa<ConstantSDNode>(ExtIdx))
6329 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6331 // Quit if extracted from vector of different type.
6332 if (ExtractedFromVec.getValueType() != VT)
6335 if (!VecIn1.getNode())
6336 VecIn1 = ExtractedFromVec;
6337 else if (VecIn1 != ExtractedFromVec) {
6338 if (!VecIn2.getNode())
6339 VecIn2 = ExtractedFromVec;
6340 else if (VecIn2 != ExtractedFromVec)
6341 // Quit if more than 2 vectors to shuffle
6345 if (ExtractedFromVec == VecIn1)
6347 else if (ExtractedFromVec == VecIn2)
6348 Mask[i] = Idx + NumElems;
6351 if (!VecIn1.getNode())
6354 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6355 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6356 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6357 unsigned Idx = InsertIndices[i];
6358 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6359 DAG.getIntPtrConstant(Idx));
6365 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6367 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6369 MVT VT = Op.getSimpleValueType();
6370 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6371 "Unexpected type in LowerBUILD_VECTORvXi1!");
6374 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6375 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6376 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6377 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6380 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6381 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6382 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6383 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6386 bool AllContants = true;
6387 uint64_t Immediate = 0;
6388 int NonConstIdx = -1;
6389 bool IsSplat = true;
6390 unsigned NumNonConsts = 0;
6391 unsigned NumConsts = 0;
6392 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6393 SDValue In = Op.getOperand(idx);
6394 if (In.getOpcode() == ISD::UNDEF)
6396 if (!isa<ConstantSDNode>(In)) {
6397 AllContants = false;
6402 if (cast<ConstantSDNode>(In)->getZExtValue())
6403 Immediate |= (1ULL << idx);
6405 if (In != Op.getOperand(0))
6410 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6411 DAG.getConstant(Immediate, MVT::i16));
6412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6413 DAG.getIntPtrConstant(0));
6416 if (NumNonConsts == 1 && NonConstIdx != 0) {
6419 SDValue VecAsImm = DAG.getConstant(Immediate,
6420 MVT::getIntegerVT(VT.getSizeInBits()));
6421 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6424 DstVec = DAG.getUNDEF(VT);
6425 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6426 Op.getOperand(NonConstIdx),
6427 DAG.getIntPtrConstant(NonConstIdx));
6429 if (!IsSplat && (NonConstIdx != 0))
6430 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6431 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6434 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6435 DAG.getConstant(-1, SelectVT),
6436 DAG.getConstant(0, SelectVT));
6438 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6439 DAG.getConstant((Immediate | 1), SelectVT),
6440 DAG.getConstant(Immediate, SelectVT));
6441 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6444 /// \brief Return true if \p N implements a horizontal binop and return the
6445 /// operands for the horizontal binop into V0 and V1.
6447 /// This is a helper function of PerformBUILD_VECTORCombine.
6448 /// This function checks that the build_vector \p N in input implements a
6449 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6450 /// operation to match.
6451 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6452 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6453 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6456 /// This function only analyzes elements of \p N whose indices are
6457 /// in range [BaseIdx, LastIdx).
6458 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6460 unsigned BaseIdx, unsigned LastIdx,
6461 SDValue &V0, SDValue &V1) {
6462 EVT VT = N->getValueType(0);
6464 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6465 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6466 "Invalid Vector in input!");
6468 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6469 bool CanFold = true;
6470 unsigned ExpectedVExtractIdx = BaseIdx;
6471 unsigned NumElts = LastIdx - BaseIdx;
6472 V0 = DAG.getUNDEF(VT);
6473 V1 = DAG.getUNDEF(VT);
6475 // Check if N implements a horizontal binop.
6476 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6477 SDValue Op = N->getOperand(i + BaseIdx);
6480 if (Op->getOpcode() == ISD::UNDEF) {
6481 // Update the expected vector extract index.
6482 if (i * 2 == NumElts)
6483 ExpectedVExtractIdx = BaseIdx;
6484 ExpectedVExtractIdx += 2;
6488 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6493 SDValue Op0 = Op.getOperand(0);
6494 SDValue Op1 = Op.getOperand(1);
6496 // Try to match the following pattern:
6497 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6498 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6499 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6500 Op0.getOperand(0) == Op1.getOperand(0) &&
6501 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6502 isa<ConstantSDNode>(Op1.getOperand(1)));
6506 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6507 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6509 if (i * 2 < NumElts) {
6510 if (V0.getOpcode() == ISD::UNDEF)
6511 V0 = Op0.getOperand(0);
6513 if (V1.getOpcode() == ISD::UNDEF)
6514 V1 = Op0.getOperand(0);
6515 if (i * 2 == NumElts)
6516 ExpectedVExtractIdx = BaseIdx;
6519 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6520 if (I0 == ExpectedVExtractIdx)
6521 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6522 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6523 // Try to match the following dag sequence:
6524 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6525 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6529 ExpectedVExtractIdx += 2;
6535 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6536 /// a concat_vector.
6538 /// This is a helper function of PerformBUILD_VECTORCombine.
6539 /// This function expects two 256-bit vectors called V0 and V1.
6540 /// At first, each vector is split into two separate 128-bit vectors.
6541 /// Then, the resulting 128-bit vectors are used to implement two
6542 /// horizontal binary operations.
6544 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6546 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6547 /// the two new horizontal binop.
6548 /// When Mode is set, the first horizontal binop dag node would take as input
6549 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6550 /// horizontal binop dag node would take as input the lower 128-bit of V1
6551 /// and the upper 128-bit of V1.
6553 /// HADD V0_LO, V0_HI
6554 /// HADD V1_LO, V1_HI
6556 /// Otherwise, the first horizontal binop dag node takes as input the lower
6557 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6558 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6560 /// HADD V0_LO, V1_LO
6561 /// HADD V0_HI, V1_HI
6563 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6564 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6565 /// the upper 128-bits of the result.
6566 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6567 SDLoc DL, SelectionDAG &DAG,
6568 unsigned X86Opcode, bool Mode,
6569 bool isUndefLO, bool isUndefHI) {
6570 EVT VT = V0.getValueType();
6571 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6572 "Invalid nodes in input!");
6574 unsigned NumElts = VT.getVectorNumElements();
6575 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6576 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6577 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6578 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6579 EVT NewVT = V0_LO.getValueType();
6581 SDValue LO = DAG.getUNDEF(NewVT);
6582 SDValue HI = DAG.getUNDEF(NewVT);
6585 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6586 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6587 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6588 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6589 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6591 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6592 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6593 V1_LO->getOpcode() != ISD::UNDEF))
6594 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6596 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6597 V1_HI->getOpcode() != ISD::UNDEF))
6598 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6601 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6604 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6605 /// sequence of 'vadd + vsub + blendi'.
6606 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6607 const X86Subtarget *Subtarget) {
6609 EVT VT = BV->getValueType(0);
6610 unsigned NumElts = VT.getVectorNumElements();
6611 SDValue InVec0 = DAG.getUNDEF(VT);
6612 SDValue InVec1 = DAG.getUNDEF(VT);
6614 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6615 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6617 // Odd-numbered elements in the input build vector are obtained from
6618 // adding two integer/float elements.
6619 // Even-numbered elements in the input build vector are obtained from
6620 // subtracting two integer/float elements.
6621 unsigned ExpectedOpcode = ISD::FSUB;
6622 unsigned NextExpectedOpcode = ISD::FADD;
6623 bool AddFound = false;
6624 bool SubFound = false;
6626 for (unsigned i = 0, e = NumElts; i != e; i++) {
6627 SDValue Op = BV->getOperand(i);
6629 // Skip 'undef' values.
6630 unsigned Opcode = Op.getOpcode();
6631 if (Opcode == ISD::UNDEF) {
6632 std::swap(ExpectedOpcode, NextExpectedOpcode);
6636 // Early exit if we found an unexpected opcode.
6637 if (Opcode != ExpectedOpcode)
6640 SDValue Op0 = Op.getOperand(0);
6641 SDValue Op1 = Op.getOperand(1);
6643 // Try to match the following pattern:
6644 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6645 // Early exit if we cannot match that sequence.
6646 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6647 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6648 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6649 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6650 Op0.getOperand(1) != Op1.getOperand(1))
6653 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6657 // We found a valid add/sub node. Update the information accordingly.
6663 // Update InVec0 and InVec1.
6664 if (InVec0.getOpcode() == ISD::UNDEF)
6665 InVec0 = Op0.getOperand(0);
6666 if (InVec1.getOpcode() == ISD::UNDEF)
6667 InVec1 = Op1.getOperand(0);
6669 // Make sure that operands in input to each add/sub node always
6670 // come from a same pair of vectors.
6671 if (InVec0 != Op0.getOperand(0)) {
6672 if (ExpectedOpcode == ISD::FSUB)
6675 // FADD is commutable. Try to commute the operands
6676 // and then test again.
6677 std::swap(Op0, Op1);
6678 if (InVec0 != Op0.getOperand(0))
6682 if (InVec1 != Op1.getOperand(0))
6685 // Update the pair of expected opcodes.
6686 std::swap(ExpectedOpcode, NextExpectedOpcode);
6689 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6690 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6691 InVec1.getOpcode() != ISD::UNDEF)
6692 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6697 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6698 const X86Subtarget *Subtarget) {
6700 EVT VT = N->getValueType(0);
6701 unsigned NumElts = VT.getVectorNumElements();
6702 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6703 SDValue InVec0, InVec1;
6705 // Try to match an ADDSUB.
6706 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6707 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6708 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6709 if (Value.getNode())
6713 // Try to match horizontal ADD/SUB.
6714 unsigned NumUndefsLO = 0;
6715 unsigned NumUndefsHI = 0;
6716 unsigned Half = NumElts/2;
6718 // Count the number of UNDEF operands in the build_vector in input.
6719 for (unsigned i = 0, e = Half; i != e; ++i)
6720 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6723 for (unsigned i = Half, e = NumElts; i != e; ++i)
6724 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6727 // Early exit if this is either a build_vector of all UNDEFs or all the
6728 // operands but one are UNDEF.
6729 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6732 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6733 // Try to match an SSE3 float HADD/HSUB.
6734 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6735 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6737 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6738 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6739 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6740 // Try to match an SSSE3 integer HADD/HSUB.
6741 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6742 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6744 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6745 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6748 if (!Subtarget->hasAVX())
6751 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6752 // Try to match an AVX horizontal add/sub of packed single/double
6753 // precision floating point values from 256-bit vectors.
6754 SDValue InVec2, InVec3;
6755 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6756 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6757 ((InVec0.getOpcode() == ISD::UNDEF ||
6758 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6759 ((InVec1.getOpcode() == ISD::UNDEF ||
6760 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6761 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6763 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6764 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6765 ((InVec0.getOpcode() == ISD::UNDEF ||
6766 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6767 ((InVec1.getOpcode() == ISD::UNDEF ||
6768 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6769 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6770 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6771 // Try to match an AVX2 horizontal add/sub of signed integers.
6772 SDValue InVec2, InVec3;
6774 bool CanFold = true;
6776 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6777 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6778 ((InVec0.getOpcode() == ISD::UNDEF ||
6779 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6780 ((InVec1.getOpcode() == ISD::UNDEF ||
6781 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6782 X86Opcode = X86ISD::HADD;
6783 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6784 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6785 ((InVec0.getOpcode() == ISD::UNDEF ||
6786 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6787 ((InVec1.getOpcode() == ISD::UNDEF ||
6788 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6789 X86Opcode = X86ISD::HSUB;
6794 // Fold this build_vector into a single horizontal add/sub.
6795 // Do this only if the target has AVX2.
6796 if (Subtarget->hasAVX2())
6797 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6799 // Do not try to expand this build_vector into a pair of horizontal
6800 // add/sub if we can emit a pair of scalar add/sub.
6801 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6804 // Convert this build_vector into a pair of horizontal binop followed by
6806 bool isUndefLO = NumUndefsLO == Half;
6807 bool isUndefHI = NumUndefsHI == Half;
6808 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6809 isUndefLO, isUndefHI);
6813 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6814 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6816 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6817 X86Opcode = X86ISD::HADD;
6818 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6819 X86Opcode = X86ISD::HSUB;
6820 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6821 X86Opcode = X86ISD::FHADD;
6822 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6823 X86Opcode = X86ISD::FHSUB;
6827 // Don't try to expand this build_vector into a pair of horizontal add/sub
6828 // if we can simply emit a pair of scalar add/sub.
6829 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6832 // Convert this build_vector into two horizontal add/sub followed by
6834 bool isUndefLO = NumUndefsLO == Half;
6835 bool isUndefHI = NumUndefsHI == Half;
6836 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6837 isUndefLO, isUndefHI);
6844 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6847 MVT VT = Op.getSimpleValueType();
6848 MVT ExtVT = VT.getVectorElementType();
6849 unsigned NumElems = Op.getNumOperands();
6851 // Generate vectors for predicate vectors.
6852 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6853 return LowerBUILD_VECTORvXi1(Op, DAG);
6855 // Vectors containing all zeros can be matched by pxor and xorps later
6856 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6857 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6858 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6859 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6862 return getZeroVector(VT, Subtarget, DAG, dl);
6865 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6866 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6867 // vpcmpeqd on 256-bit vectors.
6868 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6869 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6872 if (!VT.is512BitVector())
6873 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6876 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6877 if (Broadcast.getNode())
6880 unsigned EVTBits = ExtVT.getSizeInBits();
6882 unsigned NumZero = 0;
6883 unsigned NumNonZero = 0;
6884 unsigned NonZeros = 0;
6885 bool IsAllConstants = true;
6886 SmallSet<SDValue, 8> Values;
6887 for (unsigned i = 0; i < NumElems; ++i) {
6888 SDValue Elt = Op.getOperand(i);
6889 if (Elt.getOpcode() == ISD::UNDEF)
6892 if (Elt.getOpcode() != ISD::Constant &&
6893 Elt.getOpcode() != ISD::ConstantFP)
6894 IsAllConstants = false;
6895 if (X86::isZeroNode(Elt))
6898 NonZeros |= (1 << i);
6903 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6904 if (NumNonZero == 0)
6905 return DAG.getUNDEF(VT);
6907 // Special case for single non-zero, non-undef, element.
6908 if (NumNonZero == 1) {
6909 unsigned Idx = countTrailingZeros(NonZeros);
6910 SDValue Item = Op.getOperand(Idx);
6912 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6913 // the value are obviously zero, truncate the value to i32 and do the
6914 // insertion that way. Only do this if the value is non-constant or if the
6915 // value is a constant being inserted into element 0. It is cheaper to do
6916 // a constant pool load than it is to do a movd + shuffle.
6917 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6918 (!IsAllConstants || Idx == 0)) {
6919 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6921 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6922 EVT VecVT = MVT::v4i32;
6923 unsigned VecElts = 4;
6925 // Truncate the value (which may itself be a constant) to i32, and
6926 // convert it to a vector with movd (S2V+shuffle to zero extend).
6927 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6928 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6930 // If using the new shuffle lowering, just directly insert this.
6931 if (ExperimentalVectorShuffleLowering)
6933 ISD::BITCAST, dl, VT,
6934 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6936 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6938 // Now we have our 32-bit value zero extended in the low element of
6939 // a vector. If Idx != 0, swizzle it into place.
6941 SmallVector<int, 4> Mask;
6942 Mask.push_back(Idx);
6943 for (unsigned i = 1; i != VecElts; ++i)
6945 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6948 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6952 // If we have a constant or non-constant insertion into the low element of
6953 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6954 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6955 // depending on what the source datatype is.
6958 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6960 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6961 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6962 if (VT.is256BitVector() || VT.is512BitVector()) {
6963 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6964 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6965 Item, DAG.getIntPtrConstant(0));
6967 assert(VT.is128BitVector() && "Expected an SSE value type!");
6968 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6969 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6970 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6973 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6974 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6975 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6976 if (VT.is256BitVector()) {
6977 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6978 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6980 assert(VT.is128BitVector() && "Expected an SSE value type!");
6981 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6983 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6987 // Is it a vector logical left shift?
6988 if (NumElems == 2 && Idx == 1 &&
6989 X86::isZeroNode(Op.getOperand(0)) &&
6990 !X86::isZeroNode(Op.getOperand(1))) {
6991 unsigned NumBits = VT.getSizeInBits();
6992 return getVShift(true, VT,
6993 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6994 VT, Op.getOperand(1)),
6995 NumBits/2, DAG, *this, dl);
6998 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
7001 // Otherwise, if this is a vector with i32 or f32 elements, and the element
7002 // is a non-constant being inserted into an element other than the low one,
7003 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
7004 // movd/movss) to move this into the low element, then shuffle it into
7006 if (EVTBits == 32) {
7007 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
7009 // If using the new shuffle lowering, just directly insert this.
7010 if (ExperimentalVectorShuffleLowering)
7011 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
7013 // Turn it into a shuffle of zero and zero-extended scalar to vector.
7014 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
7015 SmallVector<int, 8> MaskVec;
7016 for (unsigned i = 0; i != NumElems; ++i)
7017 MaskVec.push_back(i == Idx ? 0 : 1);
7018 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
7022 // Splat is obviously ok. Let legalizer expand it to a shuffle.
7023 if (Values.size() == 1) {
7024 if (EVTBits == 32) {
7025 // Instead of a shuffle like this:
7026 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
7027 // Check if it's possible to issue this instead.
7028 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
7029 unsigned Idx = countTrailingZeros(NonZeros);
7030 SDValue Item = Op.getOperand(Idx);
7031 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
7032 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
7037 // A vector full of immediates; various special cases are already
7038 // handled, so this is best done with a single constant-pool load.
7042 // For AVX-length vectors, see if we can use a vector load to get all of the
7043 // elements, otherwise build the individual 128-bit pieces and use
7044 // shuffles to put them in place.
7045 if (VT.is256BitVector() || VT.is512BitVector()) {
7046 SmallVector<SDValue, 64> V;
7047 for (unsigned i = 0; i != NumElems; ++i)
7048 V.push_back(Op.getOperand(i));
7050 // Check for a build vector of consecutive loads.
7051 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
7054 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
7056 // Build both the lower and upper subvector.
7057 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7058 makeArrayRef(&V[0], NumElems/2));
7059 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7060 makeArrayRef(&V[NumElems / 2], NumElems/2));
7062 // Recreate the wider vector with the lower and upper part.
7063 if (VT.is256BitVector())
7064 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7065 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7068 // Let legalizer expand 2-wide build_vectors.
7069 if (EVTBits == 64) {
7070 if (NumNonZero == 1) {
7071 // One half is zero or undef.
7072 unsigned Idx = countTrailingZeros(NonZeros);
7073 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
7074 Op.getOperand(Idx));
7075 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
7080 // If element VT is < 32 bits, convert it to inserts into a zero vector.
7081 if (EVTBits == 8 && NumElems == 16) {
7082 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
7084 if (V.getNode()) return V;
7087 if (EVTBits == 16 && NumElems == 8) {
7088 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
7090 if (V.getNode()) return V;
7093 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7094 if (EVTBits == 32 && NumElems == 4) {
7095 SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
7100 // If element VT is == 32 bits, turn it into a number of shuffles.
7101 SmallVector<SDValue, 8> V(NumElems);
7102 if (NumElems == 4 && NumZero > 0) {
7103 for (unsigned i = 0; i < 4; ++i) {
7104 bool isZero = !(NonZeros & (1 << i));
7106 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7108 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7111 for (unsigned i = 0; i < 2; ++i) {
7112 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7115 V[i] = V[i*2]; // Must be a zero vector.
7118 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7121 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7124 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7129 bool Reverse1 = (NonZeros & 0x3) == 2;
7130 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7134 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7135 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
7137 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7140 if (Values.size() > 1 && VT.is128BitVector()) {
7141 // Check for a build vector of consecutive loads.
7142 for (unsigned i = 0; i < NumElems; ++i)
7143 V[i] = Op.getOperand(i);
7145 // Check for elements which are consecutive loads.
7146 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7150 // Check for a build vector from mostly shuffle plus few inserting.
7151 SDValue Sh = buildFromShuffleMostly(Op, DAG);
7155 // For SSE 4.1, use insertps to put the high elements into the low element.
7156 if (getSubtarget()->hasSSE41()) {
7158 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7159 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7161 Result = DAG.getUNDEF(VT);
7163 for (unsigned i = 1; i < NumElems; ++i) {
7164 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7165 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7166 Op.getOperand(i), DAG.getIntPtrConstant(i));
7171 // Otherwise, expand into a number of unpckl*, start by extending each of
7172 // our (non-undef) elements to the full vector width with the element in the
7173 // bottom slot of the vector (which generates no code for SSE).
7174 for (unsigned i = 0; i < NumElems; ++i) {
7175 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7176 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7178 V[i] = DAG.getUNDEF(VT);
7181 // Next, we iteratively mix elements, e.g. for v4f32:
7182 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7183 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7184 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
7185 unsigned EltStride = NumElems >> 1;
7186 while (EltStride != 0) {
7187 for (unsigned i = 0; i < EltStride; ++i) {
7188 // If V[i+EltStride] is undef and this is the first round of mixing,
7189 // then it is safe to just drop this shuffle: V[i] is already in the
7190 // right place, the one element (since it's the first round) being
7191 // inserted as undef can be dropped. This isn't safe for successive
7192 // rounds because they will permute elements within both vectors.
7193 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7194 EltStride == NumElems/2)
7197 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7206 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7207 // to create 256-bit vectors from two other 128-bit ones.
7208 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7210 MVT ResVT = Op.getSimpleValueType();
7212 assert((ResVT.is256BitVector() ||
7213 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7215 SDValue V1 = Op.getOperand(0);
7216 SDValue V2 = Op.getOperand(1);
7217 unsigned NumElems = ResVT.getVectorNumElements();
7218 if(ResVT.is256BitVector())
7219 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7221 if (Op.getNumOperands() == 4) {
7222 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7223 ResVT.getVectorNumElements()/2);
7224 SDValue V3 = Op.getOperand(2);
7225 SDValue V4 = Op.getOperand(3);
7226 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7227 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7229 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7232 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7233 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7234 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7235 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7236 Op.getNumOperands() == 4)));
7238 // AVX can use the vinsertf128 instruction to create 256-bit vectors
7239 // from two other 128-bit ones.
7241 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7242 return LowerAVXCONCAT_VECTORS(Op, DAG);
7246 //===----------------------------------------------------------------------===//
7247 // Vector shuffle lowering
7249 // This is an experimental code path for lowering vector shuffles on x86. It is
7250 // designed to handle arbitrary vector shuffles and blends, gracefully
7251 // degrading performance as necessary. It works hard to recognize idiomatic
7252 // shuffles and lower them to optimal instruction patterns without leaving
7253 // a framework that allows reasonably efficient handling of all vector shuffle
7255 //===----------------------------------------------------------------------===//
7257 /// \brief Tiny helper function to identify a no-op mask.
7259 /// This is a somewhat boring predicate function. It checks whether the mask
7260 /// array input, which is assumed to be a single-input shuffle mask of the kind
7261 /// used by the X86 shuffle instructions (not a fully general
7262 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7263 /// in-place shuffle are 'no-op's.
7264 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7265 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7266 if (Mask[i] != -1 && Mask[i] != i)
7271 /// \brief Helper function to classify a mask as a single-input mask.
7273 /// This isn't a generic single-input test because in the vector shuffle
7274 /// lowering we canonicalize single inputs to be the first input operand. This
7275 /// means we can more quickly test for a single input by only checking whether
7276 /// an input from the second operand exists. We also assume that the size of
7277 /// mask corresponds to the size of the input vectors which isn't true in the
7278 /// fully general case.
7279 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7281 if (M >= (int)Mask.size())
7286 /// \brief Test whether there are elements crossing 128-bit lanes in this
7289 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7290 /// and we routinely test for these.
7291 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7292 int LaneSize = 128 / VT.getScalarSizeInBits();
7293 int Size = Mask.size();
7294 for (int i = 0; i < Size; ++i)
7295 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7300 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7302 /// This checks a shuffle mask to see if it is performing the same
7303 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7304 /// that it is also not lane-crossing. It may however involve a blend from the
7305 /// same lane of a second vector.
7307 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7308 /// non-trivial to compute in the face of undef lanes. The representation is
7309 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7310 /// entries from both V1 and V2 inputs to the wider mask.
7312 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7313 SmallVectorImpl<int> &RepeatedMask) {
7314 int LaneSize = 128 / VT.getScalarSizeInBits();
7315 RepeatedMask.resize(LaneSize, -1);
7316 int Size = Mask.size();
7317 for (int i = 0; i < Size; ++i) {
7320 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7321 // This entry crosses lanes, so there is no way to model this shuffle.
7324 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7325 if (RepeatedMask[i % LaneSize] == -1)
7326 // This is the first non-undef entry in this slot of a 128-bit lane.
7327 RepeatedMask[i % LaneSize] =
7328 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7329 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7330 // Found a mismatch with the repeated mask.
7336 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7337 // 2013 will allow us to use it as a non-type template parameter.
7340 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7342 /// See its documentation for details.
7343 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7344 if (Mask.size() != Args.size())
7346 for (int i = 0, e = Mask.size(); i < e; ++i) {
7347 assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7348 if (Mask[i] != -1 && Mask[i] != *Args[i])
7356 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7359 /// This is a fast way to test a shuffle mask against a fixed pattern:
7361 /// if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7363 /// It returns true if the mask is exactly as wide as the argument list, and
7364 /// each element of the mask is either -1 (signifying undef) or the value given
7365 /// in the argument.
7366 static const VariadicFunction1<
7367 bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7369 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7371 /// This helper function produces an 8-bit shuffle immediate corresponding to
7372 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7373 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7376 /// NB: We rely heavily on "undef" masks preserving the input lane.
7377 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7378 SelectionDAG &DAG) {
7379 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7380 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7381 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7382 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7383 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7386 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7387 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7388 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7389 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7390 return DAG.getConstant(Imm, MVT::i8);
7393 /// \brief Try to emit a blend instruction for a shuffle.
7395 /// This doesn't do any checks for the availability of instructions for blending
7396 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7397 /// be matched in the backend with the type given. What it does check for is
7398 /// that the shuffle mask is in fact a blend.
7399 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7400 SDValue V2, ArrayRef<int> Mask,
7401 const X86Subtarget *Subtarget,
7402 SelectionDAG &DAG) {
7404 unsigned BlendMask = 0;
7405 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7406 if (Mask[i] >= Size) {
7407 if (Mask[i] != i + Size)
7408 return SDValue(); // Shuffled V2 input!
7409 BlendMask |= 1u << i;
7412 if (Mask[i] >= 0 && Mask[i] != i)
7413 return SDValue(); // Shuffled V1 input!
7415 switch (VT.SimpleTy) {
7420 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7421 DAG.getConstant(BlendMask, MVT::i8));
7425 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7429 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7430 // that instruction.
7431 if (Subtarget->hasAVX2()) {
7432 // Scale the blend by the number of 32-bit dwords per element.
7433 int Scale = VT.getScalarSizeInBits() / 32;
7435 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7436 if (Mask[i] >= Size)
7437 for (int j = 0; j < Scale; ++j)
7438 BlendMask |= 1u << (i * Scale + j);
7440 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7441 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7442 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7443 return DAG.getNode(ISD::BITCAST, DL, VT,
7444 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7445 DAG.getConstant(BlendMask, MVT::i8)));
7449 // For integer shuffles we need to expand the mask and cast the inputs to
7450 // v8i16s prior to blending.
7451 int Scale = 8 / VT.getVectorNumElements();
7453 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7454 if (Mask[i] >= Size)
7455 for (int j = 0; j < Scale; ++j)
7456 BlendMask |= 1u << (i * Scale + j);
7458 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7459 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7460 return DAG.getNode(ISD::BITCAST, DL, VT,
7461 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7462 DAG.getConstant(BlendMask, MVT::i8)));
7466 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7467 SmallVector<int, 8> RepeatedMask;
7468 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7469 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7470 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7472 for (int i = 0; i < 8; ++i)
7473 if (RepeatedMask[i] >= 16)
7474 BlendMask |= 1u << i;
7475 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7476 DAG.getConstant(BlendMask, MVT::i8));
7481 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7482 // Scale the blend by the number of bytes per element.
7483 int Scale = VT.getScalarSizeInBits() / 8;
7484 assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7486 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7487 // mix of LLVM's code generator and the x86 backend. We tell the code
7488 // generator that boolean values in the elements of an x86 vector register
7489 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7490 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7491 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7492 // of the element (the remaining are ignored) and 0 in that high bit would
7493 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7494 // the LLVM model for boolean values in vector elements gets the relevant
7495 // bit set, it is set backwards and over constrained relative to x86's
7497 SDValue VSELECTMask[32];
7498 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7499 for (int j = 0; j < Scale; ++j)
7500 VSELECTMask[Scale * i + j] =
7501 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7502 : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7504 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7505 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7507 ISD::BITCAST, DL, VT,
7508 DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7509 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7514 llvm_unreachable("Not a supported integer vector type!");
7518 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7519 /// unblended shuffles followed by an unshuffled blend.
7521 /// This matches the extremely common pattern for handling combined
7522 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7524 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7528 SelectionDAG &DAG) {
7529 // Shuffle the input elements into the desired positions in V1 and V2 and
7530 // blend them together.
7531 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7532 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7533 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7534 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7535 if (Mask[i] >= 0 && Mask[i] < Size) {
7536 V1Mask[i] = Mask[i];
7538 } else if (Mask[i] >= Size) {
7539 V2Mask[i] = Mask[i] - Size;
7540 BlendMask[i] = i + Size;
7543 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7544 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7545 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7548 /// \brief Try to lower a vector shuffle as a byte rotation.
7550 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7551 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7552 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7553 /// try to generically lower a vector shuffle through such an pattern. It
7554 /// does not check for the profitability of lowering either as PALIGNR or
7555 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7556 /// This matches shuffle vectors that look like:
7558 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7560 /// Essentially it concatenates V1 and V2, shifts right by some number of
7561 /// elements, and takes the low elements as the result. Note that while this is
7562 /// specified as a *right shift* because x86 is little-endian, it is a *left
7563 /// rotate* of the vector lanes.
7565 /// Note that this only handles 128-bit vector widths currently.
7566 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7569 const X86Subtarget *Subtarget,
7570 SelectionDAG &DAG) {
7571 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7573 // We need to detect various ways of spelling a rotation:
7574 // [11, 12, 13, 14, 15, 0, 1, 2]
7575 // [-1, 12, 13, 14, -1, -1, 1, -1]
7576 // [-1, -1, -1, -1, -1, -1, 1, 2]
7577 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7578 // [-1, 4, 5, 6, -1, -1, 9, -1]
7579 // [-1, 4, 5, 6, -1, -1, -1, -1]
7582 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7585 assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7587 // Based on the mod-Size value of this mask element determine where
7588 // a rotated vector would have started.
7589 int StartIdx = i - (Mask[i] % Size);
7591 // The identity rotation isn't interesting, stop.
7594 // If we found the tail of a vector the rotation must be the missing
7595 // front. If we found the head of a vector, it must be how much of the head.
7596 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7599 Rotation = CandidateRotation;
7600 else if (Rotation != CandidateRotation)
7601 // The rotations don't match, so we can't match this mask.
7604 // Compute which value this mask is pointing at.
7605 SDValue MaskV = Mask[i] < Size ? V1 : V2;
7607 // Compute which of the two target values this index should be assigned to.
7608 // This reflects whether the high elements are remaining or the low elements
7610 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7612 // Either set up this value if we've not encountered it before, or check
7613 // that it remains consistent.
7616 else if (TargetV != MaskV)
7617 // This may be a rotation, but it pulls from the inputs in some
7618 // unsupported interleaving.
7622 // Check that we successfully analyzed the mask, and normalize the results.
7623 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7624 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7630 assert(VT.getSizeInBits() == 128 &&
7631 "Rotate-based lowering only supports 128-bit lowering!");
7632 assert(Mask.size() <= 16 &&
7633 "Can shuffle at most 16 bytes in a 128-bit vector!");
7635 // The actual rotate instruction rotates bytes, so we need to scale the
7636 // rotation based on how many bytes are in the vector.
7637 int Scale = 16 / Mask.size();
7639 // SSSE3 targets can use the palignr instruction
7640 if (Subtarget->hasSSSE3()) {
7641 // Cast the inputs to v16i8 to match PALIGNR.
7642 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7643 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7645 return DAG.getNode(ISD::BITCAST, DL, VT,
7646 DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7647 DAG.getConstant(Rotation * Scale, MVT::i8)));
7650 // Default SSE2 implementation
7651 int LoByteShift = 16 - Rotation * Scale;
7652 int HiByteShift = Rotation * Scale;
7654 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7655 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
7656 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
7658 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7659 DAG.getConstant(8 * LoByteShift, MVT::i8));
7660 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7661 DAG.getConstant(8 * HiByteShift, MVT::i8));
7662 return DAG.getNode(ISD::BITCAST, DL, VT,
7663 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7666 /// \brief Compute whether each element of a shuffle is zeroable.
7668 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7669 /// Either it is an undef element in the shuffle mask, the element of the input
7670 /// referenced is undef, or the element of the input referenced is known to be
7671 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7672 /// as many lanes with this technique as possible to simplify the remaining
7674 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7675 SDValue V1, SDValue V2) {
7676 SmallBitVector Zeroable(Mask.size(), false);
7678 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7679 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7681 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7683 // Handle the easy cases.
7684 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7689 // If this is an index into a build_vector node, dig out the input value and
7691 SDValue V = M < Size ? V1 : V2;
7692 if (V.getOpcode() != ISD::BUILD_VECTOR)
7695 SDValue Input = V.getOperand(M % Size);
7696 // The UNDEF opcode check really should be dead code here, but not quite
7697 // worth asserting on (it isn't invalid, just unexpected).
7698 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7705 /// \brief Try to lower a vector shuffle as a byte shift (shifts in zeros).
7707 /// Attempts to match a shuffle mask against the PSRLDQ and PSLLDQ SSE2
7708 /// byte-shift instructions. The mask must consist of a shifted sequential
7709 /// shuffle from one of the input vectors and zeroable elements for the
7710 /// remaining 'shifted in' elements.
7712 /// Note that this only handles 128-bit vector widths currently.
7713 static SDValue lowerVectorShuffleAsByteShift(SDLoc DL, MVT VT, SDValue V1,
7714 SDValue V2, ArrayRef<int> Mask,
7715 SelectionDAG &DAG) {
7716 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7718 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7720 int Size = Mask.size();
7721 int Scale = 16 / Size;
7723 for (int Shift = 1; Shift < Size; Shift++) {
7724 int ByteShift = Shift * Scale;
7726 // PSRLDQ : (little-endian) right byte shift
7727 // [ 5, 6, 7, zz, zz, zz, zz, zz]
7728 // [ -1, 5, 6, 7, zz, zz, zz, zz]
7729 // [ 1, 2, -1, -1, -1, -1, zz, zz]
7730 bool ZeroableRight = true;
7731 for (int i = Size - Shift; i < Size; i++) {
7732 ZeroableRight &= Zeroable[i];
7735 if (ZeroableRight) {
7736 bool ValidShiftRight1 =
7737 isSequentialOrUndefInRange(Mask, 0, Size - Shift, Shift);
7738 bool ValidShiftRight2 =
7739 isSequentialOrUndefInRange(Mask, 0, Size - Shift, Size + Shift);
7741 if (ValidShiftRight1 || ValidShiftRight2) {
7742 // Cast the inputs to v2i64 to match PSRLDQ.
7743 SDValue &TargetV = ValidShiftRight1 ? V1 : V2;
7744 SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7745 SDValue Shifted = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, V,
7746 DAG.getConstant(ByteShift * 8, MVT::i8));
7747 return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7751 // PSLLDQ : (little-endian) left byte shift
7752 // [ zz, 0, 1, 2, 3, 4, 5, 6]
7753 // [ zz, zz, -1, -1, 2, 3, 4, -1]
7754 // [ zz, zz, zz, zz, zz, zz, -1, 1]
7755 bool ZeroableLeft = true;
7756 for (int i = 0; i < Shift; i++) {
7757 ZeroableLeft &= Zeroable[i];
7761 bool ValidShiftLeft1 =
7762 isSequentialOrUndefInRange(Mask, Shift, Size - Shift, 0);
7763 bool ValidShiftLeft2 =
7764 isSequentialOrUndefInRange(Mask, Shift, Size - Shift, Size);
7766 if (ValidShiftLeft1 || ValidShiftLeft2) {
7767 // Cast the inputs to v2i64 to match PSLLDQ.
7768 SDValue &TargetV = ValidShiftLeft1 ? V1 : V2;
7769 SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7770 SDValue Shifted = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, V,
7771 DAG.getConstant(ByteShift * 8, MVT::i8));
7772 return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7780 /// \brief Lower a vector shuffle as a zero or any extension.
7782 /// Given a specific number of elements, element bit width, and extension
7783 /// stride, produce either a zero or any extension based on the available
7784 /// features of the subtarget.
7785 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7786 SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7787 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7788 assert(Scale > 1 && "Need a scale to extend.");
7789 int EltBits = VT.getSizeInBits() / NumElements;
7790 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7791 "Only 8, 16, and 32 bit elements can be extended.");
7792 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7794 // Found a valid zext mask! Try various lowering strategies based on the
7795 // input type and available ISA extensions.
7796 if (Subtarget->hasSSE41()) {
7797 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7798 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7799 NumElements / Scale);
7800 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7801 return DAG.getNode(ISD::BITCAST, DL, VT,
7802 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7805 // For any extends we can cheat for larger element sizes and use shuffle
7806 // instructions that can fold with a load and/or copy.
7807 if (AnyExt && EltBits == 32) {
7808 int PSHUFDMask[4] = {0, -1, 1, -1};
7810 ISD::BITCAST, DL, VT,
7811 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7812 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7813 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7815 if (AnyExt && EltBits == 16 && Scale > 2) {
7816 int PSHUFDMask[4] = {0, -1, 0, -1};
7817 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7818 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7819 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7820 int PSHUFHWMask[4] = {1, -1, -1, -1};
7822 ISD::BITCAST, DL, VT,
7823 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7824 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7825 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7828 // If this would require more than 2 unpack instructions to expand, use
7829 // pshufb when available. We can only use more than 2 unpack instructions
7830 // when zero extending i8 elements which also makes it easier to use pshufb.
7831 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7832 assert(NumElements == 16 && "Unexpected byte vector width!");
7833 SDValue PSHUFBMask[16];
7834 for (int i = 0; i < 16; ++i)
7836 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7837 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7838 return DAG.getNode(ISD::BITCAST, DL, VT,
7839 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7840 DAG.getNode(ISD::BUILD_VECTOR, DL,
7841 MVT::v16i8, PSHUFBMask)));
7844 // Otherwise emit a sequence of unpacks.
7846 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7847 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7848 : getZeroVector(InputVT, Subtarget, DAG, DL);
7849 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7850 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7854 } while (Scale > 1);
7855 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7858 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7860 /// This routine will try to do everything in its power to cleverly lower
7861 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7862 /// check for the profitability of this lowering, it tries to aggressively
7863 /// match this pattern. It will use all of the micro-architectural details it
7864 /// can to emit an efficient lowering. It handles both blends with all-zero
7865 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7866 /// masking out later).
7868 /// The reason we have dedicated lowering for zext-style shuffles is that they
7869 /// are both incredibly common and often quite performance sensitive.
7870 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7871 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7872 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7873 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7875 int Bits = VT.getSizeInBits();
7876 int NumElements = Mask.size();
7878 // Define a helper function to check a particular ext-scale and lower to it if
7880 auto Lower = [&](int Scale) -> SDValue {
7883 for (int i = 0; i < NumElements; ++i) {
7885 continue; // Valid anywhere but doesn't tell us anything.
7886 if (i % Scale != 0) {
7887 // Each of the extend elements needs to be zeroable.
7891 // We no lorger are in the anyext case.
7896 // Each of the base elements needs to be consecutive indices into the
7897 // same input vector.
7898 SDValue V = Mask[i] < NumElements ? V1 : V2;
7901 else if (InputV != V)
7902 return SDValue(); // Flip-flopping inputs.
7904 if (Mask[i] % NumElements != i / Scale)
7905 return SDValue(); // Non-consecutive strided elemenst.
7908 // If we fail to find an input, we have a zero-shuffle which should always
7909 // have already been handled.
7910 // FIXME: Maybe handle this here in case during blending we end up with one?
7914 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7915 DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7918 // The widest scale possible for extending is to a 64-bit integer.
7919 assert(Bits % 64 == 0 &&
7920 "The number of bits in a vector must be divisible by 64 on x86!");
7921 int NumExtElements = Bits / 64;
7923 // Each iteration, try extending the elements half as much, but into twice as
7925 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7926 assert(NumElements % NumExtElements == 0 &&
7927 "The input vector size must be divisble by the extended size.");
7928 if (SDValue V = Lower(NumElements / NumExtElements))
7932 // No viable ext lowering found.
7936 /// \brief Try to get a scalar value for a specific element of a vector.
7938 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7939 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7940 SelectionDAG &DAG) {
7941 MVT VT = V.getSimpleValueType();
7942 MVT EltVT = VT.getVectorElementType();
7943 while (V.getOpcode() == ISD::BITCAST)
7944 V = V.getOperand(0);
7945 // If the bitcasts shift the element size, we can't extract an equivalent
7947 MVT NewVT = V.getSimpleValueType();
7948 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7951 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7952 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
7953 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
7958 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7960 /// This is particularly important because the set of instructions varies
7961 /// significantly based on whether the operand is a load or not.
7962 static bool isShuffleFoldableLoad(SDValue V) {
7963 while (V.getOpcode() == ISD::BITCAST)
7964 V = V.getOperand(0);
7966 return ISD::isNON_EXTLoad(V.getNode());
7969 /// \brief Try to lower insertion of a single element into a zero vector.
7971 /// This is a common pattern that we have especially efficient patterns to lower
7972 /// across all subtarget feature sets.
7973 static SDValue lowerVectorShuffleAsElementInsertion(
7974 MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7975 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7976 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7978 MVT EltVT = VT.getVectorElementType();
7980 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7981 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7983 bool IsV1Zeroable = true;
7984 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7985 if (i != V2Index && !Zeroable[i]) {
7986 IsV1Zeroable = false;
7990 // Check for a single input from a SCALAR_TO_VECTOR node.
7991 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7992 // all the smarts here sunk into that routine. However, the current
7993 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7994 // vector shuffle lowering is dead.
7995 if (SDValue V2S = getScalarValueForVectorElement(
7996 V2, Mask[V2Index] - Mask.size(), DAG)) {
7997 // We need to zext the scalar if it is smaller than an i32.
7998 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7999 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8000 // Using zext to expand a narrow element won't work for non-zero
8005 // Zero-extend directly to i32.
8007 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8009 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8010 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8011 EltVT == MVT::i16) {
8012 // Either not inserting from the low element of the input or the input
8013 // element size is too small to use VZEXT_MOVL to clear the high bits.
8017 if (!IsV1Zeroable) {
8018 // If V1 can't be treated as a zero vector we have fewer options to lower
8019 // this. We can't support integer vectors or non-zero targets cheaply, and
8020 // the V1 elements can't be permuted in any way.
8021 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8022 if (!VT.isFloatingPoint() || V2Index != 0)
8024 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8025 V1Mask[V2Index] = -1;
8026 if (!isNoopShuffleMask(V1Mask))
8028 // This is essentially a special case blend operation, but if we have
8029 // general purpose blend operations, they are always faster. Bail and let
8030 // the rest of the lowering handle these as blends.
8031 if (Subtarget->hasSSE41())
8034 // Otherwise, use MOVSD or MOVSS.
8035 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8036 "Only two types of floating point element types to handle!");
8037 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8041 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8043 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8046 // If we have 4 or fewer lanes we can cheaply shuffle the element into
8047 // the desired position. Otherwise it is more efficient to do a vector
8048 // shift left. We know that we can do a vector shift left because all
8049 // the inputs are zero.
8050 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8051 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8052 V2Shuffle[V2Index] = 0;
8053 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8055 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
8057 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8059 V2Index * EltVT.getSizeInBits(),
8060 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
8061 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8067 /// \brief Try to lower broadcast of a single element.
8069 /// For convenience, this code also bundles all of the subtarget feature set
8070 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8071 /// a convenient way to factor it out.
8072 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
8074 const X86Subtarget *Subtarget,
8075 SelectionDAG &DAG) {
8076 if (!Subtarget->hasAVX())
8078 if (VT.isInteger() && !Subtarget->hasAVX2())
8081 // Check that the mask is a broadcast.
8082 int BroadcastIdx = -1;
8084 if (M >= 0 && BroadcastIdx == -1)
8086 else if (M >= 0 && M != BroadcastIdx)
8089 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8090 "a sorted mask where the broadcast "
8093 // Go up the chain of (vector) values to try and find a scalar load that
8094 // we can combine with the broadcast.
8096 switch (V.getOpcode()) {
8097 case ISD::CONCAT_VECTORS: {
8098 int OperandSize = Mask.size() / V.getNumOperands();
8099 V = V.getOperand(BroadcastIdx / OperandSize);
8100 BroadcastIdx %= OperandSize;
8104 case ISD::INSERT_SUBVECTOR: {
8105 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8106 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8110 int BeginIdx = (int)ConstantIdx->getZExtValue();
8112 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
8113 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8114 BroadcastIdx -= BeginIdx;
8125 // Check if this is a broadcast of a scalar. We special case lowering
8126 // for scalars so that we can more effectively fold with loads.
8127 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8128 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8129 V = V.getOperand(BroadcastIdx);
8131 // If the scalar isn't a load we can't broadcast from it in AVX1, only with
8133 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8135 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8136 // We can't broadcast from a vector register w/o AVX2, and we can only
8137 // broadcast from the zero-element of a vector register.
8141 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8144 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8146 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8147 /// support for floating point shuffles but not integer shuffles. These
8148 /// instructions will incur a domain crossing penalty on some chips though so
8149 /// it is better to avoid lowering through this for integer vectors where
8151 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8152 const X86Subtarget *Subtarget,
8153 SelectionDAG &DAG) {
8155 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8156 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8157 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8158 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8159 ArrayRef<int> Mask = SVOp->getMask();
8160 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8162 if (isSingleInputShuffleMask(Mask)) {
8163 // Straight shuffle of a single input vector. Simulate this by using the
8164 // single input as both of the "inputs" to this instruction..
8165 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8167 if (Subtarget->hasAVX()) {
8168 // If we have AVX, we can use VPERMILPS which will allow folding a load
8169 // into the shuffle.
8170 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8171 DAG.getConstant(SHUFPDMask, MVT::i8));
8174 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
8175 DAG.getConstant(SHUFPDMask, MVT::i8));
8177 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8178 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8180 // Use dedicated unpack instructions for masks that match their pattern.
8181 if (isShuffleEquivalent(Mask, 0, 2))
8182 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8183 if (isShuffleEquivalent(Mask, 1, 3))
8184 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8186 // If we have a single input, insert that into V1 if we can do so cheaply.
8187 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8188 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8189 MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
8191 // Try inverting the insertion since for v2 masks it is easy to do and we
8192 // can't reliably sort the mask one way or the other.
8193 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8194 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8195 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8196 MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
8200 // Try to use one of the special instruction patterns to handle two common
8201 // blend patterns if a zero-blend above didn't work.
8202 if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8203 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8204 // We can either use a special instruction to load over the low double or
8205 // to move just the low double.
8207 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8209 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8211 if (Subtarget->hasSSE41())
8212 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8216 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8217 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8218 DAG.getConstant(SHUFPDMask, MVT::i8));
8221 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8223 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8224 /// the integer unit to minimize domain crossing penalties. However, for blends
8225 /// it falls back to the floating point shuffle operation with appropriate bit
8227 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8228 const X86Subtarget *Subtarget,
8229 SelectionDAG &DAG) {
8231 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8232 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8233 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8234 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8235 ArrayRef<int> Mask = SVOp->getMask();
8236 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8238 if (isSingleInputShuffleMask(Mask)) {
8239 // Check for being able to broadcast a single element.
8240 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8241 Mask, Subtarget, DAG))
8244 // Straight shuffle of a single input vector. For everything from SSE2
8245 // onward this has a single fast instruction with no scary immediates.
8246 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8247 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8248 int WidenedMask[4] = {
8249 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8250 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8252 ISD::BITCAST, DL, MVT::v2i64,
8253 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8254 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8257 // Try to use byte shift instructions.
8258 if (SDValue Shift = lowerVectorShuffleAsByteShift(
8259 DL, MVT::v2i64, V1, V2, Mask, DAG))
8262 // If we have a single input from V2 insert that into V1 if we can do so
8264 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8265 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8266 MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8268 // Try inverting the insertion since for v2 masks it is easy to do and we
8269 // can't reliably sort the mask one way or the other.
8270 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8271 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8272 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8273 MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8277 // Use dedicated unpack instructions for masks that match their pattern.
8278 if (isShuffleEquivalent(Mask, 0, 2))
8279 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8280 if (isShuffleEquivalent(Mask, 1, 3))
8281 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8283 if (Subtarget->hasSSE41())
8284 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8288 // Try to use byte rotation instructions.
8289 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8290 if (Subtarget->hasSSSE3())
8291 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8292 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8295 // We implement this with SHUFPD which is pretty lame because it will likely
8296 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8297 // However, all the alternatives are still more cycles and newer chips don't
8298 // have this problem. It would be really nice if x86 had better shuffles here.
8299 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8300 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8301 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8302 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8305 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8307 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8308 /// It makes no assumptions about whether this is the *best* lowering, it simply
8310 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8311 ArrayRef<int> Mask, SDValue V1,
8312 SDValue V2, SelectionDAG &DAG) {
8313 SDValue LowV = V1, HighV = V2;
8314 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8317 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8319 if (NumV2Elements == 1) {
8321 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8324 // Compute the index adjacent to V2Index and in the same half by toggling
8326 int V2AdjIndex = V2Index ^ 1;
8328 if (Mask[V2AdjIndex] == -1) {
8329 // Handles all the cases where we have a single V2 element and an undef.
8330 // This will only ever happen in the high lanes because we commute the
8331 // vector otherwise.
8333 std::swap(LowV, HighV);
8334 NewMask[V2Index] -= 4;
8336 // Handle the case where the V2 element ends up adjacent to a V1 element.
8337 // To make this work, blend them together as the first step.
8338 int V1Index = V2AdjIndex;
8339 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8340 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8341 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8343 // Now proceed to reconstruct the final blend as we have the necessary
8344 // high or low half formed.
8351 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8352 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8354 } else if (NumV2Elements == 2) {
8355 if (Mask[0] < 4 && Mask[1] < 4) {
8356 // Handle the easy case where we have V1 in the low lanes and V2 in the
8360 } else if (Mask[2] < 4 && Mask[3] < 4) {
8361 // We also handle the reversed case because this utility may get called
8362 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8363 // arrange things in the right direction.
8369 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8370 // trying to place elements directly, just blend them and set up the final
8371 // shuffle to place them.
8373 // The first two blend mask elements are for V1, the second two are for
8375 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8376 Mask[2] < 4 ? Mask[2] : Mask[3],
8377 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8378 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8379 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8380 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8382 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8385 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8386 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8387 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8388 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8391 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8392 getV4X86ShuffleImm8ForMask(NewMask, DAG));
8395 /// \brief Lower 4-lane 32-bit floating point shuffles.
8397 /// Uses instructions exclusively from the floating point unit to minimize
8398 /// domain crossing penalties, as these are sufficient to implement all v4f32
8400 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8401 const X86Subtarget *Subtarget,
8402 SelectionDAG &DAG) {
8404 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8405 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8406 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8407 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8408 ArrayRef<int> Mask = SVOp->getMask();
8409 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8412 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8414 if (NumV2Elements == 0) {
8415 // Check for being able to broadcast a single element.
8416 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8417 Mask, Subtarget, DAG))
8420 if (Subtarget->hasAVX()) {
8421 // If we have AVX, we can use VPERMILPS which will allow folding a load
8422 // into the shuffle.
8423 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8424 getV4X86ShuffleImm8ForMask(Mask, DAG));
8427 // Otherwise, use a straight shuffle of a single input vector. We pass the
8428 // input vector to both operands to simulate this with a SHUFPS.
8429 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8430 getV4X86ShuffleImm8ForMask(Mask, DAG));
8433 // Use dedicated unpack instructions for masks that match their pattern.
8434 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8435 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8436 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8437 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8439 // There are special ways we can lower some single-element blends. However, we
8440 // have custom ways we can lower more complex single-element blends below that
8441 // we defer to if both this and BLENDPS fail to match, so restrict this to
8442 // when the V2 input is targeting element 0 of the mask -- that is the fast
8444 if (NumV2Elements == 1 && Mask[0] >= 4)
8445 if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8446 Mask, Subtarget, DAG))
8449 if (Subtarget->hasSSE41())
8450 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8454 // Check for whether we can use INSERTPS to perform the blend. We only use
8455 // INSERTPS when the V1 elements are already in the correct locations
8456 // because otherwise we can just always use two SHUFPS instructions which
8457 // are much smaller to encode than a SHUFPS and an INSERTPS.
8458 if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
8460 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8463 // When using INSERTPS we can zero any lane of the destination. Collect
8464 // the zero inputs into a mask and drop them from the lanes of V1 which
8465 // actually need to be present as inputs to the INSERTPS.
8466 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8468 // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
8469 bool InsertNeedsShuffle = false;
8471 for (int i = 0; i < 4; ++i)
8475 } else if (Mask[i] != i) {
8476 InsertNeedsShuffle = true;
8481 // We don't want to use INSERTPS or other insertion techniques if it will
8482 // require shuffling anyways.
8483 if (!InsertNeedsShuffle) {
8484 // If all of V1 is zeroable, replace it with undef.
8485 if ((ZMask | 1 << V2Index) == 0xF)
8486 V1 = DAG.getUNDEF(MVT::v4f32);
8488 unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
8489 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8491 // Insert the V2 element into the desired position.
8492 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8493 DAG.getConstant(InsertPSMask, MVT::i8));
8497 // Otherwise fall back to a SHUFPS lowering strategy.
8498 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8501 /// \brief Lower 4-lane i32 vector shuffles.
8503 /// We try to handle these with integer-domain shuffles where we can, but for
8504 /// blends we use the floating point domain blend instructions.
8505 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8506 const X86Subtarget *Subtarget,
8507 SelectionDAG &DAG) {
8509 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8510 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8511 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8512 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8513 ArrayRef<int> Mask = SVOp->getMask();
8514 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8516 // Whenever we can lower this as a zext, that instruction is strictly faster
8517 // than any alternative. It also allows us to fold memory operands into the
8518 // shuffle in many cases.
8519 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8520 Mask, Subtarget, DAG))
8524 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8526 if (NumV2Elements == 0) {
8527 // Check for being able to broadcast a single element.
8528 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8529 Mask, Subtarget, DAG))
8532 // Straight shuffle of a single input vector. For everything from SSE2
8533 // onward this has a single fast instruction with no scary immediates.
8534 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8535 // but we aren't actually going to use the UNPCK instruction because doing
8536 // so prevents folding a load into this instruction or making a copy.
8537 const int UnpackLoMask[] = {0, 0, 1, 1};
8538 const int UnpackHiMask[] = {2, 2, 3, 3};
8539 if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8540 Mask = UnpackLoMask;
8541 else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8542 Mask = UnpackHiMask;
8544 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8545 getV4X86ShuffleImm8ForMask(Mask, DAG));
8548 // Try to use byte shift instructions.
8549 if (SDValue Shift = lowerVectorShuffleAsByteShift(
8550 DL, MVT::v4i32, V1, V2, Mask, DAG))
8553 // There are special ways we can lower some single-element blends.
8554 if (NumV2Elements == 1)
8555 if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8556 Mask, Subtarget, DAG))
8559 // Use dedicated unpack instructions for masks that match their pattern.
8560 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8561 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8562 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8563 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8565 if (Subtarget->hasSSE41())
8566 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8570 // Try to use byte rotation instructions.
8571 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8572 if (Subtarget->hasSSSE3())
8573 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8574 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8577 // We implement this with SHUFPS because it can blend from two vectors.
8578 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8579 // up the inputs, bypassing domain shift penalties that we would encur if we
8580 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8582 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8583 DAG.getVectorShuffle(
8585 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8586 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8589 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8590 /// shuffle lowering, and the most complex part.
8592 /// The lowering strategy is to try to form pairs of input lanes which are
8593 /// targeted at the same half of the final vector, and then use a dword shuffle
8594 /// to place them onto the right half, and finally unpack the paired lanes into
8595 /// their final position.
8597 /// The exact breakdown of how to form these dword pairs and align them on the
8598 /// correct sides is really tricky. See the comments within the function for
8599 /// more of the details.
8600 static SDValue lowerV8I16SingleInputVectorShuffle(
8601 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8602 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8603 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8604 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8605 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8607 SmallVector<int, 4> LoInputs;
8608 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8609 [](int M) { return M >= 0; });
8610 std::sort(LoInputs.begin(), LoInputs.end());
8611 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8612 SmallVector<int, 4> HiInputs;
8613 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8614 [](int M) { return M >= 0; });
8615 std::sort(HiInputs.begin(), HiInputs.end());
8616 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8618 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8619 int NumHToL = LoInputs.size() - NumLToL;
8621 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8622 int NumHToH = HiInputs.size() - NumLToH;
8623 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8624 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8625 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8626 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8628 // Check for being able to broadcast a single element.
8629 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8630 Mask, Subtarget, DAG))
8633 // Try to use byte shift instructions.
8634 if (SDValue Shift = lowerVectorShuffleAsByteShift(
8635 DL, MVT::v8i16, V, V, Mask, DAG))
8638 // Use dedicated unpack instructions for masks that match their pattern.
8639 if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8640 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8641 if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8642 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8644 // Try to use byte rotation instructions.
8645 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8646 DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
8649 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8650 // such inputs we can swap two of the dwords across the half mark and end up
8651 // with <=2 inputs to each half in each half. Once there, we can fall through
8652 // to the generic code below. For example:
8654 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8655 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8657 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8658 // and an existing 2-into-2 on the other half. In this case we may have to
8659 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8660 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8661 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8662 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8663 // half than the one we target for fixing) will be fixed when we re-enter this
8664 // path. We will also combine away any sequence of PSHUFD instructions that
8665 // result into a single instruction. Here is an example of the tricky case:
8667 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8668 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8670 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8672 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8673 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8675 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8676 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8678 // The result is fine to be handled by the generic logic.
8679 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8680 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8681 int AOffset, int BOffset) {
8682 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8683 "Must call this with A having 3 or 1 inputs from the A half.");
8684 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8685 "Must call this with B having 1 or 3 inputs from the B half.");
8686 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8687 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8689 // Compute the index of dword with only one word among the three inputs in
8690 // a half by taking the sum of the half with three inputs and subtracting
8691 // the sum of the actual three inputs. The difference is the remaining
8694 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8695 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8696 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8697 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8698 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8699 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8700 int TripleNonInputIdx =
8701 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8702 TripleDWord = TripleNonInputIdx / 2;
8704 // We use xor with one to compute the adjacent DWord to whichever one the
8706 OneInputDWord = (OneInput / 2) ^ 1;
8708 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8709 // and BToA inputs. If there is also such a problem with the BToB and AToB
8710 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8711 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8712 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8713 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8714 // Compute how many inputs will be flipped by swapping these DWords. We
8716 // to balance this to ensure we don't form a 3-1 shuffle in the other
8718 int NumFlippedAToBInputs =
8719 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8720 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8721 int NumFlippedBToBInputs =
8722 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8723 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8724 if ((NumFlippedAToBInputs == 1 &&
8725 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8726 (NumFlippedBToBInputs == 1 &&
8727 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8728 // We choose whether to fix the A half or B half based on whether that
8729 // half has zero flipped inputs. At zero, we may not be able to fix it
8730 // with that half. We also bias towards fixing the B half because that
8731 // will more commonly be the high half, and we have to bias one way.
8732 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8733 ArrayRef<int> Inputs) {
8734 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8735 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8736 PinnedIdx ^ 1) != Inputs.end();
8737 // Determine whether the free index is in the flipped dword or the
8738 // unflipped dword based on where the pinned index is. We use this bit
8739 // in an xor to conditionally select the adjacent dword.
8740 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8741 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8742 FixFreeIdx) != Inputs.end();
8743 if (IsFixIdxInput == IsFixFreeIdxInput)
8745 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8746 FixFreeIdx) != Inputs.end();
8747 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8748 "We need to be changing the number of flipped inputs!");
8749 int PSHUFHalfMask[] = {0, 1, 2, 3};
8750 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8751 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8753 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8756 if (M != -1 && M == FixIdx)
8758 else if (M != -1 && M == FixFreeIdx)
8761 if (NumFlippedBToBInputs != 0) {
8763 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8764 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8766 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8768 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8769 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8774 int PSHUFDMask[] = {0, 1, 2, 3};
8775 PSHUFDMask[ADWord] = BDWord;
8776 PSHUFDMask[BDWord] = ADWord;
8777 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8778 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8779 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8780 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8782 // Adjust the mask to match the new locations of A and B.
8784 if (M != -1 && M/2 == ADWord)
8785 M = 2 * BDWord + M % 2;
8786 else if (M != -1 && M/2 == BDWord)
8787 M = 2 * ADWord + M % 2;
8789 // Recurse back into this routine to re-compute state now that this isn't
8790 // a 3 and 1 problem.
8791 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8794 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8795 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8796 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8797 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8799 // At this point there are at most two inputs to the low and high halves from
8800 // each half. That means the inputs can always be grouped into dwords and
8801 // those dwords can then be moved to the correct half with a dword shuffle.
8802 // We use at most one low and one high word shuffle to collect these paired
8803 // inputs into dwords, and finally a dword shuffle to place them.
8804 int PSHUFLMask[4] = {-1, -1, -1, -1};
8805 int PSHUFHMask[4] = {-1, -1, -1, -1};
8806 int PSHUFDMask[4] = {-1, -1, -1, -1};
8808 // First fix the masks for all the inputs that are staying in their
8809 // original halves. This will then dictate the targets of the cross-half
8811 auto fixInPlaceInputs =
8812 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8813 MutableArrayRef<int> SourceHalfMask,
8814 MutableArrayRef<int> HalfMask, int HalfOffset) {
8815 if (InPlaceInputs.empty())
8817 if (InPlaceInputs.size() == 1) {
8818 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8819 InPlaceInputs[0] - HalfOffset;
8820 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8823 if (IncomingInputs.empty()) {
8824 // Just fix all of the in place inputs.
8825 for (int Input : InPlaceInputs) {
8826 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8827 PSHUFDMask[Input / 2] = Input / 2;
8832 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8833 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8834 InPlaceInputs[0] - HalfOffset;
8835 // Put the second input next to the first so that they are packed into
8836 // a dword. We find the adjacent index by toggling the low bit.
8837 int AdjIndex = InPlaceInputs[0] ^ 1;
8838 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8839 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8840 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8842 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8843 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8845 // Now gather the cross-half inputs and place them into a free dword of
8846 // their target half.
8847 // FIXME: This operation could almost certainly be simplified dramatically to
8848 // look more like the 3-1 fixing operation.
8849 auto moveInputsToRightHalf = [&PSHUFDMask](
8850 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8851 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8852 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8854 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8855 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8857 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8859 int LowWord = Word & ~1;
8860 int HighWord = Word | 1;
8861 return isWordClobbered(SourceHalfMask, LowWord) ||
8862 isWordClobbered(SourceHalfMask, HighWord);
8865 if (IncomingInputs.empty())
8868 if (ExistingInputs.empty()) {
8869 // Map any dwords with inputs from them into the right half.
8870 for (int Input : IncomingInputs) {
8871 // If the source half mask maps over the inputs, turn those into
8872 // swaps and use the swapped lane.
8873 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8874 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8875 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8876 Input - SourceOffset;
8877 // We have to swap the uses in our half mask in one sweep.
8878 for (int &M : HalfMask)
8879 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8881 else if (M == Input)
8882 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8884 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8885 Input - SourceOffset &&
8886 "Previous placement doesn't match!");
8888 // Note that this correctly re-maps both when we do a swap and when
8889 // we observe the other side of the swap above. We rely on that to
8890 // avoid swapping the members of the input list directly.
8891 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8894 // Map the input's dword into the correct half.
8895 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8896 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8898 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8900 "Previous placement doesn't match!");
8903 // And just directly shift any other-half mask elements to be same-half
8904 // as we will have mirrored the dword containing the element into the
8905 // same position within that half.
8906 for (int &M : HalfMask)
8907 if (M >= SourceOffset && M < SourceOffset + 4) {
8908 M = M - SourceOffset + DestOffset;
8909 assert(M >= 0 && "This should never wrap below zero!");
8914 // Ensure we have the input in a viable dword of its current half. This
8915 // is particularly tricky because the original position may be clobbered
8916 // by inputs being moved and *staying* in that half.
8917 if (IncomingInputs.size() == 1) {
8918 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8919 int InputFixed = std::find(std::begin(SourceHalfMask),
8920 std::end(SourceHalfMask), -1) -
8921 std::begin(SourceHalfMask) + SourceOffset;
8922 SourceHalfMask[InputFixed - SourceOffset] =
8923 IncomingInputs[0] - SourceOffset;
8924 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8926 IncomingInputs[0] = InputFixed;
8928 } else if (IncomingInputs.size() == 2) {
8929 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8930 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8931 // We have two non-adjacent or clobbered inputs we need to extract from
8932 // the source half. To do this, we need to map them into some adjacent
8933 // dword slot in the source mask.
8934 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8935 IncomingInputs[1] - SourceOffset};
8937 // If there is a free slot in the source half mask adjacent to one of
8938 // the inputs, place the other input in it. We use (Index XOR 1) to
8939 // compute an adjacent index.
8940 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8941 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8942 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8943 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8944 InputsFixed[1] = InputsFixed[0] ^ 1;
8945 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8946 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8947 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8948 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8949 InputsFixed[0] = InputsFixed[1] ^ 1;
8950 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8951 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8952 // The two inputs are in the same DWord but it is clobbered and the
8953 // adjacent DWord isn't used at all. Move both inputs to the free
8955 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8956 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8957 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8958 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8960 // The only way we hit this point is if there is no clobbering
8961 // (because there are no off-half inputs to this half) and there is no
8962 // free slot adjacent to one of the inputs. In this case, we have to
8963 // swap an input with a non-input.
8964 for (int i = 0; i < 4; ++i)
8965 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8966 "We can't handle any clobbers here!");
8967 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8968 "Cannot have adjacent inputs here!");
8970 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8971 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8973 // We also have to update the final source mask in this case because
8974 // it may need to undo the above swap.
8975 for (int &M : FinalSourceHalfMask)
8976 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8977 M = InputsFixed[1] + SourceOffset;
8978 else if (M == InputsFixed[1] + SourceOffset)
8979 M = (InputsFixed[0] ^ 1) + SourceOffset;
8981 InputsFixed[1] = InputsFixed[0] ^ 1;
8984 // Point everything at the fixed inputs.
8985 for (int &M : HalfMask)
8986 if (M == IncomingInputs[0])
8987 M = InputsFixed[0] + SourceOffset;
8988 else if (M == IncomingInputs[1])
8989 M = InputsFixed[1] + SourceOffset;
8991 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8992 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8995 llvm_unreachable("Unhandled input size!");
8998 // Now hoist the DWord down to the right half.
8999 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9000 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9001 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9002 for (int &M : HalfMask)
9003 for (int Input : IncomingInputs)
9005 M = FreeDWord * 2 + Input % 2;
9007 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9008 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9009 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9010 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9012 // Now enact all the shuffles we've computed to move the inputs into their
9014 if (!isNoopShuffleMask(PSHUFLMask))
9015 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9016 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
9017 if (!isNoopShuffleMask(PSHUFHMask))
9018 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9019 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
9020 if (!isNoopShuffleMask(PSHUFDMask))
9021 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9022 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
9023 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
9024 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9026 // At this point, each half should contain all its inputs, and we can then
9027 // just shuffle them into their final position.
9028 assert(std::count_if(LoMask.begin(), LoMask.end(),
9029 [](int M) { return M >= 4; }) == 0 &&
9030 "Failed to lift all the high half inputs to the low mask!");
9031 assert(std::count_if(HiMask.begin(), HiMask.end(),
9032 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9033 "Failed to lift all the low half inputs to the high mask!");
9035 // Do a half shuffle for the low mask.
9036 if (!isNoopShuffleMask(LoMask))
9037 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9038 getV4X86ShuffleImm8ForMask(LoMask, DAG));
9040 // Do a half shuffle with the high mask after shifting its values down.
9041 for (int &M : HiMask)
9044 if (!isNoopShuffleMask(HiMask))
9045 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9046 getV4X86ShuffleImm8ForMask(HiMask, DAG));
9051 /// \brief Detect whether the mask pattern should be lowered through
9054 /// This essentially tests whether viewing the mask as an interleaving of two
9055 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
9056 /// lowering it through interleaving is a significantly better strategy.
9057 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
9058 int NumEvenInputs[2] = {0, 0};
9059 int NumOddInputs[2] = {0, 0};
9060 int NumLoInputs[2] = {0, 0};
9061 int NumHiInputs[2] = {0, 0};
9062 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9066 int InputIdx = Mask[i] >= Size;
9069 ++NumLoInputs[InputIdx];
9071 ++NumHiInputs[InputIdx];
9074 ++NumEvenInputs[InputIdx];
9076 ++NumOddInputs[InputIdx];
9079 // The minimum number of cross-input results for both the interleaved and
9080 // split cases. If interleaving results in fewer cross-input results, return
9082 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
9083 NumEvenInputs[0] + NumOddInputs[1]);
9084 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
9085 NumLoInputs[0] + NumHiInputs[1]);
9086 return InterleavedCrosses < SplitCrosses;
9089 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
9091 /// This strategy only works when the inputs from each vector fit into a single
9092 /// half of that vector, and generally there are not so many inputs as to leave
9093 /// the in-place shuffles required highly constrained (and thus expensive). It
9094 /// shifts all the inputs into a single side of both input vectors and then
9095 /// uses an unpack to interleave these inputs in a single vector. At that
9096 /// point, we will fall back on the generic single input shuffle lowering.
9097 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
9099 MutableArrayRef<int> Mask,
9100 const X86Subtarget *Subtarget,
9101 SelectionDAG &DAG) {
9102 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9103 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9104 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
9105 for (int i = 0; i < 8; ++i)
9106 if (Mask[i] >= 0 && Mask[i] < 4)
9107 LoV1Inputs.push_back(i);
9108 else if (Mask[i] >= 4 && Mask[i] < 8)
9109 HiV1Inputs.push_back(i);
9110 else if (Mask[i] >= 8 && Mask[i] < 12)
9111 LoV2Inputs.push_back(i);
9112 else if (Mask[i] >= 12)
9113 HiV2Inputs.push_back(i);
9115 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
9116 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
9119 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
9120 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
9121 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
9123 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
9124 HiV1Inputs.size() + HiV2Inputs.size();
9126 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
9127 ArrayRef<int> HiInputs, bool MoveToLo,
9129 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
9130 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
9131 if (BadInputs.empty())
9134 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9135 int MoveOffset = MoveToLo ? 0 : 4;
9137 if (GoodInputs.empty()) {
9138 for (int BadInput : BadInputs) {
9139 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
9140 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
9143 if (GoodInputs.size() == 2) {
9144 // If the low inputs are spread across two dwords, pack them into
9146 MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
9147 MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
9148 Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
9149 Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
9151 // Otherwise pin the good inputs.
9152 for (int GoodInput : GoodInputs)
9153 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
9156 if (BadInputs.size() == 2) {
9157 // If we have two bad inputs then there may be either one or two good
9158 // inputs fixed in place. Find a fixed input, and then find the *other*
9159 // two adjacent indices by using modular arithmetic.
9161 std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
9162 [](int M) { return M >= 0; }) -
9163 std::begin(MoveMask);
9165 ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
9166 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
9167 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
9168 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9169 MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
9170 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9171 Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
9173 assert(BadInputs.size() == 1 && "All sizes handled");
9174 int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
9175 std::end(MoveMask), -1) -
9176 std::begin(MoveMask);
9177 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9178 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9182 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
9185 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
9187 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
9190 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
9191 // cross-half traffic in the final shuffle.
9193 // Munge the mask to be a single-input mask after the unpack merges the
9197 M = 2 * (M % 4) + (M / 8);
9199 return DAG.getVectorShuffle(
9200 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
9201 DL, MVT::v8i16, V1, V2),
9202 DAG.getUNDEF(MVT::v8i16), Mask);
9205 /// \brief Generic lowering of 8-lane i16 shuffles.
9207 /// This handles both single-input shuffles and combined shuffle/blends with
9208 /// two inputs. The single input shuffles are immediately delegated to
9209 /// a dedicated lowering routine.
9211 /// The blends are lowered in one of three fundamental ways. If there are few
9212 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9213 /// of the input is significantly cheaper when lowered as an interleaving of
9214 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9215 /// halves of the inputs separately (making them have relatively few inputs)
9216 /// and then concatenate them.
9217 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9218 const X86Subtarget *Subtarget,
9219 SelectionDAG &DAG) {
9221 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9222 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9223 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9224 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9225 ArrayRef<int> OrigMask = SVOp->getMask();
9226 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9227 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9228 MutableArrayRef<int> Mask(MaskStorage);
9230 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9232 // Whenever we can lower this as a zext, that instruction is strictly faster
9233 // than any alternative.
9234 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9235 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9238 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9239 auto isV2 = [](int M) { return M >= 8; };
9241 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9242 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9244 if (NumV2Inputs == 0)
9245 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9247 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9248 "to be V1-input shuffles.");
9250 // Try to use byte shift instructions.
9251 if (SDValue Shift = lowerVectorShuffleAsByteShift(
9252 DL, MVT::v8i16, V1, V2, Mask, DAG))
9255 // There are special ways we can lower some single-element blends.
9256 if (NumV2Inputs == 1)
9257 if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9258 Mask, Subtarget, DAG))
9261 // Use dedicated unpack instructions for masks that match their pattern.
9262 if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9263 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9264 if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9265 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9267 if (Subtarget->hasSSE41())
9268 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9272 // Try to use byte rotation instructions.
9273 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9274 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9277 if (NumV1Inputs + NumV2Inputs <= 4)
9278 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9280 // Check whether an interleaving lowering is likely to be more efficient.
9281 // This isn't perfect but it is a strong heuristic that tends to work well on
9282 // the kinds of shuffles that show up in practice.
9284 // FIXME: Handle 1x, 2x, and 4x interleaving.
9285 if (shouldLowerAsInterleaving(Mask)) {
9286 // FIXME: Figure out whether we should pack these into the low or high
9289 int EMask[8], OMask[8];
9290 for (int i = 0; i < 4; ++i) {
9291 EMask[i] = Mask[2*i];
9292 OMask[i] = Mask[2*i + 1];
9297 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9298 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9300 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9303 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9304 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9306 for (int i = 0; i < 4; ++i) {
9307 LoBlendMask[i] = Mask[i];
9308 HiBlendMask[i] = Mask[i + 4];
9311 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9312 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9313 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9314 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9316 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9317 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9320 /// \brief Check whether a compaction lowering can be done by dropping even
9321 /// elements and compute how many times even elements must be dropped.
9323 /// This handles shuffles which take every Nth element where N is a power of
9324 /// two. Example shuffle masks:
9326 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9327 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9328 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9329 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9330 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9331 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9333 /// Any of these lanes can of course be undef.
9335 /// This routine only supports N <= 3.
9336 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9339 /// \returns N above, or the number of times even elements must be dropped if
9340 /// there is such a number. Otherwise returns zero.
9341 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9342 // Figure out whether we're looping over two inputs or just one.
9343 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9345 // The modulus for the shuffle vector entries is based on whether this is
9346 // a single input or not.
9347 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9348 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9349 "We should only be called with masks with a power-of-2 size!");
9351 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9353 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9354 // and 2^3 simultaneously. This is because we may have ambiguity with
9355 // partially undef inputs.
9356 bool ViableForN[3] = {true, true, true};
9358 for (int i = 0, e = Mask.size(); i < e; ++i) {
9359 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9364 bool IsAnyViable = false;
9365 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9366 if (ViableForN[j]) {
9369 // The shuffle mask must be equal to (i * 2^N) % M.
9370 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9373 ViableForN[j] = false;
9375 // Early exit if we exhaust the possible powers of two.
9380 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9384 // Return 0 as there is no viable power of two.
9388 /// \brief Generic lowering of v16i8 shuffles.
9390 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9391 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9392 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9393 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9395 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9396 const X86Subtarget *Subtarget,
9397 SelectionDAG &DAG) {
9399 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9400 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9401 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9402 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9403 ArrayRef<int> OrigMask = SVOp->getMask();
9404 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9406 // Try to use byte shift instructions.
9407 if (SDValue Shift = lowerVectorShuffleAsByteShift(
9408 DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9411 // Try to use byte rotation instructions.
9412 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9413 DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9416 // Try to use a zext lowering.
9417 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9418 DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9421 int MaskStorage[16] = {
9422 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9423 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
9424 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
9425 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9426 MutableArrayRef<int> Mask(MaskStorage);
9427 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9428 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9431 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9433 // For single-input shuffles, there are some nicer lowering tricks we can use.
9434 if (NumV2Elements == 0) {
9435 // Check for being able to broadcast a single element.
9436 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9437 Mask, Subtarget, DAG))
9440 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9441 // Notably, this handles splat and partial-splat shuffles more efficiently.
9442 // However, it only makes sense if the pre-duplication shuffle simplifies
9443 // things significantly. Currently, this means we need to be able to
9444 // express the pre-duplication shuffle as an i16 shuffle.
9446 // FIXME: We should check for other patterns which can be widened into an
9447 // i16 shuffle as well.
9448 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9449 for (int i = 0; i < 16; i += 2)
9450 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9455 auto tryToWidenViaDuplication = [&]() -> SDValue {
9456 if (!canWidenViaDuplication(Mask))
9458 SmallVector<int, 4> LoInputs;
9459 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9460 [](int M) { return M >= 0 && M < 8; });
9461 std::sort(LoInputs.begin(), LoInputs.end());
9462 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9464 SmallVector<int, 4> HiInputs;
9465 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9466 [](int M) { return M >= 8; });
9467 std::sort(HiInputs.begin(), HiInputs.end());
9468 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9471 bool TargetLo = LoInputs.size() >= HiInputs.size();
9472 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9473 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9475 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9476 SmallDenseMap<int, int, 8> LaneMap;
9477 for (int I : InPlaceInputs) {
9478 PreDupI16Shuffle[I/2] = I/2;
9481 int j = TargetLo ? 0 : 4, je = j + 4;
9482 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9483 // Check if j is already a shuffle of this input. This happens when
9484 // there are two adjacent bytes after we move the low one.
9485 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9486 // If we haven't yet mapped the input, search for a slot into which
9488 while (j < je && PreDupI16Shuffle[j] != -1)
9492 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9495 // Map this input with the i16 shuffle.
9496 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9499 // Update the lane map based on the mapping we ended up with.
9500 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9503 ISD::BITCAST, DL, MVT::v16i8,
9504 DAG.getVectorShuffle(MVT::v8i16, DL,
9505 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9506 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9508 // Unpack the bytes to form the i16s that will be shuffled into place.
9509 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9510 MVT::v16i8, V1, V1);
9512 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9513 for (int i = 0; i < 16; ++i)
9514 if (Mask[i] != -1) {
9515 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9516 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9517 if (PostDupI16Shuffle[i / 2] == -1)
9518 PostDupI16Shuffle[i / 2] = MappedMask;
9520 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9521 "Conflicting entrties in the original shuffle!");
9524 ISD::BITCAST, DL, MVT::v16i8,
9525 DAG.getVectorShuffle(MVT::v8i16, DL,
9526 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9527 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9529 if (SDValue V = tryToWidenViaDuplication())
9533 // Check whether an interleaving lowering is likely to be more efficient.
9534 // This isn't perfect but it is a strong heuristic that tends to work well on
9535 // the kinds of shuffles that show up in practice.
9537 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9538 if (shouldLowerAsInterleaving(Mask)) {
9539 int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9540 return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9542 int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9543 return (M >= 8 && M < 16) || M >= 24;
9545 int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9546 -1, -1, -1, -1, -1, -1, -1, -1};
9547 int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9548 -1, -1, -1, -1, -1, -1, -1, -1};
9549 bool UnpackLo = NumLoHalf >= NumHiHalf;
9550 MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9551 MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9552 for (int i = 0; i < 8; ++i) {
9553 TargetEMask[i] = Mask[2 * i];
9554 TargetOMask[i] = Mask[2 * i + 1];
9557 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9558 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9560 return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9561 MVT::v16i8, Evens, Odds);
9564 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9565 // with PSHUFB. It is important to do this before we attempt to generate any
9566 // blends but after all of the single-input lowerings. If the single input
9567 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9568 // want to preserve that and we can DAG combine any longer sequences into
9569 // a PSHUFB in the end. But once we start blending from multiple inputs,
9570 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9571 // and there are *very* few patterns that would actually be faster than the
9572 // PSHUFB approach because of its ability to zero lanes.
9574 // FIXME: The only exceptions to the above are blends which are exact
9575 // interleavings with direct instructions supporting them. We currently don't
9576 // handle those well here.
9577 if (Subtarget->hasSSSE3()) {
9580 for (int i = 0; i < 16; ++i)
9581 if (Mask[i] == -1) {
9582 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9584 V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9586 DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9588 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9589 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9590 if (isSingleInputShuffleMask(Mask))
9591 return V1; // Single inputs are easy.
9593 // Otherwise, blend the two.
9594 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9595 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9596 return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9599 // There are special ways we can lower some single-element blends.
9600 if (NumV2Elements == 1)
9601 if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9602 Mask, Subtarget, DAG))
9605 // Check whether a compaction lowering can be done. This handles shuffles
9606 // which take every Nth element for some even N. See the helper function for
9609 // We special case these as they can be particularly efficiently handled with
9610 // the PACKUSB instruction on x86 and they show up in common patterns of
9611 // rearranging bytes to truncate wide elements.
9612 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9613 // NumEvenDrops is the power of two stride of the elements. Another way of
9614 // thinking about it is that we need to drop the even elements this many
9615 // times to get the original input.
9616 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9618 // First we need to zero all the dropped bytes.
9619 assert(NumEvenDrops <= 3 &&
9620 "No support for dropping even elements more than 3 times.");
9621 // We use the mask type to pick which bytes are preserved based on how many
9622 // elements are dropped.
9623 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9624 SDValue ByteClearMask =
9625 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9626 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9627 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9629 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9631 // Now pack things back together.
9632 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9633 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9634 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9635 for (int i = 1; i < NumEvenDrops; ++i) {
9636 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9637 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9643 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9644 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9645 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9646 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9648 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9649 MutableArrayRef<int> V1HalfBlendMask,
9650 MutableArrayRef<int> V2HalfBlendMask) {
9651 for (int i = 0; i < 8; ++i)
9652 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9653 V1HalfBlendMask[i] = HalfMask[i];
9655 } else if (HalfMask[i] >= 16) {
9656 V2HalfBlendMask[i] = HalfMask[i] - 16;
9657 HalfMask[i] = i + 8;
9660 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9661 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9663 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9665 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9666 MutableArrayRef<int> HiBlendMask) {
9668 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9669 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9671 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9672 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9673 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9674 [](int M) { return M >= 0 && M % 2 == 1; })) {
9675 // Use a mask to drop the high bytes.
9676 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9677 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9678 DAG.getConstant(0x00FF, MVT::v8i16));
9680 // This will be a single vector shuffle instead of a blend so nuke V2.
9681 V2 = DAG.getUNDEF(MVT::v8i16);
9683 // Squash the masks to point directly into V1.
9684 for (int &M : LoBlendMask)
9687 for (int &M : HiBlendMask)
9691 // Otherwise just unpack the low half of V into V1 and the high half into
9692 // V2 so that we can blend them as i16s.
9693 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9694 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9695 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9696 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9699 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9700 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9701 return std::make_pair(BlendedLo, BlendedHi);
9703 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9704 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9705 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9707 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9708 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9710 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9713 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9715 /// This routine breaks down the specific type of 128-bit shuffle and
9716 /// dispatches to the lowering routines accordingly.
9717 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9718 MVT VT, const X86Subtarget *Subtarget,
9719 SelectionDAG &DAG) {
9720 switch (VT.SimpleTy) {
9722 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9724 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9726 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9728 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9730 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9732 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9735 llvm_unreachable("Unimplemented!");
9739 /// \brief Helper function to test whether a shuffle mask could be
9740 /// simplified by widening the elements being shuffled.
9742 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9743 /// leaves it in an unspecified state.
9745 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9746 /// shuffle masks. The latter have the special property of a '-2' representing
9747 /// a zero-ed lane of a vector.
9748 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9749 SmallVectorImpl<int> &WidenedMask) {
9750 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9751 // If both elements are undef, its trivial.
9752 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9753 WidenedMask.push_back(SM_SentinelUndef);
9757 // Check for an undef mask and a mask value properly aligned to fit with
9758 // a pair of values. If we find such a case, use the non-undef mask's value.
9759 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9760 WidenedMask.push_back(Mask[i + 1] / 2);
9763 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9764 WidenedMask.push_back(Mask[i] / 2);
9768 // When zeroing, we need to spread the zeroing across both lanes to widen.
9769 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9770 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9771 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9772 WidenedMask.push_back(SM_SentinelZero);
9778 // Finally check if the two mask values are adjacent and aligned with
9780 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9781 WidenedMask.push_back(Mask[i] / 2);
9785 // Otherwise we can't safely widen the elements used in this shuffle.
9788 assert(WidenedMask.size() == Mask.size() / 2 &&
9789 "Incorrect size of mask after widening the elements!");
9794 /// \brief Generic routine to split ector shuffle into half-sized shuffles.
9796 /// This routine just extracts two subvectors, shuffles them independently, and
9797 /// then concatenates them back together. This should work effectively with all
9798 /// AVX vector shuffle types.
9799 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9800 SDValue V2, ArrayRef<int> Mask,
9801 SelectionDAG &DAG) {
9802 assert(VT.getSizeInBits() >= 256 &&
9803 "Only for 256-bit or wider vector shuffles!");
9804 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9805 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9807 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9808 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9810 int NumElements = VT.getVectorNumElements();
9811 int SplitNumElements = NumElements / 2;
9812 MVT ScalarVT = VT.getScalarType();
9813 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9815 SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9816 DAG.getIntPtrConstant(0));
9817 SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9818 DAG.getIntPtrConstant(SplitNumElements));
9819 SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9820 DAG.getIntPtrConstant(0));
9821 SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9822 DAG.getIntPtrConstant(SplitNumElements));
9824 // Now create two 4-way blends of these half-width vectors.
9825 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9826 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9827 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9828 for (int i = 0; i < SplitNumElements; ++i) {
9829 int M = HalfMask[i];
9830 if (M >= NumElements) {
9831 if (M >= NumElements + SplitNumElements)
9835 V2BlendMask.push_back(M - NumElements);
9836 V1BlendMask.push_back(-1);
9837 BlendMask.push_back(SplitNumElements + i);
9838 } else if (M >= 0) {
9839 if (M >= SplitNumElements)
9843 V2BlendMask.push_back(-1);
9844 V1BlendMask.push_back(M);
9845 BlendMask.push_back(i);
9847 V2BlendMask.push_back(-1);
9848 V1BlendMask.push_back(-1);
9849 BlendMask.push_back(-1);
9853 // Because the lowering happens after all combining takes place, we need to
9854 // manually combine these blend masks as much as possible so that we create
9855 // a minimal number of high-level vector shuffle nodes.
9857 // First try just blending the halves of V1 or V2.
9858 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9859 return DAG.getUNDEF(SplitVT);
9860 if (!UseLoV2 && !UseHiV2)
9861 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9862 if (!UseLoV1 && !UseHiV1)
9863 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9865 SDValue V1Blend, V2Blend;
9866 if (UseLoV1 && UseHiV1) {
9868 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9870 // We only use half of V1 so map the usage down into the final blend mask.
9871 V1Blend = UseLoV1 ? LoV1 : HiV1;
9872 for (int i = 0; i < SplitNumElements; ++i)
9873 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9874 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9876 if (UseLoV2 && UseHiV2) {
9878 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9880 // We only use half of V2 so map the usage down into the final blend mask.
9881 V2Blend = UseLoV2 ? LoV2 : HiV2;
9882 for (int i = 0; i < SplitNumElements; ++i)
9883 if (BlendMask[i] >= SplitNumElements)
9884 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9886 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9888 SDValue Lo = HalfBlend(LoMask);
9889 SDValue Hi = HalfBlend(HiMask);
9890 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9893 /// \brief Either split a vector in halves or decompose the shuffles and the
9896 /// This is provided as a good fallback for many lowerings of non-single-input
9897 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9898 /// between splitting the shuffle into 128-bit components and stitching those
9899 /// back together vs. extracting the single-input shuffles and blending those
9901 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9902 SDValue V2, ArrayRef<int> Mask,
9903 SelectionDAG &DAG) {
9904 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9905 "lower single-input shuffles as it "
9906 "could then recurse on itself.");
9907 int Size = Mask.size();
9909 // If this can be modeled as a broadcast of two elements followed by a blend,
9910 // prefer that lowering. This is especially important because broadcasts can
9911 // often fold with memory operands.
9912 auto DoBothBroadcast = [&] {
9913 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9916 if (V2BroadcastIdx == -1)
9917 V2BroadcastIdx = M - Size;
9918 else if (M - Size != V2BroadcastIdx)
9920 } else if (M >= 0) {
9921 if (V1BroadcastIdx == -1)
9923 else if (M != V1BroadcastIdx)
9928 if (DoBothBroadcast())
9929 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9932 // If the inputs all stem from a single 128-bit lane of each input, then we
9933 // split them rather than blending because the split will decompose to
9934 // unusually few instructions.
9935 int LaneCount = VT.getSizeInBits() / 128;
9936 int LaneSize = Size / LaneCount;
9937 SmallBitVector LaneInputs[2];
9938 LaneInputs[0].resize(LaneCount, false);
9939 LaneInputs[1].resize(LaneCount, false);
9940 for (int i = 0; i < Size; ++i)
9942 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9943 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9944 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9946 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9947 // that the decomposed single-input shuffles don't end up here.
9948 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9951 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9952 /// a permutation and blend of those lanes.
9954 /// This essentially blends the out-of-lane inputs to each lane into the lane
9955 /// from a permuted copy of the vector. This lowering strategy results in four
9956 /// instructions in the worst case for a single-input cross lane shuffle which
9957 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9958 /// of. Special cases for each particular shuffle pattern should be handled
9959 /// prior to trying this lowering.
9960 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9961 SDValue V1, SDValue V2,
9963 SelectionDAG &DAG) {
9964 // FIXME: This should probably be generalized for 512-bit vectors as well.
9965 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9966 int LaneSize = Mask.size() / 2;
9968 // If there are only inputs from one 128-bit lane, splitting will in fact be
9969 // less expensive. The flags track wether the given lane contains an element
9970 // that crosses to another lane.
9971 bool LaneCrossing[2] = {false, false};
9972 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9973 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9974 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9975 if (!LaneCrossing[0] || !LaneCrossing[1])
9976 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9978 if (isSingleInputShuffleMask(Mask)) {
9979 SmallVector<int, 32> FlippedBlendMask;
9980 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9981 FlippedBlendMask.push_back(
9982 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9984 : Mask[i] % LaneSize +
9985 (i / LaneSize) * LaneSize + Size));
9987 // Flip the vector, and blend the results which should now be in-lane. The
9988 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9989 // 5 for the high source. The value 3 selects the high half of source 2 and
9990 // the value 2 selects the low half of source 2. We only use source 2 to
9991 // allow folding it into a memory operand.
9992 unsigned PERMMask = 3 | 2 << 4;
9993 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9994 V1, DAG.getConstant(PERMMask, MVT::i8));
9995 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9998 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9999 // will be handled by the above logic and a blend of the results, much like
10000 // other patterns in AVX.
10001 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10004 /// \brief Handle lowering 2-lane 128-bit shuffles.
10005 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10006 SDValue V2, ArrayRef<int> Mask,
10007 const X86Subtarget *Subtarget,
10008 SelectionDAG &DAG) {
10009 // Blends are faster and handle all the non-lane-crossing cases.
10010 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10014 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10015 VT.getVectorNumElements() / 2);
10016 // Check for patterns which can be matched with a single insert of a 128-bit
10018 if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
10019 isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
10020 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10021 DAG.getIntPtrConstant(0));
10022 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10023 Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
10024 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10026 if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
10027 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10028 DAG.getIntPtrConstant(0));
10029 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
10030 DAG.getIntPtrConstant(2));
10031 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10034 // Otherwise form a 128-bit permutation.
10035 // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
10036 unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
10037 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10038 DAG.getConstant(PermMask, MVT::i8));
10041 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10042 /// shuffling each lane.
10044 /// This will only succeed when the result of fixing the 128-bit lanes results
10045 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10046 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10047 /// the lane crosses early and then use simpler shuffles within each lane.
10049 /// FIXME: It might be worthwhile at some point to support this without
10050 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10051 /// in x86 only floating point has interesting non-repeating shuffles, and even
10052 /// those are still *marginally* more expensive.
10053 static SDValue lowerVectorShuffleByMerging128BitLanes(
10054 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10055 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10056 assert(!isSingleInputShuffleMask(Mask) &&
10057 "This is only useful with multiple inputs.");
10059 int Size = Mask.size();
10060 int LaneSize = 128 / VT.getScalarSizeInBits();
10061 int NumLanes = Size / LaneSize;
10062 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10064 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10065 // check whether the in-128-bit lane shuffles share a repeating pattern.
10066 SmallVector<int, 4> Lanes;
10067 Lanes.resize(NumLanes, -1);
10068 SmallVector<int, 4> InLaneMask;
10069 InLaneMask.resize(LaneSize, -1);
10070 for (int i = 0; i < Size; ++i) {
10074 int j = i / LaneSize;
10076 if (Lanes[j] < 0) {
10077 // First entry we've seen for this lane.
10078 Lanes[j] = Mask[i] / LaneSize;
10079 } else if (Lanes[j] != Mask[i] / LaneSize) {
10080 // This doesn't match the lane selected previously!
10084 // Check that within each lane we have a consistent shuffle mask.
10085 int k = i % LaneSize;
10086 if (InLaneMask[k] < 0) {
10087 InLaneMask[k] = Mask[i] % LaneSize;
10088 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10089 // This doesn't fit a repeating in-lane mask.
10094 // First shuffle the lanes into place.
10095 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10096 VT.getSizeInBits() / 64);
10097 SmallVector<int, 8> LaneMask;
10098 LaneMask.resize(NumLanes * 2, -1);
10099 for (int i = 0; i < NumLanes; ++i)
10100 if (Lanes[i] >= 0) {
10101 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10102 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10105 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
10106 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
10107 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10109 // Cast it back to the type we actually want.
10110 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
10112 // Now do a simple shuffle that isn't lane crossing.
10113 SmallVector<int, 8> NewMask;
10114 NewMask.resize(Size, -1);
10115 for (int i = 0; i < Size; ++i)
10117 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10118 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10119 "Must not introduce lane crosses at this point!");
10121 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10124 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10127 /// This returns true if the elements from a particular input are already in the
10128 /// slot required by the given mask and require no permutation.
10129 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10130 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10131 int Size = Mask.size();
10132 for (int i = 0; i < Size; ++i)
10133 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10139 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10141 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10142 /// isn't available.
10143 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10144 const X86Subtarget *Subtarget,
10145 SelectionDAG &DAG) {
10147 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10148 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10149 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10150 ArrayRef<int> Mask = SVOp->getMask();
10151 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10153 SmallVector<int, 4> WidenedMask;
10154 if (canWidenShuffleElements(Mask, WidenedMask))
10155 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10158 if (isSingleInputShuffleMask(Mask)) {
10159 // Check for being able to broadcast a single element.
10160 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
10161 Mask, Subtarget, DAG))
10164 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10165 // Non-half-crossing single input shuffles can be lowerid with an
10166 // interleaved permutation.
10167 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10168 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10169 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10170 DAG.getConstant(VPERMILPMask, MVT::i8));
10173 // With AVX2 we have direct support for this permutation.
10174 if (Subtarget->hasAVX2())
10175 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10176 getV4X86ShuffleImm8ForMask(Mask, DAG));
10178 // Otherwise, fall back.
10179 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10183 // X86 has dedicated unpack instructions that can handle specific blend
10184 // operations: UNPCKH and UNPCKL.
10185 if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10186 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10187 if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10188 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10190 // If we have a single input to the zero element, insert that into V1 if we
10191 // can do so cheaply.
10192 int NumV2Elements =
10193 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
10194 if (NumV2Elements == 1 && Mask[0] >= 4)
10195 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10196 MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
10199 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10203 // Check if the blend happens to exactly fit that of SHUFPD.
10204 if ((Mask[0] == -1 || Mask[0] < 2) &&
10205 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
10206 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
10207 (Mask[3] == -1 || Mask[3] >= 6)) {
10208 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
10209 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
10210 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
10211 DAG.getConstant(SHUFPDMask, MVT::i8));
10213 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
10214 (Mask[1] == -1 || Mask[1] < 2) &&
10215 (Mask[2] == -1 || Mask[2] >= 6) &&
10216 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
10217 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
10218 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
10219 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
10220 DAG.getConstant(SHUFPDMask, MVT::i8));
10223 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10224 // shuffle. However, if we have AVX2 and either inputs are already in place,
10225 // we will be able to shuffle even across lanes the other input in a single
10226 // instruction so skip this pattern.
10227 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10228 isShuffleMaskInputInPlace(1, Mask))))
10229 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10230 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10233 // If we have AVX2 then we always want to lower with a blend because an v4 we
10234 // can fully permute the elements.
10235 if (Subtarget->hasAVX2())
10236 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10239 // Otherwise fall back on generic lowering.
10240 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10243 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10245 /// This routine is only called when we have AVX2 and thus a reasonable
10246 /// instruction set for v4i64 shuffling..
10247 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10248 const X86Subtarget *Subtarget,
10249 SelectionDAG &DAG) {
10251 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10252 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10253 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10254 ArrayRef<int> Mask = SVOp->getMask();
10255 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10256 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10258 SmallVector<int, 4> WidenedMask;
10259 if (canWidenShuffleElements(Mask, WidenedMask))
10260 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10263 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10267 // Check for being able to broadcast a single element.
10268 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
10269 Mask, Subtarget, DAG))
10272 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10273 // use lower latency instructions that will operate on both 128-bit lanes.
10274 SmallVector<int, 2> RepeatedMask;
10275 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10276 if (isSingleInputShuffleMask(Mask)) {
10277 int PSHUFDMask[] = {-1, -1, -1, -1};
10278 for (int i = 0; i < 2; ++i)
10279 if (RepeatedMask[i] >= 0) {
10280 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10281 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10283 return DAG.getNode(
10284 ISD::BITCAST, DL, MVT::v4i64,
10285 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10286 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
10287 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
10290 // Use dedicated unpack instructions for masks that match their pattern.
10291 if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10292 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10293 if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10294 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10297 // AVX2 provides a direct instruction for permuting a single input across
10299 if (isSingleInputShuffleMask(Mask))
10300 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10301 getV4X86ShuffleImm8ForMask(Mask, DAG));
10303 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10304 // shuffle. However, if we have AVX2 and either inputs are already in place,
10305 // we will be able to shuffle even across lanes the other input in a single
10306 // instruction so skip this pattern.
10307 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10308 isShuffleMaskInputInPlace(1, Mask))))
10309 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10310 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10313 // Otherwise fall back on generic blend lowering.
10314 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10318 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10320 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10321 /// isn't available.
10322 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10323 const X86Subtarget *Subtarget,
10324 SelectionDAG &DAG) {
10326 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10327 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10328 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10329 ArrayRef<int> Mask = SVOp->getMask();
10330 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10332 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10336 // Check for being able to broadcast a single element.
10337 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
10338 Mask, Subtarget, DAG))
10341 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10342 // options to efficiently lower the shuffle.
10343 SmallVector<int, 4> RepeatedMask;
10344 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10345 assert(RepeatedMask.size() == 4 &&
10346 "Repeated masks must be half the mask width!");
10347 if (isSingleInputShuffleMask(Mask))
10348 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10349 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10351 // Use dedicated unpack instructions for masks that match their pattern.
10352 if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10353 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10354 if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10355 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10357 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10358 // have already handled any direct blends. We also need to squash the
10359 // repeated mask into a simulated v4f32 mask.
10360 for (int i = 0; i < 4; ++i)
10361 if (RepeatedMask[i] >= 8)
10362 RepeatedMask[i] -= 4;
10363 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10366 // If we have a single input shuffle with different shuffle patterns in the
10367 // two 128-bit lanes use the variable mask to VPERMILPS.
10368 if (isSingleInputShuffleMask(Mask)) {
10369 SDValue VPermMask[8];
10370 for (int i = 0; i < 8; ++i)
10371 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10372 : DAG.getConstant(Mask[i], MVT::i32);
10373 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10374 return DAG.getNode(
10375 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10376 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10378 if (Subtarget->hasAVX2())
10379 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
10380 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
10381 DAG.getNode(ISD::BUILD_VECTOR, DL,
10382 MVT::v8i32, VPermMask)),
10385 // Otherwise, fall back.
10386 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10390 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10392 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10393 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10396 // If we have AVX2 then we always want to lower with a blend because at v8 we
10397 // can fully permute the elements.
10398 if (Subtarget->hasAVX2())
10399 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10402 // Otherwise fall back on generic lowering.
10403 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10406 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10408 /// This routine is only called when we have AVX2 and thus a reasonable
10409 /// instruction set for v8i32 shuffling..
10410 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10411 const X86Subtarget *Subtarget,
10412 SelectionDAG &DAG) {
10414 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10415 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10416 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10417 ArrayRef<int> Mask = SVOp->getMask();
10418 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10419 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10421 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10425 // Check for being able to broadcast a single element.
10426 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10427 Mask, Subtarget, DAG))
10430 // If the shuffle mask is repeated in each 128-bit lane we can use more
10431 // efficient instructions that mirror the shuffles across the two 128-bit
10433 SmallVector<int, 4> RepeatedMask;
10434 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10435 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10436 if (isSingleInputShuffleMask(Mask))
10437 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10438 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10440 // Use dedicated unpack instructions for masks that match their pattern.
10441 if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10442 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10443 if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10444 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10447 // If the shuffle patterns aren't repeated but it is a single input, directly
10448 // generate a cross-lane VPERMD instruction.
10449 if (isSingleInputShuffleMask(Mask)) {
10450 SDValue VPermMask[8];
10451 for (int i = 0; i < 8; ++i)
10452 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10453 : DAG.getConstant(Mask[i], MVT::i32);
10454 return DAG.getNode(
10455 X86ISD::VPERMV, DL, MVT::v8i32,
10456 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10459 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10461 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10462 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10465 // Otherwise fall back on generic blend lowering.
10466 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10470 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10472 /// This routine is only called when we have AVX2 and thus a reasonable
10473 /// instruction set for v16i16 shuffling..
10474 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10475 const X86Subtarget *Subtarget,
10476 SelectionDAG &DAG) {
10478 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10479 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10480 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10481 ArrayRef<int> Mask = SVOp->getMask();
10482 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10483 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10485 // Check for being able to broadcast a single element.
10486 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10487 Mask, Subtarget, DAG))
10490 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10494 // Use dedicated unpack instructions for masks that match their pattern.
10495 if (isShuffleEquivalent(Mask,
10496 // First 128-bit lane:
10497 0, 16, 1, 17, 2, 18, 3, 19,
10498 // Second 128-bit lane:
10499 8, 24, 9, 25, 10, 26, 11, 27))
10500 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10501 if (isShuffleEquivalent(Mask,
10502 // First 128-bit lane:
10503 4, 20, 5, 21, 6, 22, 7, 23,
10504 // Second 128-bit lane:
10505 12, 28, 13, 29, 14, 30, 15, 31))
10506 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10508 if (isSingleInputShuffleMask(Mask)) {
10509 // There are no generalized cross-lane shuffle operations available on i16
10511 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10512 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10515 SDValue PSHUFBMask[32];
10516 for (int i = 0; i < 16; ++i) {
10517 if (Mask[i] == -1) {
10518 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10522 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10523 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10524 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10525 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10527 return DAG.getNode(
10528 ISD::BITCAST, DL, MVT::v16i16,
10530 X86ISD::PSHUFB, DL, MVT::v32i8,
10531 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10532 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10535 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10537 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10538 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10541 // Otherwise fall back on generic lowering.
10542 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10545 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10547 /// This routine is only called when we have AVX2 and thus a reasonable
10548 /// instruction set for v32i8 shuffling..
10549 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10550 const X86Subtarget *Subtarget,
10551 SelectionDAG &DAG) {
10553 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10554 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10555 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10556 ArrayRef<int> Mask = SVOp->getMask();
10557 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10558 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10560 // Check for being able to broadcast a single element.
10561 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10562 Mask, Subtarget, DAG))
10565 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10569 // Use dedicated unpack instructions for masks that match their pattern.
10570 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10572 if (isShuffleEquivalent(
10574 // First 128-bit lane:
10575 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10576 // Second 128-bit lane:
10577 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10578 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10579 if (isShuffleEquivalent(
10581 // First 128-bit lane:
10582 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10583 // Second 128-bit lane:
10584 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10585 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10587 if (isSingleInputShuffleMask(Mask)) {
10588 // There are no generalized cross-lane shuffle operations available on i8
10590 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10591 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10594 SDValue PSHUFBMask[32];
10595 for (int i = 0; i < 32; ++i)
10598 ? DAG.getUNDEF(MVT::i8)
10599 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10601 return DAG.getNode(
10602 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10603 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10606 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10608 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10609 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10612 // Otherwise fall back on generic lowering.
10613 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10616 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10618 /// This routine either breaks down the specific type of a 256-bit x86 vector
10619 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10620 /// together based on the available instructions.
10621 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10622 MVT VT, const X86Subtarget *Subtarget,
10623 SelectionDAG &DAG) {
10625 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10626 ArrayRef<int> Mask = SVOp->getMask();
10628 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10629 // check for those subtargets here and avoid much of the subtarget querying in
10630 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10631 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10632 // floating point types there eventually, just immediately cast everything to
10633 // a float and operate entirely in that domain.
10634 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10635 int ElementBits = VT.getScalarSizeInBits();
10636 if (ElementBits < 32)
10637 // No floating point type available, decompose into 128-bit vectors.
10638 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10640 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10641 VT.getVectorNumElements());
10642 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10643 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10644 return DAG.getNode(ISD::BITCAST, DL, VT,
10645 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10648 switch (VT.SimpleTy) {
10650 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10652 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10654 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10656 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10658 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10660 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10663 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10667 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10668 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10669 const X86Subtarget *Subtarget,
10670 SelectionDAG &DAG) {
10672 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10673 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10674 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10675 ArrayRef<int> Mask = SVOp->getMask();
10676 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10678 // FIXME: Implement direct support for this type!
10679 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10682 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10683 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10684 const X86Subtarget *Subtarget,
10685 SelectionDAG &DAG) {
10687 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10688 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10689 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10690 ArrayRef<int> Mask = SVOp->getMask();
10691 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10693 // FIXME: Implement direct support for this type!
10694 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10697 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10698 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10699 const X86Subtarget *Subtarget,
10700 SelectionDAG &DAG) {
10702 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10703 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10704 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10705 ArrayRef<int> Mask = SVOp->getMask();
10706 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10708 // FIXME: Implement direct support for this type!
10709 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10712 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10713 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10714 const X86Subtarget *Subtarget,
10715 SelectionDAG &DAG) {
10717 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10718 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10719 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10720 ArrayRef<int> Mask = SVOp->getMask();
10721 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10723 // FIXME: Implement direct support for this type!
10724 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10727 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10728 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10729 const X86Subtarget *Subtarget,
10730 SelectionDAG &DAG) {
10732 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10733 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10734 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10735 ArrayRef<int> Mask = SVOp->getMask();
10736 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10737 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10739 // FIXME: Implement direct support for this type!
10740 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10743 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10744 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10745 const X86Subtarget *Subtarget,
10746 SelectionDAG &DAG) {
10748 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10749 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10750 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10751 ArrayRef<int> Mask = SVOp->getMask();
10752 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10753 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10755 // FIXME: Implement direct support for this type!
10756 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10759 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10761 /// This routine either breaks down the specific type of a 512-bit x86 vector
10762 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10763 /// together based on the available instructions.
10764 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10765 MVT VT, const X86Subtarget *Subtarget,
10766 SelectionDAG &DAG) {
10768 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10769 ArrayRef<int> Mask = SVOp->getMask();
10770 assert(Subtarget->hasAVX512() &&
10771 "Cannot lower 512-bit vectors w/ basic ISA!");
10773 // Check for being able to broadcast a single element.
10774 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
10775 Mask, Subtarget, DAG))
10778 // Dispatch to each element type for lowering. If we don't have supprot for
10779 // specific element type shuffles at 512 bits, immediately split them and
10780 // lower them. Each lowering routine of a given type is allowed to assume that
10781 // the requisite ISA extensions for that element type are available.
10782 switch (VT.SimpleTy) {
10784 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10786 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10788 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10790 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10792 if (Subtarget->hasBWI())
10793 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10796 if (Subtarget->hasBWI())
10797 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10801 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10804 // Otherwise fall back on splitting.
10805 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10808 /// \brief Top-level lowering for x86 vector shuffles.
10810 /// This handles decomposition, canonicalization, and lowering of all x86
10811 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10812 /// above in helper routines. The canonicalization attempts to widen shuffles
10813 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10814 /// s.t. only one of the two inputs needs to be tested, etc.
10815 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10816 SelectionDAG &DAG) {
10817 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10818 ArrayRef<int> Mask = SVOp->getMask();
10819 SDValue V1 = Op.getOperand(0);
10820 SDValue V2 = Op.getOperand(1);
10821 MVT VT = Op.getSimpleValueType();
10822 int NumElements = VT.getVectorNumElements();
10825 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10827 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10828 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10829 if (V1IsUndef && V2IsUndef)
10830 return DAG.getUNDEF(VT);
10832 // When we create a shuffle node we put the UNDEF node to second operand,
10833 // but in some cases the first operand may be transformed to UNDEF.
10834 // In this case we should just commute the node.
10836 return DAG.getCommutedVectorShuffle(*SVOp);
10838 // Check for non-undef masks pointing at an undef vector and make the masks
10839 // undef as well. This makes it easier to match the shuffle based solely on
10843 if (M >= NumElements) {
10844 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10845 for (int &M : NewMask)
10846 if (M >= NumElements)
10848 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10851 // Try to collapse shuffles into using a vector type with fewer elements but
10852 // wider element types. We cap this to not form integers or floating point
10853 // elements wider than 64 bits, but it might be interesting to form i128
10854 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10855 SmallVector<int, 16> WidenedMask;
10856 if (VT.getScalarSizeInBits() < 64 &&
10857 canWidenShuffleElements(Mask, WidenedMask)) {
10858 MVT NewEltVT = VT.isFloatingPoint()
10859 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10860 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10861 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10862 // Make sure that the new vector type is legal. For example, v2f64 isn't
10864 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10865 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10866 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10867 return DAG.getNode(ISD::BITCAST, dl, VT,
10868 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10872 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10873 for (int M : SVOp->getMask())
10875 ++NumUndefElements;
10876 else if (M < NumElements)
10881 // Commute the shuffle as needed such that more elements come from V1 than
10882 // V2. This allows us to match the shuffle pattern strictly on how many
10883 // elements come from V1 without handling the symmetric cases.
10884 if (NumV2Elements > NumV1Elements)
10885 return DAG.getCommutedVectorShuffle(*SVOp);
10887 // When the number of V1 and V2 elements are the same, try to minimize the
10888 // number of uses of V2 in the low half of the vector. When that is tied,
10889 // ensure that the sum of indices for V1 is equal to or lower than the sum
10890 // indices for V2. When those are equal, try to ensure that the number of odd
10891 // indices for V1 is lower than the number of odd indices for V2.
10892 if (NumV1Elements == NumV2Elements) {
10893 int LowV1Elements = 0, LowV2Elements = 0;
10894 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10895 if (M >= NumElements)
10899 if (LowV2Elements > LowV1Elements) {
10900 return DAG.getCommutedVectorShuffle(*SVOp);
10901 } else if (LowV2Elements == LowV1Elements) {
10902 int SumV1Indices = 0, SumV2Indices = 0;
10903 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10904 if (SVOp->getMask()[i] >= NumElements)
10906 else if (SVOp->getMask()[i] >= 0)
10908 if (SumV2Indices < SumV1Indices) {
10909 return DAG.getCommutedVectorShuffle(*SVOp);
10910 } else if (SumV2Indices == SumV1Indices) {
10911 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10912 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10913 if (SVOp->getMask()[i] >= NumElements)
10914 NumV2OddIndices += i % 2;
10915 else if (SVOp->getMask()[i] >= 0)
10916 NumV1OddIndices += i % 2;
10917 if (NumV2OddIndices < NumV1OddIndices)
10918 return DAG.getCommutedVectorShuffle(*SVOp);
10923 // For each vector width, delegate to a specialized lowering routine.
10924 if (VT.getSizeInBits() == 128)
10925 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10927 if (VT.getSizeInBits() == 256)
10928 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10930 // Force AVX-512 vectors to be scalarized for now.
10931 // FIXME: Implement AVX-512 support!
10932 if (VT.getSizeInBits() == 512)
10933 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10935 llvm_unreachable("Unimplemented!");
10939 //===----------------------------------------------------------------------===//
10940 // Legacy vector shuffle lowering
10942 // This code is the legacy code handling vector shuffles until the above
10943 // replaces its functionality and performance.
10944 //===----------------------------------------------------------------------===//
10946 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
10947 bool hasInt256, unsigned *MaskOut = nullptr) {
10948 MVT EltVT = VT.getVectorElementType();
10950 // There is no blend with immediate in AVX-512.
10951 if (VT.is512BitVector())
10954 if (!hasSSE41 || EltVT == MVT::i8)
10956 if (!hasInt256 && VT == MVT::v16i16)
10959 unsigned MaskValue = 0;
10960 unsigned NumElems = VT.getVectorNumElements();
10961 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10962 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10963 unsigned NumElemsInLane = NumElems / NumLanes;
10965 // Blend for v16i16 should be symetric for the both lanes.
10966 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10968 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
10969 int EltIdx = MaskVals[i];
10971 if ((EltIdx < 0 || EltIdx == (int)i) &&
10972 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
10975 if (((unsigned)EltIdx == (i + NumElems)) &&
10976 (SndLaneEltIdx < 0 ||
10977 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
10978 MaskValue |= (1 << i);
10984 *MaskOut = MaskValue;
10988 // Try to lower a shuffle node into a simple blend instruction.
10989 // This function assumes isBlendMask returns true for this
10990 // SuffleVectorSDNode
10991 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
10992 unsigned MaskValue,
10993 const X86Subtarget *Subtarget,
10994 SelectionDAG &DAG) {
10995 MVT VT = SVOp->getSimpleValueType(0);
10996 MVT EltVT = VT.getVectorElementType();
10997 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
10998 Subtarget->hasInt256() && "Trying to lower a "
10999 "VECTOR_SHUFFLE to a Blend but "
11000 "with the wrong mask"));
11001 SDValue V1 = SVOp->getOperand(0);
11002 SDValue V2 = SVOp->getOperand(1);
11004 unsigned NumElems = VT.getVectorNumElements();
11006 // Convert i32 vectors to floating point if it is not AVX2.
11007 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
11009 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
11010 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
11012 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
11013 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
11016 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
11017 DAG.getConstant(MaskValue, MVT::i32));
11018 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
11021 /// In vector type \p VT, return true if the element at index \p InputIdx
11022 /// falls on a different 128-bit lane than \p OutputIdx.
11023 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
11024 unsigned OutputIdx) {
11025 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
11026 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
11029 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
11030 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
11031 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
11032 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
11034 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
11035 SelectionDAG &DAG) {
11036 MVT VT = V1.getSimpleValueType();
11037 assert(VT.is128BitVector() || VT.is256BitVector());
11039 MVT EltVT = VT.getVectorElementType();
11040 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
11041 unsigned NumElts = VT.getVectorNumElements();
11043 SmallVector<SDValue, 32> PshufbMask;
11044 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
11045 int InputIdx = MaskVals[OutputIdx];
11046 unsigned InputByteIdx;
11048 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
11049 InputByteIdx = 0x80;
11051 // Cross lane is not allowed.
11052 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
11054 InputByteIdx = InputIdx * EltSizeInBytes;
11055 // Index is an byte offset within the 128-bit lane.
11056 InputByteIdx &= 0xf;
11059 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
11060 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
11061 if (InputByteIdx != 0x80)
11066 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
11068 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
11069 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
11070 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
11073 // v8i16 shuffles - Prefer shuffles in the following order:
11074 // 1. [all] pshuflw, pshufhw, optional move
11075 // 2. [ssse3] 1 x pshufb
11076 // 3. [ssse3] 2 x pshufb + 1 x por
11077 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
11079 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
11080 SelectionDAG &DAG) {
11081 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11082 SDValue V1 = SVOp->getOperand(0);
11083 SDValue V2 = SVOp->getOperand(1);
11085 SmallVector<int, 8> MaskVals;
11087 // Determine if more than 1 of the words in each of the low and high quadwords
11088 // of the result come from the same quadword of one of the two inputs. Undef
11089 // mask values count as coming from any quadword, for better codegen.
11091 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
11092 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
11093 unsigned LoQuad[] = { 0, 0, 0, 0 };
11094 unsigned HiQuad[] = { 0, 0, 0, 0 };
11095 // Indices of quads used.
11096 std::bitset<4> InputQuads;
11097 for (unsigned i = 0; i < 8; ++i) {
11098 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
11099 int EltIdx = SVOp->getMaskElt(i);
11100 MaskVals.push_back(EltIdx);
11108 ++Quad[EltIdx / 4];
11109 InputQuads.set(EltIdx / 4);
11112 int BestLoQuad = -1;
11113 unsigned MaxQuad = 1;
11114 for (unsigned i = 0; i < 4; ++i) {
11115 if (LoQuad[i] > MaxQuad) {
11117 MaxQuad = LoQuad[i];
11121 int BestHiQuad = -1;
11123 for (unsigned i = 0; i < 4; ++i) {
11124 if (HiQuad[i] > MaxQuad) {
11126 MaxQuad = HiQuad[i];
11130 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
11131 // of the two input vectors, shuffle them into one input vector so only a
11132 // single pshufb instruction is necessary. If there are more than 2 input
11133 // quads, disable the next transformation since it does not help SSSE3.
11134 bool V1Used = InputQuads[0] || InputQuads[1];
11135 bool V2Used = InputQuads[2] || InputQuads[3];
11136 if (Subtarget->hasSSSE3()) {
11137 if (InputQuads.count() == 2 && V1Used && V2Used) {
11138 BestLoQuad = InputQuads[0] ? 0 : 1;
11139 BestHiQuad = InputQuads[2] ? 2 : 3;
11141 if (InputQuads.count() > 2) {
11147 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
11148 // the shuffle mask. If a quad is scored as -1, that means that it contains
11149 // words from all 4 input quadwords.
11151 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
11153 BestLoQuad < 0 ? 0 : BestLoQuad,
11154 BestHiQuad < 0 ? 1 : BestHiQuad
11156 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
11157 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
11158 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
11159 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
11161 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
11162 // source words for the shuffle, to aid later transformations.
11163 bool AllWordsInNewV = true;
11164 bool InOrder[2] = { true, true };
11165 for (unsigned i = 0; i != 8; ++i) {
11166 int idx = MaskVals[i];
11168 InOrder[i/4] = false;
11169 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
11171 AllWordsInNewV = false;
11175 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
11176 if (AllWordsInNewV) {
11177 for (int i = 0; i != 8; ++i) {
11178 int idx = MaskVals[i];
11181 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
11182 if ((idx != i) && idx < 4)
11184 if ((idx != i) && idx > 3)
11193 // If we've eliminated the use of V2, and the new mask is a pshuflw or
11194 // pshufhw, that's as cheap as it gets. Return the new shuffle.
11195 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
11196 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
11197 unsigned TargetMask = 0;
11198 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
11199 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
11200 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11201 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
11202 getShufflePSHUFLWImmediate(SVOp);
11203 V1 = NewV.getOperand(0);
11204 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
11208 // Promote splats to a larger type which usually leads to more efficient code.
11209 // FIXME: Is this true if pshufb is available?
11210 if (SVOp->isSplat())
11211 return PromoteSplat(SVOp, DAG);
11213 // If we have SSSE3, and all words of the result are from 1 input vector,
11214 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
11215 // is present, fall back to case 4.
11216 if (Subtarget->hasSSSE3()) {
11217 SmallVector<SDValue,16> pshufbMask;
11219 // If we have elements from both input vectors, set the high bit of the
11220 // shuffle mask element to zero out elements that come from V2 in the V1
11221 // mask, and elements that come from V1 in the V2 mask, so that the two
11222 // results can be OR'd together.
11223 bool TwoInputs = V1Used && V2Used;
11224 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
11226 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11228 // Calculate the shuffle mask for the second input, shuffle it, and
11229 // OR it with the first shuffled input.
11230 CommuteVectorShuffleMask(MaskVals, 8);
11231 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
11232 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11233 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11236 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
11237 // and update MaskVals with new element order.
11238 std::bitset<8> InOrder;
11239 if (BestLoQuad >= 0) {
11240 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
11241 for (int i = 0; i != 4; ++i) {
11242 int idx = MaskVals[i];
11245 } else if ((idx / 4) == BestLoQuad) {
11246 MaskV[i] = idx & 3;
11250 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11253 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11254 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11255 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
11256 NewV.getOperand(0),
11257 getShufflePSHUFLWImmediate(SVOp), DAG);
11261 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
11262 // and update MaskVals with the new element order.
11263 if (BestHiQuad >= 0) {
11264 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
11265 for (unsigned i = 4; i != 8; ++i) {
11266 int idx = MaskVals[i];
11269 } else if ((idx / 4) == BestHiQuad) {
11270 MaskV[i] = (idx & 3) + 4;
11274 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11277 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11278 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11279 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
11280 NewV.getOperand(0),
11281 getShufflePSHUFHWImmediate(SVOp), DAG);
11285 // In case BestHi & BestLo were both -1, which means each quadword has a word
11286 // from each of the four input quadwords, calculate the InOrder bitvector now
11287 // before falling through to the insert/extract cleanup.
11288 if (BestLoQuad == -1 && BestHiQuad == -1) {
11290 for (int i = 0; i != 8; ++i)
11291 if (MaskVals[i] < 0 || MaskVals[i] == i)
11295 // The other elements are put in the right place using pextrw and pinsrw.
11296 for (unsigned i = 0; i != 8; ++i) {
11299 int EltIdx = MaskVals[i];
11302 SDValue ExtOp = (EltIdx < 8) ?
11303 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
11304 DAG.getIntPtrConstant(EltIdx)) :
11305 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
11306 DAG.getIntPtrConstant(EltIdx - 8));
11307 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
11308 DAG.getIntPtrConstant(i));
11313 /// \brief v16i16 shuffles
11315 /// FIXME: We only support generation of a single pshufb currently. We can
11316 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
11317 /// well (e.g 2 x pshufb + 1 x por).
11319 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
11320 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11321 SDValue V1 = SVOp->getOperand(0);
11322 SDValue V2 = SVOp->getOperand(1);
11325 if (V2.getOpcode() != ISD::UNDEF)
11328 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11329 return getPSHUFB(MaskVals, V1, dl, DAG);
11332 // v16i8 shuffles - Prefer shuffles in the following order:
11333 // 1. [ssse3] 1 x pshufb
11334 // 2. [ssse3] 2 x pshufb + 1 x por
11335 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
11336 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
11337 const X86Subtarget* Subtarget,
11338 SelectionDAG &DAG) {
11339 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11340 SDValue V1 = SVOp->getOperand(0);
11341 SDValue V2 = SVOp->getOperand(1);
11343 ArrayRef<int> MaskVals = SVOp->getMask();
11345 // Promote splats to a larger type which usually leads to more efficient code.
11346 // FIXME: Is this true if pshufb is available?
11347 if (SVOp->isSplat())
11348 return PromoteSplat(SVOp, DAG);
11350 // If we have SSSE3, case 1 is generated when all result bytes come from
11351 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
11352 // present, fall back to case 3.
11354 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
11355 if (Subtarget->hasSSSE3()) {
11356 SmallVector<SDValue,16> pshufbMask;
11358 // If all result elements are from one input vector, then only translate
11359 // undef mask values to 0x80 (zero out result) in the pshufb mask.
11361 // Otherwise, we have elements from both input vectors, and must zero out
11362 // elements that come from V2 in the first mask, and V1 in the second mask
11363 // so that we can OR them together.
11364 for (unsigned i = 0; i != 16; ++i) {
11365 int EltIdx = MaskVals[i];
11366 if (EltIdx < 0 || EltIdx >= 16)
11368 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11370 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
11371 DAG.getNode(ISD::BUILD_VECTOR, dl,
11372 MVT::v16i8, pshufbMask));
11374 // As PSHUFB will zero elements with negative indices, it's safe to ignore
11375 // the 2nd operand if it's undefined or zero.
11376 if (V2.getOpcode() == ISD::UNDEF ||
11377 ISD::isBuildVectorAllZeros(V2.getNode()))
11380 // Calculate the shuffle mask for the second input, shuffle it, and
11381 // OR it with the first shuffled input.
11382 pshufbMask.clear();
11383 for (unsigned i = 0; i != 16; ++i) {
11384 int EltIdx = MaskVals[i];
11385 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
11386 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11388 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
11389 DAG.getNode(ISD::BUILD_VECTOR, dl,
11390 MVT::v16i8, pshufbMask));
11391 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11394 // No SSSE3 - Calculate in place words and then fix all out of place words
11395 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
11396 // the 16 different words that comprise the two doublequadword input vectors.
11397 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11398 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
11400 for (int i = 0; i != 8; ++i) {
11401 int Elt0 = MaskVals[i*2];
11402 int Elt1 = MaskVals[i*2+1];
11404 // This word of the result is all undef, skip it.
11405 if (Elt0 < 0 && Elt1 < 0)
11408 // This word of the result is already in the correct place, skip it.
11409 if ((Elt0 == i*2) && (Elt1 == i*2+1))
11412 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
11413 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
11416 // If Elt0 and Elt1 are defined, are consecutive, and can be load
11417 // using a single extract together, load it and store it.
11418 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
11419 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11420 DAG.getIntPtrConstant(Elt1 / 2));
11421 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11422 DAG.getIntPtrConstant(i));
11426 // If Elt1 is defined, extract it from the appropriate source. If the
11427 // source byte is not also odd, shift the extracted word left 8 bits
11428 // otherwise clear the bottom 8 bits if we need to do an or.
11430 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11431 DAG.getIntPtrConstant(Elt1 / 2));
11432 if ((Elt1 & 1) == 0)
11433 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11435 TLI.getShiftAmountTy(InsElt.getValueType())));
11436 else if (Elt0 >= 0)
11437 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11438 DAG.getConstant(0xFF00, MVT::i16));
11440 // If Elt0 is defined, extract it from the appropriate source. If the
11441 // source byte is not also even, shift the extracted word right 8 bits. If
11442 // Elt1 was also defined, OR the extracted values together before
11443 // inserting them in the result.
11445 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11446 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11447 if ((Elt0 & 1) != 0)
11448 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11450 TLI.getShiftAmountTy(InsElt0.getValueType())));
11451 else if (Elt1 >= 0)
11452 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11453 DAG.getConstant(0x00FF, MVT::i16));
11454 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11457 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11458 DAG.getIntPtrConstant(i));
11460 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11463 // v32i8 shuffles - Translate to VPSHUFB if possible.
11465 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11466 const X86Subtarget *Subtarget,
11467 SelectionDAG &DAG) {
11468 MVT VT = SVOp->getSimpleValueType(0);
11469 SDValue V1 = SVOp->getOperand(0);
11470 SDValue V2 = SVOp->getOperand(1);
11472 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11474 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11475 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11476 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11478 // VPSHUFB may be generated if
11479 // (1) one of input vector is undefined or zeroinitializer.
11480 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11481 // And (2) the mask indexes don't cross the 128-bit lane.
11482 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11483 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11486 if (V1IsAllZero && !V2IsAllZero) {
11487 CommuteVectorShuffleMask(MaskVals, 32);
11490 return getPSHUFB(MaskVals, V1, dl, DAG);
11493 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11494 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11495 /// done when every pair / quad of shuffle mask elements point to elements in
11496 /// the right sequence. e.g.
11497 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11499 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11500 SelectionDAG &DAG) {
11501 MVT VT = SVOp->getSimpleValueType(0);
11503 unsigned NumElems = VT.getVectorNumElements();
11506 switch (VT.SimpleTy) {
11507 default: llvm_unreachable("Unexpected!");
11510 return SDValue(SVOp, 0);
11511 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
11512 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
11513 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
11514 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
11515 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11516 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
11519 SmallVector<int, 8> MaskVec;
11520 for (unsigned i = 0; i != NumElems; i += Scale) {
11522 for (unsigned j = 0; j != Scale; ++j) {
11523 int EltIdx = SVOp->getMaskElt(i+j);
11527 StartIdx = (EltIdx / Scale);
11528 if (EltIdx != (int)(StartIdx*Scale + j))
11531 MaskVec.push_back(StartIdx);
11534 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11535 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11536 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11539 /// getVZextMovL - Return a zero-extending vector move low node.
11541 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11542 SDValue SrcOp, SelectionDAG &DAG,
11543 const X86Subtarget *Subtarget, SDLoc dl) {
11544 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11545 LoadSDNode *LD = nullptr;
11546 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11547 LD = dyn_cast<LoadSDNode>(SrcOp);
11549 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11551 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11552 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11553 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11554 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11555 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
11557 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
11558 return DAG.getNode(ISD::BITCAST, dl, VT,
11559 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11560 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11562 SrcOp.getOperand(0)
11568 return DAG.getNode(ISD::BITCAST, dl, VT,
11569 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11570 DAG.getNode(ISD::BITCAST, dl,
11574 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
11575 /// which could not be matched by any known target speficic shuffle
11577 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11579 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
11580 if (NewOp.getNode())
11583 MVT VT = SVOp->getSimpleValueType(0);
11585 unsigned NumElems = VT.getVectorNumElements();
11586 unsigned NumLaneElems = NumElems / 2;
11589 MVT EltVT = VT.getVectorElementType();
11590 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
11593 SmallVector<int, 16> Mask;
11594 for (unsigned l = 0; l < 2; ++l) {
11595 // Build a shuffle mask for the output, discovering on the fly which
11596 // input vectors to use as shuffle operands (recorded in InputUsed).
11597 // If building a suitable shuffle vector proves too hard, then bail
11598 // out with UseBuildVector set.
11599 bool UseBuildVector = false;
11600 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
11601 unsigned LaneStart = l * NumLaneElems;
11602 for (unsigned i = 0; i != NumLaneElems; ++i) {
11603 // The mask element. This indexes into the input.
11604 int Idx = SVOp->getMaskElt(i+LaneStart);
11606 // the mask element does not index into any input vector.
11607 Mask.push_back(-1);
11611 // The input vector this mask element indexes into.
11612 int Input = Idx / NumLaneElems;
11614 // Turn the index into an offset from the start of the input vector.
11615 Idx -= Input * NumLaneElems;
11617 // Find or create a shuffle vector operand to hold this input.
11619 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
11620 if (InputUsed[OpNo] == Input)
11621 // This input vector is already an operand.
11623 if (InputUsed[OpNo] < 0) {
11624 // Create a new operand for this input vector.
11625 InputUsed[OpNo] = Input;
11630 if (OpNo >= array_lengthof(InputUsed)) {
11631 // More than two input vectors used! Give up on trying to create a
11632 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
11633 UseBuildVector = true;
11637 // Add the mask index for the new shuffle vector.
11638 Mask.push_back(Idx + OpNo * NumLaneElems);
11641 if (UseBuildVector) {
11642 SmallVector<SDValue, 16> SVOps;
11643 for (unsigned i = 0; i != NumLaneElems; ++i) {
11644 // The mask element. This indexes into the input.
11645 int Idx = SVOp->getMaskElt(i+LaneStart);
11647 SVOps.push_back(DAG.getUNDEF(EltVT));
11651 // The input vector this mask element indexes into.
11652 int Input = Idx / NumElems;
11654 // Turn the index into an offset from the start of the input vector.
11655 Idx -= Input * NumElems;
11657 // Extract the vector element by hand.
11658 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
11659 SVOp->getOperand(Input),
11660 DAG.getIntPtrConstant(Idx)));
11663 // Construct the output using a BUILD_VECTOR.
11664 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
11665 } else if (InputUsed[0] < 0) {
11666 // No input vectors were used! The result is undefined.
11667 Output[l] = DAG.getUNDEF(NVT);
11669 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
11670 (InputUsed[0] % 2) * NumLaneElems,
11672 // If only one input was used, use an undefined vector for the other.
11673 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
11674 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
11675 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
11676 // At least one input vector was used. Create a new shuffle vector.
11677 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
11683 // Concatenate the result back
11684 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
11687 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
11688 /// 4 elements, and match them with several different shuffle types.
11690 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11691 SDValue V1 = SVOp->getOperand(0);
11692 SDValue V2 = SVOp->getOperand(1);
11694 MVT VT = SVOp->getSimpleValueType(0);
11696 assert(VT.is128BitVector() && "Unsupported vector size");
11698 std::pair<int, int> Locs[4];
11699 int Mask1[] = { -1, -1, -1, -1 };
11700 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
11702 unsigned NumHi = 0;
11703 unsigned NumLo = 0;
11704 for (unsigned i = 0; i != 4; ++i) {
11705 int Idx = PermMask[i];
11707 Locs[i] = std::make_pair(-1, -1);
11709 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
11711 Locs[i] = std::make_pair(0, NumLo);
11712 Mask1[NumLo] = Idx;
11715 Locs[i] = std::make_pair(1, NumHi);
11717 Mask1[2+NumHi] = Idx;
11723 if (NumLo <= 2 && NumHi <= 2) {
11724 // If no more than two elements come from either vector. This can be
11725 // implemented with two shuffles. First shuffle gather the elements.
11726 // The second shuffle, which takes the first shuffle as both of its
11727 // vector operands, put the elements into the right order.
11728 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11730 int Mask2[] = { -1, -1, -1, -1 };
11732 for (unsigned i = 0; i != 4; ++i)
11733 if (Locs[i].first != -1) {
11734 unsigned Idx = (i < 2) ? 0 : 4;
11735 Idx += Locs[i].first * 2 + Locs[i].second;
11739 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
11742 if (NumLo == 3 || NumHi == 3) {
11743 // Otherwise, we must have three elements from one vector, call it X, and
11744 // one element from the other, call it Y. First, use a shufps to build an
11745 // intermediate vector with the one element from Y and the element from X
11746 // that will be in the same half in the final destination (the indexes don't
11747 // matter). Then, use a shufps to build the final vector, taking the half
11748 // containing the element from Y from the intermediate, and the other half
11751 // Normalize it so the 3 elements come from V1.
11752 CommuteVectorShuffleMask(PermMask, 4);
11756 // Find the element from V2.
11758 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
11759 int Val = PermMask[HiIndex];
11766 Mask1[0] = PermMask[HiIndex];
11768 Mask1[2] = PermMask[HiIndex^1];
11770 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11772 if (HiIndex >= 2) {
11773 Mask1[0] = PermMask[0];
11774 Mask1[1] = PermMask[1];
11775 Mask1[2] = HiIndex & 1 ? 6 : 4;
11776 Mask1[3] = HiIndex & 1 ? 4 : 6;
11777 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11780 Mask1[0] = HiIndex & 1 ? 2 : 0;
11781 Mask1[1] = HiIndex & 1 ? 0 : 2;
11782 Mask1[2] = PermMask[2];
11783 Mask1[3] = PermMask[3];
11788 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
11791 // Break it into (shuffle shuffle_hi, shuffle_lo).
11792 int LoMask[] = { -1, -1, -1, -1 };
11793 int HiMask[] = { -1, -1, -1, -1 };
11795 int *MaskPtr = LoMask;
11796 unsigned MaskIdx = 0;
11797 unsigned LoIdx = 0;
11798 unsigned HiIdx = 2;
11799 for (unsigned i = 0; i != 4; ++i) {
11806 int Idx = PermMask[i];
11808 Locs[i] = std::make_pair(-1, -1);
11809 } else if (Idx < 4) {
11810 Locs[i] = std::make_pair(MaskIdx, LoIdx);
11811 MaskPtr[LoIdx] = Idx;
11814 Locs[i] = std::make_pair(MaskIdx, HiIdx);
11815 MaskPtr[HiIdx] = Idx;
11820 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
11821 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
11822 int MaskOps[] = { -1, -1, -1, -1 };
11823 for (unsigned i = 0; i != 4; ++i)
11824 if (Locs[i].first != -1)
11825 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
11826 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
11829 static bool MayFoldVectorLoad(SDValue V) {
11830 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
11831 V = V.getOperand(0);
11833 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
11834 V = V.getOperand(0);
11835 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
11836 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
11837 // BUILD_VECTOR (load), undef
11838 V = V.getOperand(0);
11840 return MayFoldLoad(V);
11844 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
11845 MVT VT = Op.getSimpleValueType();
11847 // Canonizalize to v2f64.
11848 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
11849 return DAG.getNode(ISD::BITCAST, dl, VT,
11850 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
11855 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
11857 SDValue V1 = Op.getOperand(0);
11858 SDValue V2 = Op.getOperand(1);
11859 MVT VT = Op.getSimpleValueType();
11861 assert(VT != MVT::v2i64 && "unsupported shuffle type");
11863 if (HasSSE2 && VT == MVT::v2f64)
11864 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
11866 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
11867 return DAG.getNode(ISD::BITCAST, dl, VT,
11868 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
11869 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
11870 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
11874 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
11875 SDValue V1 = Op.getOperand(0);
11876 SDValue V2 = Op.getOperand(1);
11877 MVT VT = Op.getSimpleValueType();
11879 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
11880 "unsupported shuffle type");
11882 if (V2.getOpcode() == ISD::UNDEF)
11886 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
11890 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
11891 SDValue V1 = Op.getOperand(0);
11892 SDValue V2 = Op.getOperand(1);
11893 MVT VT = Op.getSimpleValueType();
11894 unsigned NumElems = VT.getVectorNumElements();
11896 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
11897 // operand of these instructions is only memory, so check if there's a
11898 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
11900 bool CanFoldLoad = false;
11902 // Trivial case, when V2 comes from a load.
11903 if (MayFoldVectorLoad(V2))
11904 CanFoldLoad = true;
11906 // When V1 is a load, it can be folded later into a store in isel, example:
11907 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
11909 // (MOVLPSmr addr:$src1, VR128:$src2)
11910 // So, recognize this potential and also use MOVLPS or MOVLPD
11911 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
11912 CanFoldLoad = true;
11914 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11916 if (HasSSE2 && NumElems == 2)
11917 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
11920 // If we don't care about the second element, proceed to use movss.
11921 if (SVOp->getMaskElt(1) != -1)
11922 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
11925 // movl and movlp will both match v2i64, but v2i64 is never matched by
11926 // movl earlier because we make it strict to avoid messing with the movlp load
11927 // folding logic (see the code above getMOVLP call). Match it here then,
11928 // this is horrible, but will stay like this until we move all shuffle
11929 // matching to x86 specific nodes. Note that for the 1st condition all
11930 // types are matched with movsd.
11932 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
11933 // as to remove this logic from here, as much as possible
11934 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
11935 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11936 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11939 assert(VT != MVT::v4i32 && "unsupported shuffle type");
11941 // Invert the operand order and use SHUFPS to match it.
11942 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
11943 getShuffleSHUFImmediate(SVOp), DAG);
11946 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
11947 SelectionDAG &DAG) {
11949 MVT VT = Load->getSimpleValueType(0);
11950 MVT EVT = VT.getVectorElementType();
11951 SDValue Addr = Load->getOperand(1);
11952 SDValue NewAddr = DAG.getNode(
11953 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
11954 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
11957 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
11958 DAG.getMachineFunction().getMachineMemOperand(
11959 Load->getMemOperand(), 0, EVT.getStoreSize()));
11963 // It is only safe to call this function if isINSERTPSMask is true for
11964 // this shufflevector mask.
11965 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
11966 SelectionDAG &DAG) {
11967 // Generate an insertps instruction when inserting an f32 from memory onto a
11968 // v4f32 or when copying a member from one v4f32 to another.
11969 // We also use it for transferring i32 from one register to another,
11970 // since it simply copies the same bits.
11971 // If we're transferring an i32 from memory to a specific element in a
11972 // register, we output a generic DAG that will match the PINSRD
11974 MVT VT = SVOp->getSimpleValueType(0);
11975 MVT EVT = VT.getVectorElementType();
11976 SDValue V1 = SVOp->getOperand(0);
11977 SDValue V2 = SVOp->getOperand(1);
11978 auto Mask = SVOp->getMask();
11979 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
11980 "unsupported vector type for insertps/pinsrd");
11982 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
11983 auto FromV2Predicate = [](const int &i) { return i >= 4; };
11984 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
11988 unsigned DestIndex;
11992 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
11995 // If we have 1 element from each vector, we have to check if we're
11996 // changing V1's element's place. If so, we're done. Otherwise, we
11997 // should assume we're changing V2's element's place and behave
11999 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
12000 assert(DestIndex <= INT32_MAX && "truncated destination index");
12001 if (FromV1 == FromV2 &&
12002 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
12006 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
12009 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
12010 "More than one element from V1 and from V2, or no elements from one "
12011 "of the vectors. This case should not have returned true from "
12016 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
12019 // Get an index into the source vector in the range [0,4) (the mask is
12020 // in the range [0,8) because it can address V1 and V2)
12021 unsigned SrcIndex = Mask[DestIndex] % 4;
12022 if (MayFoldLoad(From)) {
12023 // Trivial case, when From comes from a load and is only used by the
12024 // shuffle. Make it use insertps from the vector that we need from that
12027 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
12028 if (!NewLoad.getNode())
12031 if (EVT == MVT::f32) {
12032 // Create this as a scalar to vector to match the instruction pattern.
12033 SDValue LoadScalarToVector =
12034 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
12035 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
12036 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
12038 } else { // EVT == MVT::i32
12039 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
12040 // instruction, to match the PINSRD instruction, which loads an i32 to a
12041 // certain vector element.
12042 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
12043 DAG.getConstant(DestIndex, MVT::i32));
12047 // Vector-element-to-vector
12048 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
12049 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
12052 // Reduce a vector shuffle to zext.
12053 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
12054 SelectionDAG &DAG) {
12055 // PMOVZX is only available from SSE41.
12056 if (!Subtarget->hasSSE41())
12059 MVT VT = Op.getSimpleValueType();
12061 // Only AVX2 support 256-bit vector integer extending.
12062 if (!Subtarget->hasInt256() && VT.is256BitVector())
12065 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12067 SDValue V1 = Op.getOperand(0);
12068 SDValue V2 = Op.getOperand(1);
12069 unsigned NumElems = VT.getVectorNumElements();
12071 // Extending is an unary operation and the element type of the source vector
12072 // won't be equal to or larger than i64.
12073 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
12074 VT.getVectorElementType() == MVT::i64)
12077 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
12078 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
12079 while ((1U << Shift) < NumElems) {
12080 if (SVOp->getMaskElt(1U << Shift) == 1)
12083 // The maximal ratio is 8, i.e. from i8 to i64.
12088 // Check the shuffle mask.
12089 unsigned Mask = (1U << Shift) - 1;
12090 for (unsigned i = 0; i != NumElems; ++i) {
12091 int EltIdx = SVOp->getMaskElt(i);
12092 if ((i & Mask) != 0 && EltIdx != -1)
12094 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
12098 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
12099 MVT NeVT = MVT::getIntegerVT(NBits);
12100 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
12102 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
12105 return DAG.getNode(ISD::BITCAST, DL, VT,
12106 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
12109 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
12110 SelectionDAG &DAG) {
12111 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12112 MVT VT = Op.getSimpleValueType();
12114 SDValue V1 = Op.getOperand(0);
12115 SDValue V2 = Op.getOperand(1);
12117 if (isZeroShuffle(SVOp))
12118 return getZeroVector(VT, Subtarget, DAG, dl);
12120 // Handle splat operations
12121 if (SVOp->isSplat()) {
12122 // Use vbroadcast whenever the splat comes from a foldable load
12123 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
12124 if (Broadcast.getNode())
12128 // Check integer expanding shuffles.
12129 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
12130 if (NewOp.getNode())
12133 // If the shuffle can be profitably rewritten as a narrower shuffle, then
12135 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
12136 VT == MVT::v32i8) {
12137 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12138 if (NewOp.getNode())
12139 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
12140 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
12141 // FIXME: Figure out a cleaner way to do this.
12142 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
12143 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12144 if (NewOp.getNode()) {
12145 MVT NewVT = NewOp.getSimpleValueType();
12146 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
12147 NewVT, true, false))
12148 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
12151 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
12152 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12153 if (NewOp.getNode()) {
12154 MVT NewVT = NewOp.getSimpleValueType();
12155 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
12156 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
12165 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
12166 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12167 SDValue V1 = Op.getOperand(0);
12168 SDValue V2 = Op.getOperand(1);
12169 MVT VT = Op.getSimpleValueType();
12171 unsigned NumElems = VT.getVectorNumElements();
12172 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
12173 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
12174 bool V1IsSplat = false;
12175 bool V2IsSplat = false;
12176 bool HasSSE2 = Subtarget->hasSSE2();
12177 bool HasFp256 = Subtarget->hasFp256();
12178 bool HasInt256 = Subtarget->hasInt256();
12179 MachineFunction &MF = DAG.getMachineFunction();
12180 bool OptForSize = MF.getFunction()->getAttributes().
12181 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
12183 // Check if we should use the experimental vector shuffle lowering. If so,
12184 // delegate completely to that code path.
12185 if (ExperimentalVectorShuffleLowering)
12186 return lowerVectorShuffle(Op, Subtarget, DAG);
12188 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
12190 if (V1IsUndef && V2IsUndef)
12191 return DAG.getUNDEF(VT);
12193 // When we create a shuffle node we put the UNDEF node to second operand,
12194 // but in some cases the first operand may be transformed to UNDEF.
12195 // In this case we should just commute the node.
12197 return DAG.getCommutedVectorShuffle(*SVOp);
12199 // Vector shuffle lowering takes 3 steps:
12201 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
12202 // narrowing and commutation of operands should be handled.
12203 // 2) Matching of shuffles with known shuffle masks to x86 target specific
12205 // 3) Rewriting of unmatched masks into new generic shuffle operations,
12206 // so the shuffle can be broken into other shuffles and the legalizer can
12207 // try the lowering again.
12209 // The general idea is that no vector_shuffle operation should be left to
12210 // be matched during isel, all of them must be converted to a target specific
12213 // Normalize the input vectors. Here splats, zeroed vectors, profitable
12214 // narrowing and commutation of operands should be handled. The actual code
12215 // doesn't include all of those, work in progress...
12216 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
12217 if (NewOp.getNode())
12220 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
12222 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
12223 // unpckh_undef). Only use pshufd if speed is more important than size.
12224 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12225 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12226 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12227 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12229 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
12230 V2IsUndef && MayFoldVectorLoad(V1))
12231 return getMOVDDup(Op, dl, V1, DAG);
12233 if (isMOVHLPS_v_undef_Mask(M, VT))
12234 return getMOVHighToLow(Op, dl, DAG);
12236 // Use to match splats
12237 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
12238 (VT == MVT::v2f64 || VT == MVT::v2i64))
12239 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12241 if (isPSHUFDMask(M, VT)) {
12242 // The actual implementation will match the mask in the if above and then
12243 // during isel it can match several different instructions, not only pshufd
12244 // as its name says, sad but true, emulate the behavior for now...
12245 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
12246 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
12248 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
12250 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
12251 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
12253 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
12254 return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
12257 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
12261 if (isPALIGNRMask(M, VT, Subtarget))
12262 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
12263 getShufflePALIGNRImmediate(SVOp),
12266 if (isVALIGNMask(M, VT, Subtarget))
12267 return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
12268 getShuffleVALIGNImmediate(SVOp),
12271 // Check if this can be converted into a logical shift.
12272 bool isLeft = false;
12273 unsigned ShAmt = 0;
12275 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
12276 if (isShift && ShVal.hasOneUse()) {
12277 // If the shifted value has multiple uses, it may be cheaper to use
12278 // v_set0 + movlhps or movhlps, etc.
12279 MVT EltVT = VT.getVectorElementType();
12280 ShAmt *= EltVT.getSizeInBits();
12281 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12284 if (isMOVLMask(M, VT)) {
12285 if (ISD::isBuildVectorAllZeros(V1.getNode()))
12286 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
12287 if (!isMOVLPMask(M, VT)) {
12288 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
12289 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
12291 if (VT == MVT::v4i32 || VT == MVT::v4f32)
12292 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
12296 // FIXME: fold these into legal mask.
12297 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
12298 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
12300 if (isMOVHLPSMask(M, VT))
12301 return getMOVHighToLow(Op, dl, DAG);
12303 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
12304 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
12306 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
12307 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
12309 if (isMOVLPMask(M, VT))
12310 return getMOVLP(Op, dl, DAG, HasSSE2);
12312 if (ShouldXformToMOVHLPS(M, VT) ||
12313 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
12314 return DAG.getCommutedVectorShuffle(*SVOp);
12317 // No better options. Use a vshldq / vsrldq.
12318 MVT EltVT = VT.getVectorElementType();
12319 ShAmt *= EltVT.getSizeInBits();
12320 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12323 bool Commuted = false;
12324 // FIXME: This should also accept a bitcast of a splat? Be careful, not
12325 // 1,1,1,1 -> v8i16 though.
12326 BitVector UndefElements;
12327 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
12328 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12330 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
12331 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12334 // Canonicalize the splat or undef, if present, to be on the RHS.
12335 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
12336 CommuteVectorShuffleMask(M, NumElems);
12338 std::swap(V1IsSplat, V2IsSplat);
12342 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
12343 // Shuffling low element of v1 into undef, just return v1.
12346 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
12347 // the instruction selector will not match, so get a canonical MOVL with
12348 // swapped operands to undo the commute.
12349 return getMOVL(DAG, dl, VT, V2, V1);
12352 if (isUNPCKLMask(M, VT, HasInt256))
12353 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12355 if (isUNPCKHMask(M, VT, HasInt256))
12356 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12359 // Normalize mask so all entries that point to V2 points to its first
12360 // element then try to match unpck{h|l} again. If match, return a
12361 // new vector_shuffle with the corrected mask.p
12362 SmallVector<int, 8> NewMask(M.begin(), M.end());
12363 NormalizeMask(NewMask, NumElems);
12364 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
12365 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12366 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
12367 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12371 // Commute is back and try unpck* again.
12372 // FIXME: this seems wrong.
12373 CommuteVectorShuffleMask(M, NumElems);
12375 std::swap(V1IsSplat, V2IsSplat);
12377 if (isUNPCKLMask(M, VT, HasInt256))
12378 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12380 if (isUNPCKHMask(M, VT, HasInt256))
12381 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12384 // Normalize the node to match x86 shuffle ops if needed
12385 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
12386 return DAG.getCommutedVectorShuffle(*SVOp);
12388 // The checks below are all present in isShuffleMaskLegal, but they are
12389 // inlined here right now to enable us to directly emit target specific
12390 // nodes, and remove one by one until they don't return Op anymore.
12392 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
12393 SVOp->getSplatIndex() == 0 && V2IsUndef) {
12394 if (VT == MVT::v2f64 || VT == MVT::v2i64)
12395 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12398 if (isPSHUFHWMask(M, VT, HasInt256))
12399 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
12400 getShufflePSHUFHWImmediate(SVOp),
12403 if (isPSHUFLWMask(M, VT, HasInt256))
12404 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
12405 getShufflePSHUFLWImmediate(SVOp),
12408 unsigned MaskValue;
12409 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
12411 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
12413 if (isSHUFPMask(M, VT))
12414 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
12415 getShuffleSHUFImmediate(SVOp), DAG);
12417 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12418 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12419 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12420 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12422 //===--------------------------------------------------------------------===//
12423 // Generate target specific nodes for 128 or 256-bit shuffles only
12424 // supported in the AVX instruction set.
12427 // Handle VMOVDDUPY permutations
12428 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12429 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12431 // Handle VPERMILPS/D* permutations
12432 if (isVPERMILPMask(M, VT)) {
12433 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12434 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12435 getShuffleSHUFImmediate(SVOp), DAG);
12436 return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12437 getShuffleSHUFImmediate(SVOp), DAG);
12441 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12442 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12443 Idx*(NumElems/2), DAG, dl);
12445 // Handle VPERM2F128/VPERM2I128 permutations
12446 if (isVPERM2X128Mask(M, VT, HasFp256))
12447 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12448 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12450 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12451 return getINSERTPS(SVOp, dl, DAG);
12454 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12455 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12457 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12458 VT.is512BitVector()) {
12459 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12460 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12461 SmallVector<SDValue, 16> permclMask;
12462 for (unsigned i = 0; i != NumElems; ++i) {
12463 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12466 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12468 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12469 return DAG.getNode(X86ISD::VPERMV, dl, VT,
12470 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12471 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12472 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12475 //===--------------------------------------------------------------------===//
12476 // Since no target specific shuffle was selected for this generic one,
12477 // lower it into other known shuffles. FIXME: this isn't true yet, but
12478 // this is the plan.
12481 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12482 if (VT == MVT::v8i16) {
12483 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12484 if (NewOp.getNode())
12488 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
12489 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12490 if (NewOp.getNode())
12494 if (VT == MVT::v16i8) {
12495 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12496 if (NewOp.getNode())
12500 if (VT == MVT::v32i8) {
12501 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12502 if (NewOp.getNode())
12506 // Handle all 128-bit wide vectors with 4 elements, and match them with
12507 // several different shuffle types.
12508 if (NumElems == 4 && VT.is128BitVector())
12509 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12511 // Handle general 256-bit shuffles
12512 if (VT.is256BitVector())
12513 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12518 // This function assumes its argument is a BUILD_VECTOR of constants or
12519 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12521 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12522 unsigned &MaskValue) {
12524 unsigned NumElems = BuildVector->getNumOperands();
12525 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12526 unsigned NumLanes = (NumElems - 1) / 8 + 1;
12527 unsigned NumElemsInLane = NumElems / NumLanes;
12529 // Blend for v16i16 should be symetric for the both lanes.
12530 for (unsigned i = 0; i < NumElemsInLane; ++i) {
12531 SDValue EltCond = BuildVector->getOperand(i);
12532 SDValue SndLaneEltCond =
12533 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12535 int Lane1Cond = -1, Lane2Cond = -1;
12536 if (isa<ConstantSDNode>(EltCond))
12537 Lane1Cond = !isZero(EltCond);
12538 if (isa<ConstantSDNode>(SndLaneEltCond))
12539 Lane2Cond = !isZero(SndLaneEltCond);
12541 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12542 // Lane1Cond != 0, means we want the first argument.
12543 // Lane1Cond == 0, means we want the second argument.
12544 // The encoding of this argument is 0 for the first argument, 1
12545 // for the second. Therefore, invert the condition.
12546 MaskValue |= !Lane1Cond << i;
12547 else if (Lane1Cond < 0)
12548 MaskValue |= !Lane2Cond << i;
12555 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12557 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
12558 SelectionDAG &DAG) {
12559 SDValue Cond = Op.getOperand(0);
12560 SDValue LHS = Op.getOperand(1);
12561 SDValue RHS = Op.getOperand(2);
12563 MVT VT = Op.getSimpleValueType();
12564 MVT EltVT = VT.getVectorElementType();
12565 unsigned NumElems = VT.getVectorNumElements();
12567 // There is no blend with immediate in AVX-512.
12568 if (VT.is512BitVector())
12571 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
12573 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
12576 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12579 // Check the mask for BLEND and build the value.
12580 unsigned MaskValue = 0;
12581 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
12584 // Convert i32 vectors to floating point if it is not AVX2.
12585 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
12587 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
12588 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
12590 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
12591 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
12594 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
12595 DAG.getConstant(MaskValue, MVT::i32));
12596 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
12599 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12600 // A vselect where all conditions and data are constants can be optimized into
12601 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12602 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12603 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12604 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12607 SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
12608 if (BlendOp.getNode())
12611 // Some types for vselect were previously set to Expand, not Legal or
12612 // Custom. Return an empty SDValue so we fall-through to Expand, after
12613 // the Custom lowering phase.
12614 MVT VT = Op.getSimpleValueType();
12615 switch (VT.SimpleTy) {
12620 if (Subtarget->hasBWI() && Subtarget->hasVLX())
12625 // We couldn't create a "Blend with immediate" node.
12626 // This node should still be legal, but we'll have to emit a blendv*
12631 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12632 MVT VT = Op.getSimpleValueType();
12635 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12638 if (VT.getSizeInBits() == 8) {
12639 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12640 Op.getOperand(0), Op.getOperand(1));
12641 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12642 DAG.getValueType(VT));
12643 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12646 if (VT.getSizeInBits() == 16) {
12647 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12648 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12650 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12651 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12652 DAG.getNode(ISD::BITCAST, dl,
12655 Op.getOperand(1)));
12656 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12657 Op.getOperand(0), Op.getOperand(1));
12658 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12659 DAG.getValueType(VT));
12660 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12663 if (VT == MVT::f32) {
12664 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12665 // the result back to FR32 register. It's only worth matching if the
12666 // result has a single use which is a store or a bitcast to i32. And in
12667 // the case of a store, it's not worth it if the index is a constant 0,
12668 // because a MOVSSmr can be used instead, which is smaller and faster.
12669 if (!Op.hasOneUse())
12671 SDNode *User = *Op.getNode()->use_begin();
12672 if ((User->getOpcode() != ISD::STORE ||
12673 (isa<ConstantSDNode>(Op.getOperand(1)) &&
12674 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
12675 (User->getOpcode() != ISD::BITCAST ||
12676 User->getValueType(0) != MVT::i32))
12678 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12679 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
12682 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
12685 if (VT == MVT::i32 || VT == MVT::i64) {
12686 // ExtractPS/pextrq works with constant index.
12687 if (isa<ConstantSDNode>(Op.getOperand(1)))
12693 /// Extract one bit from mask vector, like v16i1 or v8i1.
12694 /// AVX-512 feature.
12696 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12697 SDValue Vec = Op.getOperand(0);
12699 MVT VecVT = Vec.getSimpleValueType();
12700 SDValue Idx = Op.getOperand(1);
12701 MVT EltVT = Op.getSimpleValueType();
12703 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12705 // variable index can't be handled in mask registers,
12706 // extend vector to VR512
12707 if (!isa<ConstantSDNode>(Idx)) {
12708 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
12709 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12710 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12711 ExtVT.getVectorElementType(), Ext, Idx);
12712 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12715 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12716 const TargetRegisterClass* rc = getRegClassFor(VecVT);
12717 unsigned MaxSift = rc->getSize()*8 - 1;
12718 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12719 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12720 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12721 DAG.getConstant(MaxSift, MVT::i8));
12722 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12723 DAG.getIntPtrConstant(0));
12727 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12728 SelectionDAG &DAG) const {
12730 SDValue Vec = Op.getOperand(0);
12731 MVT VecVT = Vec.getSimpleValueType();
12732 SDValue Idx = Op.getOperand(1);
12734 if (Op.getSimpleValueType() == MVT::i1)
12735 return ExtractBitFromMaskVector(Op, DAG);
12737 if (!isa<ConstantSDNode>(Idx)) {
12738 if (VecVT.is512BitVector() ||
12739 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
12740 VecVT.getVectorElementType().getSizeInBits() == 32)) {
12743 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12744 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12745 MaskEltVT.getSizeInBits());
12747 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12748 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12749 getZeroVector(MaskVT, Subtarget, DAG, dl),
12750 Idx, DAG.getConstant(0, getPointerTy()));
12751 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12752 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
12753 Perm, DAG.getConstant(0, getPointerTy()));
12758 // If this is a 256-bit vector result, first extract the 128-bit vector and
12759 // then extract the element from the 128-bit vector.
12760 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12762 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12763 // Get the 128-bit vector.
12764 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
12765 MVT EltVT = VecVT.getVectorElementType();
12767 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12769 //if (IdxVal >= NumElems/2)
12770 // IdxVal -= NumElems/2;
12771 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
12772 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12773 DAG.getConstant(IdxVal, MVT::i32));
12776 assert(VecVT.is128BitVector() && "Unexpected vector length");
12778 if (Subtarget->hasSSE41()) {
12779 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
12784 MVT VT = Op.getSimpleValueType();
12785 // TODO: handle v16i8.
12786 if (VT.getSizeInBits() == 16) {
12787 SDValue Vec = Op.getOperand(0);
12788 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12790 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12791 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12792 DAG.getNode(ISD::BITCAST, dl,
12794 Op.getOperand(1)));
12795 // Transform it so it match pextrw which produces a 32-bit result.
12796 MVT EltVT = MVT::i32;
12797 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
12798 Op.getOperand(0), Op.getOperand(1));
12799 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12800 DAG.getValueType(VT));
12801 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12804 if (VT.getSizeInBits() == 32) {
12805 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12809 // SHUFPS the element to the lowest double word, then movss.
12810 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
12811 MVT VVT = Op.getOperand(0).getSimpleValueType();
12812 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12813 DAG.getUNDEF(VVT), Mask);
12814 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12815 DAG.getIntPtrConstant(0));
12818 if (VT.getSizeInBits() == 64) {
12819 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12820 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12821 // to match extract_elt for f64.
12822 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12826 // UNPCKHPD the element to the lowest double word, then movsd.
12827 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12828 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12829 int Mask[2] = { 1, -1 };
12830 MVT VVT = Op.getOperand(0).getSimpleValueType();
12831 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12832 DAG.getUNDEF(VVT), Mask);
12833 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12834 DAG.getIntPtrConstant(0));
12840 /// Insert one bit to mask vector, like v16i1 or v8i1.
12841 /// AVX-512 feature.
12843 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12845 SDValue Vec = Op.getOperand(0);
12846 SDValue Elt = Op.getOperand(1);
12847 SDValue Idx = Op.getOperand(2);
12848 MVT VecVT = Vec.getSimpleValueType();
12850 if (!isa<ConstantSDNode>(Idx)) {
12851 // Non constant index. Extend source and destination,
12852 // insert element and then truncate the result.
12853 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
12854 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
12855 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
12856 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12857 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12858 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12861 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12862 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12863 if (Vec.getOpcode() == ISD::UNDEF)
12864 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12865 DAG.getConstant(IdxVal, MVT::i8));
12866 const TargetRegisterClass* rc = getRegClassFor(VecVT);
12867 unsigned MaxSift = rc->getSize()*8 - 1;
12868 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12869 DAG.getConstant(MaxSift, MVT::i8));
12870 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
12871 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12872 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12875 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12876 SelectionDAG &DAG) const {
12877 MVT VT = Op.getSimpleValueType();
12878 MVT EltVT = VT.getVectorElementType();
12880 if (EltVT == MVT::i1)
12881 return InsertBitToMaskVector(Op, DAG);
12884 SDValue N0 = Op.getOperand(0);
12885 SDValue N1 = Op.getOperand(1);
12886 SDValue N2 = Op.getOperand(2);
12887 if (!isa<ConstantSDNode>(N2))
12889 auto *N2C = cast<ConstantSDNode>(N2);
12890 unsigned IdxVal = N2C->getZExtValue();
12892 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12893 // into that, and then insert the subvector back into the result.
12894 if (VT.is256BitVector() || VT.is512BitVector()) {
12895 // Get the desired 128-bit vector half.
12896 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
12898 // Insert the element into the desired half.
12899 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12900 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
12902 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12903 DAG.getConstant(IdxIn128, MVT::i32));
12905 // Insert the changed part back to the 256-bit vector
12906 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
12908 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12910 if (Subtarget->hasSSE41()) {
12911 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12913 if (VT == MVT::v8i16) {
12914 Opc = X86ISD::PINSRW;
12916 assert(VT == MVT::v16i8);
12917 Opc = X86ISD::PINSRB;
12920 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12922 if (N1.getValueType() != MVT::i32)
12923 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12924 if (N2.getValueType() != MVT::i32)
12925 N2 = DAG.getIntPtrConstant(IdxVal);
12926 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12929 if (EltVT == MVT::f32) {
12930 // Bits [7:6] of the constant are the source select. This will always be
12931 // zero here. The DAG Combiner may combine an extract_elt index into
12933 // bits. For example (insert (extract, 3), 2) could be matched by
12935 // the '3' into bits [7:6] of X86ISD::INSERTPS.
12936 // Bits [5:4] of the constant are the destination select. This is the
12937 // value of the incoming immediate.
12938 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
12939 // combine either bitwise AND or insert of float 0.0 to set these bits.
12940 N2 = DAG.getIntPtrConstant(IdxVal << 4);
12941 // Create this as a scalar to vector..
12942 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12943 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12946 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12947 // PINSR* works with constant index.
12952 if (EltVT == MVT::i8)
12955 if (EltVT.getSizeInBits() == 16) {
12956 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12957 // as its second argument.
12958 if (N1.getValueType() != MVT::i32)
12959 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12960 if (N2.getValueType() != MVT::i32)
12961 N2 = DAG.getIntPtrConstant(IdxVal);
12962 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12967 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12969 MVT OpVT = Op.getSimpleValueType();
12971 // If this is a 256-bit vector result, first insert into a 128-bit
12972 // vector and then insert into the 256-bit vector.
12973 if (!OpVT.is128BitVector()) {
12974 // Insert into a 128-bit vector.
12975 unsigned SizeFactor = OpVT.getSizeInBits()/128;
12976 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12977 OpVT.getVectorNumElements() / SizeFactor);
12979 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12981 // Insert the 128-bit vector.
12982 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12985 if (OpVT == MVT::v1i64 &&
12986 Op.getOperand(0).getValueType() == MVT::i64)
12987 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12989 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12990 assert(OpVT.is128BitVector() && "Expected an SSE type!");
12991 return DAG.getNode(ISD::BITCAST, dl, OpVT,
12992 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
12995 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
12996 // a simple subregister reference or explicit instructions to grab
12997 // upper bits of a vector.
12998 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12999 SelectionDAG &DAG) {
13001 SDValue In = Op.getOperand(0);
13002 SDValue Idx = Op.getOperand(1);
13003 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13004 MVT ResVT = Op.getSimpleValueType();
13005 MVT InVT = In.getSimpleValueType();
13007 if (Subtarget->hasFp256()) {
13008 if (ResVT.is128BitVector() &&
13009 (InVT.is256BitVector() || InVT.is512BitVector()) &&
13010 isa<ConstantSDNode>(Idx)) {
13011 return Extract128BitVector(In, IdxVal, DAG, dl);
13013 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
13014 isa<ConstantSDNode>(Idx)) {
13015 return Extract256BitVector(In, IdxVal, DAG, dl);
13021 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
13022 // simple superregister reference or explicit instructions to insert
13023 // the upper bits of a vector.
13024 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
13025 SelectionDAG &DAG) {
13026 if (Subtarget->hasFp256()) {
13027 SDLoc dl(Op.getNode());
13028 SDValue Vec = Op.getNode()->getOperand(0);
13029 SDValue SubVec = Op.getNode()->getOperand(1);
13030 SDValue Idx = Op.getNode()->getOperand(2);
13032 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
13033 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
13034 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
13035 isa<ConstantSDNode>(Idx)) {
13036 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13037 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
13040 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
13041 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
13042 isa<ConstantSDNode>(Idx)) {
13043 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13044 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
13050 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
13051 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
13052 // one of the above mentioned nodes. It has to be wrapped because otherwise
13053 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
13054 // be used to form addressing mode. These wrapped nodes will be selected
13057 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
13058 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
13060 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13061 // global base reg.
13062 unsigned char OpFlag = 0;
13063 unsigned WrapperKind = X86ISD::Wrapper;
13064 CodeModel::Model M = DAG.getTarget().getCodeModel();
13066 if (Subtarget->isPICStyleRIPRel() &&
13067 (M == CodeModel::Small || M == CodeModel::Kernel))
13068 WrapperKind = X86ISD::WrapperRIP;
13069 else if (Subtarget->isPICStyleGOT())
13070 OpFlag = X86II::MO_GOTOFF;
13071 else if (Subtarget->isPICStyleStubPIC())
13072 OpFlag = X86II::MO_PIC_BASE_OFFSET;
13074 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
13075 CP->getAlignment(),
13076 CP->getOffset(), OpFlag);
13078 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13079 // With PIC, the address is actually $g + Offset.
13081 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13082 DAG.getNode(X86ISD::GlobalBaseReg,
13083 SDLoc(), getPointerTy()),
13090 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
13091 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
13093 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13094 // global base reg.
13095 unsigned char OpFlag = 0;
13096 unsigned WrapperKind = X86ISD::Wrapper;
13097 CodeModel::Model M = DAG.getTarget().getCodeModel();
13099 if (Subtarget->isPICStyleRIPRel() &&
13100 (M == CodeModel::Small || M == CodeModel::Kernel))
13101 WrapperKind = X86ISD::WrapperRIP;
13102 else if (Subtarget->isPICStyleGOT())
13103 OpFlag = X86II::MO_GOTOFF;
13104 else if (Subtarget->isPICStyleStubPIC())
13105 OpFlag = X86II::MO_PIC_BASE_OFFSET;
13107 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
13110 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13112 // With PIC, the address is actually $g + Offset.
13114 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13115 DAG.getNode(X86ISD::GlobalBaseReg,
13116 SDLoc(), getPointerTy()),
13123 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
13124 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13126 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13127 // global base reg.
13128 unsigned char OpFlag = 0;
13129 unsigned WrapperKind = X86ISD::Wrapper;
13130 CodeModel::Model M = DAG.getTarget().getCodeModel();
13132 if (Subtarget->isPICStyleRIPRel() &&
13133 (M == CodeModel::Small || M == CodeModel::Kernel)) {
13134 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
13135 OpFlag = X86II::MO_GOTPCREL;
13136 WrapperKind = X86ISD::WrapperRIP;
13137 } else if (Subtarget->isPICStyleGOT()) {
13138 OpFlag = X86II::MO_GOT;
13139 } else if (Subtarget->isPICStyleStubPIC()) {
13140 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
13141 } else if (Subtarget->isPICStyleStubNoDynamic()) {
13142 OpFlag = X86II::MO_DARWIN_NONLAZY;
13145 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
13148 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13150 // With PIC, the address is actually $g + Offset.
13151 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
13152 !Subtarget->is64Bit()) {
13153 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13154 DAG.getNode(X86ISD::GlobalBaseReg,
13155 SDLoc(), getPointerTy()),
13159 // For symbols that require a load from a stub to get the address, emit the
13161 if (isGlobalStubReference(OpFlag))
13162 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
13163 MachinePointerInfo::getGOT(), false, false, false, 0);
13169 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
13170 // Create the TargetBlockAddressAddress node.
13171 unsigned char OpFlags =
13172 Subtarget->ClassifyBlockAddressReference();
13173 CodeModel::Model M = DAG.getTarget().getCodeModel();
13174 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
13175 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
13177 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
13180 if (Subtarget->isPICStyleRIPRel() &&
13181 (M == CodeModel::Small || M == CodeModel::Kernel))
13182 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13184 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13186 // With PIC, the address is actually $g + Offset.
13187 if (isGlobalRelativeToPICBase(OpFlags)) {
13188 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13189 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13197 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
13198 int64_t Offset, SelectionDAG &DAG) const {
13199 // Create the TargetGlobalAddress node, folding in the constant
13200 // offset if it is legal.
13201 unsigned char OpFlags =
13202 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
13203 CodeModel::Model M = DAG.getTarget().getCodeModel();
13205 if (OpFlags == X86II::MO_NO_FLAG &&
13206 X86::isOffsetSuitableForCodeModel(Offset, M)) {
13207 // A direct static reference to a global.
13208 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
13211 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
13214 if (Subtarget->isPICStyleRIPRel() &&
13215 (M == CodeModel::Small || M == CodeModel::Kernel))
13216 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13218 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13220 // With PIC, the address is actually $g + Offset.
13221 if (isGlobalRelativeToPICBase(OpFlags)) {
13222 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13223 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13227 // For globals that require a load from a stub to get the address, emit the
13229 if (isGlobalStubReference(OpFlags))
13230 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
13231 MachinePointerInfo::getGOT(), false, false, false, 0);
13233 // If there was a non-zero offset that we didn't fold, create an explicit
13234 // addition for it.
13236 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
13237 DAG.getConstant(Offset, getPointerTy()));
13243 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
13244 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
13245 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
13246 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
13250 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
13251 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
13252 unsigned char OperandFlags, bool LocalDynamic = false) {
13253 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13254 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13256 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13257 GA->getValueType(0),
13261 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
13265 SDValue Ops[] = { Chain, TGA, *InFlag };
13266 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13268 SDValue Ops[] = { Chain, TGA };
13269 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13272 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
13273 MFI->setAdjustsStack(true);
13274 MFI->setHasCalls(true);
13276 SDValue Flag = Chain.getValue(1);
13277 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
13280 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
13282 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13285 SDLoc dl(GA); // ? function entry point might be better
13286 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13287 DAG.getNode(X86ISD::GlobalBaseReg,
13288 SDLoc(), PtrVT), InFlag);
13289 InFlag = Chain.getValue(1);
13291 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
13294 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
13296 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13298 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
13299 X86::RAX, X86II::MO_TLSGD);
13302 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
13308 // Get the start address of the TLS block for this module.
13309 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
13310 .getInfo<X86MachineFunctionInfo>();
13311 MFI->incNumLocalDynamicTLSAccesses();
13315 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
13316 X86II::MO_TLSLD, /*LocalDynamic=*/true);
13319 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13320 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
13321 InFlag = Chain.getValue(1);
13322 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
13323 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
13326 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
13330 unsigned char OperandFlags = X86II::MO_DTPOFF;
13331 unsigned WrapperKind = X86ISD::Wrapper;
13332 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13333 GA->getValueType(0),
13334 GA->getOffset(), OperandFlags);
13335 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13337 // Add x@dtpoff with the base.
13338 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
13341 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
13342 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13343 const EVT PtrVT, TLSModel::Model model,
13344 bool is64Bit, bool isPIC) {
13347 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
13348 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
13349 is64Bit ? 257 : 256));
13351 SDValue ThreadPointer =
13352 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
13353 MachinePointerInfo(Ptr), false, false, false, 0);
13355 unsigned char OperandFlags = 0;
13356 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
13358 unsigned WrapperKind = X86ISD::Wrapper;
13359 if (model == TLSModel::LocalExec) {
13360 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
13361 } else if (model == TLSModel::InitialExec) {
13363 OperandFlags = X86II::MO_GOTTPOFF;
13364 WrapperKind = X86ISD::WrapperRIP;
13366 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
13369 llvm_unreachable("Unexpected model");
13372 // emit "addl x@ntpoff,%eax" (local exec)
13373 // or "addl x@indntpoff,%eax" (initial exec)
13374 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
13376 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
13377 GA->getOffset(), OperandFlags);
13378 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13380 if (model == TLSModel::InitialExec) {
13381 if (isPIC && !is64Bit) {
13382 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13383 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13387 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13388 MachinePointerInfo::getGOT(), false, false, false, 0);
13391 // The address of the thread local variable is the add of the thread
13392 // pointer with the offset of the variable.
13393 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13397 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13399 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13400 const GlobalValue *GV = GA->getGlobal();
13402 if (Subtarget->isTargetELF()) {
13403 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13406 case TLSModel::GeneralDynamic:
13407 if (Subtarget->is64Bit())
13408 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
13409 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
13410 case TLSModel::LocalDynamic:
13411 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
13412 Subtarget->is64Bit());
13413 case TLSModel::InitialExec:
13414 case TLSModel::LocalExec:
13415 return LowerToTLSExecModel(
13416 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
13417 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
13419 llvm_unreachable("Unknown TLS model.");
13422 if (Subtarget->isTargetDarwin()) {
13423 // Darwin only has one model of TLS. Lower to that.
13424 unsigned char OpFlag = 0;
13425 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
13426 X86ISD::WrapperRIP : X86ISD::Wrapper;
13428 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13429 // global base reg.
13430 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13431 !Subtarget->is64Bit();
13433 OpFlag = X86II::MO_TLVP_PIC_BASE;
13435 OpFlag = X86II::MO_TLVP;
13437 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13438 GA->getValueType(0),
13439 GA->getOffset(), OpFlag);
13440 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13442 // With PIC32, the address is actually $g + Offset.
13444 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13445 DAG.getNode(X86ISD::GlobalBaseReg,
13446 SDLoc(), getPointerTy()),
13449 // Lowering the machine isd will make sure everything is in the right
13451 SDValue Chain = DAG.getEntryNode();
13452 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13453 SDValue Args[] = { Chain, Offset };
13454 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13456 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13457 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13458 MFI->setAdjustsStack(true);
13460 // And our return value (tls address) is in the standard call return value
13462 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13463 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13464 Chain.getValue(1));
13467 if (Subtarget->isTargetKnownWindowsMSVC() ||
13468 Subtarget->isTargetWindowsGNU()) {
13469 // Just use the implicit TLS architecture
13470 // Need to generate someting similar to:
13471 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13473 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
13474 // mov rcx, qword [rdx+rcx*8]
13475 // mov eax, .tls$:tlsvar
13476 // [rax+rcx] contains the address
13477 // Windows 64bit: gs:0x58
13478 // Windows 32bit: fs:__tls_array
13481 SDValue Chain = DAG.getEntryNode();
13483 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13484 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13485 // use its literal value of 0x2C.
13486 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13487 ? Type::getInt8PtrTy(*DAG.getContext(),
13489 : Type::getInt32PtrTy(*DAG.getContext(),
13493 Subtarget->is64Bit()
13494 ? DAG.getIntPtrConstant(0x58)
13495 : (Subtarget->isTargetWindowsGNU()
13496 ? DAG.getIntPtrConstant(0x2C)
13497 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13499 SDValue ThreadPointer =
13500 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13501 MachinePointerInfo(Ptr), false, false, false, 0);
13503 // Load the _tls_index variable
13504 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13505 if (Subtarget->is64Bit())
13506 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13507 IDX, MachinePointerInfo(), MVT::i32,
13508 false, false, false, 0);
13510 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13511 false, false, false, 0);
13513 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13515 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13517 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13518 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13519 false, false, false, 0);
13521 // Get the offset of start of .tls section
13522 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13523 GA->getValueType(0),
13524 GA->getOffset(), X86II::MO_SECREL);
13525 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13527 // The address of the thread local variable is the add of the thread
13528 // pointer with the offset of the variable.
13529 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13532 llvm_unreachable("TLS not implemented for this target.");
13535 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
13536 /// and take a 2 x i32 value to shift plus a shift amount.
13537 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13538 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13539 MVT VT = Op.getSimpleValueType();
13540 unsigned VTBits = VT.getSizeInBits();
13542 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13543 SDValue ShOpLo = Op.getOperand(0);
13544 SDValue ShOpHi = Op.getOperand(1);
13545 SDValue ShAmt = Op.getOperand(2);
13546 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13547 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13549 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13550 DAG.getConstant(VTBits - 1, MVT::i8));
13551 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13552 DAG.getConstant(VTBits - 1, MVT::i8))
13553 : DAG.getConstant(0, VT);
13555 SDValue Tmp2, Tmp3;
13556 if (Op.getOpcode() == ISD::SHL_PARTS) {
13557 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13558 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13560 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13561 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13564 // If the shift amount is larger or equal than the width of a part we can't
13565 // rely on the results of shld/shrd. Insert a test and select the appropriate
13566 // values for large shift amounts.
13567 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13568 DAG.getConstant(VTBits, MVT::i8));
13569 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13570 AndNode, DAG.getConstant(0, MVT::i8));
13573 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13574 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13575 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13577 if (Op.getOpcode() == ISD::SHL_PARTS) {
13578 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13579 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13581 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13582 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13585 SDValue Ops[2] = { Lo, Hi };
13586 return DAG.getMergeValues(Ops, dl);
13589 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13590 SelectionDAG &DAG) const {
13591 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13594 if (SrcVT.isVector()) {
13595 if (SrcVT.getVectorElementType() == MVT::i1) {
13596 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
13597 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13598 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
13599 Op.getOperand(0)));
13604 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13605 "Unknown SINT_TO_FP to lower!");
13607 // These are really Legal; return the operand so the caller accepts it as
13609 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13611 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13612 Subtarget->is64Bit()) {
13616 unsigned Size = SrcVT.getSizeInBits()/8;
13617 MachineFunction &MF = DAG.getMachineFunction();
13618 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13619 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13620 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13622 MachinePointerInfo::getFixedStack(SSFI),
13624 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13627 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13629 SelectionDAG &DAG) const {
13633 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13635 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13637 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13639 unsigned ByteSize = SrcVT.getSizeInBits()/8;
13641 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13642 MachineMemOperand *MMO;
13644 int SSFI = FI->getIndex();
13646 DAG.getMachineFunction()
13647 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13648 MachineMemOperand::MOLoad, ByteSize, ByteSize);
13650 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13651 StackSlot = StackSlot.getOperand(1);
13653 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13654 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13656 Tys, Ops, SrcVT, MMO);
13659 Chain = Result.getValue(1);
13660 SDValue InFlag = Result.getValue(2);
13662 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13663 // shouldn't be necessary except that RFP cannot be live across
13664 // multiple blocks. When stackifier is fixed, they can be uncoupled.
13665 MachineFunction &MF = DAG.getMachineFunction();
13666 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13667 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13668 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13669 Tys = DAG.getVTList(MVT::Other);
13671 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13673 MachineMemOperand *MMO =
13674 DAG.getMachineFunction()
13675 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13676 MachineMemOperand::MOStore, SSFISize, SSFISize);
13678 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13679 Ops, Op.getValueType(), MMO);
13680 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
13681 MachinePointerInfo::getFixedStack(SSFI),
13682 false, false, false, 0);
13688 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
13689 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13690 SelectionDAG &DAG) const {
13691 // This algorithm is not obvious. Here it is what we're trying to output:
13694 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13695 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13697 haddpd %xmm0, %xmm0
13699 pshufd $0x4e, %xmm0, %xmm1
13705 LLVMContext *Context = DAG.getContext();
13707 // Build some magic constants.
13708 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13709 Constant *C0 = ConstantDataVector::get(*Context, CV0);
13710 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
13712 SmallVector<Constant*,2> CV1;
13714 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13715 APInt(64, 0x4330000000000000ULL))));
13717 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13718 APInt(64, 0x4530000000000000ULL))));
13719 Constant *C1 = ConstantVector::get(CV1);
13720 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
13722 // Load the 64-bit value into an XMM register.
13723 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13725 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13726 MachinePointerInfo::getConstantPool(),
13727 false, false, false, 16);
13728 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
13729 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
13732 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13733 MachinePointerInfo::getConstantPool(),
13734 false, false, false, 16);
13735 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
13736 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13739 if (Subtarget->hasSSE3()) {
13740 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13741 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13743 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
13744 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13746 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13747 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
13751 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13752 DAG.getIntPtrConstant(0));
13755 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
13756 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13757 SelectionDAG &DAG) const {
13759 // FP constant to bias correct the final result.
13760 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13763 // Load the 32-bit value into an XMM register.
13764 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13767 // Zero out the upper parts of the register.
13768 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13770 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13771 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
13772 DAG.getIntPtrConstant(0));
13774 // Or the load with the bias.
13775 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
13776 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13777 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13778 MVT::v2f64, Load)),
13779 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13780 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13781 MVT::v2f64, Bias)));
13782 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13783 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
13784 DAG.getIntPtrConstant(0));
13786 // Subtract the bias.
13787 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13789 // Handle final rounding.
13790 EVT DestVT = Op.getValueType();
13792 if (DestVT.bitsLT(MVT::f64))
13793 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13794 DAG.getIntPtrConstant(0));
13795 if (DestVT.bitsGT(MVT::f64))
13796 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13798 // Handle final rounding.
13802 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13803 const X86Subtarget &Subtarget) {
13804 // The algorithm is the following:
13805 // #ifdef __SSE4_1__
13806 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13807 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13808 // (uint4) 0x53000000, 0xaa);
13810 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13811 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
13813 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13814 // return (float4) lo + fhi;
13817 SDValue V = Op->getOperand(0);
13818 EVT VecIntVT = V.getValueType();
13819 bool Is128 = VecIntVT == MVT::v4i32;
13820 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13821 // If we convert to something else than the supported type, e.g., to v4f64,
13823 if (VecFloatVT != Op->getValueType(0))
13826 unsigned NumElts = VecIntVT.getVectorNumElements();
13827 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13828 "Unsupported custom type");
13829 assert(NumElts <= 8 && "The size of the constant array must be fixed");
13831 // In the #idef/#else code, we have in common:
13832 // - The vector of constants:
13838 // Create the splat vector for 0x4b000000.
13839 SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
13840 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
13841 CstLow, CstLow, CstLow, CstLow};
13842 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13843 makeArrayRef(&CstLowArray[0], NumElts));
13844 // Create the splat vector for 0x53000000.
13845 SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
13846 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
13847 CstHigh, CstHigh, CstHigh, CstHigh};
13848 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13849 makeArrayRef(&CstHighArray[0], NumElts));
13851 // Create the right shift.
13852 SDValue CstShift = DAG.getConstant(16, MVT::i32);
13853 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
13854 CstShift, CstShift, CstShift, CstShift};
13855 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13856 makeArrayRef(&CstShiftArray[0], NumElts));
13857 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13860 if (Subtarget.hasSSE41()) {
13861 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13862 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13863 SDValue VecCstLowBitcast =
13864 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
13865 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
13866 // Low will be bitcasted right away, so do not bother bitcasting back to its
13868 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13869 VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
13870 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13871 // (uint4) 0x53000000, 0xaa);
13872 SDValue VecCstHighBitcast =
13873 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
13874 SDValue VecShiftBitcast =
13875 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
13876 // High will be bitcasted right away, so do not bother bitcasting back to
13877 // its original type.
13878 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13879 VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
13881 SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
13882 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13883 CstMask, CstMask, CstMask);
13884 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13885 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13886 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13888 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
13889 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13892 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13893 SDValue CstFAdd = DAG.getConstantFP(
13894 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
13895 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13896 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13897 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13898 makeArrayRef(&CstFAddArray[0], NumElts));
13900 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13901 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
13903 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13904 // return (float4) lo + fhi;
13905 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
13906 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13909 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13910 SelectionDAG &DAG) const {
13911 SDValue N0 = Op.getOperand(0);
13912 MVT SVT = N0.getSimpleValueType();
13915 switch (SVT.SimpleTy) {
13917 llvm_unreachable("Custom UINT_TO_FP is not supported!");
13922 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13923 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13924 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13928 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13930 llvm_unreachable(nullptr);
13933 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13934 SelectionDAG &DAG) const {
13935 SDValue N0 = Op.getOperand(0);
13938 if (Op.getValueType().isVector())
13939 return lowerUINT_TO_FP_vec(Op, DAG);
13941 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13942 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13943 // the optimization here.
13944 if (DAG.SignBitIsZero(N0))
13945 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13947 MVT SrcVT = N0.getSimpleValueType();
13948 MVT DstVT = Op.getSimpleValueType();
13949 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13950 return LowerUINT_TO_FP_i64(Op, DAG);
13951 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13952 return LowerUINT_TO_FP_i32(Op, DAG);
13953 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13956 // Make a 64-bit buffer, and use it to build an FILD.
13957 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13958 if (SrcVT == MVT::i32) {
13959 SDValue WordOff = DAG.getConstant(4, getPointerTy());
13960 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
13961 getPointerTy(), StackSlot, WordOff);
13962 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13963 StackSlot, MachinePointerInfo(),
13965 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
13966 OffsetSlot, MachinePointerInfo(),
13968 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13972 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13973 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13974 StackSlot, MachinePointerInfo(),
13976 // For i64 source, we need to add the appropriate power of 2 if the input
13977 // was negative. This is the same as the optimization in
13978 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13979 // we must be careful to do the computation in x87 extended precision, not
13980 // in SSE. (The generic code can't know it's OK to do this, or how to.)
13981 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13982 MachineMemOperand *MMO =
13983 DAG.getMachineFunction()
13984 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13985 MachineMemOperand::MOLoad, 8, 8);
13987 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13988 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13989 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13992 APInt FF(32, 0x5F800000ULL);
13994 // Check whether the sign bit is set.
13995 SDValue SignSet = DAG.getSetCC(dl,
13996 getSetCCResultType(*DAG.getContext(), MVT::i64),
13997 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
14000 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
14001 SDValue FudgePtr = DAG.getConstantPool(
14002 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
14005 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
14006 SDValue Zero = DAG.getIntPtrConstant(0);
14007 SDValue Four = DAG.getIntPtrConstant(4);
14008 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
14010 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
14012 // Load the value out, extending it from f32 to f80.
14013 // FIXME: Avoid the extend by constructing the right constant pool?
14014 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
14015 FudgePtr, MachinePointerInfo::getConstantPool(),
14016 MVT::f32, false, false, false, 4);
14017 // Extend everything to 80 bits to force it to be done on x87.
14018 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
14019 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
14022 std::pair<SDValue,SDValue>
14023 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
14024 bool IsSigned, bool IsReplace) const {
14027 EVT DstTy = Op.getValueType();
14029 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
14030 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
14034 assert(DstTy.getSimpleVT() <= MVT::i64 &&
14035 DstTy.getSimpleVT() >= MVT::i16 &&
14036 "Unknown FP_TO_INT to lower!");
14038 // These are really Legal.
14039 if (DstTy == MVT::i32 &&
14040 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14041 return std::make_pair(SDValue(), SDValue());
14042 if (Subtarget->is64Bit() &&
14043 DstTy == MVT::i64 &&
14044 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14045 return std::make_pair(SDValue(), SDValue());
14047 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
14048 // stack slot, or into the FTOL runtime function.
14049 MachineFunction &MF = DAG.getMachineFunction();
14050 unsigned MemSize = DstTy.getSizeInBits()/8;
14051 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14052 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14055 if (!IsSigned && isIntegerTypeFTOL(DstTy))
14056 Opc = X86ISD::WIN_FTOL;
14058 switch (DstTy.getSimpleVT().SimpleTy) {
14059 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
14060 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
14061 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
14062 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
14065 SDValue Chain = DAG.getEntryNode();
14066 SDValue Value = Op.getOperand(0);
14067 EVT TheVT = Op.getOperand(0).getValueType();
14068 // FIXME This causes a redundant load/store if the SSE-class value is already
14069 // in memory, such as if it is on the callstack.
14070 if (isScalarFPTypeInSSEReg(TheVT)) {
14071 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
14072 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
14073 MachinePointerInfo::getFixedStack(SSFI),
14075 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
14077 Chain, StackSlot, DAG.getValueType(TheVT)
14080 MachineMemOperand *MMO =
14081 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14082 MachineMemOperand::MOLoad, MemSize, MemSize);
14083 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
14084 Chain = Value.getValue(1);
14085 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14086 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14089 MachineMemOperand *MMO =
14090 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14091 MachineMemOperand::MOStore, MemSize, MemSize);
14093 if (Opc != X86ISD::WIN_FTOL) {
14094 // Build the FP_TO_INT*_IN_MEM
14095 SDValue Ops[] = { Chain, Value, StackSlot };
14096 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
14098 return std::make_pair(FIST, StackSlot);
14100 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
14101 DAG.getVTList(MVT::Other, MVT::Glue),
14103 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
14104 MVT::i32, ftol.getValue(1));
14105 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
14106 MVT::i32, eax.getValue(2));
14107 SDValue Ops[] = { eax, edx };
14108 SDValue pair = IsReplace
14109 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
14110 : DAG.getMergeValues(Ops, DL);
14111 return std::make_pair(pair, SDValue());
14115 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
14116 const X86Subtarget *Subtarget) {
14117 MVT VT = Op->getSimpleValueType(0);
14118 SDValue In = Op->getOperand(0);
14119 MVT InVT = In.getSimpleValueType();
14122 // Optimize vectors in AVX mode:
14125 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
14126 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
14127 // Concat upper and lower parts.
14130 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
14131 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
14132 // Concat upper and lower parts.
14135 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
14136 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
14137 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
14140 if (Subtarget->hasInt256())
14141 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
14143 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
14144 SDValue Undef = DAG.getUNDEF(InVT);
14145 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
14146 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14147 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14149 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
14150 VT.getVectorNumElements()/2);
14152 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14153 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14155 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14158 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
14159 SelectionDAG &DAG) {
14160 MVT VT = Op->getSimpleValueType(0);
14161 SDValue In = Op->getOperand(0);
14162 MVT InVT = In.getSimpleValueType();
14164 unsigned int NumElts = VT.getVectorNumElements();
14165 if (NumElts != 8 && NumElts != 16)
14168 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14169 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
14171 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
14172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14173 // Now we have only mask extension
14174 assert(InVT.getVectorElementType() == MVT::i1);
14175 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
14176 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14177 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
14178 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14179 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14180 MachinePointerInfo::getConstantPool(),
14181 false, false, false, Alignment);
14183 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
14184 if (VT.is512BitVector())
14186 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
14189 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14190 SelectionDAG &DAG) {
14191 if (Subtarget->hasFp256()) {
14192 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14200 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14201 SelectionDAG &DAG) {
14203 MVT VT = Op.getSimpleValueType();
14204 SDValue In = Op.getOperand(0);
14205 MVT SVT = In.getSimpleValueType();
14207 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
14208 return LowerZERO_EXTEND_AVX512(Op, DAG);
14210 if (Subtarget->hasFp256()) {
14211 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14216 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
14217 VT.getVectorNumElements() != SVT.getVectorNumElements());
14221 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
14223 MVT VT = Op.getSimpleValueType();
14224 SDValue In = Op.getOperand(0);
14225 MVT InVT = In.getSimpleValueType();
14227 if (VT == MVT::i1) {
14228 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
14229 "Invalid scalar TRUNCATE operation");
14230 if (InVT.getSizeInBits() >= 32)
14232 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
14233 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
14235 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
14236 "Invalid TRUNCATE operation");
14238 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
14239 if (VT.getVectorElementType().getSizeInBits() >=8)
14240 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
14242 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14243 unsigned NumElts = InVT.getVectorNumElements();
14244 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
14245 if (InVT.getSizeInBits() < 512) {
14246 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
14247 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
14251 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
14252 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14253 SDValue CP = DAG.getConstantPool(C, getPointerTy());
14254 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14255 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14256 MachinePointerInfo::getConstantPool(),
14257 false, false, false, Alignment);
14258 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
14259 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
14260 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
14263 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
14264 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
14265 if (Subtarget->hasInt256()) {
14266 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14267 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
14268 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
14270 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
14271 DAG.getIntPtrConstant(0));
14274 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14275 DAG.getIntPtrConstant(0));
14276 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14277 DAG.getIntPtrConstant(2));
14278 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14279 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14280 static const int ShufMask[] = {0, 2, 4, 6};
14281 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
14284 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
14285 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
14286 if (Subtarget->hasInt256()) {
14287 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
14289 SmallVector<SDValue,32> pshufbMask;
14290 for (unsigned i = 0; i < 2; ++i) {
14291 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14292 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14293 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14294 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14295 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14296 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14297 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14298 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14299 for (unsigned j = 0; j < 8; ++j)
14300 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14302 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
14303 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
14304 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
14306 static const int ShufMask[] = {0, 2, -1, -1};
14307 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
14309 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14310 DAG.getIntPtrConstant(0));
14311 return DAG.getNode(ISD::BITCAST, DL, VT, In);
14314 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14315 DAG.getIntPtrConstant(0));
14317 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14318 DAG.getIntPtrConstant(4));
14320 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
14321 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
14323 // The PSHUFB mask:
14324 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14325 -1, -1, -1, -1, -1, -1, -1, -1};
14327 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14328 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
14329 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
14331 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14332 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14334 // The MOVLHPS Mask:
14335 static const int ShufMask2[] = {0, 1, 4, 5};
14336 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
14337 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
14340 // Handle truncation of V256 to V128 using shuffles.
14341 if (!VT.is128BitVector() || !InVT.is256BitVector())
14344 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
14346 unsigned NumElems = VT.getVectorNumElements();
14347 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
14349 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
14350 // Prepare truncation shuffle mask
14351 for (unsigned i = 0; i != NumElems; ++i)
14352 MaskVec[i] = i * 2;
14353 SDValue V = DAG.getVectorShuffle(NVT, DL,
14354 DAG.getNode(ISD::BITCAST, DL, NVT, In),
14355 DAG.getUNDEF(NVT), &MaskVec[0]);
14356 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
14357 DAG.getIntPtrConstant(0));
14360 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
14361 SelectionDAG &DAG) const {
14362 assert(!Op.getSimpleValueType().isVector());
14364 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14365 /*IsSigned=*/ true, /*IsReplace=*/ false);
14366 SDValue FIST = Vals.first, StackSlot = Vals.second;
14367 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14368 if (!FIST.getNode()) return Op;
14370 if (StackSlot.getNode())
14371 // Load the result.
14372 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14373 FIST, StackSlot, MachinePointerInfo(),
14374 false, false, false, 0);
14376 // The node is the result.
14380 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
14381 SelectionDAG &DAG) const {
14382 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14383 /*IsSigned=*/ false, /*IsReplace=*/ false);
14384 SDValue FIST = Vals.first, StackSlot = Vals.second;
14385 assert(FIST.getNode() && "Unexpected failure");
14387 if (StackSlot.getNode())
14388 // Load the result.
14389 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14390 FIST, StackSlot, MachinePointerInfo(),
14391 false, false, false, 0);
14393 // The node is the result.
14397 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14399 MVT VT = Op.getSimpleValueType();
14400 SDValue In = Op.getOperand(0);
14401 MVT SVT = In.getSimpleValueType();
14403 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14405 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14406 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14407 In, DAG.getUNDEF(SVT)));
14410 /// The only differences between FABS and FNEG are the mask and the logic op.
14411 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14412 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14413 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14414 "Wrong opcode for lowering FABS or FNEG.");
14416 bool IsFABS = (Op.getOpcode() == ISD::FABS);
14418 // If this is a FABS and it has an FNEG user, bail out to fold the combination
14419 // into an FNABS. We'll lower the FABS after that if it is still in use.
14421 for (SDNode *User : Op->uses())
14422 if (User->getOpcode() == ISD::FNEG)
14425 SDValue Op0 = Op.getOperand(0);
14426 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14429 MVT VT = Op.getSimpleValueType();
14430 // Assume scalar op for initialization; update for vector if needed.
14431 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
14432 // generate a 16-byte vector constant and logic op even for the scalar case.
14433 // Using a 16-byte mask allows folding the load of the mask with
14434 // the logic op, so it can save (~4 bytes) on code size.
14436 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
14437 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14438 // decide if we should generate a 16-byte constant mask when we only need 4 or
14439 // 8 bytes for the scalar case.
14440 if (VT.isVector()) {
14441 EltVT = VT.getVectorElementType();
14442 NumElts = VT.getVectorNumElements();
14445 unsigned EltBits = EltVT.getSizeInBits();
14446 LLVMContext *Context = DAG.getContext();
14447 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14449 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14450 Constant *C = ConstantInt::get(*Context, MaskElt);
14451 C = ConstantVector::getSplat(NumElts, C);
14452 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14453 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14454 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14455 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14456 MachinePointerInfo::getConstantPool(),
14457 false, false, false, Alignment);
14459 if (VT.isVector()) {
14460 // For a vector, cast operands to a vector type, perform the logic op,
14461 // and cast the result back to the original value type.
14462 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14463 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14464 SDValue Operand = IsFNABS ?
14465 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14466 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14467 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14468 return DAG.getNode(ISD::BITCAST, dl, VT,
14469 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14472 // If not vector, then scalar.
14473 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14474 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14475 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14478 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14479 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14480 LLVMContext *Context = DAG.getContext();
14481 SDValue Op0 = Op.getOperand(0);
14482 SDValue Op1 = Op.getOperand(1);
14484 MVT VT = Op.getSimpleValueType();
14485 MVT SrcVT = Op1.getSimpleValueType();
14487 // If second operand is smaller, extend it first.
14488 if (SrcVT.bitsLT(VT)) {
14489 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14492 // And if it is bigger, shrink it first.
14493 if (SrcVT.bitsGT(VT)) {
14494 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14498 // At this point the operands and the result should have the same
14499 // type, and that won't be f80 since that is not custom lowered.
14501 const fltSemantics &Sem =
14502 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
14503 const unsigned SizeInBits = VT.getSizeInBits();
14505 SmallVector<Constant *, 4> CV(
14506 VT == MVT::f64 ? 2 : 4,
14507 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
14509 // First, clear all bits but the sign bit from the second operand (sign).
14510 CV[0] = ConstantFP::get(*Context,
14511 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
14512 Constant *C = ConstantVector::get(CV);
14513 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14514 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14515 MachinePointerInfo::getConstantPool(),
14516 false, false, false, 16);
14517 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14519 // Next, clear the sign bit from the first operand (magnitude).
14520 // If it's a constant, we can clear it here.
14521 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
14522 APFloat APF = Op0CN->getValueAPF();
14523 // If the magnitude is a positive zero, the sign bit alone is enough.
14524 if (APF.isPosZero())
14527 CV[0] = ConstantFP::get(*Context, APF);
14529 CV[0] = ConstantFP::get(
14531 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
14533 C = ConstantVector::get(CV);
14534 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14535 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14536 MachinePointerInfo::getConstantPool(),
14537 false, false, false, 16);
14538 // If the magnitude operand wasn't a constant, we need to AND out the sign.
14539 if (!isa<ConstantFPSDNode>(Op0))
14540 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
14542 // OR the magnitude value with the sign bit.
14543 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
14546 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14547 SDValue N0 = Op.getOperand(0);
14549 MVT VT = Op.getSimpleValueType();
14551 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
14552 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
14553 DAG.getConstant(1, VT));
14554 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
14557 // Check whether an OR'd tree is PTEST-able.
14558 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
14559 SelectionDAG &DAG) {
14560 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14562 if (!Subtarget->hasSSE41())
14565 if (!Op->hasOneUse())
14568 SDNode *N = Op.getNode();
14571 SmallVector<SDValue, 8> Opnds;
14572 DenseMap<SDValue, unsigned> VecInMap;
14573 SmallVector<SDValue, 8> VecIns;
14574 EVT VT = MVT::Other;
14576 // Recognize a special case where a vector is casted into wide integer to
14578 Opnds.push_back(N->getOperand(0));
14579 Opnds.push_back(N->getOperand(1));
14581 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14582 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14583 // BFS traverse all OR'd operands.
14584 if (I->getOpcode() == ISD::OR) {
14585 Opnds.push_back(I->getOperand(0));
14586 Opnds.push_back(I->getOperand(1));
14587 // Re-evaluate the number of nodes to be traversed.
14588 e += 2; // 2 more nodes (LHS and RHS) are pushed.
14592 // Quit if a non-EXTRACT_VECTOR_ELT
14593 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14596 // Quit if without a constant index.
14597 SDValue Idx = I->getOperand(1);
14598 if (!isa<ConstantSDNode>(Idx))
14601 SDValue ExtractedFromVec = I->getOperand(0);
14602 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14603 if (M == VecInMap.end()) {
14604 VT = ExtractedFromVec.getValueType();
14605 // Quit if not 128/256-bit vector.
14606 if (!VT.is128BitVector() && !VT.is256BitVector())
14608 // Quit if not the same type.
14609 if (VecInMap.begin() != VecInMap.end() &&
14610 VT != VecInMap.begin()->first.getValueType())
14612 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14613 VecIns.push_back(ExtractedFromVec);
14615 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14618 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14619 "Not extracted from 128-/256-bit vector.");
14621 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14623 for (DenseMap<SDValue, unsigned>::const_iterator
14624 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14625 // Quit if not all elements are used.
14626 if (I->second != FullMask)
14630 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14632 // Cast all vectors into TestVT for PTEST.
14633 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14634 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
14636 // If more than one full vectors are evaluated, OR them first before PTEST.
14637 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14638 // Each iteration will OR 2 nodes and append the result until there is only
14639 // 1 node left, i.e. the final OR'd value of all vectors.
14640 SDValue LHS = VecIns[Slot];
14641 SDValue RHS = VecIns[Slot + 1];
14642 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14645 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14646 VecIns.back(), VecIns.back());
14649 /// \brief return true if \c Op has a use that doesn't just read flags.
14650 static bool hasNonFlagsUse(SDValue Op) {
14651 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14653 SDNode *User = *UI;
14654 unsigned UOpNo = UI.getOperandNo();
14655 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14656 // Look pass truncate.
14657 UOpNo = User->use_begin().getOperandNo();
14658 User = *User->use_begin();
14661 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14662 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14668 /// Emit nodes that will be selected as "test Op0,Op0", or something
14670 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
14671 SelectionDAG &DAG) const {
14672 if (Op.getValueType() == MVT::i1)
14673 // KORTEST instruction should be selected
14674 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14675 DAG.getConstant(0, Op.getValueType()));
14677 // CF and OF aren't always set the way we want. Determine which
14678 // of these we need.
14679 bool NeedCF = false;
14680 bool NeedOF = false;
14683 case X86::COND_A: case X86::COND_AE:
14684 case X86::COND_B: case X86::COND_BE:
14687 case X86::COND_G: case X86::COND_GE:
14688 case X86::COND_L: case X86::COND_LE:
14689 case X86::COND_O: case X86::COND_NO: {
14690 // Check if we really need to set the
14691 // Overflow flag. If NoSignedWrap is present
14692 // that is not actually needed.
14693 switch (Op->getOpcode()) {
14698 const BinaryWithFlagsSDNode *BinNode =
14699 cast<BinaryWithFlagsSDNode>(Op.getNode());
14700 if (BinNode->hasNoSignedWrap())
14710 // See if we can use the EFLAGS value from the operand instead of
14711 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14712 // we prove that the arithmetic won't overflow, we can't use OF or CF.
14713 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14714 // Emit a CMP with 0, which is the TEST pattern.
14715 //if (Op.getValueType() == MVT::i1)
14716 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14717 // DAG.getConstant(0, MVT::i1));
14718 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14719 DAG.getConstant(0, Op.getValueType()));
14721 unsigned Opcode = 0;
14722 unsigned NumOperands = 0;
14724 // Truncate operations may prevent the merge of the SETCC instruction
14725 // and the arithmetic instruction before it. Attempt to truncate the operands
14726 // of the arithmetic instruction and use a reduced bit-width instruction.
14727 bool NeedTruncation = false;
14728 SDValue ArithOp = Op;
14729 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14730 SDValue Arith = Op->getOperand(0);
14731 // Both the trunc and the arithmetic op need to have one user each.
14732 if (Arith->hasOneUse())
14733 switch (Arith.getOpcode()) {
14740 NeedTruncation = true;
14746 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14747 // which may be the result of a CAST. We use the variable 'Op', which is the
14748 // non-casted variable when we check for possible users.
14749 switch (ArithOp.getOpcode()) {
14751 // Due to an isel shortcoming, be conservative if this add is likely to be
14752 // selected as part of a load-modify-store instruction. When the root node
14753 // in a match is a store, isel doesn't know how to remap non-chain non-flag
14754 // uses of other nodes in the match, such as the ADD in this case. This
14755 // leads to the ADD being left around and reselected, with the result being
14756 // two adds in the output. Alas, even if none our users are stores, that
14757 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
14758 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
14759 // climbing the DAG back to the root, and it doesn't seem to be worth the
14761 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14762 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14763 if (UI->getOpcode() != ISD::CopyToReg &&
14764 UI->getOpcode() != ISD::SETCC &&
14765 UI->getOpcode() != ISD::STORE)
14768 if (ConstantSDNode *C =
14769 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14770 // An add of one will be selected as an INC.
14771 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
14772 Opcode = X86ISD::INC;
14777 // An add of negative one (subtract of one) will be selected as a DEC.
14778 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
14779 Opcode = X86ISD::DEC;
14785 // Otherwise use a regular EFLAGS-setting add.
14786 Opcode = X86ISD::ADD;
14791 // If we have a constant logical shift that's only used in a comparison
14792 // against zero turn it into an equivalent AND. This allows turning it into
14793 // a TEST instruction later.
14794 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14795 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14796 EVT VT = Op.getValueType();
14797 unsigned BitWidth = VT.getSizeInBits();
14798 unsigned ShAmt = Op->getConstantOperandVal(1);
14799 if (ShAmt >= BitWidth) // Avoid undefined shifts.
14801 APInt Mask = ArithOp.getOpcode() == ISD::SRL
14802 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14803 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14804 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14806 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14807 DAG.getConstant(Mask, VT));
14808 DAG.ReplaceAllUsesWith(Op, New);
14814 // If the primary and result isn't used, don't bother using X86ISD::AND,
14815 // because a TEST instruction will be better.
14816 if (!hasNonFlagsUse(Op))
14822 // Due to the ISEL shortcoming noted above, be conservative if this op is
14823 // likely to be selected as part of a load-modify-store instruction.
14824 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14825 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14826 if (UI->getOpcode() == ISD::STORE)
14829 // Otherwise use a regular EFLAGS-setting instruction.
14830 switch (ArithOp.getOpcode()) {
14831 default: llvm_unreachable("unexpected operator!");
14832 case ISD::SUB: Opcode = X86ISD::SUB; break;
14833 case ISD::XOR: Opcode = X86ISD::XOR; break;
14834 case ISD::AND: Opcode = X86ISD::AND; break;
14836 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14837 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14838 if (EFLAGS.getNode())
14841 Opcode = X86ISD::OR;
14855 return SDValue(Op.getNode(), 1);
14861 // If we found that truncation is beneficial, perform the truncation and
14863 if (NeedTruncation) {
14864 EVT VT = Op.getValueType();
14865 SDValue WideVal = Op->getOperand(0);
14866 EVT WideVT = WideVal.getValueType();
14867 unsigned ConvertedOp = 0;
14868 // Use a target machine opcode to prevent further DAGCombine
14869 // optimizations that may separate the arithmetic operations
14870 // from the setcc node.
14871 switch (WideVal.getOpcode()) {
14873 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14874 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14875 case ISD::AND: ConvertedOp = X86ISD::AND; break;
14876 case ISD::OR: ConvertedOp = X86ISD::OR; break;
14877 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14881 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14882 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14883 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14884 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14885 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14891 // Emit a CMP with 0, which is the TEST pattern.
14892 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14893 DAG.getConstant(0, Op.getValueType()));
14895 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14896 SmallVector<SDValue, 4> Ops;
14897 for (unsigned i = 0; i != NumOperands; ++i)
14898 Ops.push_back(Op.getOperand(i));
14900 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14901 DAG.ReplaceAllUsesWith(Op, New);
14902 return SDValue(New.getNode(), 1);
14905 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14907 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14908 SDLoc dl, SelectionDAG &DAG) const {
14909 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
14910 if (C->getAPIntValue() == 0)
14911 return EmitTest(Op0, X86CC, dl, DAG);
14913 if (Op0.getValueType() == MVT::i1)
14914 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
14917 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14918 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14919 // Do the comparison at i32 if it's smaller, besides the Atom case.
14920 // This avoids subregister aliasing issues. Keep the smaller reference
14921 // if we're optimizing for size, however, as that'll allow better folding
14922 // of memory operations.
14923 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14924 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
14925 AttributeSet::FunctionIndex, Attribute::MinSize) &&
14926 !Subtarget->isAtom()) {
14927 unsigned ExtendOp =
14928 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14929 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14930 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14932 // Use SUB instead of CMP to enable CSE between SUB and CMP.
14933 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14934 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14936 return SDValue(Sub.getNode(), 1);
14938 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14941 /// Convert a comparison if required by the subtarget.
14942 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14943 SelectionDAG &DAG) const {
14944 // If the subtarget does not support the FUCOMI instruction, floating-point
14945 // comparisons have to be converted.
14946 if (Subtarget->hasCMov() ||
14947 Cmp.getOpcode() != X86ISD::CMP ||
14948 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14949 !Cmp.getOperand(1).getValueType().isFloatingPoint())
14952 // The instruction selector will select an FUCOM instruction instead of
14953 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14954 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14955 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14957 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14958 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14959 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14960 DAG.getConstant(8, MVT::i8));
14961 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14962 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14965 /// The minimum architected relative accuracy is 2^-12. We need one
14966 /// Newton-Raphson step to have a good float result (24 bits of precision).
14967 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14968 DAGCombinerInfo &DCI,
14969 unsigned &RefinementSteps,
14970 bool &UseOneConstNR) const {
14971 // FIXME: We should use instruction latency models to calculate the cost of
14972 // each potential sequence, but this is very hard to do reliably because
14973 // at least Intel's Core* chips have variable timing based on the number of
14974 // significant digits in the divisor and/or sqrt operand.
14975 if (!Subtarget->useSqrtEst())
14978 EVT VT = Op.getValueType();
14980 // SSE1 has rsqrtss and rsqrtps.
14981 // TODO: Add support for AVX512 (v16f32).
14982 // It is likely not profitable to do this for f64 because a double-precision
14983 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14984 // instructions: convert to single, rsqrtss, convert back to double, refine
14985 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14986 // along with FMA, this could be a throughput win.
14987 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14988 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14989 RefinementSteps = 1;
14990 UseOneConstNR = false;
14991 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14996 /// The minimum architected relative accuracy is 2^-12. We need one
14997 /// Newton-Raphson step to have a good float result (24 bits of precision).
14998 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14999 DAGCombinerInfo &DCI,
15000 unsigned &RefinementSteps) const {
15001 // FIXME: We should use instruction latency models to calculate the cost of
15002 // each potential sequence, but this is very hard to do reliably because
15003 // at least Intel's Core* chips have variable timing based on the number of
15004 // significant digits in the divisor.
15005 if (!Subtarget->useReciprocalEst())
15008 EVT VT = Op.getValueType();
15010 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
15011 // TODO: Add support for AVX512 (v16f32).
15012 // It is likely not profitable to do this for f64 because a double-precision
15013 // reciprocal estimate with refinement on x86 prior to FMA requires
15014 // 15 instructions: convert to single, rcpss, convert back to double, refine
15015 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
15016 // along with FMA, this could be a throughput win.
15017 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
15018 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
15019 RefinementSteps = ReciprocalEstimateRefinementSteps;
15020 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
15025 static bool isAllOnes(SDValue V) {
15026 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15027 return C && C->isAllOnesValue();
15030 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
15031 /// if it's possible.
15032 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
15033 SDLoc dl, SelectionDAG &DAG) const {
15034 SDValue Op0 = And.getOperand(0);
15035 SDValue Op1 = And.getOperand(1);
15036 if (Op0.getOpcode() == ISD::TRUNCATE)
15037 Op0 = Op0.getOperand(0);
15038 if (Op1.getOpcode() == ISD::TRUNCATE)
15039 Op1 = Op1.getOperand(0);
15042 if (Op1.getOpcode() == ISD::SHL)
15043 std::swap(Op0, Op1);
15044 if (Op0.getOpcode() == ISD::SHL) {
15045 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
15046 if (And00C->getZExtValue() == 1) {
15047 // If we looked past a truncate, check that it's only truncating away
15049 unsigned BitWidth = Op0.getValueSizeInBits();
15050 unsigned AndBitWidth = And.getValueSizeInBits();
15051 if (BitWidth > AndBitWidth) {
15053 DAG.computeKnownBits(Op0, Zeros, Ones);
15054 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
15058 RHS = Op0.getOperand(1);
15060 } else if (Op1.getOpcode() == ISD::Constant) {
15061 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
15062 uint64_t AndRHSVal = AndRHS->getZExtValue();
15063 SDValue AndLHS = Op0;
15065 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
15066 LHS = AndLHS.getOperand(0);
15067 RHS = AndLHS.getOperand(1);
15070 // Use BT if the immediate can't be encoded in a TEST instruction.
15071 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
15073 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
15077 if (LHS.getNode()) {
15078 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
15079 // instruction. Since the shift amount is in-range-or-undefined, we know
15080 // that doing a bittest on the i32 value is ok. We extend to i32 because
15081 // the encoding for the i16 version is larger than the i32 version.
15082 // Also promote i16 to i32 for performance / code size reason.
15083 if (LHS.getValueType() == MVT::i8 ||
15084 LHS.getValueType() == MVT::i16)
15085 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
15087 // If the operand types disagree, extend the shift amount to match. Since
15088 // BT ignores high bits (like shifts) we can use anyextend.
15089 if (LHS.getValueType() != RHS.getValueType())
15090 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
15092 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
15093 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
15094 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15095 DAG.getConstant(Cond, MVT::i8), BT);
15101 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
15103 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
15108 // SSE Condition code mapping:
15117 switch (SetCCOpcode) {
15118 default: llvm_unreachable("Unexpected SETCC condition");
15120 case ISD::SETEQ: SSECC = 0; break;
15122 case ISD::SETGT: Swap = true; // Fallthrough
15124 case ISD::SETOLT: SSECC = 1; break;
15126 case ISD::SETGE: Swap = true; // Fallthrough
15128 case ISD::SETOLE: SSECC = 2; break;
15129 case ISD::SETUO: SSECC = 3; break;
15131 case ISD::SETNE: SSECC = 4; break;
15132 case ISD::SETULE: Swap = true; // Fallthrough
15133 case ISD::SETUGE: SSECC = 5; break;
15134 case ISD::SETULT: Swap = true; // Fallthrough
15135 case ISD::SETUGT: SSECC = 6; break;
15136 case ISD::SETO: SSECC = 7; break;
15138 case ISD::SETONE: SSECC = 8; break;
15141 std::swap(Op0, Op1);
15146 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
15147 // ones, and then concatenate the result back.
15148 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
15149 MVT VT = Op.getSimpleValueType();
15151 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
15152 "Unsupported value type for operation");
15154 unsigned NumElems = VT.getVectorNumElements();
15156 SDValue CC = Op.getOperand(2);
15158 // Extract the LHS vectors
15159 SDValue LHS = Op.getOperand(0);
15160 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15161 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15163 // Extract the RHS vectors
15164 SDValue RHS = Op.getOperand(1);
15165 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15166 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15168 // Issue the operation on the smaller types and concatenate the result back
15169 MVT EltVT = VT.getVectorElementType();
15170 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15171 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15172 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
15173 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
15176 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
15177 const X86Subtarget *Subtarget) {
15178 SDValue Op0 = Op.getOperand(0);
15179 SDValue Op1 = Op.getOperand(1);
15180 SDValue CC = Op.getOperand(2);
15181 MVT VT = Op.getSimpleValueType();
15184 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
15185 Op.getValueType().getScalarType() == MVT::i1 &&
15186 "Cannot set masked compare for this operation");
15188 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15190 bool Unsigned = false;
15193 switch (SetCCOpcode) {
15194 default: llvm_unreachable("Unexpected SETCC condition");
15195 case ISD::SETNE: SSECC = 4; break;
15196 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
15197 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
15198 case ISD::SETLT: Swap = true; //fall-through
15199 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
15200 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
15201 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
15202 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
15203 case ISD::SETULE: Unsigned = true; //fall-through
15204 case ISD::SETLE: SSECC = 2; break;
15208 std::swap(Op0, Op1);
15210 return DAG.getNode(Opc, dl, VT, Op0, Op1);
15211 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
15212 return DAG.getNode(Opc, dl, VT, Op0, Op1,
15213 DAG.getConstant(SSECC, MVT::i8));
15216 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
15217 /// operand \p Op1. If non-trivial (for example because it's not constant)
15218 /// return an empty value.
15219 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
15221 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
15225 MVT VT = Op1.getSimpleValueType();
15226 MVT EVT = VT.getVectorElementType();
15227 unsigned n = VT.getVectorNumElements();
15228 SmallVector<SDValue, 8> ULTOp1;
15230 for (unsigned i = 0; i < n; ++i) {
15231 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
15232 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
15235 // Avoid underflow.
15236 APInt Val = Elt->getAPIntValue();
15240 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
15243 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
15246 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
15247 SelectionDAG &DAG) {
15248 SDValue Op0 = Op.getOperand(0);
15249 SDValue Op1 = Op.getOperand(1);
15250 SDValue CC = Op.getOperand(2);
15251 MVT VT = Op.getSimpleValueType();
15252 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15253 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
15258 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
15259 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
15262 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
15263 unsigned Opc = X86ISD::CMPP;
15264 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
15265 assert(VT.getVectorNumElements() <= 16);
15266 Opc = X86ISD::CMPM;
15268 // In the two special cases we can't handle, emit two comparisons.
15271 unsigned CombineOpc;
15272 if (SetCCOpcode == ISD::SETUEQ) {
15273 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
15275 assert(SetCCOpcode == ISD::SETONE);
15276 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
15279 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15280 DAG.getConstant(CC0, MVT::i8));
15281 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15282 DAG.getConstant(CC1, MVT::i8));
15283 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
15285 // Handle all other FP comparisons here.
15286 return DAG.getNode(Opc, dl, VT, Op0, Op1,
15287 DAG.getConstant(SSECC, MVT::i8));
15290 // Break 256-bit integer vector compare into smaller ones.
15291 if (VT.is256BitVector() && !Subtarget->hasInt256())
15292 return Lower256IntVSETCC(Op, DAG);
15294 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
15295 EVT OpVT = Op1.getValueType();
15296 if (Subtarget->hasAVX512()) {
15297 if (Op1.getValueType().is512BitVector() ||
15298 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
15299 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
15300 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
15302 // In AVX-512 architecture setcc returns mask with i1 elements,
15303 // But there is no compare instruction for i8 and i16 elements in KNL.
15304 // We are not talking about 512-bit operands in this case, these
15305 // types are illegal.
15307 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
15308 OpVT.getVectorElementType().getSizeInBits() >= 8))
15309 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15310 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
15313 // We are handling one of the integer comparisons here. Since SSE only has
15314 // GT and EQ comparisons for integer, swapping operands and multiple
15315 // operations may be required for some comparisons.
15317 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
15318 bool Subus = false;
15320 switch (SetCCOpcode) {
15321 default: llvm_unreachable("Unexpected SETCC condition");
15322 case ISD::SETNE: Invert = true;
15323 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
15324 case ISD::SETLT: Swap = true;
15325 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
15326 case ISD::SETGE: Swap = true;
15327 case ISD::SETLE: Opc = X86ISD::PCMPGT;
15328 Invert = true; break;
15329 case ISD::SETULT: Swap = true;
15330 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
15331 FlipSigns = true; break;
15332 case ISD::SETUGE: Swap = true;
15333 case ISD::SETULE: Opc = X86ISD::PCMPGT;
15334 FlipSigns = true; Invert = true; break;
15337 // Special case: Use min/max operations for SETULE/SETUGE
15338 MVT VET = VT.getVectorElementType();
15340 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
15341 || (Subtarget->hasSSE2() && (VET == MVT::i8));
15344 switch (SetCCOpcode) {
15346 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
15347 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
15350 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
15353 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
15354 if (!MinMax && hasSubus) {
15355 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
15357 // t = psubus Op0, Op1
15358 // pcmpeq t, <0..0>
15359 switch (SetCCOpcode) {
15361 case ISD::SETULT: {
15362 // If the comparison is against a constant we can turn this into a
15363 // setule. With psubus, setule does not require a swap. This is
15364 // beneficial because the constant in the register is no longer
15365 // destructed as the destination so it can be hoisted out of a loop.
15366 // Only do this pre-AVX since vpcmp* is no longer destructive.
15367 if (Subtarget->hasAVX())
15369 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
15370 if (ULEOp1.getNode()) {
15372 Subus = true; Invert = false; Swap = false;
15376 // Psubus is better than flip-sign because it requires no inversion.
15377 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
15378 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
15382 Opc = X86ISD::SUBUS;
15388 std::swap(Op0, Op1);
15390 // Check that the operation in question is available (most are plain SSE2,
15391 // but PCMPGTQ and PCMPEQQ have different requirements).
15392 if (VT == MVT::v2i64) {
15393 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
15394 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
15396 // First cast everything to the right type.
15397 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15398 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15400 // Since SSE has no unsigned integer comparisons, we need to flip the sign
15401 // bits of the inputs before performing those operations. The lower
15402 // compare is always unsigned.
15405 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
15407 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
15408 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
15409 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
15410 Sign, Zero, Sign, Zero);
15412 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15413 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15415 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15416 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15417 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15419 // Create masks for only the low parts/high parts of the 64 bit integers.
15420 static const int MaskHi[] = { 1, 1, 3, 3 };
15421 static const int MaskLo[] = { 0, 0, 2, 2 };
15422 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15423 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15424 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15426 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15427 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15430 Result = DAG.getNOT(dl, Result, MVT::v4i32);
15432 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15435 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15436 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15437 // pcmpeqd + pshufd + pand.
15438 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15440 // First cast everything to the right type.
15441 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15442 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15445 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15447 // Make sure the lower and upper halves are both all-ones.
15448 static const int Mask[] = { 1, 0, 3, 2 };
15449 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15450 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15453 Result = DAG.getNOT(dl, Result, MVT::v4i32);
15455 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15459 // Since SSE has no unsigned integer comparisons, we need to flip the sign
15460 // bits of the inputs before performing those operations.
15462 EVT EltVT = VT.getVectorElementType();
15463 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15464 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15465 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15468 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15470 // If the logical-not of the result is required, perform that now.
15472 Result = DAG.getNOT(dl, Result, VT);
15475 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15478 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15479 getZeroVector(VT, Subtarget, DAG, dl));
15484 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15486 MVT VT = Op.getSimpleValueType();
15488 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15490 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15491 && "SetCC type must be 8-bit or 1-bit integer");
15492 SDValue Op0 = Op.getOperand(0);
15493 SDValue Op1 = Op.getOperand(1);
15495 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15497 // Optimize to BT if possible.
15498 // Lower (X & (1 << N)) == 0 to BT(X, N).
15499 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15500 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15501 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15502 Op1.getOpcode() == ISD::Constant &&
15503 cast<ConstantSDNode>(Op1)->isNullValue() &&
15504 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15505 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15506 if (NewSetCC.getNode()) {
15508 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
15513 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
15515 if (Op1.getOpcode() == ISD::Constant &&
15516 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15517 cast<ConstantSDNode>(Op1)->isNullValue()) &&
15518 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15520 // If the input is a setcc, then reuse the input setcc or use a new one with
15521 // the inverted condition.
15522 if (Op0.getOpcode() == X86ISD::SETCC) {
15523 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15524 bool Invert = (CC == ISD::SETNE) ^
15525 cast<ConstantSDNode>(Op1)->isNullValue();
15529 CCode = X86::GetOppositeBranchCondition(CCode);
15530 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15531 DAG.getConstant(CCode, MVT::i8),
15532 Op0.getOperand(1));
15534 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15538 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
15539 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
15540 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15542 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15543 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
15546 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15547 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
15548 if (X86CC == X86::COND_INVALID)
15551 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15552 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15553 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15554 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
15556 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15560 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
15561 static bool isX86LogicalCmp(SDValue Op) {
15562 unsigned Opc = Op.getNode()->getOpcode();
15563 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15564 Opc == X86ISD::SAHF)
15566 if (Op.getResNo() == 1 &&
15567 (Opc == X86ISD::ADD ||
15568 Opc == X86ISD::SUB ||
15569 Opc == X86ISD::ADC ||
15570 Opc == X86ISD::SBB ||
15571 Opc == X86ISD::SMUL ||
15572 Opc == X86ISD::UMUL ||
15573 Opc == X86ISD::INC ||
15574 Opc == X86ISD::DEC ||
15575 Opc == X86ISD::OR ||
15576 Opc == X86ISD::XOR ||
15577 Opc == X86ISD::AND))
15580 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15586 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15587 if (V.getOpcode() != ISD::TRUNCATE)
15590 SDValue VOp0 = V.getOperand(0);
15591 unsigned InBits = VOp0.getValueSizeInBits();
15592 unsigned Bits = V.getValueSizeInBits();
15593 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15596 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15597 bool addTest = true;
15598 SDValue Cond = Op.getOperand(0);
15599 SDValue Op1 = Op.getOperand(1);
15600 SDValue Op2 = Op.getOperand(2);
15602 EVT VT = Op1.getValueType();
15605 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15606 // are available. Otherwise fp cmovs get lowered into a less efficient branch
15607 // sequence later on.
15608 if (Cond.getOpcode() == ISD::SETCC &&
15609 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15610 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15611 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
15612 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15613 int SSECC = translateX86FSETCC(
15614 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15617 if (Subtarget->hasAVX512()) {
15618 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15619 DAG.getConstant(SSECC, MVT::i8));
15620 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15622 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15623 DAG.getConstant(SSECC, MVT::i8));
15624 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15625 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15626 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15630 if (Cond.getOpcode() == ISD::SETCC) {
15631 SDValue NewCond = LowerSETCC(Cond, DAG);
15632 if (NewCond.getNode())
15636 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15637 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15638 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15639 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15640 if (Cond.getOpcode() == X86ISD::SETCC &&
15641 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15642 isZero(Cond.getOperand(1).getOperand(1))) {
15643 SDValue Cmp = Cond.getOperand(1);
15645 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15647 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
15648 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15649 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
15651 SDValue CmpOp0 = Cmp.getOperand(0);
15652 // Apply further optimizations for special cases
15653 // (select (x != 0), -1, 0) -> neg & sbb
15654 // (select (x == 0), 0, -1) -> neg & sbb
15655 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
15656 if (YC->isNullValue() &&
15657 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
15658 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15659 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15660 DAG.getConstant(0, CmpOp0.getValueType()),
15662 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15663 DAG.getConstant(X86::COND_B, MVT::i8),
15664 SDValue(Neg.getNode(), 1));
15668 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15669 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
15670 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15672 SDValue Res = // Res = 0 or -1.
15673 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15674 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
15676 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
15677 Res = DAG.getNOT(DL, Res, Res.getValueType());
15679 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
15680 if (!N2C || !N2C->isNullValue())
15681 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15686 // Look past (and (setcc_carry (cmp ...)), 1).
15687 if (Cond.getOpcode() == ISD::AND &&
15688 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15689 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15690 if (C && C->getAPIntValue() == 1)
15691 Cond = Cond.getOperand(0);
15694 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15695 // setting operand in place of the X86ISD::SETCC.
15696 unsigned CondOpcode = Cond.getOpcode();
15697 if (CondOpcode == X86ISD::SETCC ||
15698 CondOpcode == X86ISD::SETCC_CARRY) {
15699 CC = Cond.getOperand(0);
15701 SDValue Cmp = Cond.getOperand(1);
15702 unsigned Opc = Cmp.getOpcode();
15703 MVT VT = Op.getSimpleValueType();
15705 bool IllegalFPCMov = false;
15706 if (VT.isFloatingPoint() && !VT.isVector() &&
15707 !isScalarFPTypeInSSEReg(VT)) // FPStack?
15708 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15710 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15711 Opc == X86ISD::BT) { // FIXME
15715 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15716 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15717 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15718 Cond.getOperand(0).getValueType() != MVT::i8)) {
15719 SDValue LHS = Cond.getOperand(0);
15720 SDValue RHS = Cond.getOperand(1);
15721 unsigned X86Opcode;
15724 switch (CondOpcode) {
15725 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15726 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15727 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15728 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15729 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15730 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15731 default: llvm_unreachable("unexpected overflowing operator");
15733 if (CondOpcode == ISD::UMULO)
15734 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15737 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15739 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15741 if (CondOpcode == ISD::UMULO)
15742 Cond = X86Op.getValue(2);
15744 Cond = X86Op.getValue(1);
15746 CC = DAG.getConstant(X86Cond, MVT::i8);
15751 // Look pass the truncate if the high bits are known zero.
15752 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15753 Cond = Cond.getOperand(0);
15755 // We know the result of AND is compared against zero. Try to match
15757 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15758 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
15759 if (NewSetCC.getNode()) {
15760 CC = NewSetCC.getOperand(0);
15761 Cond = NewSetCC.getOperand(1);
15768 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15769 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15772 // a < b ? -1 : 0 -> RES = ~setcc_carry
15773 // a < b ? 0 : -1 -> RES = setcc_carry
15774 // a >= b ? -1 : 0 -> RES = setcc_carry
15775 // a >= b ? 0 : -1 -> RES = ~setcc_carry
15776 if (Cond.getOpcode() == X86ISD::SUB) {
15777 Cond = ConvertCmpIfNecessary(Cond, DAG);
15778 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15780 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15781 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
15782 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15783 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
15784 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
15785 return DAG.getNOT(DL, Res, Res.getValueType());
15790 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15791 // widen the cmov and push the truncate through. This avoids introducing a new
15792 // branch during isel and doesn't add any extensions.
15793 if (Op.getValueType() == MVT::i8 &&
15794 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15795 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15796 if (T1.getValueType() == T2.getValueType() &&
15797 // Blacklist CopyFromReg to avoid partial register stalls.
15798 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15799 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15800 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15801 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15805 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15806 // condition is true.
15807 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15808 SDValue Ops[] = { Op2, Op1, CC, Cond };
15809 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15812 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
15813 SelectionDAG &DAG) {
15814 MVT VT = Op->getSimpleValueType(0);
15815 SDValue In = Op->getOperand(0);
15816 MVT InVT = In.getSimpleValueType();
15817 MVT VTElt = VT.getVectorElementType();
15818 MVT InVTElt = InVT.getVectorElementType();
15822 if ((InVTElt == MVT::i1) &&
15823 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15824 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15826 ((Subtarget->hasBWI() && VT.is512BitVector() &&
15827 VTElt.getSizeInBits() <= 16)) ||
15829 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15830 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15832 ((Subtarget->hasDQI() && VT.is512BitVector() &&
15833 VTElt.getSizeInBits() >= 32))))
15834 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15836 unsigned int NumElts = VT.getVectorNumElements();
15838 if (NumElts != 8 && NumElts != 16)
15841 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15842 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15843 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15844 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15847 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15848 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15850 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
15851 Constant *C = ConstantInt::get(*DAG.getContext(),
15852 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
15854 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
15855 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
15856 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
15857 MachinePointerInfo::getConstantPool(),
15858 false, false, false, Alignment);
15859 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
15860 if (VT.is512BitVector())
15862 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
15865 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15866 SelectionDAG &DAG) {
15867 MVT VT = Op->getSimpleValueType(0);
15868 SDValue In = Op->getOperand(0);
15869 MVT InVT = In.getSimpleValueType();
15872 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15873 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15875 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15876 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15877 (VT != MVT::v16i16 || InVT != MVT::v16i8))
15880 if (Subtarget->hasInt256())
15881 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15883 // Optimize vectors in AVX mode
15884 // Sign extend v8i16 to v8i32 and
15887 // Divide input vector into two parts
15888 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15889 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15890 // concat the vectors to original VT
15892 unsigned NumElems = InVT.getVectorNumElements();
15893 SDValue Undef = DAG.getUNDEF(InVT);
15895 SmallVector<int,8> ShufMask1(NumElems, -1);
15896 for (unsigned i = 0; i != NumElems/2; ++i)
15899 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15901 SmallVector<int,8> ShufMask2(NumElems, -1);
15902 for (unsigned i = 0; i != NumElems/2; ++i)
15903 ShufMask2[i] = i + NumElems/2;
15905 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15907 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15908 VT.getVectorNumElements()/2);
15910 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15911 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15913 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15916 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15917 // may emit an illegal shuffle but the expansion is still better than scalar
15918 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15919 // we'll emit a shuffle and a arithmetic shift.
15920 // TODO: It is possible to support ZExt by zeroing the undef values during
15921 // the shuffle phase or after the shuffle.
15922 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15923 SelectionDAG &DAG) {
15924 MVT RegVT = Op.getSimpleValueType();
15925 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15926 assert(RegVT.isInteger() &&
15927 "We only custom lower integer vector sext loads.");
15929 // Nothing useful we can do without SSE2 shuffles.
15930 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15932 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15934 EVT MemVT = Ld->getMemoryVT();
15935 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15936 unsigned RegSz = RegVT.getSizeInBits();
15938 ISD::LoadExtType Ext = Ld->getExtensionType();
15940 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15941 && "Only anyext and sext are currently implemented.");
15942 assert(MemVT != RegVT && "Cannot extend to the same type");
15943 assert(MemVT.isVector() && "Must load a vector from memory");
15945 unsigned NumElems = RegVT.getVectorNumElements();
15946 unsigned MemSz = MemVT.getSizeInBits();
15947 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15949 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15950 // The only way in which we have a legal 256-bit vector result but not the
15951 // integer 256-bit operations needed to directly lower a sextload is if we
15952 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15953 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15954 // correctly legalized. We do this late to allow the canonical form of
15955 // sextload to persist throughout the rest of the DAG combiner -- it wants
15956 // to fold together any extensions it can, and so will fuse a sign_extend
15957 // of an sextload into a sextload targeting a wider value.
15959 if (MemSz == 128) {
15960 // Just switch this to a normal load.
15961 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15962 "it must be a legal 128-bit vector "
15964 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15965 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15966 Ld->isInvariant(), Ld->getAlignment());
15968 assert(MemSz < 128 &&
15969 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15970 // Do an sext load to a 128-bit vector type. We want to use the same
15971 // number of elements, but elements half as wide. This will end up being
15972 // recursively lowered by this routine, but will succeed as we definitely
15973 // have all the necessary features if we're using AVX1.
15975 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15976 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15978 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15979 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15980 Ld->isNonTemporal(), Ld->isInvariant(),
15981 Ld->getAlignment());
15984 // Replace chain users with the new chain.
15985 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15986 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15988 // Finally, do a normal sign-extend to the desired register.
15989 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15992 // All sizes must be a power of two.
15993 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15994 "Non-power-of-two elements are not custom lowered!");
15996 // Attempt to load the original value using scalar loads.
15997 // Find the largest scalar type that divides the total loaded size.
15998 MVT SclrLoadTy = MVT::i8;
15999 for (MVT Tp : MVT::integer_valuetypes()) {
16000 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16005 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16006 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16008 SclrLoadTy = MVT::f64;
16010 // Calculate the number of scalar loads that we need to perform
16011 // in order to load our vector from memory.
16012 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16014 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
16015 "Can only lower sext loads with a single scalar load!");
16017 unsigned loadRegZize = RegSz;
16018 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16021 // Represent our vector as a sequence of elements which are the
16022 // largest scalar that we can load.
16023 EVT LoadUnitVecVT = EVT::getVectorVT(
16024 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
16026 // Represent the data using the same element type that is stored in
16027 // memory. In practice, we ''widen'' MemVT.
16029 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16030 loadRegZize / MemVT.getScalarType().getSizeInBits());
16032 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16033 "Invalid vector type");
16035 // We can't shuffle using an illegal type.
16036 assert(TLI.isTypeLegal(WideVecVT) &&
16037 "We only lower types that form legal widened vector types");
16039 SmallVector<SDValue, 8> Chains;
16040 SDValue Ptr = Ld->getBasePtr();
16041 SDValue Increment =
16042 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
16043 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16045 for (unsigned i = 0; i < NumLoads; ++i) {
16046 // Perform a single load.
16047 SDValue ScalarLoad =
16048 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
16049 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
16050 Ld->getAlignment());
16051 Chains.push_back(ScalarLoad.getValue(1));
16052 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16053 // another round of DAGCombining.
16055 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16057 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16058 ScalarLoad, DAG.getIntPtrConstant(i));
16060 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16063 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16065 // Bitcast the loaded value to a vector of the original element type, in
16066 // the size of the target vector type.
16067 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16068 unsigned SizeRatio = RegSz / MemSz;
16070 if (Ext == ISD::SEXTLOAD) {
16071 // If we have SSE4.1, we can directly emit a VSEXT node.
16072 if (Subtarget->hasSSE41()) {
16073 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16074 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16078 // Otherwise we'll shuffle the small elements in the high bits of the
16079 // larger type and perform an arithmetic shift. If the shift is not legal
16080 // it's better to scalarize.
16081 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
16082 "We can't implement a sext load without an arithmetic right shift!");
16084 // Redistribute the loaded elements into the different locations.
16085 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16086 for (unsigned i = 0; i != NumElems; ++i)
16087 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
16089 SDValue Shuff = DAG.getVectorShuffle(
16090 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16092 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16094 // Build the arithmetic shift.
16095 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16096 MemVT.getVectorElementType().getSizeInBits();
16098 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
16100 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16104 // Redistribute the loaded elements into the different locations.
16105 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16106 for (unsigned i = 0; i != NumElems; ++i)
16107 ShuffleVec[i * SizeRatio] = i;
16109 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16110 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16112 // Bitcast to the requested type.
16113 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16114 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16118 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
16119 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
16120 // from the AND / OR.
16121 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
16122 Opc = Op.getOpcode();
16123 if (Opc != ISD::OR && Opc != ISD::AND)
16125 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16126 Op.getOperand(0).hasOneUse() &&
16127 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
16128 Op.getOperand(1).hasOneUse());
16131 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
16132 // 1 and that the SETCC node has a single use.
16133 static bool isXor1OfSetCC(SDValue Op) {
16134 if (Op.getOpcode() != ISD::XOR)
16136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16137 if (N1C && N1C->getAPIntValue() == 1) {
16138 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16139 Op.getOperand(0).hasOneUse();
16144 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
16145 bool addTest = true;
16146 SDValue Chain = Op.getOperand(0);
16147 SDValue Cond = Op.getOperand(1);
16148 SDValue Dest = Op.getOperand(2);
16151 bool Inverted = false;
16153 if (Cond.getOpcode() == ISD::SETCC) {
16154 // Check for setcc([su]{add,sub,mul}o == 0).
16155 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
16156 isa<ConstantSDNode>(Cond.getOperand(1)) &&
16157 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
16158 Cond.getOperand(0).getResNo() == 1 &&
16159 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
16160 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
16161 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
16162 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
16163 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
16164 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
16166 Cond = Cond.getOperand(0);
16168 SDValue NewCond = LowerSETCC(Cond, DAG);
16169 if (NewCond.getNode())
16174 // FIXME: LowerXALUO doesn't handle these!!
16175 else if (Cond.getOpcode() == X86ISD::ADD ||
16176 Cond.getOpcode() == X86ISD::SUB ||
16177 Cond.getOpcode() == X86ISD::SMUL ||
16178 Cond.getOpcode() == X86ISD::UMUL)
16179 Cond = LowerXALUO(Cond, DAG);
16182 // Look pass (and (setcc_carry (cmp ...)), 1).
16183 if (Cond.getOpcode() == ISD::AND &&
16184 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
16185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
16186 if (C && C->getAPIntValue() == 1)
16187 Cond = Cond.getOperand(0);
16190 // If condition flag is set by a X86ISD::CMP, then use it as the condition
16191 // setting operand in place of the X86ISD::SETCC.
16192 unsigned CondOpcode = Cond.getOpcode();
16193 if (CondOpcode == X86ISD::SETCC ||
16194 CondOpcode == X86ISD::SETCC_CARRY) {
16195 CC = Cond.getOperand(0);
16197 SDValue Cmp = Cond.getOperand(1);
16198 unsigned Opc = Cmp.getOpcode();
16199 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
16200 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
16204 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
16208 // These can only come from an arithmetic instruction with overflow,
16209 // e.g. SADDO, UADDO.
16210 Cond = Cond.getNode()->getOperand(1);
16216 CondOpcode = Cond.getOpcode();
16217 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16218 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16219 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16220 Cond.getOperand(0).getValueType() != MVT::i8)) {
16221 SDValue LHS = Cond.getOperand(0);
16222 SDValue RHS = Cond.getOperand(1);
16223 unsigned X86Opcode;
16226 // Keep this in sync with LowerXALUO, otherwise we might create redundant
16227 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
16229 switch (CondOpcode) {
16230 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16232 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16234 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
16237 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16238 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16242 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
16245 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16246 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16247 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16248 default: llvm_unreachable("unexpected overflowing operator");
16251 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
16252 if (CondOpcode == ISD::UMULO)
16253 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16256 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16258 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
16260 if (CondOpcode == ISD::UMULO)
16261 Cond = X86Op.getValue(2);
16263 Cond = X86Op.getValue(1);
16265 CC = DAG.getConstant(X86Cond, MVT::i8);
16269 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
16270 SDValue Cmp = Cond.getOperand(0).getOperand(1);
16271 if (CondOpc == ISD::OR) {
16272 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
16273 // two branches instead of an explicit OR instruction with a
16275 if (Cmp == Cond.getOperand(1).getOperand(1) &&
16276 isX86LogicalCmp(Cmp)) {
16277 CC = Cond.getOperand(0).getOperand(0);
16278 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16279 Chain, Dest, CC, Cmp);
16280 CC = Cond.getOperand(1).getOperand(0);
16284 } else { // ISD::AND
16285 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
16286 // two branches instead of an explicit AND instruction with a
16287 // separate test. However, we only do this if this block doesn't
16288 // have a fall-through edge, because this requires an explicit
16289 // jmp when the condition is false.
16290 if (Cmp == Cond.getOperand(1).getOperand(1) &&
16291 isX86LogicalCmp(Cmp) &&
16292 Op.getNode()->hasOneUse()) {
16293 X86::CondCode CCode =
16294 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16295 CCode = X86::GetOppositeBranchCondition(CCode);
16296 CC = DAG.getConstant(CCode, MVT::i8);
16297 SDNode *User = *Op.getNode()->use_begin();
16298 // Look for an unconditional branch following this conditional branch.
16299 // We need this because we need to reverse the successors in order
16300 // to implement FCMP_OEQ.
16301 if (User->getOpcode() == ISD::BR) {
16302 SDValue FalseBB = User->getOperand(1);
16304 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16305 assert(NewBR == User);
16309 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16310 Chain, Dest, CC, Cmp);
16311 X86::CondCode CCode =
16312 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
16313 CCode = X86::GetOppositeBranchCondition(CCode);
16314 CC = DAG.getConstant(CCode, MVT::i8);
16320 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
16321 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
16322 // It should be transformed during dag combiner except when the condition
16323 // is set by a arithmetics with overflow node.
16324 X86::CondCode CCode =
16325 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16326 CCode = X86::GetOppositeBranchCondition(CCode);
16327 CC = DAG.getConstant(CCode, MVT::i8);
16328 Cond = Cond.getOperand(0).getOperand(1);
16330 } else if (Cond.getOpcode() == ISD::SETCC &&
16331 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
16332 // For FCMP_OEQ, we can emit
16333 // two branches instead of an explicit AND instruction with a
16334 // separate test. However, we only do this if this block doesn't
16335 // have a fall-through edge, because this requires an explicit
16336 // jmp when the condition is false.
16337 if (Op.getNode()->hasOneUse()) {
16338 SDNode *User = *Op.getNode()->use_begin();
16339 // Look for an unconditional branch following this conditional branch.
16340 // We need this because we need to reverse the successors in order
16341 // to implement FCMP_OEQ.
16342 if (User->getOpcode() == ISD::BR) {
16343 SDValue FalseBB = User->getOperand(1);
16345 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16346 assert(NewBR == User);
16350 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16351 Cond.getOperand(0), Cond.getOperand(1));
16352 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16353 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16354 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16355 Chain, Dest, CC, Cmp);
16356 CC = DAG.getConstant(X86::COND_P, MVT::i8);
16361 } else if (Cond.getOpcode() == ISD::SETCC &&
16362 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
16363 // For FCMP_UNE, we can emit
16364 // two branches instead of an explicit AND instruction with a
16365 // separate test. However, we only do this if this block doesn't
16366 // have a fall-through edge, because this requires an explicit
16367 // jmp when the condition is false.
16368 if (Op.getNode()->hasOneUse()) {
16369 SDNode *User = *Op.getNode()->use_begin();
16370 // Look for an unconditional branch following this conditional branch.
16371 // We need this because we need to reverse the successors in order
16372 // to implement FCMP_UNE.
16373 if (User->getOpcode() == ISD::BR) {
16374 SDValue FalseBB = User->getOperand(1);
16376 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16377 assert(NewBR == User);
16380 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16381 Cond.getOperand(0), Cond.getOperand(1));
16382 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16383 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16384 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16385 Chain, Dest, CC, Cmp);
16386 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
16396 // Look pass the truncate if the high bits are known zero.
16397 if (isTruncWithZeroHighBitsInput(Cond, DAG))
16398 Cond = Cond.getOperand(0);
16400 // We know the result of AND is compared against zero. Try to match
16402 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16403 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
16404 if (NewSetCC.getNode()) {
16405 CC = NewSetCC.getOperand(0);
16406 Cond = NewSetCC.getOperand(1);
16413 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16414 CC = DAG.getConstant(X86Cond, MVT::i8);
16415 Cond = EmitTest(Cond, X86Cond, dl, DAG);
16417 Cond = ConvertCmpIfNecessary(Cond, DAG);
16418 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16419 Chain, Dest, CC, Cond);
16422 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16423 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16424 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16425 // that the guard pages used by the OS virtual memory manager are allocated in
16426 // correct sequence.
16428 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16429 SelectionDAG &DAG) const {
16430 MachineFunction &MF = DAG.getMachineFunction();
16431 bool SplitStack = MF.shouldSplitStack();
16432 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
16437 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16438 SDNode* Node = Op.getNode();
16440 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16441 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16442 " not tell us which reg is the stack pointer!");
16443 EVT VT = Node->getValueType(0);
16444 SDValue Tmp1 = SDValue(Node, 0);
16445 SDValue Tmp2 = SDValue(Node, 1);
16446 SDValue Tmp3 = Node->getOperand(2);
16447 SDValue Chain = Tmp1.getOperand(0);
16449 // Chain the dynamic stack allocation so that it doesn't modify the stack
16450 // pointer when other instructions are using the stack.
16451 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16454 SDValue Size = Tmp2.getOperand(1);
16455 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16456 Chain = SP.getValue(1);
16457 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16458 const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
16459 unsigned StackAlign = TFI.getStackAlignment();
16460 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16461 if (Align > StackAlign)
16462 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16463 DAG.getConstant(-(uint64_t)Align, VT));
16464 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16466 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16467 DAG.getIntPtrConstant(0, true), SDValue(),
16470 SDValue Ops[2] = { Tmp1, Tmp2 };
16471 return DAG.getMergeValues(Ops, dl);
16475 SDValue Chain = Op.getOperand(0);
16476 SDValue Size = Op.getOperand(1);
16477 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16478 EVT VT = Op.getNode()->getValueType(0);
16480 bool Is64Bit = Subtarget->is64Bit();
16481 EVT SPTy = getPointerTy();
16484 MachineRegisterInfo &MRI = MF.getRegInfo();
16487 // The 64 bit implementation of segmented stacks needs to clobber both r10
16488 // r11. This makes it impossible to use it along with nested parameters.
16489 const Function *F = MF.getFunction();
16491 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16493 if (I->hasNestAttr())
16494 report_fatal_error("Cannot use segmented stacks with functions that "
16495 "have nested arguments.");
16498 const TargetRegisterClass *AddrRegClass =
16499 getRegClassFor(getPointerTy());
16500 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16501 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16502 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16503 DAG.getRegister(Vreg, SPTy));
16504 SDValue Ops1[2] = { Value, Chain };
16505 return DAG.getMergeValues(Ops1, dl);
16508 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16510 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16511 Flag = Chain.getValue(1);
16512 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16514 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16516 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16517 DAG.getSubtarget().getRegisterInfo());
16518 unsigned SPReg = RegInfo->getStackRegister();
16519 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16520 Chain = SP.getValue(1);
16523 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16524 DAG.getConstant(-(uint64_t)Align, VT));
16525 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16528 SDValue Ops1[2] = { SP, Chain };
16529 return DAG.getMergeValues(Ops1, dl);
16533 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16534 MachineFunction &MF = DAG.getMachineFunction();
16535 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16537 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16540 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
16541 // vastart just stores the address of the VarArgsFrameIndex slot into the
16542 // memory location argument.
16543 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16545 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16546 MachinePointerInfo(SV), false, false, 0);
16550 // gp_offset (0 - 6 * 8)
16551 // fp_offset (48 - 48 + 8 * 16)
16552 // overflow_arg_area (point to parameters coming in memory).
16554 SmallVector<SDValue, 8> MemOps;
16555 SDValue FIN = Op.getOperand(1);
16557 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16558 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16560 FIN, MachinePointerInfo(SV), false, false, 0);
16561 MemOps.push_back(Store);
16564 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16565 FIN, DAG.getIntPtrConstant(4));
16566 Store = DAG.getStore(Op.getOperand(0), DL,
16567 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
16569 FIN, MachinePointerInfo(SV, 4), false, false, 0);
16570 MemOps.push_back(Store);
16572 // Store ptr to overflow_arg_area
16573 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16574 FIN, DAG.getIntPtrConstant(4));
16575 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16577 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16578 MachinePointerInfo(SV, 8),
16580 MemOps.push_back(Store);
16582 // Store ptr to reg_save_area.
16583 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16584 FIN, DAG.getIntPtrConstant(8));
16585 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
16587 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
16588 MachinePointerInfo(SV, 16), false, false, 0);
16589 MemOps.push_back(Store);
16590 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16593 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16594 assert(Subtarget->is64Bit() &&
16595 "LowerVAARG only handles 64-bit va_arg!");
16596 assert((Subtarget->isTargetLinux() ||
16597 Subtarget->isTargetDarwin()) &&
16598 "Unhandled target in LowerVAARG");
16599 assert(Op.getNode()->getNumOperands() == 4);
16600 SDValue Chain = Op.getOperand(0);
16601 SDValue SrcPtr = Op.getOperand(1);
16602 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16603 unsigned Align = Op.getConstantOperandVal(3);
16606 EVT ArgVT = Op.getNode()->getValueType(0);
16607 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16608 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
16611 // Decide which area this value should be read from.
16612 // TODO: Implement the AMD64 ABI in its entirety. This simple
16613 // selection mechanism works only for the basic types.
16614 if (ArgVT == MVT::f80) {
16615 llvm_unreachable("va_arg for f80 not yet implemented");
16616 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16617 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
16618 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16619 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
16621 llvm_unreachable("Unhandled argument type in LowerVAARG");
16624 if (ArgMode == 2) {
16625 // Sanity Check: Make sure using fp_offset makes sense.
16626 assert(!DAG.getTarget().Options.UseSoftFloat &&
16627 !(DAG.getMachineFunction()
16628 .getFunction()->getAttributes()
16629 .hasAttribute(AttributeSet::FunctionIndex,
16630 Attribute::NoImplicitFloat)) &&
16631 Subtarget->hasSSE1());
16634 // Insert VAARG_64 node into the DAG
16635 // VAARG_64 returns two values: Variable Argument Address, Chain
16636 SmallVector<SDValue, 11> InstOps;
16637 InstOps.push_back(Chain);
16638 InstOps.push_back(SrcPtr);
16639 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
16640 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
16641 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
16642 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
16643 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16644 VTs, InstOps, MVT::i64,
16645 MachinePointerInfo(SV),
16647 /*Volatile=*/false,
16649 /*WriteMem=*/true);
16650 Chain = VAARG.getValue(1);
16652 // Load the next argument and return it
16653 return DAG.getLoad(ArgVT, dl,
16656 MachinePointerInfo(),
16657 false, false, false, 0);
16660 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16661 SelectionDAG &DAG) {
16662 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
16663 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16664 SDValue Chain = Op.getOperand(0);
16665 SDValue DstPtr = Op.getOperand(1);
16666 SDValue SrcPtr = Op.getOperand(2);
16667 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16668 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16671 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16672 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
16674 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16677 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16678 // amount is a constant. Takes immediate version of shift as input.
16679 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16680 SDValue SrcOp, uint64_t ShiftAmt,
16681 SelectionDAG &DAG) {
16682 MVT ElementType = VT.getVectorElementType();
16684 // Fold this packed shift into its first operand if ShiftAmt is 0.
16688 // Check for ShiftAmt >= element width
16689 if (ShiftAmt >= ElementType.getSizeInBits()) {
16690 if (Opc == X86ISD::VSRAI)
16691 ShiftAmt = ElementType.getSizeInBits() - 1;
16693 return DAG.getConstant(0, VT);
16696 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16697 && "Unknown target vector shift-by-constant node");
16699 // Fold this packed vector shift into a build vector if SrcOp is a
16700 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16701 if (VT == SrcOp.getSimpleValueType() &&
16702 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16703 SmallVector<SDValue, 8> Elts;
16704 unsigned NumElts = SrcOp->getNumOperands();
16705 ConstantSDNode *ND;
16708 default: llvm_unreachable(nullptr);
16709 case X86ISD::VSHLI:
16710 for (unsigned i=0; i!=NumElts; ++i) {
16711 SDValue CurrentOp = SrcOp->getOperand(i);
16712 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16713 Elts.push_back(CurrentOp);
16716 ND = cast<ConstantSDNode>(CurrentOp);
16717 const APInt &C = ND->getAPIntValue();
16718 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
16721 case X86ISD::VSRLI:
16722 for (unsigned i=0; i!=NumElts; ++i) {
16723 SDValue CurrentOp = SrcOp->getOperand(i);
16724 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16725 Elts.push_back(CurrentOp);
16728 ND = cast<ConstantSDNode>(CurrentOp);
16729 const APInt &C = ND->getAPIntValue();
16730 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
16733 case X86ISD::VSRAI:
16734 for (unsigned i=0; i!=NumElts; ++i) {
16735 SDValue CurrentOp = SrcOp->getOperand(i);
16736 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16737 Elts.push_back(CurrentOp);
16740 ND = cast<ConstantSDNode>(CurrentOp);
16741 const APInt &C = ND->getAPIntValue();
16742 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
16747 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16750 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
16753 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16754 // may or may not be a constant. Takes immediate version of shift as input.
16755 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16756 SDValue SrcOp, SDValue ShAmt,
16757 SelectionDAG &DAG) {
16758 MVT SVT = ShAmt.getSimpleValueType();
16759 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16761 // Catch shift-by-constant.
16762 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16763 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16764 CShAmt->getZExtValue(), DAG);
16766 // Change opcode to non-immediate version
16768 default: llvm_unreachable("Unknown target vector shift node");
16769 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16770 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16771 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16774 const X86Subtarget &Subtarget =
16775 DAG.getTarget().getSubtarget<X86Subtarget>();
16776 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16777 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16778 // Let the shuffle legalizer expand this shift amount node.
16779 SDValue Op0 = ShAmt.getOperand(0);
16780 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16781 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16783 // Need to build a vector containing shift amount.
16784 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16785 SmallVector<SDValue, 4> ShOps;
16786 ShOps.push_back(ShAmt);
16787 if (SVT == MVT::i32) {
16788 ShOps.push_back(DAG.getConstant(0, SVT));
16789 ShOps.push_back(DAG.getUNDEF(SVT));
16791 ShOps.push_back(DAG.getUNDEF(SVT));
16793 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16794 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16797 // The return type has to be a 128-bit type with the same element
16798 // type as the input type.
16799 MVT EltVT = VT.getVectorElementType();
16800 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16802 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
16803 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16806 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16807 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16808 /// necessary casting for \p Mask when lowering masking intrinsics.
16809 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16810 SDValue PreservedSrc,
16811 const X86Subtarget *Subtarget,
16812 SelectionDAG &DAG) {
16813 EVT VT = Op.getValueType();
16814 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16815 MVT::i1, VT.getVectorNumElements());
16816 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16817 Mask.getValueType().getSizeInBits());
16820 assert(MaskVT.isSimple() && "invalid mask type");
16822 if (isAllOnes(Mask))
16825 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16826 // are extracted by EXTRACT_SUBVECTOR.
16827 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16828 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16829 DAG.getIntPtrConstant(0));
16831 switch (Op.getOpcode()) {
16833 case X86ISD::PCMPEQM:
16834 case X86ISD::PCMPGTM:
16836 case X86ISD::CMPMU:
16837 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16839 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16840 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16841 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
16844 /// \brief Creates an SDNode for a predicated scalar operation.
16845 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16846 /// The mask is comming as MVT::i8 and it should be truncated
16847 /// to MVT::i1 while lowering masking intrinsics.
16848 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16849 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
16850 /// a scalar instruction.
16851 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16852 SDValue PreservedSrc,
16853 const X86Subtarget *Subtarget,
16854 SelectionDAG &DAG) {
16855 if (isAllOnes(Mask))
16858 EVT VT = Op.getValueType();
16860 // The mask should be of type MVT::i1
16861 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16863 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16864 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16865 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16868 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
16870 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16871 case Intrinsic::x86_fma_vfmadd_ps:
16872 case Intrinsic::x86_fma_vfmadd_pd:
16873 case Intrinsic::x86_fma_vfmadd_ps_256:
16874 case Intrinsic::x86_fma_vfmadd_pd_256:
16875 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16876 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16877 return X86ISD::FMADD;
16878 case Intrinsic::x86_fma_vfmsub_ps:
16879 case Intrinsic::x86_fma_vfmsub_pd:
16880 case Intrinsic::x86_fma_vfmsub_ps_256:
16881 case Intrinsic::x86_fma_vfmsub_pd_256:
16882 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16883 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16884 return X86ISD::FMSUB;
16885 case Intrinsic::x86_fma_vfnmadd_ps:
16886 case Intrinsic::x86_fma_vfnmadd_pd:
16887 case Intrinsic::x86_fma_vfnmadd_ps_256:
16888 case Intrinsic::x86_fma_vfnmadd_pd_256:
16889 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16890 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16891 return X86ISD::FNMADD;
16892 case Intrinsic::x86_fma_vfnmsub_ps:
16893 case Intrinsic::x86_fma_vfnmsub_pd:
16894 case Intrinsic::x86_fma_vfnmsub_ps_256:
16895 case Intrinsic::x86_fma_vfnmsub_pd_256:
16896 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16897 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16898 return X86ISD::FNMSUB;
16899 case Intrinsic::x86_fma_vfmaddsub_ps:
16900 case Intrinsic::x86_fma_vfmaddsub_pd:
16901 case Intrinsic::x86_fma_vfmaddsub_ps_256:
16902 case Intrinsic::x86_fma_vfmaddsub_pd_256:
16903 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16904 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16905 return X86ISD::FMADDSUB;
16906 case Intrinsic::x86_fma_vfmsubadd_ps:
16907 case Intrinsic::x86_fma_vfmsubadd_pd:
16908 case Intrinsic::x86_fma_vfmsubadd_ps_256:
16909 case Intrinsic::x86_fma_vfmsubadd_pd_256:
16910 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16911 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
16912 return X86ISD::FMSUBADD;
16916 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16917 SelectionDAG &DAG) {
16919 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16920 EVT VT = Op.getValueType();
16921 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16923 switch(IntrData->Type) {
16924 case INTR_TYPE_1OP:
16925 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16926 case INTR_TYPE_2OP:
16927 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16929 case INTR_TYPE_3OP:
16930 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16931 Op.getOperand(2), Op.getOperand(3));
16932 case INTR_TYPE_1OP_MASK_RM: {
16933 SDValue Src = Op.getOperand(1);
16934 SDValue Src0 = Op.getOperand(2);
16935 SDValue Mask = Op.getOperand(3);
16936 SDValue RoundingMode = Op.getOperand(4);
16937 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16939 Mask, Src0, Subtarget, DAG);
16941 case INTR_TYPE_SCALAR_MASK_RM: {
16942 SDValue Src1 = Op.getOperand(1);
16943 SDValue Src2 = Op.getOperand(2);
16944 SDValue Src0 = Op.getOperand(3);
16945 SDValue Mask = Op.getOperand(4);
16946 SDValue RoundingMode = Op.getOperand(5);
16947 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16949 Mask, Src0, Subtarget, DAG);
16951 case INTR_TYPE_2OP_MASK: {
16952 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Op.getOperand(1),
16954 Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);
16957 case CMP_MASK_CC: {
16958 // Comparison intrinsics with masks.
16959 // Example of transformation:
16960 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16961 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16963 // (v8i1 (insert_subvector undef,
16964 // (v2i1 (and (PCMPEQM %a, %b),
16965 // (extract_subvector
16966 // (v8i1 (bitcast %mask)), 0))), 0))))
16967 EVT VT = Op.getOperand(1).getValueType();
16968 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16969 VT.getVectorNumElements());
16970 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16971 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16972 Mask.getValueType().getSizeInBits());
16974 if (IntrData->Type == CMP_MASK_CC) {
16975 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16976 Op.getOperand(2), Op.getOperand(3));
16978 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16979 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16982 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16983 DAG.getTargetConstant(0, MaskVT),
16985 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16986 DAG.getUNDEF(BitcastVT), CmpMask,
16987 DAG.getIntPtrConstant(0));
16988 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
16990 case COMI: { // Comparison intrinsics
16991 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16992 SDValue LHS = Op.getOperand(1);
16993 SDValue RHS = Op.getOperand(2);
16994 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
16995 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16996 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16997 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16998 DAG.getConstant(X86CC, MVT::i8), Cond);
16999 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17002 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
17003 Op.getOperand(1), Op.getOperand(2), DAG);
17005 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
17006 Op.getSimpleValueType(),
17008 Op.getOperand(2), DAG),
17009 Op.getOperand(4), Op.getOperand(3), Subtarget,
17011 case COMPRESS_EXPAND_IN_REG: {
17012 SDValue Mask = Op.getOperand(3);
17013 SDValue DataToCompress = Op.getOperand(1);
17014 SDValue PassThru = Op.getOperand(2);
17015 if (isAllOnes(Mask)) // return data as is
17016 return Op.getOperand(1);
17017 EVT VT = Op.getValueType();
17018 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17019 VT.getVectorNumElements());
17020 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17021 Mask.getValueType().getSizeInBits());
17023 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17024 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17025 DAG.getIntPtrConstant(0));
17027 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
17031 SDValue Mask = Op.getOperand(3);
17032 EVT VT = Op.getValueType();
17033 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17034 VT.getVectorNumElements());
17035 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17036 Mask.getValueType().getSizeInBits());
17038 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17039 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17040 DAG.getIntPtrConstant(0));
17041 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
17046 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
17047 dl, Op.getValueType(),
17051 Op.getOperand(4), Op.getOperand(1),
17060 default: return SDValue(); // Don't custom lower most intrinsics.
17062 case Intrinsic::x86_avx512_mask_valign_q_512:
17063 case Intrinsic::x86_avx512_mask_valign_d_512:
17064 // Vector source operands are swapped.
17065 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
17066 Op.getValueType(), Op.getOperand(2),
17069 Op.getOperand(5), Op.getOperand(4),
17072 // ptest and testp intrinsics. The intrinsic these come from are designed to
17073 // return an integer value, not just an instruction so lower it to the ptest
17074 // or testp pattern and a setcc for the result.
17075 case Intrinsic::x86_sse41_ptestz:
17076 case Intrinsic::x86_sse41_ptestc:
17077 case Intrinsic::x86_sse41_ptestnzc:
17078 case Intrinsic::x86_avx_ptestz_256:
17079 case Intrinsic::x86_avx_ptestc_256:
17080 case Intrinsic::x86_avx_ptestnzc_256:
17081 case Intrinsic::x86_avx_vtestz_ps:
17082 case Intrinsic::x86_avx_vtestc_ps:
17083 case Intrinsic::x86_avx_vtestnzc_ps:
17084 case Intrinsic::x86_avx_vtestz_pd:
17085 case Intrinsic::x86_avx_vtestc_pd:
17086 case Intrinsic::x86_avx_vtestnzc_pd:
17087 case Intrinsic::x86_avx_vtestz_ps_256:
17088 case Intrinsic::x86_avx_vtestc_ps_256:
17089 case Intrinsic::x86_avx_vtestnzc_ps_256:
17090 case Intrinsic::x86_avx_vtestz_pd_256:
17091 case Intrinsic::x86_avx_vtestc_pd_256:
17092 case Intrinsic::x86_avx_vtestnzc_pd_256: {
17093 bool IsTestPacked = false;
17096 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17097 case Intrinsic::x86_avx_vtestz_ps:
17098 case Intrinsic::x86_avx_vtestz_pd:
17099 case Intrinsic::x86_avx_vtestz_ps_256:
17100 case Intrinsic::x86_avx_vtestz_pd_256:
17101 IsTestPacked = true; // Fallthrough
17102 case Intrinsic::x86_sse41_ptestz:
17103 case Intrinsic::x86_avx_ptestz_256:
17105 X86CC = X86::COND_E;
17107 case Intrinsic::x86_avx_vtestc_ps:
17108 case Intrinsic::x86_avx_vtestc_pd:
17109 case Intrinsic::x86_avx_vtestc_ps_256:
17110 case Intrinsic::x86_avx_vtestc_pd_256:
17111 IsTestPacked = true; // Fallthrough
17112 case Intrinsic::x86_sse41_ptestc:
17113 case Intrinsic::x86_avx_ptestc_256:
17115 X86CC = X86::COND_B;
17117 case Intrinsic::x86_avx_vtestnzc_ps:
17118 case Intrinsic::x86_avx_vtestnzc_pd:
17119 case Intrinsic::x86_avx_vtestnzc_ps_256:
17120 case Intrinsic::x86_avx_vtestnzc_pd_256:
17121 IsTestPacked = true; // Fallthrough
17122 case Intrinsic::x86_sse41_ptestnzc:
17123 case Intrinsic::x86_avx_ptestnzc_256:
17125 X86CC = X86::COND_A;
17129 SDValue LHS = Op.getOperand(1);
17130 SDValue RHS = Op.getOperand(2);
17131 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17132 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17133 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17134 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17135 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17137 case Intrinsic::x86_avx512_kortestz_w:
17138 case Intrinsic::x86_avx512_kortestc_w: {
17139 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17140 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
17141 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
17142 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17143 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17144 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17145 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17148 case Intrinsic::x86_sse42_pcmpistria128:
17149 case Intrinsic::x86_sse42_pcmpestria128:
17150 case Intrinsic::x86_sse42_pcmpistric128:
17151 case Intrinsic::x86_sse42_pcmpestric128:
17152 case Intrinsic::x86_sse42_pcmpistrio128:
17153 case Intrinsic::x86_sse42_pcmpestrio128:
17154 case Intrinsic::x86_sse42_pcmpistris128:
17155 case Intrinsic::x86_sse42_pcmpestris128:
17156 case Intrinsic::x86_sse42_pcmpistriz128:
17157 case Intrinsic::x86_sse42_pcmpestriz128: {
17161 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17162 case Intrinsic::x86_sse42_pcmpistria128:
17163 Opcode = X86ISD::PCMPISTRI;
17164 X86CC = X86::COND_A;
17166 case Intrinsic::x86_sse42_pcmpestria128:
17167 Opcode = X86ISD::PCMPESTRI;
17168 X86CC = X86::COND_A;
17170 case Intrinsic::x86_sse42_pcmpistric128:
17171 Opcode = X86ISD::PCMPISTRI;
17172 X86CC = X86::COND_B;
17174 case Intrinsic::x86_sse42_pcmpestric128:
17175 Opcode = X86ISD::PCMPESTRI;
17176 X86CC = X86::COND_B;
17178 case Intrinsic::x86_sse42_pcmpistrio128:
17179 Opcode = X86ISD::PCMPISTRI;
17180 X86CC = X86::COND_O;
17182 case Intrinsic::x86_sse42_pcmpestrio128:
17183 Opcode = X86ISD::PCMPESTRI;
17184 X86CC = X86::COND_O;
17186 case Intrinsic::x86_sse42_pcmpistris128:
17187 Opcode = X86ISD::PCMPISTRI;
17188 X86CC = X86::COND_S;
17190 case Intrinsic::x86_sse42_pcmpestris128:
17191 Opcode = X86ISD::PCMPESTRI;
17192 X86CC = X86::COND_S;
17194 case Intrinsic::x86_sse42_pcmpistriz128:
17195 Opcode = X86ISD::PCMPISTRI;
17196 X86CC = X86::COND_E;
17198 case Intrinsic::x86_sse42_pcmpestriz128:
17199 Opcode = X86ISD::PCMPESTRI;
17200 X86CC = X86::COND_E;
17203 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17204 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17205 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17206 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17207 DAG.getConstant(X86CC, MVT::i8),
17208 SDValue(PCMP.getNode(), 1));
17209 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17212 case Intrinsic::x86_sse42_pcmpistri128:
17213 case Intrinsic::x86_sse42_pcmpestri128: {
17215 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17216 Opcode = X86ISD::PCMPISTRI;
17218 Opcode = X86ISD::PCMPESTRI;
17220 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17221 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17222 return DAG.getNode(Opcode, dl, VTs, NewOps);
17225 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
17226 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
17227 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
17228 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
17229 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
17230 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
17231 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
17232 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
17233 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
17234 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
17235 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
17236 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
17237 auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
17238 if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
17239 return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
17240 dl, Op.getValueType(),
17244 Op.getOperand(4), Op.getOperand(1),
17250 case Intrinsic::x86_fma_vfmadd_ps:
17251 case Intrinsic::x86_fma_vfmadd_pd:
17252 case Intrinsic::x86_fma_vfmsub_ps:
17253 case Intrinsic::x86_fma_vfmsub_pd:
17254 case Intrinsic::x86_fma_vfnmadd_ps:
17255 case Intrinsic::x86_fma_vfnmadd_pd:
17256 case Intrinsic::x86_fma_vfnmsub_ps:
17257 case Intrinsic::x86_fma_vfnmsub_pd:
17258 case Intrinsic::x86_fma_vfmaddsub_ps:
17259 case Intrinsic::x86_fma_vfmaddsub_pd:
17260 case Intrinsic::x86_fma_vfmsubadd_ps:
17261 case Intrinsic::x86_fma_vfmsubadd_pd:
17262 case Intrinsic::x86_fma_vfmadd_ps_256:
17263 case Intrinsic::x86_fma_vfmadd_pd_256:
17264 case Intrinsic::x86_fma_vfmsub_ps_256:
17265 case Intrinsic::x86_fma_vfmsub_pd_256:
17266 case Intrinsic::x86_fma_vfnmadd_ps_256:
17267 case Intrinsic::x86_fma_vfnmadd_pd_256:
17268 case Intrinsic::x86_fma_vfnmsub_ps_256:
17269 case Intrinsic::x86_fma_vfnmsub_pd_256:
17270 case Intrinsic::x86_fma_vfmaddsub_ps_256:
17271 case Intrinsic::x86_fma_vfmaddsub_pd_256:
17272 case Intrinsic::x86_fma_vfmsubadd_ps_256:
17273 case Intrinsic::x86_fma_vfmsubadd_pd_256:
17274 return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
17275 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
17279 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17280 SDValue Src, SDValue Mask, SDValue Base,
17281 SDValue Index, SDValue ScaleOp, SDValue Chain,
17282 const X86Subtarget * Subtarget) {
17284 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17285 assert(C && "Invalid scale type");
17286 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17287 EVT MaskVT = MVT::getVectorVT(MVT::i1,
17288 Index.getSimpleValueType().getVectorNumElements());
17290 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17292 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17294 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17295 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17296 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17297 SDValue Segment = DAG.getRegister(0, MVT::i32);
17298 if (Src.getOpcode() == ISD::UNDEF)
17299 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
17300 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17301 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17302 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17303 return DAG.getMergeValues(RetOps, dl);
17306 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17307 SDValue Src, SDValue Mask, SDValue Base,
17308 SDValue Index, SDValue ScaleOp, SDValue Chain) {
17310 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17311 assert(C && "Invalid scale type");
17312 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17313 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17314 SDValue Segment = DAG.getRegister(0, MVT::i32);
17315 EVT MaskVT = MVT::getVectorVT(MVT::i1,
17316 Index.getSimpleValueType().getVectorNumElements());
17318 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17320 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17322 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17323 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17324 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17325 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17326 return SDValue(Res, 1);
17329 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17330 SDValue Mask, SDValue Base, SDValue Index,
17331 SDValue ScaleOp, SDValue Chain) {
17333 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17334 assert(C && "Invalid scale type");
17335 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17336 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17337 SDValue Segment = DAG.getRegister(0, MVT::i32);
17339 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17341 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17343 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17345 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17346 //SDVTList VTs = DAG.getVTList(MVT::Other);
17347 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17348 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17349 return SDValue(Res, 0);
17352 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17353 // read performance monitor counters (x86_rdpmc).
17354 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17355 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17356 SmallVectorImpl<SDValue> &Results) {
17357 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17358 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17361 // The ECX register is used to select the index of the performance counter
17363 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17365 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17367 // Reads the content of a 64-bit performance counter and returns it in the
17368 // registers EDX:EAX.
17369 if (Subtarget->is64Bit()) {
17370 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17371 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17374 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17375 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17378 Chain = HI.getValue(1);
17380 if (Subtarget->is64Bit()) {
17381 // The EAX register is loaded with the low-order 32 bits. The EDX register
17382 // is loaded with the supported high-order bits of the counter.
17383 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17384 DAG.getConstant(32, MVT::i8));
17385 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17386 Results.push_back(Chain);
17390 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17391 SDValue Ops[] = { LO, HI };
17392 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17393 Results.push_back(Pair);
17394 Results.push_back(Chain);
17397 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17398 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17399 // also used to custom lower READCYCLECOUNTER nodes.
17400 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17401 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17402 SmallVectorImpl<SDValue> &Results) {
17403 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17404 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17407 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17408 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17409 // and the EAX register is loaded with the low-order 32 bits.
17410 if (Subtarget->is64Bit()) {
17411 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17412 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17415 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17416 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17419 SDValue Chain = HI.getValue(1);
17421 if (Opcode == X86ISD::RDTSCP_DAG) {
17422 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17424 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17425 // the ECX register. Add 'ecx' explicitly to the chain.
17426 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17428 // Explicitly store the content of ECX at the location passed in input
17429 // to the 'rdtscp' intrinsic.
17430 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17431 MachinePointerInfo(), false, false, 0);
17434 if (Subtarget->is64Bit()) {
17435 // The EDX register is loaded with the high-order 32 bits of the MSR, and
17436 // the EAX register is loaded with the low-order 32 bits.
17437 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17438 DAG.getConstant(32, MVT::i8));
17439 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17440 Results.push_back(Chain);
17444 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17445 SDValue Ops[] = { LO, HI };
17446 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17447 Results.push_back(Pair);
17448 Results.push_back(Chain);
17451 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17452 SelectionDAG &DAG) {
17453 SmallVector<SDValue, 2> Results;
17455 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17457 return DAG.getMergeValues(Results, DL);
17461 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17462 SelectionDAG &DAG) {
17463 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17465 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17470 switch(IntrData->Type) {
17472 llvm_unreachable("Unknown Intrinsic Type");
17476 // Emit the node with the right value type.
17477 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17478 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17480 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17481 // Otherwise return the value from Rand, which is always 0, casted to i32.
17482 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17483 DAG.getConstant(1, Op->getValueType(1)),
17484 DAG.getConstant(X86::COND_B, MVT::i32),
17485 SDValue(Result.getNode(), 1) };
17486 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17487 DAG.getVTList(Op->getValueType(1), MVT::Glue),
17490 // Return { result, isValid, chain }.
17491 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17492 SDValue(Result.getNode(), 2));
17495 //gather(v1, mask, index, base, scale);
17496 SDValue Chain = Op.getOperand(0);
17497 SDValue Src = Op.getOperand(2);
17498 SDValue Base = Op.getOperand(3);
17499 SDValue Index = Op.getOperand(4);
17500 SDValue Mask = Op.getOperand(5);
17501 SDValue Scale = Op.getOperand(6);
17502 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17506 //scatter(base, mask, index, v1, scale);
17507 SDValue Chain = Op.getOperand(0);
17508 SDValue Base = Op.getOperand(2);
17509 SDValue Mask = Op.getOperand(3);
17510 SDValue Index = Op.getOperand(4);
17511 SDValue Src = Op.getOperand(5);
17512 SDValue Scale = Op.getOperand(6);
17513 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17516 SDValue Hint = Op.getOperand(6);
17518 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17519 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17520 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17521 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17522 SDValue Chain = Op.getOperand(0);
17523 SDValue Mask = Op.getOperand(2);
17524 SDValue Index = Op.getOperand(3);
17525 SDValue Base = Op.getOperand(4);
17526 SDValue Scale = Op.getOperand(5);
17527 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17529 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17531 SmallVector<SDValue, 2> Results;
17532 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17533 return DAG.getMergeValues(Results, dl);
17535 // Read Performance Monitoring Counters.
17537 SmallVector<SDValue, 2> Results;
17538 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17539 return DAG.getMergeValues(Results, dl);
17541 // XTEST intrinsics.
17543 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17544 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17545 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17546 DAG.getConstant(X86::COND_NE, MVT::i8),
17548 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17549 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17550 Ret, SDValue(InTrans.getNode(), 1));
17554 SmallVector<SDValue, 2> Results;
17555 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17556 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17557 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17558 DAG.getConstant(-1, MVT::i8));
17559 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17560 Op.getOperand(4), GenCF.getValue(1));
17561 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17562 Op.getOperand(5), MachinePointerInfo(),
17564 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17565 DAG.getConstant(X86::COND_B, MVT::i8),
17567 Results.push_back(SetCC);
17568 Results.push_back(Store);
17569 return DAG.getMergeValues(Results, dl);
17571 case COMPRESS_TO_MEM: {
17573 SDValue Mask = Op.getOperand(4);
17574 SDValue DataToCompress = Op.getOperand(3);
17575 SDValue Addr = Op.getOperand(2);
17576 SDValue Chain = Op.getOperand(0);
17578 if (isAllOnes(Mask)) // return just a store
17579 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17580 MachinePointerInfo(), false, false, 0);
17582 EVT VT = DataToCompress.getValueType();
17583 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17584 VT.getVectorNumElements());
17585 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17586 Mask.getValueType().getSizeInBits());
17587 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17588 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17589 DAG.getIntPtrConstant(0));
17591 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
17592 DataToCompress, DAG.getUNDEF(VT));
17593 return DAG.getStore(Chain, dl, Compressed, Addr,
17594 MachinePointerInfo(), false, false, 0);
17596 case EXPAND_FROM_MEM: {
17598 SDValue Mask = Op.getOperand(4);
17599 SDValue PathThru = Op.getOperand(3);
17600 SDValue Addr = Op.getOperand(2);
17601 SDValue Chain = Op.getOperand(0);
17602 EVT VT = Op.getValueType();
17604 if (isAllOnes(Mask)) // return just a load
17605 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17607 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17608 VT.getVectorNumElements());
17609 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17610 Mask.getValueType().getSizeInBits());
17611 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17612 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17613 DAG.getIntPtrConstant(0));
17615 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17616 false, false, false, 0);
17618 SmallVector<SDValue, 2> Results;
17619 Results.push_back(DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand,
17621 Results.push_back(Chain);
17622 return DAG.getMergeValues(Results, dl);
17627 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17628 SelectionDAG &DAG) const {
17629 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17630 MFI->setReturnAddressIsTaken(true);
17632 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17635 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17637 EVT PtrVT = getPointerTy();
17640 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17641 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17642 DAG.getSubtarget().getRegisterInfo());
17643 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
17644 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17645 DAG.getNode(ISD::ADD, dl, PtrVT,
17646 FrameAddr, Offset),
17647 MachinePointerInfo(), false, false, false, 0);
17650 // Just load the return address.
17651 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17652 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17653 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17656 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17657 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17658 MFI->setFrameAddressIsTaken(true);
17660 EVT VT = Op.getValueType();
17661 SDLoc dl(Op); // FIXME probably not meaningful
17662 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17663 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17664 DAG.getSubtarget().getRegisterInfo());
17665 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(
17666 DAG.getMachineFunction());
17667 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17668 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17669 "Invalid Frame Register!");
17670 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17672 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17673 MachinePointerInfo(),
17674 false, false, false, 0);
17678 // FIXME? Maybe this could be a TableGen attribute on some registers and
17679 // this table could be generated automatically from RegInfo.
17680 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
17682 unsigned Reg = StringSwitch<unsigned>(RegName)
17683 .Case("esp", X86::ESP)
17684 .Case("rsp", X86::RSP)
17688 report_fatal_error("Invalid register name global variable");
17691 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17692 SelectionDAG &DAG) const {
17693 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17694 DAG.getSubtarget().getRegisterInfo());
17695 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
17698 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17699 SDValue Chain = Op.getOperand(0);
17700 SDValue Offset = Op.getOperand(1);
17701 SDValue Handler = Op.getOperand(2);
17704 EVT PtrVT = getPointerTy();
17705 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17706 DAG.getSubtarget().getRegisterInfo());
17707 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17708 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17709 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17710 "Invalid Frame Register!");
17711 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17712 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17714 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17715 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
17716 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17717 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17719 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17721 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17722 DAG.getRegister(StoreAddrReg, PtrVT));
17725 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17726 SelectionDAG &DAG) const {
17728 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17729 DAG.getVTList(MVT::i32, MVT::Other),
17730 Op.getOperand(0), Op.getOperand(1));
17733 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17734 SelectionDAG &DAG) const {
17736 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17737 Op.getOperand(0), Op.getOperand(1));
17740 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17741 return Op.getOperand(0);
17744 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17745 SelectionDAG &DAG) const {
17746 SDValue Root = Op.getOperand(0);
17747 SDValue Trmp = Op.getOperand(1); // trampoline
17748 SDValue FPtr = Op.getOperand(2); // nested function
17749 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17752 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17753 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
17755 if (Subtarget->is64Bit()) {
17756 SDValue OutChains[6];
17758 // Large code-model.
17759 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17760 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17762 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17763 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17765 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17767 // Load the pointer to the nested function into R11.
17768 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17769 SDValue Addr = Trmp;
17770 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17771 Addr, MachinePointerInfo(TrmpAddr),
17774 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17775 DAG.getConstant(2, MVT::i64));
17776 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17777 MachinePointerInfo(TrmpAddr, 2),
17780 // Load the 'nest' parameter value into R10.
17781 // R10 is specified in X86CallingConv.td
17782 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17783 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17784 DAG.getConstant(10, MVT::i64));
17785 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17786 Addr, MachinePointerInfo(TrmpAddr, 10),
17789 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17790 DAG.getConstant(12, MVT::i64));
17791 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17792 MachinePointerInfo(TrmpAddr, 12),
17795 // Jump to the nested function.
17796 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17797 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17798 DAG.getConstant(20, MVT::i64));
17799 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17800 Addr, MachinePointerInfo(TrmpAddr, 20),
17803 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17804 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17805 DAG.getConstant(22, MVT::i64));
17806 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
17807 MachinePointerInfo(TrmpAddr, 22),
17810 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17812 const Function *Func =
17813 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17814 CallingConv::ID CC = Func->getCallingConv();
17819 llvm_unreachable("Unsupported calling convention");
17820 case CallingConv::C:
17821 case CallingConv::X86_StdCall: {
17822 // Pass 'nest' parameter in ECX.
17823 // Must be kept in sync with X86CallingConv.td
17824 NestReg = X86::ECX;
17826 // Check that ECX wasn't needed by an 'inreg' parameter.
17827 FunctionType *FTy = Func->getFunctionType();
17828 const AttributeSet &Attrs = Func->getAttributes();
17830 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17831 unsigned InRegCount = 0;
17834 for (FunctionType::param_iterator I = FTy->param_begin(),
17835 E = FTy->param_end(); I != E; ++I, ++Idx)
17836 if (Attrs.hasAttribute(Idx, Attribute::InReg))
17837 // FIXME: should only count parameters that are lowered to integers.
17838 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
17840 if (InRegCount > 2) {
17841 report_fatal_error("Nest register in use - reduce number of inreg"
17847 case CallingConv::X86_FastCall:
17848 case CallingConv::X86_ThisCall:
17849 case CallingConv::Fast:
17850 // Pass 'nest' parameter in EAX.
17851 // Must be kept in sync with X86CallingConv.td
17852 NestReg = X86::EAX;
17856 SDValue OutChains[4];
17857 SDValue Addr, Disp;
17859 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17860 DAG.getConstant(10, MVT::i32));
17861 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17863 // This is storing the opcode for MOV32ri.
17864 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17865 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17866 OutChains[0] = DAG.getStore(Root, dl,
17867 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
17868 Trmp, MachinePointerInfo(TrmpAddr),
17871 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17872 DAG.getConstant(1, MVT::i32));
17873 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17874 MachinePointerInfo(TrmpAddr, 1),
17877 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17878 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17879 DAG.getConstant(5, MVT::i32));
17880 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
17881 MachinePointerInfo(TrmpAddr, 5),
17884 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17885 DAG.getConstant(6, MVT::i32));
17886 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17887 MachinePointerInfo(TrmpAddr, 6),
17890 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17894 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17895 SelectionDAG &DAG) const {
17897 The rounding mode is in bits 11:10 of FPSR, and has the following
17899 00 Round to nearest
17904 FLT_ROUNDS, on the other hand, expects the following:
17911 To perform the conversion, we do:
17912 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17915 MachineFunction &MF = DAG.getMachineFunction();
17916 const TargetMachine &TM = MF.getTarget();
17917 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
17918 unsigned StackAlignment = TFI.getStackAlignment();
17919 MVT VT = Op.getSimpleValueType();
17922 // Save FP Control Word to stack slot
17923 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17924 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
17926 MachineMemOperand *MMO =
17927 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
17928 MachineMemOperand::MOStore, 2, 2);
17930 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17931 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17932 DAG.getVTList(MVT::Other),
17933 Ops, MVT::i16, MMO);
17935 // Load FP Control Word from stack slot
17936 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17937 MachinePointerInfo(), false, false, false, 0);
17939 // Transform as necessary
17941 DAG.getNode(ISD::SRL, DL, MVT::i16,
17942 DAG.getNode(ISD::AND, DL, MVT::i16,
17943 CWD, DAG.getConstant(0x800, MVT::i16)),
17944 DAG.getConstant(11, MVT::i8));
17946 DAG.getNode(ISD::SRL, DL, MVT::i16,
17947 DAG.getNode(ISD::AND, DL, MVT::i16,
17948 CWD, DAG.getConstant(0x400, MVT::i16)),
17949 DAG.getConstant(9, MVT::i8));
17952 DAG.getNode(ISD::AND, DL, MVT::i16,
17953 DAG.getNode(ISD::ADD, DL, MVT::i16,
17954 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17955 DAG.getConstant(1, MVT::i16)),
17956 DAG.getConstant(3, MVT::i16));
17958 return DAG.getNode((VT.getSizeInBits() < 16 ?
17959 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17962 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17963 MVT VT = Op.getSimpleValueType();
17965 unsigned NumBits = VT.getSizeInBits();
17968 Op = Op.getOperand(0);
17969 if (VT == MVT::i8) {
17970 // Zero extend to i32 since there is not an i8 bsr.
17972 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17975 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17976 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17977 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17979 // If src is zero (i.e. bsr sets ZF), returns NumBits.
17982 DAG.getConstant(NumBits+NumBits-1, OpVT),
17983 DAG.getConstant(X86::COND_E, MVT::i8),
17986 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17988 // Finally xor with NumBits-1.
17989 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17992 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17996 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17997 MVT VT = Op.getSimpleValueType();
17999 unsigned NumBits = VT.getSizeInBits();
18002 Op = Op.getOperand(0);
18003 if (VT == MVT::i8) {
18004 // Zero extend to i32 since there is not an i8 bsr.
18006 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18009 // Issue a bsr (scan bits in reverse).
18010 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18011 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18013 // And xor with NumBits-1.
18014 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
18017 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18021 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18022 MVT VT = Op.getSimpleValueType();
18023 unsigned NumBits = VT.getSizeInBits();
18025 Op = Op.getOperand(0);
18027 // Issue a bsf (scan bits forward) which also sets EFLAGS.
18028 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18029 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
18031 // If src is zero (i.e. bsf sets ZF), returns NumBits.
18034 DAG.getConstant(NumBits, VT),
18035 DAG.getConstant(X86::COND_E, MVT::i8),
18038 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18041 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18042 // ones, and then concatenate the result back.
18043 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18044 MVT VT = Op.getSimpleValueType();
18046 assert(VT.is256BitVector() && VT.isInteger() &&
18047 "Unsupported value type for operation");
18049 unsigned NumElems = VT.getVectorNumElements();
18052 // Extract the LHS vectors
18053 SDValue LHS = Op.getOperand(0);
18054 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18055 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18057 // Extract the RHS vectors
18058 SDValue RHS = Op.getOperand(1);
18059 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18060 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18062 MVT EltVT = VT.getVectorElementType();
18063 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18065 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18066 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18067 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18070 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18071 assert(Op.getSimpleValueType().is256BitVector() &&
18072 Op.getSimpleValueType().isInteger() &&
18073 "Only handle AVX 256-bit vector integer operation");
18074 return Lower256IntArith(Op, DAG);
18077 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18078 assert(Op.getSimpleValueType().is256BitVector() &&
18079 Op.getSimpleValueType().isInteger() &&
18080 "Only handle AVX 256-bit vector integer operation");
18081 return Lower256IntArith(Op, DAG);
18084 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18085 SelectionDAG &DAG) {
18087 MVT VT = Op.getSimpleValueType();
18089 // Decompose 256-bit ops into smaller 128-bit ops.
18090 if (VT.is256BitVector() && !Subtarget->hasInt256())
18091 return Lower256IntArith(Op, DAG);
18093 SDValue A = Op.getOperand(0);
18094 SDValue B = Op.getOperand(1);
18096 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18097 if (VT == MVT::v4i32) {
18098 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18099 "Should not custom lower when pmuldq is available!");
18101 // Extract the odd parts.
18102 static const int UnpackMask[] = { 1, -1, 3, -1 };
18103 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18104 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18106 // Multiply the even parts.
18107 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18108 // Now multiply odd parts.
18109 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18111 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
18112 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
18114 // Merge the two vectors back together with a shuffle. This expands into 2
18116 static const int ShufMask[] = { 0, 4, 2, 6 };
18117 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18120 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18121 "Only know how to lower V2I64/V4I64/V8I64 multiply");
18123 // Ahi = psrlqi(a, 32);
18124 // Bhi = psrlqi(b, 32);
18126 // AloBlo = pmuludq(a, b);
18127 // AloBhi = pmuludq(a, Bhi);
18128 // AhiBlo = pmuludq(Ahi, b);
18130 // AloBhi = psllqi(AloBhi, 32);
18131 // AhiBlo = psllqi(AhiBlo, 32);
18132 // return AloBlo + AloBhi + AhiBlo;
18134 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18135 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18137 // Bit cast to 32-bit vectors for MULUDQ
18138 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18139 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18140 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
18141 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
18142 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
18143 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
18145 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18146 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18147 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18149 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18150 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18152 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18153 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18156 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18157 assert(Subtarget->isTargetWin64() && "Unexpected target");
18158 EVT VT = Op.getValueType();
18159 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18160 "Unexpected return type for lowering");
18164 switch (Op->getOpcode()) {
18165 default: llvm_unreachable("Unexpected request for libcall!");
18166 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
18167 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
18168 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
18169 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
18170 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
18171 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18175 SDValue InChain = DAG.getEntryNode();
18177 TargetLowering::ArgListTy Args;
18178 TargetLowering::ArgListEntry Entry;
18179 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18180 EVT ArgVT = Op->getOperand(i).getValueType();
18181 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18182 "Unexpected argument type for lowering");
18183 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18184 Entry.Node = StackPtr;
18185 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18187 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18188 Entry.Ty = PointerType::get(ArgTy,0);
18189 Entry.isSExt = false;
18190 Entry.isZExt = false;
18191 Args.push_back(Entry);
18194 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18197 TargetLowering::CallLoweringInfo CLI(DAG);
18198 CLI.setDebugLoc(dl).setChain(InChain)
18199 .setCallee(getLibcallCallingConv(LC),
18200 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18201 Callee, std::move(Args), 0)
18202 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18204 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18205 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
18208 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18209 SelectionDAG &DAG) {
18210 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18211 EVT VT = Op0.getValueType();
18214 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18215 (VT == MVT::v8i32 && Subtarget->hasInt256()));
18217 // PMULxD operations multiply each even value (starting at 0) of LHS with
18218 // the related value of RHS and produce a widen result.
18219 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18220 // => <2 x i64> <ae|cg>
18222 // In other word, to have all the results, we need to perform two PMULxD:
18223 // 1. one with the even values.
18224 // 2. one with the odd values.
18225 // To achieve #2, with need to place the odd values at an even position.
18227 // Place the odd value at an even position (basically, shift all values 1
18228 // step to the left):
18229 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18230 // <a|b|c|d> => <b|undef|d|undef>
18231 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18232 // <e|f|g|h> => <f|undef|h|undef>
18233 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18235 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18237 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18238 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18240 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18241 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18242 // => <2 x i64> <ae|cg>
18243 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
18244 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18245 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18246 // => <2 x i64> <bf|dh>
18247 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
18248 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18250 // Shuffle it back into the right order.
18251 SDValue Highs, Lows;
18252 if (VT == MVT::v8i32) {
18253 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18254 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18255 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18256 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18258 const int HighMask[] = {1, 5, 3, 7};
18259 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18260 const int LowMask[] = {0, 4, 2, 6};
18261 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18264 // If we have a signed multiply but no PMULDQ fix up the high parts of a
18265 // unsigned multiply.
18266 if (IsSigned && !Subtarget->hasSSE41()) {
18268 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
18269 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18270 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18271 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18272 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18274 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18275 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18278 // The first result of MUL_LOHI is actually the low value, followed by the
18280 SDValue Ops[] = {Lows, Highs};
18281 return DAG.getMergeValues(Ops, dl);
18284 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18285 const X86Subtarget *Subtarget) {
18286 MVT VT = Op.getSimpleValueType();
18288 SDValue R = Op.getOperand(0);
18289 SDValue Amt = Op.getOperand(1);
18291 // Optimize shl/srl/sra with constant shift amount.
18292 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18293 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18294 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18296 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
18297 (Subtarget->hasInt256() &&
18298 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18299 (Subtarget->hasAVX512() &&
18300 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18301 if (Op.getOpcode() == ISD::SHL)
18302 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18304 if (Op.getOpcode() == ISD::SRL)
18305 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18307 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
18308 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18312 if (VT == MVT::v16i8) {
18313 if (Op.getOpcode() == ISD::SHL) {
18314 // Make a large shift.
18315 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18316 MVT::v8i16, R, ShiftAmt,
18318 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18319 // Zero out the rightmost bits.
18320 SmallVector<SDValue, 16> V(16,
18321 DAG.getConstant(uint8_t(-1U << ShiftAmt),
18323 return DAG.getNode(ISD::AND, dl, VT, SHL,
18324 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18326 if (Op.getOpcode() == ISD::SRL) {
18327 // Make a large shift.
18328 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18329 MVT::v8i16, R, ShiftAmt,
18331 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18332 // Zero out the leftmost bits.
18333 SmallVector<SDValue, 16> V(16,
18334 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18336 return DAG.getNode(ISD::AND, dl, VT, SRL,
18337 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18339 if (Op.getOpcode() == ISD::SRA) {
18340 if (ShiftAmt == 7) {
18341 // R s>> 7 === R s< 0
18342 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18343 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18346 // R s>> a === ((R u>> a) ^ m) - m
18347 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18348 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
18350 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18351 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18352 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18355 llvm_unreachable("Unknown shift opcode.");
18358 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
18359 if (Op.getOpcode() == ISD::SHL) {
18360 // Make a large shift.
18361 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18362 MVT::v16i16, R, ShiftAmt,
18364 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18365 // Zero out the rightmost bits.
18366 SmallVector<SDValue, 32> V(32,
18367 DAG.getConstant(uint8_t(-1U << ShiftAmt),
18369 return DAG.getNode(ISD::AND, dl, VT, SHL,
18370 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18372 if (Op.getOpcode() == ISD::SRL) {
18373 // Make a large shift.
18374 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18375 MVT::v16i16, R, ShiftAmt,
18377 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18378 // Zero out the leftmost bits.
18379 SmallVector<SDValue, 32> V(32,
18380 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18382 return DAG.getNode(ISD::AND, dl, VT, SRL,
18383 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18385 if (Op.getOpcode() == ISD::SRA) {
18386 if (ShiftAmt == 7) {
18387 // R s>> 7 === R s< 0
18388 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18389 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18392 // R s>> a === ((R u>> a) ^ m) - m
18393 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18394 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
18396 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18397 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18398 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18401 llvm_unreachable("Unknown shift opcode.");
18406 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18407 if (!Subtarget->is64Bit() &&
18408 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18409 Amt.getOpcode() == ISD::BITCAST &&
18410 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18411 Amt = Amt.getOperand(0);
18412 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18413 VT.getVectorNumElements();
18414 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18415 uint64_t ShiftAmt = 0;
18416 for (unsigned i = 0; i != Ratio; ++i) {
18417 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
18421 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18423 // Check remaining shift amounts.
18424 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18425 uint64_t ShAmt = 0;
18426 for (unsigned j = 0; j != Ratio; ++j) {
18427 ConstantSDNode *C =
18428 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18432 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18434 if (ShAmt != ShiftAmt)
18437 switch (Op.getOpcode()) {
18439 llvm_unreachable("Unknown shift opcode!");
18441 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18444 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18447 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18455 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18456 const X86Subtarget* Subtarget) {
18457 MVT VT = Op.getSimpleValueType();
18459 SDValue R = Op.getOperand(0);
18460 SDValue Amt = Op.getOperand(1);
18462 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18463 VT == MVT::v4i32 || VT == MVT::v8i16 ||
18464 (Subtarget->hasInt256() &&
18465 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18466 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18467 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18469 EVT EltVT = VT.getVectorElementType();
18471 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18472 // Check if this build_vector node is doing a splat.
18473 // If so, then set BaseShAmt equal to the splat value.
18474 BaseShAmt = BV->getSplatValue();
18475 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18476 BaseShAmt = SDValue();
18478 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18479 Amt = Amt.getOperand(0);
18481 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18482 if (SVN && SVN->isSplat()) {
18483 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18484 SDValue InVec = Amt.getOperand(0);
18485 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18486 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18487 "Unexpected shuffle index found!");
18488 BaseShAmt = InVec.getOperand(SplatIdx);
18489 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18490 if (ConstantSDNode *C =
18491 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18492 if (C->getZExtValue() == SplatIdx)
18493 BaseShAmt = InVec.getOperand(1);
18498 // Avoid introducing an extract element from a shuffle.
18499 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18500 DAG.getIntPtrConstant(SplatIdx));
18504 if (BaseShAmt.getNode()) {
18505 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18506 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18507 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18508 else if (EltVT.bitsLT(MVT::i32))
18509 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18511 switch (Op.getOpcode()) {
18513 llvm_unreachable("Unknown shift opcode!");
18515 switch (VT.SimpleTy) {
18516 default: return SDValue();
18525 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18528 switch (VT.SimpleTy) {
18529 default: return SDValue();
18536 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18539 switch (VT.SimpleTy) {
18540 default: return SDValue();
18549 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18555 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18556 if (!Subtarget->is64Bit() &&
18557 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18558 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18559 Amt.getOpcode() == ISD::BITCAST &&
18560 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18561 Amt = Amt.getOperand(0);
18562 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18563 VT.getVectorNumElements();
18564 std::vector<SDValue> Vals(Ratio);
18565 for (unsigned i = 0; i != Ratio; ++i)
18566 Vals[i] = Amt.getOperand(i);
18567 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18568 for (unsigned j = 0; j != Ratio; ++j)
18569 if (Vals[j] != Amt.getOperand(i + j))
18572 switch (Op.getOpcode()) {
18574 llvm_unreachable("Unknown shift opcode!");
18576 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18578 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18580 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18587 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18588 SelectionDAG &DAG) {
18589 MVT VT = Op.getSimpleValueType();
18591 SDValue R = Op.getOperand(0);
18592 SDValue Amt = Op.getOperand(1);
18595 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18596 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18598 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
18602 V = LowerScalarVariableShift(Op, DAG, Subtarget);
18606 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
18608 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
18609 if (Subtarget->hasInt256()) {
18610 if (Op.getOpcode() == ISD::SRL &&
18611 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18612 VT == MVT::v4i64 || VT == MVT::v8i32))
18614 if (Op.getOpcode() == ISD::SHL &&
18615 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18616 VT == MVT::v4i64 || VT == MVT::v8i32))
18618 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
18622 // If possible, lower this packed shift into a vector multiply instead of
18623 // expanding it into a sequence of scalar shifts.
18624 // Do this only if the vector shift count is a constant build_vector.
18625 if (Op.getOpcode() == ISD::SHL &&
18626 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18627 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18628 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18629 SmallVector<SDValue, 8> Elts;
18630 EVT SVT = VT.getScalarType();
18631 unsigned SVTBits = SVT.getSizeInBits();
18632 const APInt &One = APInt(SVTBits, 1);
18633 unsigned NumElems = VT.getVectorNumElements();
18635 for (unsigned i=0; i !=NumElems; ++i) {
18636 SDValue Op = Amt->getOperand(i);
18637 if (Op->getOpcode() == ISD::UNDEF) {
18638 Elts.push_back(Op);
18642 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18643 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18644 uint64_t ShAmt = C.getZExtValue();
18645 if (ShAmt >= SVTBits) {
18646 Elts.push_back(DAG.getUNDEF(SVT));
18649 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
18651 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18652 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18655 // Lower SHL with variable shift amount.
18656 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18657 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
18659 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
18660 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
18661 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18662 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18665 // If possible, lower this shift as a sequence of two shifts by
18666 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18668 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18670 // Could be rewritten as:
18671 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18673 // The advantage is that the two shifts from the example would be
18674 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18675 // the vector shift into four scalar shifts plus four pairs of vector
18677 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18678 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18679 unsigned TargetOpcode = X86ISD::MOVSS;
18680 bool CanBeSimplified;
18681 // The splat value for the first packed shift (the 'X' from the example).
18682 SDValue Amt1 = Amt->getOperand(0);
18683 // The splat value for the second packed shift (the 'Y' from the example).
18684 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18685 Amt->getOperand(2);
18687 // See if it is possible to replace this node with a sequence of
18688 // two shifts followed by a MOVSS/MOVSD
18689 if (VT == MVT::v4i32) {
18690 // Check if it is legal to use a MOVSS.
18691 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18692 Amt2 == Amt->getOperand(3);
18693 if (!CanBeSimplified) {
18694 // Otherwise, check if we can still simplify this node using a MOVSD.
18695 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18696 Amt->getOperand(2) == Amt->getOperand(3);
18697 TargetOpcode = X86ISD::MOVSD;
18698 Amt2 = Amt->getOperand(2);
18701 // Do similar checks for the case where the machine value type
18703 CanBeSimplified = Amt1 == Amt->getOperand(1);
18704 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18705 CanBeSimplified = Amt2 == Amt->getOperand(i);
18707 if (!CanBeSimplified) {
18708 TargetOpcode = X86ISD::MOVSD;
18709 CanBeSimplified = true;
18710 Amt2 = Amt->getOperand(4);
18711 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18712 CanBeSimplified = Amt1 == Amt->getOperand(i);
18713 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18714 CanBeSimplified = Amt2 == Amt->getOperand(j);
18718 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18719 isa<ConstantSDNode>(Amt2)) {
18720 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18721 EVT CastVT = MVT::v4i32;
18723 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
18724 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18726 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
18727 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18728 if (TargetOpcode == X86ISD::MOVSD)
18729 CastVT = MVT::v2i64;
18730 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
18731 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
18732 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18734 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
18738 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
18739 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
18742 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
18743 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
18745 // Turn 'a' into a mask suitable for VSELECT
18746 SDValue VSelM = DAG.getConstant(0x80, VT);
18747 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18748 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18750 SDValue CM1 = DAG.getConstant(0x0f, VT);
18751 SDValue CM2 = DAG.getConstant(0x3f, VT);
18753 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
18754 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
18755 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
18756 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18757 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18760 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18761 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18762 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18764 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
18765 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
18766 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
18767 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18768 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18771 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18772 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18773 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18775 // return VSELECT(r, r+r, a);
18776 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
18777 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
18781 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18782 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18783 // solution better.
18784 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18785 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
18787 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18788 R = DAG.getNode(ExtOpc, dl, NewVT, R);
18789 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
18790 return DAG.getNode(ISD::TRUNCATE, dl, VT,
18791 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
18794 // Decompose 256-bit shifts into smaller 128-bit shifts.
18795 if (VT.is256BitVector()) {
18796 unsigned NumElems = VT.getVectorNumElements();
18797 MVT EltVT = VT.getVectorElementType();
18798 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18800 // Extract the two vectors
18801 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18802 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18804 // Recreate the shift amount vectors
18805 SDValue Amt1, Amt2;
18806 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18807 // Constant shift amount
18808 SmallVector<SDValue, 4> Amt1Csts;
18809 SmallVector<SDValue, 4> Amt2Csts;
18810 for (unsigned i = 0; i != NumElems/2; ++i)
18811 Amt1Csts.push_back(Amt->getOperand(i));
18812 for (unsigned i = NumElems/2; i != NumElems; ++i)
18813 Amt2Csts.push_back(Amt->getOperand(i));
18815 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18816 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18818 // Variable shift amount
18819 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18820 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18823 // Issue new vector shifts for the smaller types
18824 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18825 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18827 // Concatenate the result back
18828 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18834 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18835 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18836 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18837 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18838 // has only one use.
18839 SDNode *N = Op.getNode();
18840 SDValue LHS = N->getOperand(0);
18841 SDValue RHS = N->getOperand(1);
18842 unsigned BaseOp = 0;
18845 switch (Op.getOpcode()) {
18846 default: llvm_unreachable("Unknown ovf instruction!");
18848 // A subtract of one will be selected as a INC. Note that INC doesn't
18849 // set CF, so we can't do this for UADDO.
18850 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18852 BaseOp = X86ISD::INC;
18853 Cond = X86::COND_O;
18856 BaseOp = X86ISD::ADD;
18857 Cond = X86::COND_O;
18860 BaseOp = X86ISD::ADD;
18861 Cond = X86::COND_B;
18864 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18865 // set CF, so we can't do this for USUBO.
18866 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18868 BaseOp = X86ISD::DEC;
18869 Cond = X86::COND_O;
18872 BaseOp = X86ISD::SUB;
18873 Cond = X86::COND_O;
18876 BaseOp = X86ISD::SUB;
18877 Cond = X86::COND_B;
18880 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18881 Cond = X86::COND_O;
18883 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18884 if (N->getValueType(0) == MVT::i8) {
18885 BaseOp = X86ISD::UMUL8;
18886 Cond = X86::COND_O;
18889 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18891 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18894 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18895 DAG.getConstant(X86::COND_O, MVT::i32),
18896 SDValue(Sum.getNode(), 2));
18898 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18902 // Also sets EFLAGS.
18903 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18904 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18907 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18908 DAG.getConstant(Cond, MVT::i32),
18909 SDValue(Sum.getNode(), 1));
18911 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18914 // Sign extension of the low part of vector elements. This may be used either
18915 // when sign extend instructions are not available or if the vector element
18916 // sizes already match the sign-extended size. If the vector elements are in
18917 // their pre-extended size and sign extend instructions are available, that will
18918 // be handled by LowerSIGN_EXTEND.
18919 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
18920 SelectionDAG &DAG) const {
18922 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
18923 MVT VT = Op.getSimpleValueType();
18925 if (!Subtarget->hasSSE2() || !VT.isVector())
18928 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
18929 ExtraVT.getScalarType().getSizeInBits();
18931 switch (VT.SimpleTy) {
18932 default: return SDValue();
18935 if (!Subtarget->hasFp256())
18937 if (!Subtarget->hasInt256()) {
18938 // needs to be split
18939 unsigned NumElems = VT.getVectorNumElements();
18941 // Extract the LHS vectors
18942 SDValue LHS = Op.getOperand(0);
18943 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18944 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18946 MVT EltVT = VT.getVectorElementType();
18947 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18949 EVT ExtraEltVT = ExtraVT.getVectorElementType();
18950 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
18951 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
18953 SDValue Extra = DAG.getValueType(ExtraVT);
18955 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
18956 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
18958 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
18963 SDValue Op0 = Op.getOperand(0);
18965 // This is a sign extension of some low part of vector elements without
18966 // changing the size of the vector elements themselves:
18967 // Shift-Left + Shift-Right-Algebraic.
18968 SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
18970 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
18976 /// Returns true if the operand type is exactly twice the native width, and
18977 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18978 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18979 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18980 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
18981 const X86Subtarget &Subtarget =
18982 getTargetMachine().getSubtarget<X86Subtarget>();
18983 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18986 return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18987 else if (OpWidth == 128)
18988 return Subtarget.hasCmpxchg16b();
18993 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18994 return needsCmpXchgNb(SI->getValueOperand()->getType());
18997 // Note: this turns large loads into lock cmpxchg8b/16b.
18998 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18999 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19000 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19001 return needsCmpXchgNb(PTy->getElementType());
19004 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19005 const X86Subtarget &Subtarget =
19006 getTargetMachine().getSubtarget<X86Subtarget>();
19007 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
19008 const Type *MemType = AI->getType();
19010 // If the operand is too big, we must see if cmpxchg8/16b is available
19011 // and default to library calls otherwise.
19012 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19013 return needsCmpXchgNb(MemType);
19015 AtomicRMWInst::BinOp Op = AI->getOperation();
19018 llvm_unreachable("Unknown atomic operation");
19019 case AtomicRMWInst::Xchg:
19020 case AtomicRMWInst::Add:
19021 case AtomicRMWInst::Sub:
19022 // It's better to use xadd, xsub or xchg for these in all cases.
19024 case AtomicRMWInst::Or:
19025 case AtomicRMWInst::And:
19026 case AtomicRMWInst::Xor:
19027 // If the atomicrmw's result isn't actually used, we can just add a "lock"
19028 // prefix to a normal instruction for these operations.
19029 return !AI->use_empty();
19030 case AtomicRMWInst::Nand:
19031 case AtomicRMWInst::Max:
19032 case AtomicRMWInst::Min:
19033 case AtomicRMWInst::UMax:
19034 case AtomicRMWInst::UMin:
19035 // These always require a non-trivial set of data operations on x86. We must
19036 // use a cmpxchg loop.
19041 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19042 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19043 // no-sse2). There isn't any reason to disable it if the target processor
19045 return Subtarget.hasSSE2() || Subtarget.is64Bit();
19049 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19050 const X86Subtarget &Subtarget =
19051 getTargetMachine().getSubtarget<X86Subtarget>();
19052 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
19053 const Type *MemType = AI->getType();
19054 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19055 // there is no benefit in turning such RMWs into loads, and it is actually
19056 // harmful as it introduces a mfence.
19057 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19060 auto Builder = IRBuilder<>(AI);
19061 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19062 auto SynchScope = AI->getSynchScope();
19063 // We must restrict the ordering to avoid generating loads with Release or
19064 // ReleaseAcquire orderings.
19065 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19066 auto Ptr = AI->getPointerOperand();
19068 // Before the load we need a fence. Here is an example lifted from
19069 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19072 // x.store(1, relaxed);
19073 // r1 = y.fetch_add(0, release);
19075 // y.fetch_add(42, acquire);
19076 // r2 = x.load(relaxed);
19077 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19078 // lowered to just a load without a fence. A mfence flushes the store buffer,
19079 // making the optimization clearly correct.
19080 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19081 // otherwise, we might be able to be more agressive on relaxed idempotent
19082 // rmw. In practice, they do not look useful, so we don't try to be
19083 // especially clever.
19084 if (SynchScope == SingleThread) {
19085 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19086 // the IR level, so we must wrap it in an intrinsic.
19088 } else if (hasMFENCE(Subtarget)) {
19089 Function *MFence = llvm::Intrinsic::getDeclaration(M,
19090 Intrinsic::x86_sse2_mfence);
19091 Builder.CreateCall(MFence);
19093 // FIXME: it might make sense to use a locked operation here but on a
19094 // different cache-line to prevent cache-line bouncing. In practice it
19095 // is probably a small win, and x86 processors without mfence are rare
19096 // enough that we do not bother.
19100 // Finally we can emit the atomic load.
19101 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19102 AI->getType()->getPrimitiveSizeInBits());
19103 Loaded->setAtomic(Order, SynchScope);
19104 AI->replaceAllUsesWith(Loaded);
19105 AI->eraseFromParent();
19109 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19110 SelectionDAG &DAG) {
19112 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19113 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19114 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19115 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19117 // The only fence that needs an instruction is a sequentially-consistent
19118 // cross-thread fence.
19119 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19120 if (hasMFENCE(*Subtarget))
19121 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19123 SDValue Chain = Op.getOperand(0);
19124 SDValue Zero = DAG.getConstant(0, MVT::i32);
19126 DAG.getRegister(X86::ESP, MVT::i32), // Base
19127 DAG.getTargetConstant(1, MVT::i8), // Scale
19128 DAG.getRegister(0, MVT::i32), // Index
19129 DAG.getTargetConstant(0, MVT::i32), // Disp
19130 DAG.getRegister(0, MVT::i32), // Segment.
19134 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19135 return SDValue(Res, 0);
19138 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19139 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19142 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19143 SelectionDAG &DAG) {
19144 MVT T = Op.getSimpleValueType();
19148 switch(T.SimpleTy) {
19149 default: llvm_unreachable("Invalid value type!");
19150 case MVT::i8: Reg = X86::AL; size = 1; break;
19151 case MVT::i16: Reg = X86::AX; size = 2; break;
19152 case MVT::i32: Reg = X86::EAX; size = 4; break;
19154 assert(Subtarget->is64Bit() && "Node not type legal!");
19155 Reg = X86::RAX; size = 8;
19158 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19159 Op.getOperand(2), SDValue());
19160 SDValue Ops[] = { cpIn.getValue(0),
19163 DAG.getTargetConstant(size, MVT::i8),
19164 cpIn.getValue(1) };
19165 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19166 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19167 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19171 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19172 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19173 MVT::i32, cpOut.getValue(2));
19174 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19175 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19177 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19178 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19179 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19183 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19184 SelectionDAG &DAG) {
19185 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19186 MVT DstVT = Op.getSimpleValueType();
19188 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19189 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19190 if (DstVT != MVT::f64)
19191 // This conversion needs to be expanded.
19194 SDValue InVec = Op->getOperand(0);
19196 unsigned NumElts = SrcVT.getVectorNumElements();
19197 EVT SVT = SrcVT.getVectorElementType();
19199 // Widen the vector in input in the case of MVT::v2i32.
19200 // Example: from MVT::v2i32 to MVT::v4i32.
19201 SmallVector<SDValue, 16> Elts;
19202 for (unsigned i = 0, e = NumElts; i != e; ++i)
19203 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19204 DAG.getIntPtrConstant(i)));
19206 // Explicitly mark the extra elements as Undef.
19207 SDValue Undef = DAG.getUNDEF(SVT);
19208 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
19209 Elts.push_back(Undef);
19211 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19212 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19213 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
19214 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19215 DAG.getIntPtrConstant(0));
19218 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19219 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19220 assert((DstVT == MVT::i64 ||
19221 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19222 "Unexpected custom BITCAST");
19223 // i64 <=> MMX conversions are Legal.
19224 if (SrcVT==MVT::i64 && DstVT.isVector())
19226 if (DstVT==MVT::i64 && SrcVT.isVector())
19228 // MMX <=> MMX conversions are Legal.
19229 if (SrcVT.isVector() && DstVT.isVector())
19231 // All other conversions need to be expanded.
19235 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19236 SelectionDAG &DAG) {
19237 SDNode *Node = Op.getNode();
19240 Op = Op.getOperand(0);
19241 EVT VT = Op.getValueType();
19242 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19243 "CTPOP lowering only implemented for 128/256-bit wide vector types");
19245 unsigned NumElts = VT.getVectorNumElements();
19246 EVT EltVT = VT.getVectorElementType();
19247 unsigned Len = EltVT.getSizeInBits();
19249 // This is the vectorized version of the "best" algorithm from
19250 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19251 // with a minor tweak to use a series of adds + shifts instead of vector
19252 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
19254 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
19255 // v8i32 => Always profitable
19257 // FIXME: There a couple of possible improvements:
19259 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
19260 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
19262 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
19263 "CTPOP not implemented for this vector element type.");
19265 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
19266 // extra legalization.
19267 bool NeedsBitcast = EltVT == MVT::i32;
19268 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
19270 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
19271 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
19272 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
19274 // v = v - ((v >> 1) & 0x55555555...)
19275 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
19276 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
19277 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
19279 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
19281 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
19282 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
19284 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
19286 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
19287 if (VT != And.getValueType())
19288 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19289 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
19291 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19292 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
19293 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
19294 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
19295 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
19297 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
19298 if (NeedsBitcast) {
19299 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
19300 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
19301 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
19304 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
19305 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
19306 if (VT != AndRHS.getValueType()) {
19307 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
19308 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
19310 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
19312 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19313 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
19314 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
19315 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
19316 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
19318 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
19319 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
19320 if (NeedsBitcast) {
19321 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
19322 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
19324 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
19325 if (VT != And.getValueType())
19326 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19328 // The algorithm mentioned above uses:
19329 // v = (v * 0x01010101...) >> (Len - 8)
19331 // Change it to use vector adds + vector shifts which yield faster results on
19332 // Haswell than using vector integer multiplication.
19334 // For i32 elements:
19335 // v = v + (v >> 8)
19336 // v = v + (v >> 16)
19338 // For i64 elements:
19339 // v = v + (v >> 8)
19340 // v = v + (v >> 16)
19341 // v = v + (v >> 32)
19344 SmallVector<SDValue, 8> Csts;
19345 for (unsigned i = 8; i <= Len/2; i *= 2) {
19346 Csts.assign(NumElts, DAG.getConstant(i, EltVT));
19347 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
19348 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
19349 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
19353 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
19354 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
19355 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
19356 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
19357 if (NeedsBitcast) {
19358 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
19359 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
19361 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
19362 if (VT != And.getValueType())
19363 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19368 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19369 SDNode *Node = Op.getNode();
19371 EVT T = Node->getValueType(0);
19372 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19373 DAG.getConstant(0, T), Node->getOperand(2));
19374 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19375 cast<AtomicSDNode>(Node)->getMemoryVT(),
19376 Node->getOperand(0),
19377 Node->getOperand(1), negOp,
19378 cast<AtomicSDNode>(Node)->getMemOperand(),
19379 cast<AtomicSDNode>(Node)->getOrdering(),
19380 cast<AtomicSDNode>(Node)->getSynchScope());
19383 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19384 SDNode *Node = Op.getNode();
19386 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19388 // Convert seq_cst store -> xchg
19389 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19390 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19391 // (The only way to get a 16-byte store is cmpxchg16b)
19392 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19393 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19394 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19395 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19396 cast<AtomicSDNode>(Node)->getMemoryVT(),
19397 Node->getOperand(0),
19398 Node->getOperand(1), Node->getOperand(2),
19399 cast<AtomicSDNode>(Node)->getMemOperand(),
19400 cast<AtomicSDNode>(Node)->getOrdering(),
19401 cast<AtomicSDNode>(Node)->getSynchScope());
19402 return Swap.getValue(1);
19404 // Other atomic stores have a simple pattern.
19408 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19409 EVT VT = Op.getNode()->getSimpleValueType(0);
19411 // Let legalize expand this if it isn't a legal type yet.
19412 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19415 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19418 bool ExtraOp = false;
19419 switch (Op.getOpcode()) {
19420 default: llvm_unreachable("Invalid code");
19421 case ISD::ADDC: Opc = X86ISD::ADD; break;
19422 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19423 case ISD::SUBC: Opc = X86ISD::SUB; break;
19424 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19428 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19430 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19431 Op.getOperand(1), Op.getOperand(2));
19434 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19435 SelectionDAG &DAG) {
19436 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19438 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19439 // which returns the values as { float, float } (in XMM0) or
19440 // { double, double } (which is returned in XMM0, XMM1).
19442 SDValue Arg = Op.getOperand(0);
19443 EVT ArgVT = Arg.getValueType();
19444 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19446 TargetLowering::ArgListTy Args;
19447 TargetLowering::ArgListEntry Entry;
19451 Entry.isSExt = false;
19452 Entry.isZExt = false;
19453 Args.push_back(Entry);
19455 bool isF64 = ArgVT == MVT::f64;
19456 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19457 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19458 // the results are returned via SRet in memory.
19459 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19460 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19461 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
19463 Type *RetTy = isF64
19464 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19465 : (Type*)VectorType::get(ArgTy, 4);
19467 TargetLowering::CallLoweringInfo CLI(DAG);
19468 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19469 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19471 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19474 // Returned in xmm0 and xmm1.
19475 return CallResult.first;
19477 // Returned in bits 0:31 and 32:64 xmm0.
19478 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19479 CallResult.first, DAG.getIntPtrConstant(0));
19480 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19481 CallResult.first, DAG.getIntPtrConstant(1));
19482 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19483 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19486 /// LowerOperation - Provide custom lowering hooks for some operations.
19488 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19489 switch (Op.getOpcode()) {
19490 default: llvm_unreachable("Should not custom lower this!");
19491 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
19492 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19493 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19494 return LowerCMP_SWAP(Op, Subtarget, DAG);
19495 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
19496 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
19497 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
19498 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
19499 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
19500 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
19501 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
19502 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19503 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
19504 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19505 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19506 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
19507 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
19508 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
19509 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
19510 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
19511 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
19512 case ISD::SHL_PARTS:
19513 case ISD::SRA_PARTS:
19514 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
19515 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
19516 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
19517 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
19518 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
19519 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19520 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
19521 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
19522 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
19523 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
19524 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
19526 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
19527 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
19528 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
19529 case ISD::SETCC: return LowerSETCC(Op, DAG);
19530 case ISD::SELECT: return LowerSELECT(Op, DAG);
19531 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
19532 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
19533 case ISD::VASTART: return LowerVASTART(Op, DAG);
19534 case ISD::VAARG: return LowerVAARG(Op, DAG);
19535 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
19536 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19537 case ISD::INTRINSIC_VOID:
19538 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19539 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
19540 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
19541 case ISD::FRAME_TO_ARGS_OFFSET:
19542 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19543 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19544 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
19545 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
19546 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
19547 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
19548 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
19549 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
19550 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
19551 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19552 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
19553 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
19554 case ISD::UMUL_LOHI:
19555 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
19558 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
19564 case ISD::UMULO: return LowerXALUO(Op, DAG);
19565 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19566 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
19570 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19571 case ISD::ADD: return LowerADD(Op, DAG);
19572 case ISD::SUB: return LowerSUB(Op, DAG);
19573 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
19577 /// ReplaceNodeResults - Replace a node with an illegal result type
19578 /// with a new node built out of custom code.
19579 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19580 SmallVectorImpl<SDValue>&Results,
19581 SelectionDAG &DAG) const {
19583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19584 switch (N->getOpcode()) {
19586 llvm_unreachable("Do not know how to custom type legalize this operation!");
19587 case ISD::SIGN_EXTEND_INREG:
19592 // We don't want to expand or promote these.
19599 case ISD::UDIVREM: {
19600 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19601 Results.push_back(V);
19604 case ISD::FP_TO_SINT:
19605 case ISD::FP_TO_UINT: {
19606 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19608 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
19611 std::pair<SDValue,SDValue> Vals =
19612 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19613 SDValue FIST = Vals.first, StackSlot = Vals.second;
19614 if (FIST.getNode()) {
19615 EVT VT = N->getValueType(0);
19616 // Return a load from the stack slot.
19617 if (StackSlot.getNode())
19618 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19619 MachinePointerInfo(),
19620 false, false, false, 0));
19622 Results.push_back(FIST);
19626 case ISD::UINT_TO_FP: {
19627 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19628 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19629 N->getValueType(0) != MVT::v2f32)
19631 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19633 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
19635 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19636 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19637 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
19638 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
19639 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19640 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19643 case ISD::FP_ROUND: {
19644 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19646 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19647 Results.push_back(V);
19650 case ISD::INTRINSIC_W_CHAIN: {
19651 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19653 default : llvm_unreachable("Do not know how to custom type "
19654 "legalize this intrinsic operation!");
19655 case Intrinsic::x86_rdtsc:
19656 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19658 case Intrinsic::x86_rdtscp:
19659 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19661 case Intrinsic::x86_rdpmc:
19662 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19665 case ISD::READCYCLECOUNTER: {
19666 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19669 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19670 EVT T = N->getValueType(0);
19671 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19672 bool Regs64bit = T == MVT::i128;
19673 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19674 SDValue cpInL, cpInH;
19675 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19676 DAG.getConstant(0, HalfT));
19677 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19678 DAG.getConstant(1, HalfT));
19679 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19680 Regs64bit ? X86::RAX : X86::EAX,
19682 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19683 Regs64bit ? X86::RDX : X86::EDX,
19684 cpInH, cpInL.getValue(1));
19685 SDValue swapInL, swapInH;
19686 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19687 DAG.getConstant(0, HalfT));
19688 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19689 DAG.getConstant(1, HalfT));
19690 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19691 Regs64bit ? X86::RBX : X86::EBX,
19692 swapInL, cpInH.getValue(1));
19693 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19694 Regs64bit ? X86::RCX : X86::ECX,
19695 swapInH, swapInL.getValue(1));
19696 SDValue Ops[] = { swapInH.getValue(0),
19698 swapInH.getValue(1) };
19699 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19700 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19701 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19702 X86ISD::LCMPXCHG8_DAG;
19703 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19704 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19705 Regs64bit ? X86::RAX : X86::EAX,
19706 HalfT, Result.getValue(1));
19707 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19708 Regs64bit ? X86::RDX : X86::EDX,
19709 HalfT, cpOutL.getValue(2));
19710 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19712 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19713 MVT::i32, cpOutH.getValue(2));
19715 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19716 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19717 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19719 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19720 Results.push_back(Success);
19721 Results.push_back(EFLAGS.getValue(1));
19724 case ISD::ATOMIC_SWAP:
19725 case ISD::ATOMIC_LOAD_ADD:
19726 case ISD::ATOMIC_LOAD_SUB:
19727 case ISD::ATOMIC_LOAD_AND:
19728 case ISD::ATOMIC_LOAD_OR:
19729 case ISD::ATOMIC_LOAD_XOR:
19730 case ISD::ATOMIC_LOAD_NAND:
19731 case ISD::ATOMIC_LOAD_MIN:
19732 case ISD::ATOMIC_LOAD_MAX:
19733 case ISD::ATOMIC_LOAD_UMIN:
19734 case ISD::ATOMIC_LOAD_UMAX:
19735 case ISD::ATOMIC_LOAD: {
19736 // Delegate to generic TypeLegalization. Situations we can really handle
19737 // should have already been dealt with by AtomicExpandPass.cpp.
19740 case ISD::BITCAST: {
19741 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19742 EVT DstVT = N->getValueType(0);
19743 EVT SrcVT = N->getOperand(0)->getValueType(0);
19745 if (SrcVT != MVT::f64 ||
19746 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19749 unsigned NumElts = DstVT.getVectorNumElements();
19750 EVT SVT = DstVT.getVectorElementType();
19751 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19752 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19753 MVT::v2f64, N->getOperand(0));
19754 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
19756 if (ExperimentalVectorWideningLegalization) {
19757 // If we are legalizing vectors by widening, we already have the desired
19758 // legal vector type, just return it.
19759 Results.push_back(ToVecInt);
19763 SmallVector<SDValue, 8> Elts;
19764 for (unsigned i = 0, e = NumElts; i != e; ++i)
19765 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19766 ToVecInt, DAG.getIntPtrConstant(i)));
19768 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19773 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19775 default: return nullptr;
19776 case X86ISD::BSF: return "X86ISD::BSF";
19777 case X86ISD::BSR: return "X86ISD::BSR";
19778 case X86ISD::SHLD: return "X86ISD::SHLD";
19779 case X86ISD::SHRD: return "X86ISD::SHRD";
19780 case X86ISD::FAND: return "X86ISD::FAND";
19781 case X86ISD::FANDN: return "X86ISD::FANDN";
19782 case X86ISD::FOR: return "X86ISD::FOR";
19783 case X86ISD::FXOR: return "X86ISD::FXOR";
19784 case X86ISD::FSRL: return "X86ISD::FSRL";
19785 case X86ISD::FILD: return "X86ISD::FILD";
19786 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19787 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19788 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19789 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19790 case X86ISD::FLD: return "X86ISD::FLD";
19791 case X86ISD::FST: return "X86ISD::FST";
19792 case X86ISD::CALL: return "X86ISD::CALL";
19793 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19794 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19795 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19796 case X86ISD::BT: return "X86ISD::BT";
19797 case X86ISD::CMP: return "X86ISD::CMP";
19798 case X86ISD::COMI: return "X86ISD::COMI";
19799 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19800 case X86ISD::CMPM: return "X86ISD::CMPM";
19801 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19802 case X86ISD::SETCC: return "X86ISD::SETCC";
19803 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19804 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19805 case X86ISD::CMOV: return "X86ISD::CMOV";
19806 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19807 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19808 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19809 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19810 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19811 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19812 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19813 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19814 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19815 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19816 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19817 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19818 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19819 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19820 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19821 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19822 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19823 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19824 case X86ISD::HADD: return "X86ISD::HADD";
19825 case X86ISD::HSUB: return "X86ISD::HSUB";
19826 case X86ISD::FHADD: return "X86ISD::FHADD";
19827 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19828 case X86ISD::UMAX: return "X86ISD::UMAX";
19829 case X86ISD::UMIN: return "X86ISD::UMIN";
19830 case X86ISD::SMAX: return "X86ISD::SMAX";
19831 case X86ISD::SMIN: return "X86ISD::SMIN";
19832 case X86ISD::FMAX: return "X86ISD::FMAX";
19833 case X86ISD::FMIN: return "X86ISD::FMIN";
19834 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19835 case X86ISD::FMINC: return "X86ISD::FMINC";
19836 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19837 case X86ISD::FRCP: return "X86ISD::FRCP";
19838 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19839 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19840 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19841 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19842 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19843 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19844 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19845 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19846 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19847 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19848 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19849 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19850 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19851 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19852 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19853 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19854 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19855 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
19856 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19857 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19858 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19859 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19860 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19861 case X86ISD::VSHL: return "X86ISD::VSHL";
19862 case X86ISD::VSRL: return "X86ISD::VSRL";
19863 case X86ISD::VSRA: return "X86ISD::VSRA";
19864 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19865 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19866 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19867 case X86ISD::CMPP: return "X86ISD::CMPP";
19868 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19869 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19870 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19871 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19872 case X86ISD::ADD: return "X86ISD::ADD";
19873 case X86ISD::SUB: return "X86ISD::SUB";
19874 case X86ISD::ADC: return "X86ISD::ADC";
19875 case X86ISD::SBB: return "X86ISD::SBB";
19876 case X86ISD::SMUL: return "X86ISD::SMUL";
19877 case X86ISD::UMUL: return "X86ISD::UMUL";
19878 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19879 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19880 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19881 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19882 case X86ISD::INC: return "X86ISD::INC";
19883 case X86ISD::DEC: return "X86ISD::DEC";
19884 case X86ISD::OR: return "X86ISD::OR";
19885 case X86ISD::XOR: return "X86ISD::XOR";
19886 case X86ISD::AND: return "X86ISD::AND";
19887 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19888 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19889 case X86ISD::PTEST: return "X86ISD::PTEST";
19890 case X86ISD::TESTP: return "X86ISD::TESTP";
19891 case X86ISD::TESTM: return "X86ISD::TESTM";
19892 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19893 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19894 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19895 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19896 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19897 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19898 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19899 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19900 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19901 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19902 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19903 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19904 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19905 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19906 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19907 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19908 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19909 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19910 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19911 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19912 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19913 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19914 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19915 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
19916 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19917 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19918 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19919 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19920 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19921 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19922 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19923 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19924 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19925 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19926 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19927 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19928 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19929 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19930 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
19931 case X86ISD::SAHF: return "X86ISD::SAHF";
19932 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19933 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19934 case X86ISD::FMADD: return "X86ISD::FMADD";
19935 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19936 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19937 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19938 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19939 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19940 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19941 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19942 case X86ISD::XTEST: return "X86ISD::XTEST";
19943 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19944 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19945 case X86ISD::SELECT: return "X86ISD::SELECT";
19949 // isLegalAddressingMode - Return true if the addressing mode represented
19950 // by AM is legal for this target, for a load/store of the specified type.
19951 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
19953 // X86 supports extremely general addressing modes.
19954 CodeModel::Model M = getTargetMachine().getCodeModel();
19955 Reloc::Model R = getTargetMachine().getRelocationModel();
19957 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19958 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19963 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19965 // If a reference to this global requires an extra load, we can't fold it.
19966 if (isGlobalStubReference(GVFlags))
19969 // If BaseGV requires a register for the PIC base, we cannot also have a
19970 // BaseReg specified.
19971 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19974 // If lower 4G is not available, then we must use rip-relative addressing.
19975 if ((M != CodeModel::Small || R != Reloc::Static) &&
19976 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19980 switch (AM.Scale) {
19986 // These scales always work.
19991 // These scales are formed with basereg+scalereg. Only accept if there is
19996 default: // Other stuff never works.
20003 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20004 unsigned Bits = Ty->getScalarSizeInBits();
20006 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20007 // particularly cheaper than those without.
20011 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20012 // variable shifts just as cheap as scalar ones.
20013 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20016 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20017 // fully general vector.
20021 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20022 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20024 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20025 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20026 return NumBits1 > NumBits2;
20029 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20030 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20033 if (!isTypeLegal(EVT::getEVT(Ty1)))
20036 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20038 // Assuming the caller doesn't have a zeroext or signext return parameter,
20039 // truncation all the way down to i1 is valid.
20043 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20044 return isInt<32>(Imm);
20047 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20048 // Can also use sub to handle negated immediates.
20049 return isInt<32>(Imm);
20052 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20053 if (!VT1.isInteger() || !VT2.isInteger())
20055 unsigned NumBits1 = VT1.getSizeInBits();
20056 unsigned NumBits2 = VT2.getSizeInBits();
20057 return NumBits1 > NumBits2;
20060 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20061 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20062 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20065 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20066 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20067 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20070 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20071 EVT VT1 = Val.getValueType();
20072 if (isZExtFree(VT1, VT2))
20075 if (Val.getOpcode() != ISD::LOAD)
20078 if (!VT1.isSimple() || !VT1.isInteger() ||
20079 !VT2.isSimple() || !VT2.isInteger())
20082 switch (VT1.getSimpleVT().SimpleTy) {
20087 // X86 has 8, 16, and 32-bit zero-extending loads.
20095 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20096 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
20099 VT = VT.getScalarType();
20101 if (!VT.isSimple())
20104 switch (VT.getSimpleVT().SimpleTy) {
20115 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20116 // i16 instructions are longer (0x66 prefix) and potentially slower.
20117 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20120 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20121 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20122 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20123 /// are assumed to be legal.
20125 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20127 if (!VT.isSimple())
20130 MVT SVT = VT.getSimpleVT();
20132 // Very little shuffling can be done for 64-bit vectors right now.
20133 if (VT.getSizeInBits() == 64)
20136 // If this is a single-input shuffle with no 128 bit lane crossings we can
20137 // lower it into pshufb.
20138 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
20139 (SVT.is256BitVector() && Subtarget->hasInt256())) {
20140 bool isLegal = true;
20141 for (unsigned I = 0, E = M.size(); I != E; ++I) {
20142 if (M[I] >= (int)SVT.getVectorNumElements() ||
20143 ShuffleCrosses128bitLane(SVT, I, M[I])) {
20152 // FIXME: blends, shifts.
20153 return (SVT.getVectorNumElements() == 2 ||
20154 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
20155 isMOVLMask(M, SVT) ||
20156 isCommutedMOVLMask(M, SVT) ||
20157 isMOVHLPSMask(M, SVT) ||
20158 isSHUFPMask(M, SVT) ||
20159 isSHUFPMask(M, SVT, /* Commuted */ true) ||
20160 isPSHUFDMask(M, SVT) ||
20161 isPSHUFDMask(M, SVT, /* SecondOperand */ true) ||
20162 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
20163 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
20164 isPALIGNRMask(M, SVT, Subtarget) ||
20165 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
20166 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
20167 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20168 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20169 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
20170 (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
20174 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20176 if (!VT.isSimple())
20179 MVT SVT = VT.getSimpleVT();
20180 unsigned NumElts = SVT.getVectorNumElements();
20181 // FIXME: This collection of masks seems suspect.
20184 if (NumElts == 4 && SVT.is128BitVector()) {
20185 return (isMOVLMask(Mask, SVT) ||
20186 isCommutedMOVLMask(Mask, SVT, true) ||
20187 isSHUFPMask(Mask, SVT) ||
20188 isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
20189 isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
20190 Subtarget->hasInt256()));
20195 //===----------------------------------------------------------------------===//
20196 // X86 Scheduler Hooks
20197 //===----------------------------------------------------------------------===//
20199 /// Utility function to emit xbegin specifying the start of an RTM region.
20200 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20201 const TargetInstrInfo *TII) {
20202 DebugLoc DL = MI->getDebugLoc();
20204 const BasicBlock *BB = MBB->getBasicBlock();
20205 MachineFunction::iterator I = MBB;
20208 // For the v = xbegin(), we generate
20219 MachineBasicBlock *thisMBB = MBB;
20220 MachineFunction *MF = MBB->getParent();
20221 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20222 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20223 MF->insert(I, mainMBB);
20224 MF->insert(I, sinkMBB);
20226 // Transfer the remainder of BB and its successor edges to sinkMBB.
20227 sinkMBB->splice(sinkMBB->begin(), MBB,
20228 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20229 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20233 // # fallthrough to mainMBB
20234 // # abortion to sinkMBB
20235 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20236 thisMBB->addSuccessor(mainMBB);
20237 thisMBB->addSuccessor(sinkMBB);
20241 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20242 mainMBB->addSuccessor(sinkMBB);
20245 // EAX is live into the sinkMBB
20246 sinkMBB->addLiveIn(X86::EAX);
20247 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20248 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20251 MI->eraseFromParent();
20255 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20256 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20257 // in the .td file.
20258 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20259 const TargetInstrInfo *TII) {
20261 switch (MI->getOpcode()) {
20262 default: llvm_unreachable("illegal opcode!");
20263 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
20264 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20265 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
20266 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20267 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
20268 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20269 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
20270 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20273 DebugLoc dl = MI->getDebugLoc();
20274 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20276 unsigned NumArgs = MI->getNumOperands();
20277 for (unsigned i = 1; i < NumArgs; ++i) {
20278 MachineOperand &Op = MI->getOperand(i);
20279 if (!(Op.isReg() && Op.isImplicit()))
20280 MIB.addOperand(Op);
20282 if (MI->hasOneMemOperand())
20283 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20285 BuildMI(*BB, MI, dl,
20286 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20287 .addReg(X86::XMM0);
20289 MI->eraseFromParent();
20293 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20294 // defs in an instruction pattern
20295 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20296 const TargetInstrInfo *TII) {
20298 switch (MI->getOpcode()) {
20299 default: llvm_unreachable("illegal opcode!");
20300 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
20301 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20302 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
20303 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20304 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
20305 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20306 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
20307 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20310 DebugLoc dl = MI->getDebugLoc();
20311 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20313 unsigned NumArgs = MI->getNumOperands(); // remove the results
20314 for (unsigned i = 1; i < NumArgs; ++i) {
20315 MachineOperand &Op = MI->getOperand(i);
20316 if (!(Op.isReg() && Op.isImplicit()))
20317 MIB.addOperand(Op);
20319 if (MI->hasOneMemOperand())
20320 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20322 BuildMI(*BB, MI, dl,
20323 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20326 MI->eraseFromParent();
20330 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20331 const TargetInstrInfo *TII,
20332 const X86Subtarget* Subtarget) {
20333 DebugLoc dl = MI->getDebugLoc();
20335 // Address into RAX/EAX, other two args into ECX, EDX.
20336 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20337 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20338 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20339 for (int i = 0; i < X86::AddrNumOperands; ++i)
20340 MIB.addOperand(MI->getOperand(i));
20342 unsigned ValOps = X86::AddrNumOperands;
20343 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20344 .addReg(MI->getOperand(ValOps).getReg());
20345 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20346 .addReg(MI->getOperand(ValOps+1).getReg());
20348 // The instruction doesn't actually take any operands though.
20349 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20351 MI->eraseFromParent(); // The pseudo is gone now.
20355 MachineBasicBlock *
20356 X86TargetLowering::EmitVAARG64WithCustomInserter(
20358 MachineBasicBlock *MBB) const {
20359 // Emit va_arg instruction on X86-64.
20361 // Operands to this pseudo-instruction:
20362 // 0 ) Output : destination address (reg)
20363 // 1-5) Input : va_list address (addr, i64mem)
20364 // 6 ) ArgSize : Size (in bytes) of vararg type
20365 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20366 // 8 ) Align : Alignment of type
20367 // 9 ) EFLAGS (implicit-def)
20369 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20370 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
20372 unsigned DestReg = MI->getOperand(0).getReg();
20373 MachineOperand &Base = MI->getOperand(1);
20374 MachineOperand &Scale = MI->getOperand(2);
20375 MachineOperand &Index = MI->getOperand(3);
20376 MachineOperand &Disp = MI->getOperand(4);
20377 MachineOperand &Segment = MI->getOperand(5);
20378 unsigned ArgSize = MI->getOperand(6).getImm();
20379 unsigned ArgMode = MI->getOperand(7).getImm();
20380 unsigned Align = MI->getOperand(8).getImm();
20382 // Memory Reference
20383 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20384 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20385 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20387 // Machine Information
20388 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20389 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20390 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20391 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20392 DebugLoc DL = MI->getDebugLoc();
20394 // struct va_list {
20397 // i64 overflow_area (address)
20398 // i64 reg_save_area (address)
20400 // sizeof(va_list) = 24
20401 // alignment(va_list) = 8
20403 unsigned TotalNumIntRegs = 6;
20404 unsigned TotalNumXMMRegs = 8;
20405 bool UseGPOffset = (ArgMode == 1);
20406 bool UseFPOffset = (ArgMode == 2);
20407 unsigned MaxOffset = TotalNumIntRegs * 8 +
20408 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20410 /* Align ArgSize to a multiple of 8 */
20411 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20412 bool NeedsAlign = (Align > 8);
20414 MachineBasicBlock *thisMBB = MBB;
20415 MachineBasicBlock *overflowMBB;
20416 MachineBasicBlock *offsetMBB;
20417 MachineBasicBlock *endMBB;
20419 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
20420 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
20421 unsigned OffsetReg = 0;
20423 if (!UseGPOffset && !UseFPOffset) {
20424 // If we only pull from the overflow region, we don't create a branch.
20425 // We don't need to alter control flow.
20426 OffsetDestReg = 0; // unused
20427 OverflowDestReg = DestReg;
20429 offsetMBB = nullptr;
20430 overflowMBB = thisMBB;
20433 // First emit code to check if gp_offset (or fp_offset) is below the bound.
20434 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20435 // If not, pull from overflow_area. (branch to overflowMBB)
20440 // offsetMBB overflowMBB
20445 // Registers for the PHI in endMBB
20446 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20447 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20449 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20450 MachineFunction *MF = MBB->getParent();
20451 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20452 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20453 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20455 MachineFunction::iterator MBBIter = MBB;
20458 // Insert the new basic blocks
20459 MF->insert(MBBIter, offsetMBB);
20460 MF->insert(MBBIter, overflowMBB);
20461 MF->insert(MBBIter, endMBB);
20463 // Transfer the remainder of MBB and its successor edges to endMBB.
20464 endMBB->splice(endMBB->begin(), thisMBB,
20465 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20466 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20468 // Make offsetMBB and overflowMBB successors of thisMBB
20469 thisMBB->addSuccessor(offsetMBB);
20470 thisMBB->addSuccessor(overflowMBB);
20472 // endMBB is a successor of both offsetMBB and overflowMBB
20473 offsetMBB->addSuccessor(endMBB);
20474 overflowMBB->addSuccessor(endMBB);
20476 // Load the offset value into a register
20477 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20478 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20482 .addDisp(Disp, UseFPOffset ? 4 : 0)
20483 .addOperand(Segment)
20484 .setMemRefs(MMOBegin, MMOEnd);
20486 // Check if there is enough room left to pull this argument.
20487 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20489 .addImm(MaxOffset + 8 - ArgSizeA8);
20491 // Branch to "overflowMBB" if offset >= max
20492 // Fall through to "offsetMBB" otherwise
20493 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20494 .addMBB(overflowMBB);
20497 // In offsetMBB, emit code to use the reg_save_area.
20499 assert(OffsetReg != 0);
20501 // Read the reg_save_area address.
20502 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20503 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20508 .addOperand(Segment)
20509 .setMemRefs(MMOBegin, MMOEnd);
20511 // Zero-extend the offset
20512 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20513 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20516 .addImm(X86::sub_32bit);
20518 // Add the offset to the reg_save_area to get the final address.
20519 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20520 .addReg(OffsetReg64)
20521 .addReg(RegSaveReg);
20523 // Compute the offset for the next argument
20524 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20525 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20527 .addImm(UseFPOffset ? 16 : 8);
20529 // Store it back into the va_list.
20530 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20534 .addDisp(Disp, UseFPOffset ? 4 : 0)
20535 .addOperand(Segment)
20536 .addReg(NextOffsetReg)
20537 .setMemRefs(MMOBegin, MMOEnd);
20540 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20545 // Emit code to use overflow area
20548 // Load the overflow_area address into a register.
20549 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20550 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20555 .addOperand(Segment)
20556 .setMemRefs(MMOBegin, MMOEnd);
20558 // If we need to align it, do so. Otherwise, just copy the address
20559 // to OverflowDestReg.
20561 // Align the overflow address
20562 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20563 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20565 // aligned_addr = (addr + (align-1)) & ~(align-1)
20566 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20567 .addReg(OverflowAddrReg)
20570 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20572 .addImm(~(uint64_t)(Align-1));
20574 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20575 .addReg(OverflowAddrReg);
20578 // Compute the next overflow address after this argument.
20579 // (the overflow address should be kept 8-byte aligned)
20580 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20581 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20582 .addReg(OverflowDestReg)
20583 .addImm(ArgSizeA8);
20585 // Store the new overflow address.
20586 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20591 .addOperand(Segment)
20592 .addReg(NextAddrReg)
20593 .setMemRefs(MMOBegin, MMOEnd);
20595 // If we branched, emit the PHI to the front of endMBB.
20597 BuildMI(*endMBB, endMBB->begin(), DL,
20598 TII->get(X86::PHI), DestReg)
20599 .addReg(OffsetDestReg).addMBB(offsetMBB)
20600 .addReg(OverflowDestReg).addMBB(overflowMBB);
20603 // Erase the pseudo instruction
20604 MI->eraseFromParent();
20609 MachineBasicBlock *
20610 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20612 MachineBasicBlock *MBB) const {
20613 // Emit code to save XMM registers to the stack. The ABI says that the
20614 // number of registers to save is given in %al, so it's theoretically
20615 // possible to do an indirect jump trick to avoid saving all of them,
20616 // however this code takes a simpler approach and just executes all
20617 // of the stores if %al is non-zero. It's less code, and it's probably
20618 // easier on the hardware branch predictor, and stores aren't all that
20619 // expensive anyway.
20621 // Create the new basic blocks. One block contains all the XMM stores,
20622 // and one block is the final destination regardless of whether any
20623 // stores were performed.
20624 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20625 MachineFunction *F = MBB->getParent();
20626 MachineFunction::iterator MBBIter = MBB;
20628 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20629 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20630 F->insert(MBBIter, XMMSaveMBB);
20631 F->insert(MBBIter, EndMBB);
20633 // Transfer the remainder of MBB and its successor edges to EndMBB.
20634 EndMBB->splice(EndMBB->begin(), MBB,
20635 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20636 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20638 // The original block will now fall through to the XMM save block.
20639 MBB->addSuccessor(XMMSaveMBB);
20640 // The XMMSaveMBB will fall through to the end block.
20641 XMMSaveMBB->addSuccessor(EndMBB);
20643 // Now add the instructions.
20644 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20645 DebugLoc DL = MI->getDebugLoc();
20647 unsigned CountReg = MI->getOperand(0).getReg();
20648 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20649 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20651 if (!Subtarget->isTargetWin64()) {
20652 // If %al is 0, branch around the XMM save block.
20653 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20654 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20655 MBB->addSuccessor(EndMBB);
20658 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20659 // that was just emitted, but clearly shouldn't be "saved".
20660 assert((MI->getNumOperands() <= 3 ||
20661 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20662 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20663 && "Expected last argument to be EFLAGS");
20664 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20665 // In the XMM save block, save all the XMM argument registers.
20666 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20667 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20668 MachineMemOperand *MMO =
20669 F->getMachineMemOperand(
20670 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
20671 MachineMemOperand::MOStore,
20672 /*Size=*/16, /*Align=*/16);
20673 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20674 .addFrameIndex(RegSaveFrameIndex)
20675 .addImm(/*Scale=*/1)
20676 .addReg(/*IndexReg=*/0)
20677 .addImm(/*Disp=*/Offset)
20678 .addReg(/*Segment=*/0)
20679 .addReg(MI->getOperand(i).getReg())
20680 .addMemOperand(MMO);
20683 MI->eraseFromParent(); // The pseudo instruction is gone now.
20688 // The EFLAGS operand of SelectItr might be missing a kill marker
20689 // because there were multiple uses of EFLAGS, and ISel didn't know
20690 // which to mark. Figure out whether SelectItr should have had a
20691 // kill marker, and set it if it should. Returns the correct kill
20693 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20694 MachineBasicBlock* BB,
20695 const TargetRegisterInfo* TRI) {
20696 // Scan forward through BB for a use/def of EFLAGS.
20697 MachineBasicBlock::iterator miI(std::next(SelectItr));
20698 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20699 const MachineInstr& mi = *miI;
20700 if (mi.readsRegister(X86::EFLAGS))
20702 if (mi.definesRegister(X86::EFLAGS))
20703 break; // Should have kill-flag - update below.
20706 // If we hit the end of the block, check whether EFLAGS is live into a
20708 if (miI == BB->end()) {
20709 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20710 sEnd = BB->succ_end();
20711 sItr != sEnd; ++sItr) {
20712 MachineBasicBlock* succ = *sItr;
20713 if (succ->isLiveIn(X86::EFLAGS))
20718 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20719 // out. SelectMI should have a kill flag on EFLAGS.
20720 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20724 MachineBasicBlock *
20725 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20726 MachineBasicBlock *BB) const {
20727 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20728 DebugLoc DL = MI->getDebugLoc();
20730 // To "insert" a SELECT_CC instruction, we actually have to insert the
20731 // diamond control-flow pattern. The incoming instruction knows the
20732 // destination vreg to set, the condition code register to branch on, the
20733 // true/false values to select between, and a branch opcode to use.
20734 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20735 MachineFunction::iterator It = BB;
20741 // cmpTY ccX, r1, r2
20743 // fallthrough --> copy0MBB
20744 MachineBasicBlock *thisMBB = BB;
20745 MachineFunction *F = BB->getParent();
20746 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20747 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20748 F->insert(It, copy0MBB);
20749 F->insert(It, sinkMBB);
20751 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20752 // live into the sink and copy blocks.
20753 const TargetRegisterInfo *TRI =
20754 BB->getParent()->getSubtarget().getRegisterInfo();
20755 if (!MI->killsRegister(X86::EFLAGS) &&
20756 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
20757 copy0MBB->addLiveIn(X86::EFLAGS);
20758 sinkMBB->addLiveIn(X86::EFLAGS);
20761 // Transfer the remainder of BB and its successor edges to sinkMBB.
20762 sinkMBB->splice(sinkMBB->begin(), BB,
20763 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20764 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20766 // Add the true and fallthrough blocks as its successors.
20767 BB->addSuccessor(copy0MBB);
20768 BB->addSuccessor(sinkMBB);
20770 // Create the conditional branch instruction.
20772 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20773 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20776 // %FalseValue = ...
20777 // # fallthrough to sinkMBB
20778 copy0MBB->addSuccessor(sinkMBB);
20781 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20783 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20784 TII->get(X86::PHI), MI->getOperand(0).getReg())
20785 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20786 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20788 MI->eraseFromParent(); // The pseudo instruction is gone now.
20792 MachineBasicBlock *
20793 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20794 MachineBasicBlock *BB) const {
20795 MachineFunction *MF = BB->getParent();
20796 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20797 DebugLoc DL = MI->getDebugLoc();
20798 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20800 assert(MF->shouldSplitStack());
20802 const bool Is64Bit = Subtarget->is64Bit();
20803 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20805 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20806 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20809 // ... [Till the alloca]
20810 // If stacklet is not large enough, jump to mallocMBB
20813 // Allocate by subtracting from RSP
20814 // Jump to continueMBB
20817 // Allocate by call to runtime
20821 // [rest of original BB]
20824 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20825 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20826 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20828 MachineRegisterInfo &MRI = MF->getRegInfo();
20829 const TargetRegisterClass *AddrRegClass =
20830 getRegClassFor(getPointerTy());
20832 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20833 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20834 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20835 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20836 sizeVReg = MI->getOperand(1).getReg(),
20837 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20839 MachineFunction::iterator MBBIter = BB;
20842 MF->insert(MBBIter, bumpMBB);
20843 MF->insert(MBBIter, mallocMBB);
20844 MF->insert(MBBIter, continueMBB);
20846 continueMBB->splice(continueMBB->begin(), BB,
20847 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20848 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20850 // Add code to the main basic block to check if the stack limit has been hit,
20851 // and if so, jump to mallocMBB otherwise to bumpMBB.
20852 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20853 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20854 .addReg(tmpSPVReg).addReg(sizeVReg);
20855 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20856 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20857 .addReg(SPLimitVReg);
20858 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20860 // bumpMBB simply decreases the stack pointer, since we know the current
20861 // stacklet has enough space.
20862 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20863 .addReg(SPLimitVReg);
20864 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20865 .addReg(SPLimitVReg);
20866 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20868 // Calls into a routine in libgcc to allocate more space from the heap.
20869 const uint32_t *RegMask = MF->getTarget()
20870 .getSubtargetImpl()
20871 ->getRegisterInfo()
20872 ->getCallPreservedMask(CallingConv::C);
20874 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20876 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20877 .addExternalSymbol("__morestack_allocate_stack_space")
20878 .addRegMask(RegMask)
20879 .addReg(X86::RDI, RegState::Implicit)
20880 .addReg(X86::RAX, RegState::ImplicitDefine);
20881 } else if (Is64Bit) {
20882 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20884 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20885 .addExternalSymbol("__morestack_allocate_stack_space")
20886 .addRegMask(RegMask)
20887 .addReg(X86::EDI, RegState::Implicit)
20888 .addReg(X86::EAX, RegState::ImplicitDefine);
20890 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20892 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20893 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20894 .addExternalSymbol("__morestack_allocate_stack_space")
20895 .addRegMask(RegMask)
20896 .addReg(X86::EAX, RegState::ImplicitDefine);
20900 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20903 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20904 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20905 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20907 // Set up the CFG correctly.
20908 BB->addSuccessor(bumpMBB);
20909 BB->addSuccessor(mallocMBB);
20910 mallocMBB->addSuccessor(continueMBB);
20911 bumpMBB->addSuccessor(continueMBB);
20913 // Take care of the PHI nodes.
20914 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20915 MI->getOperand(0).getReg())
20916 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20917 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20919 // Delete the original pseudo instruction.
20920 MI->eraseFromParent();
20923 return continueMBB;
20926 MachineBasicBlock *
20927 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20928 MachineBasicBlock *BB) const {
20929 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20930 DebugLoc DL = MI->getDebugLoc();
20932 assert(!Subtarget->isTargetMachO());
20934 // The lowering is pretty easy: we're just emitting the call to _alloca. The
20935 // non-trivial part is impdef of ESP.
20937 if (Subtarget->isTargetWin64()) {
20938 if (Subtarget->isTargetCygMing()) {
20939 // ___chkstk(Mingw64):
20940 // Clobbers R10, R11, RAX and EFLAGS.
20942 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20943 .addExternalSymbol("___chkstk")
20944 .addReg(X86::RAX, RegState::Implicit)
20945 .addReg(X86::RSP, RegState::Implicit)
20946 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
20947 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
20948 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20950 // __chkstk(MSVCRT): does not update stack pointer.
20951 // Clobbers R10, R11 and EFLAGS.
20952 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20953 .addExternalSymbol("__chkstk")
20954 .addReg(X86::RAX, RegState::Implicit)
20955 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20956 // RAX has the offset to be subtracted from RSP.
20957 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
20962 const char *StackProbeSymbol = (Subtarget->isTargetKnownWindowsMSVC() ||
20963 Subtarget->isTargetWindowsItanium())
20967 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
20968 .addExternalSymbol(StackProbeSymbol)
20969 .addReg(X86::EAX, RegState::Implicit)
20970 .addReg(X86::ESP, RegState::Implicit)
20971 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
20972 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
20973 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20976 MI->eraseFromParent(); // The pseudo instruction is gone now.
20980 MachineBasicBlock *
20981 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20982 MachineBasicBlock *BB) const {
20983 // This is pretty easy. We're taking the value that we received from
20984 // our load from the relocation, sticking it in either RDI (x86-64)
20985 // or EAX and doing an indirect call. The return value will then
20986 // be in the normal return register.
20987 MachineFunction *F = BB->getParent();
20988 const X86InstrInfo *TII =
20989 static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
20990 DebugLoc DL = MI->getDebugLoc();
20992 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20993 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20995 // Get a register mask for the lowered call.
20996 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20997 // proper register mask.
20998 const uint32_t *RegMask = F->getTarget()
20999 .getSubtargetImpl()
21000 ->getRegisterInfo()
21001 ->getCallPreservedMask(CallingConv::C);
21002 if (Subtarget->is64Bit()) {
21003 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21004 TII->get(X86::MOV64rm), X86::RDI)
21006 .addImm(0).addReg(0)
21007 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21008 MI->getOperand(3).getTargetFlags())
21010 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21011 addDirectMem(MIB, X86::RDI);
21012 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21013 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21014 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21015 TII->get(X86::MOV32rm), X86::EAX)
21017 .addImm(0).addReg(0)
21018 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21019 MI->getOperand(3).getTargetFlags())
21021 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21022 addDirectMem(MIB, X86::EAX);
21023 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21025 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21026 TII->get(X86::MOV32rm), X86::EAX)
21027 .addReg(TII->getGlobalBaseReg(F))
21028 .addImm(0).addReg(0)
21029 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21030 MI->getOperand(3).getTargetFlags())
21032 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21033 addDirectMem(MIB, X86::EAX);
21034 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21037 MI->eraseFromParent(); // The pseudo instruction is gone now.
21041 MachineBasicBlock *
21042 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21043 MachineBasicBlock *MBB) const {
21044 DebugLoc DL = MI->getDebugLoc();
21045 MachineFunction *MF = MBB->getParent();
21046 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21047 MachineRegisterInfo &MRI = MF->getRegInfo();
21049 const BasicBlock *BB = MBB->getBasicBlock();
21050 MachineFunction::iterator I = MBB;
21053 // Memory Reference
21054 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21055 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21058 unsigned MemOpndSlot = 0;
21060 unsigned CurOp = 0;
21062 DstReg = MI->getOperand(CurOp++).getReg();
21063 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21064 assert(RC->hasType(MVT::i32) && "Invalid destination!");
21065 unsigned mainDstReg = MRI.createVirtualRegister(RC);
21066 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21068 MemOpndSlot = CurOp;
21070 MVT PVT = getPointerTy();
21071 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21072 "Invalid Pointer Size!");
21074 // For v = setjmp(buf), we generate
21077 // buf[LabelOffset] = restoreMBB
21078 // SjLjSetup restoreMBB
21084 // v = phi(main, restore)
21087 // if base pointer being used, load it from frame
21090 MachineBasicBlock *thisMBB = MBB;
21091 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21092 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21093 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21094 MF->insert(I, mainMBB);
21095 MF->insert(I, sinkMBB);
21096 MF->push_back(restoreMBB);
21098 MachineInstrBuilder MIB;
21100 // Transfer the remainder of BB and its successor edges to sinkMBB.
21101 sinkMBB->splice(sinkMBB->begin(), MBB,
21102 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21103 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21106 unsigned PtrStoreOpc = 0;
21107 unsigned LabelReg = 0;
21108 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21109 Reloc::Model RM = MF->getTarget().getRelocationModel();
21110 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21111 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21113 // Prepare IP either in reg or imm.
21114 if (!UseImmLabel) {
21115 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21116 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21117 LabelReg = MRI.createVirtualRegister(PtrRC);
21118 if (Subtarget->is64Bit()) {
21119 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21123 .addMBB(restoreMBB)
21126 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21127 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21128 .addReg(XII->getGlobalBaseReg(MF))
21131 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21135 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21137 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21138 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21139 if (i == X86::AddrDisp)
21140 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21142 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21145 MIB.addReg(LabelReg);
21147 MIB.addMBB(restoreMBB);
21148 MIB.setMemRefs(MMOBegin, MMOEnd);
21150 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21151 .addMBB(restoreMBB);
21153 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21154 MF->getSubtarget().getRegisterInfo());
21155 MIB.addRegMask(RegInfo->getNoPreservedMask());
21156 thisMBB->addSuccessor(mainMBB);
21157 thisMBB->addSuccessor(restoreMBB);
21161 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21162 mainMBB->addSuccessor(sinkMBB);
21165 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21166 TII->get(X86::PHI), DstReg)
21167 .addReg(mainDstReg).addMBB(mainMBB)
21168 .addReg(restoreDstReg).addMBB(restoreMBB);
21171 if (RegInfo->hasBasePointer(*MF)) {
21172 const X86Subtarget &STI = MF->getTarget().getSubtarget<X86Subtarget>();
21173 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
21174 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21175 X86FI->setRestoreBasePointer(MF);
21176 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21177 unsigned BasePtr = RegInfo->getBaseRegister();
21178 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21179 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21180 FramePtr, true, X86FI->getRestoreBasePointerOffset())
21181 .setMIFlag(MachineInstr::FrameSetup);
21183 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21184 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21185 restoreMBB->addSuccessor(sinkMBB);
21187 MI->eraseFromParent();
21191 MachineBasicBlock *
21192 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21193 MachineBasicBlock *MBB) const {
21194 DebugLoc DL = MI->getDebugLoc();
21195 MachineFunction *MF = MBB->getParent();
21196 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21197 MachineRegisterInfo &MRI = MF->getRegInfo();
21199 // Memory Reference
21200 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21201 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21203 MVT PVT = getPointerTy();
21204 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21205 "Invalid Pointer Size!");
21207 const TargetRegisterClass *RC =
21208 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21209 unsigned Tmp = MRI.createVirtualRegister(RC);
21210 // Since FP is only updated here but NOT referenced, it's treated as GPR.
21211 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21212 MF->getSubtarget().getRegisterInfo());
21213 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21214 unsigned SP = RegInfo->getStackRegister();
21216 MachineInstrBuilder MIB;
21218 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21219 const int64_t SPOffset = 2 * PVT.getStoreSize();
21221 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21222 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21225 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21226 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21227 MIB.addOperand(MI->getOperand(i));
21228 MIB.setMemRefs(MMOBegin, MMOEnd);
21230 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21231 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21232 if (i == X86::AddrDisp)
21233 MIB.addDisp(MI->getOperand(i), LabelOffset);
21235 MIB.addOperand(MI->getOperand(i));
21237 MIB.setMemRefs(MMOBegin, MMOEnd);
21239 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21240 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21241 if (i == X86::AddrDisp)
21242 MIB.addDisp(MI->getOperand(i), SPOffset);
21244 MIB.addOperand(MI->getOperand(i));
21246 MIB.setMemRefs(MMOBegin, MMOEnd);
21248 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21250 MI->eraseFromParent();
21254 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21255 // accumulator loops. Writing back to the accumulator allows the coalescer
21256 // to remove extra copies in the loop.
21257 MachineBasicBlock *
21258 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21259 MachineBasicBlock *MBB) const {
21260 MachineOperand &AddendOp = MI->getOperand(3);
21262 // Bail out early if the addend isn't a register - we can't switch these.
21263 if (!AddendOp.isReg())
21266 MachineFunction &MF = *MBB->getParent();
21267 MachineRegisterInfo &MRI = MF.getRegInfo();
21269 // Check whether the addend is defined by a PHI:
21270 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21271 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21272 if (!AddendDef.isPHI())
21275 // Look for the following pattern:
21277 // %addend = phi [%entry, 0], [%loop, %result]
21279 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21283 // %addend = phi [%entry, 0], [%loop, %result]
21285 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21287 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21288 assert(AddendDef.getOperand(i).isReg());
21289 MachineOperand PHISrcOp = AddendDef.getOperand(i);
21290 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21291 if (&PHISrcInst == MI) {
21292 // Found a matching instruction.
21293 unsigned NewFMAOpc = 0;
21294 switch (MI->getOpcode()) {
21295 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21296 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21297 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21298 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21299 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21300 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21301 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21302 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21303 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21304 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21305 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21306 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21307 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21308 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21309 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21310 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21311 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21312 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21313 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21314 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21316 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21317 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21318 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21319 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21320 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21321 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21322 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21323 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21324 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21325 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21326 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21327 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21328 default: llvm_unreachable("Unrecognized FMA variant.");
21331 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
21332 MachineInstrBuilder MIB =
21333 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21334 .addOperand(MI->getOperand(0))
21335 .addOperand(MI->getOperand(3))
21336 .addOperand(MI->getOperand(2))
21337 .addOperand(MI->getOperand(1));
21338 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21339 MI->eraseFromParent();
21346 MachineBasicBlock *
21347 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21348 MachineBasicBlock *BB) const {
21349 switch (MI->getOpcode()) {
21350 default: llvm_unreachable("Unexpected instr type to insert");
21351 case X86::TAILJMPd64:
21352 case X86::TAILJMPr64:
21353 case X86::TAILJMPm64:
21354 llvm_unreachable("TAILJMP64 would not be touched here.");
21355 case X86::TCRETURNdi64:
21356 case X86::TCRETURNri64:
21357 case X86::TCRETURNmi64:
21359 case X86::WIN_ALLOCA:
21360 return EmitLoweredWinAlloca(MI, BB);
21361 case X86::SEG_ALLOCA_32:
21362 case X86::SEG_ALLOCA_64:
21363 return EmitLoweredSegAlloca(MI, BB);
21364 case X86::TLSCall_32:
21365 case X86::TLSCall_64:
21366 return EmitLoweredTLSCall(MI, BB);
21367 case X86::CMOV_GR8:
21368 case X86::CMOV_FR32:
21369 case X86::CMOV_FR64:
21370 case X86::CMOV_V4F32:
21371 case X86::CMOV_V2F64:
21372 case X86::CMOV_V2I64:
21373 case X86::CMOV_V8F32:
21374 case X86::CMOV_V4F64:
21375 case X86::CMOV_V4I64:
21376 case X86::CMOV_V16F32:
21377 case X86::CMOV_V8F64:
21378 case X86::CMOV_V8I64:
21379 case X86::CMOV_GR16:
21380 case X86::CMOV_GR32:
21381 case X86::CMOV_RFP32:
21382 case X86::CMOV_RFP64:
21383 case X86::CMOV_RFP80:
21384 return EmitLoweredSelect(MI, BB);
21386 case X86::FP32_TO_INT16_IN_MEM:
21387 case X86::FP32_TO_INT32_IN_MEM:
21388 case X86::FP32_TO_INT64_IN_MEM:
21389 case X86::FP64_TO_INT16_IN_MEM:
21390 case X86::FP64_TO_INT32_IN_MEM:
21391 case X86::FP64_TO_INT64_IN_MEM:
21392 case X86::FP80_TO_INT16_IN_MEM:
21393 case X86::FP80_TO_INT32_IN_MEM:
21394 case X86::FP80_TO_INT64_IN_MEM: {
21395 MachineFunction *F = BB->getParent();
21396 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
21397 DebugLoc DL = MI->getDebugLoc();
21399 // Change the floating point control register to use "round towards zero"
21400 // mode when truncating to an integer value.
21401 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21402 addFrameReference(BuildMI(*BB, MI, DL,
21403 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21405 // Load the old value of the high byte of the control word...
21407 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21408 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21411 // Set the high part to be round to zero...
21412 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21415 // Reload the modified control word now...
21416 addFrameReference(BuildMI(*BB, MI, DL,
21417 TII->get(X86::FLDCW16m)), CWFrameIdx);
21419 // Restore the memory image of control word to original value
21420 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21423 // Get the X86 opcode to use.
21425 switch (MI->getOpcode()) {
21426 default: llvm_unreachable("illegal opcode!");
21427 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21428 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21429 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21430 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21431 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21432 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21433 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21434 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21435 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21439 MachineOperand &Op = MI->getOperand(0);
21441 AM.BaseType = X86AddressMode::RegBase;
21442 AM.Base.Reg = Op.getReg();
21444 AM.BaseType = X86AddressMode::FrameIndexBase;
21445 AM.Base.FrameIndex = Op.getIndex();
21447 Op = MI->getOperand(1);
21449 AM.Scale = Op.getImm();
21450 Op = MI->getOperand(2);
21452 AM.IndexReg = Op.getImm();
21453 Op = MI->getOperand(3);
21454 if (Op.isGlobal()) {
21455 AM.GV = Op.getGlobal();
21457 AM.Disp = Op.getImm();
21459 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21460 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21462 // Reload the original control word now.
21463 addFrameReference(BuildMI(*BB, MI, DL,
21464 TII->get(X86::FLDCW16m)), CWFrameIdx);
21466 MI->eraseFromParent(); // The pseudo instruction is gone now.
21469 // String/text processing lowering.
21470 case X86::PCMPISTRM128REG:
21471 case X86::VPCMPISTRM128REG:
21472 case X86::PCMPISTRM128MEM:
21473 case X86::VPCMPISTRM128MEM:
21474 case X86::PCMPESTRM128REG:
21475 case X86::VPCMPESTRM128REG:
21476 case X86::PCMPESTRM128MEM:
21477 case X86::VPCMPESTRM128MEM:
21478 assert(Subtarget->hasSSE42() &&
21479 "Target must have SSE4.2 or AVX features enabled");
21480 return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21482 // String/text processing lowering.
21483 case X86::PCMPISTRIREG:
21484 case X86::VPCMPISTRIREG:
21485 case X86::PCMPISTRIMEM:
21486 case X86::VPCMPISTRIMEM:
21487 case X86::PCMPESTRIREG:
21488 case X86::VPCMPESTRIREG:
21489 case X86::PCMPESTRIMEM:
21490 case X86::VPCMPESTRIMEM:
21491 assert(Subtarget->hasSSE42() &&
21492 "Target must have SSE4.2 or AVX features enabled");
21493 return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21495 // Thread synchronization.
21497 return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
21502 return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21504 case X86::VASTART_SAVE_XMM_REGS:
21505 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21507 case X86::VAARG_64:
21508 return EmitVAARG64WithCustomInserter(MI, BB);
21510 case X86::EH_SjLj_SetJmp32:
21511 case X86::EH_SjLj_SetJmp64:
21512 return emitEHSjLjSetJmp(MI, BB);
21514 case X86::EH_SjLj_LongJmp32:
21515 case X86::EH_SjLj_LongJmp64:
21516 return emitEHSjLjLongJmp(MI, BB);
21518 case TargetOpcode::STATEPOINT:
21519 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21520 // this point in the process. We diverge later.
21521 return emitPatchPoint(MI, BB);
21523 case TargetOpcode::STACKMAP:
21524 case TargetOpcode::PATCHPOINT:
21525 return emitPatchPoint(MI, BB);
21527 case X86::VFMADDPDr213r:
21528 case X86::VFMADDPSr213r:
21529 case X86::VFMADDSDr213r:
21530 case X86::VFMADDSSr213r:
21531 case X86::VFMSUBPDr213r:
21532 case X86::VFMSUBPSr213r:
21533 case X86::VFMSUBSDr213r:
21534 case X86::VFMSUBSSr213r:
21535 case X86::VFNMADDPDr213r:
21536 case X86::VFNMADDPSr213r:
21537 case X86::VFNMADDSDr213r:
21538 case X86::VFNMADDSSr213r:
21539 case X86::VFNMSUBPDr213r:
21540 case X86::VFNMSUBPSr213r:
21541 case X86::VFNMSUBSDr213r:
21542 case X86::VFNMSUBSSr213r:
21543 case X86::VFMADDSUBPDr213r:
21544 case X86::VFMADDSUBPSr213r:
21545 case X86::VFMSUBADDPDr213r:
21546 case X86::VFMSUBADDPSr213r:
21547 case X86::VFMADDPDr213rY:
21548 case X86::VFMADDPSr213rY:
21549 case X86::VFMSUBPDr213rY:
21550 case X86::VFMSUBPSr213rY:
21551 case X86::VFNMADDPDr213rY:
21552 case X86::VFNMADDPSr213rY:
21553 case X86::VFNMSUBPDr213rY:
21554 case X86::VFNMSUBPSr213rY:
21555 case X86::VFMADDSUBPDr213rY:
21556 case X86::VFMADDSUBPSr213rY:
21557 case X86::VFMSUBADDPDr213rY:
21558 case X86::VFMSUBADDPSr213rY:
21559 return emitFMA3Instr(MI, BB);
21563 //===----------------------------------------------------------------------===//
21564 // X86 Optimization Hooks
21565 //===----------------------------------------------------------------------===//
21567 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21570 const SelectionDAG &DAG,
21571 unsigned Depth) const {
21572 unsigned BitWidth = KnownZero.getBitWidth();
21573 unsigned Opc = Op.getOpcode();
21574 assert((Opc >= ISD::BUILTIN_OP_END ||
21575 Opc == ISD::INTRINSIC_WO_CHAIN ||
21576 Opc == ISD::INTRINSIC_W_CHAIN ||
21577 Opc == ISD::INTRINSIC_VOID) &&
21578 "Should use MaskedValueIsZero if you don't know whether Op"
21579 " is a target node!");
21581 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21595 // These nodes' second result is a boolean.
21596 if (Op.getResNo() == 0)
21599 case X86ISD::SETCC:
21600 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21602 case ISD::INTRINSIC_WO_CHAIN: {
21603 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21604 unsigned NumLoBits = 0;
21607 case Intrinsic::x86_sse_movmsk_ps:
21608 case Intrinsic::x86_avx_movmsk_ps_256:
21609 case Intrinsic::x86_sse2_movmsk_pd:
21610 case Intrinsic::x86_avx_movmsk_pd_256:
21611 case Intrinsic::x86_mmx_pmovmskb:
21612 case Intrinsic::x86_sse2_pmovmskb_128:
21613 case Intrinsic::x86_avx2_pmovmskb: {
21614 // High bits of movmskp{s|d}, pmovmskb are known zero.
21616 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21617 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21618 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21619 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21620 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21621 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21622 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21623 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21625 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21634 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21636 const SelectionDAG &,
21637 unsigned Depth) const {
21638 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21639 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21640 return Op.getValueType().getScalarType().getSizeInBits();
21646 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21647 /// node is a GlobalAddress + offset.
21648 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21649 const GlobalValue* &GA,
21650 int64_t &Offset) const {
21651 if (N->getOpcode() == X86ISD::Wrapper) {
21652 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21653 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21654 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21658 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21661 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21662 /// same as extracting the high 128-bit part of 256-bit vector and then
21663 /// inserting the result into the low part of a new 256-bit vector
21664 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21665 EVT VT = SVOp->getValueType(0);
21666 unsigned NumElems = VT.getVectorNumElements();
21668 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21669 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21670 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21671 SVOp->getMaskElt(j) >= 0)
21677 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21678 /// same as extracting the low 128-bit part of 256-bit vector and then
21679 /// inserting the result into the high part of a new 256-bit vector
21680 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21681 EVT VT = SVOp->getValueType(0);
21682 unsigned NumElems = VT.getVectorNumElements();
21684 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21685 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21686 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21687 SVOp->getMaskElt(j) >= 0)
21693 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21694 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21695 TargetLowering::DAGCombinerInfo &DCI,
21696 const X86Subtarget* Subtarget) {
21698 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21699 SDValue V1 = SVOp->getOperand(0);
21700 SDValue V2 = SVOp->getOperand(1);
21701 EVT VT = SVOp->getValueType(0);
21702 unsigned NumElems = VT.getVectorNumElements();
21704 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21705 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21709 // V UNDEF BUILD_VECTOR UNDEF
21711 // CONCAT_VECTOR CONCAT_VECTOR
21714 // RESULT: V + zero extended
21716 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21717 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21718 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21721 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21724 // To match the shuffle mask, the first half of the mask should
21725 // be exactly the first vector, and all the rest a splat with the
21726 // first element of the second one.
21727 for (unsigned i = 0; i != NumElems/2; ++i)
21728 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21729 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21732 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21733 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21734 if (Ld->hasNUsesOfValue(1, 0)) {
21735 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21736 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21738 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21740 Ld->getPointerInfo(),
21741 Ld->getAlignment(),
21742 false/*isVolatile*/, true/*ReadMem*/,
21743 false/*WriteMem*/);
21745 // Make sure the newly-created LOAD is in the same position as Ld in
21746 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21747 // and update uses of Ld's output chain to use the TokenFactor.
21748 if (Ld->hasAnyUseOfValue(1)) {
21749 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21750 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21751 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21752 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21753 SDValue(ResNode.getNode(), 1));
21756 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
21760 // Emit a zeroed vector and insert the desired subvector on its
21762 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21763 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21764 return DCI.CombineTo(N, InsV);
21767 //===--------------------------------------------------------------------===//
21768 // Combine some shuffles into subvector extracts and inserts:
21771 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21772 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21773 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21774 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21775 return DCI.CombineTo(N, InsV);
21778 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21779 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21780 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21781 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21782 return DCI.CombineTo(N, InsV);
21788 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21791 /// This is the leaf of the recursive combinine below. When we have found some
21792 /// chain of single-use x86 shuffle instructions and accumulated the combined
21793 /// shuffle mask represented by them, this will try to pattern match that mask
21794 /// into either a single instruction if there is a special purpose instruction
21795 /// for this operation, or into a PSHUFB instruction which is a fully general
21796 /// instruction but should only be used to replace chains over a certain depth.
21797 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21798 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21799 TargetLowering::DAGCombinerInfo &DCI,
21800 const X86Subtarget *Subtarget) {
21801 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21803 // Find the operand that enters the chain. Note that multiple uses are OK
21804 // here, we're not going to remove the operand we find.
21805 SDValue Input = Op.getOperand(0);
21806 while (Input.getOpcode() == ISD::BITCAST)
21807 Input = Input.getOperand(0);
21809 MVT VT = Input.getSimpleValueType();
21810 MVT RootVT = Root.getSimpleValueType();
21813 // Just remove no-op shuffle masks.
21814 if (Mask.size() == 1) {
21815 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
21820 // Use the float domain if the operand type is a floating point type.
21821 bool FloatDomain = VT.isFloatingPoint();
21823 // For floating point shuffles, we don't have free copies in the shuffle
21824 // instructions or the ability to load as part of the instruction, so
21825 // canonicalize their shuffles to UNPCK or MOV variants.
21827 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21828 // vectors because it can have a load folded into it that UNPCK cannot. This
21829 // doesn't preclude something switching to the shorter encoding post-RA.
21831 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
21832 bool Lo = Mask.equals(0, 0);
21835 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21836 // is no slower than UNPCKLPD but has the option to fold the input operand
21837 // into even an unaligned memory load.
21838 if (Lo && Subtarget->hasSSE3()) {
21839 Shuffle = X86ISD::MOVDDUP;
21840 ShuffleVT = MVT::v2f64;
21842 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21843 // than the UNPCK variants.
21844 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21845 ShuffleVT = MVT::v4f32;
21847 if (Depth == 1 && Root->getOpcode() == Shuffle)
21848 return false; // Nothing to do!
21849 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21850 DCI.AddToWorklist(Op.getNode());
21851 if (Shuffle == X86ISD::MOVDDUP)
21852 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21854 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21855 DCI.AddToWorklist(Op.getNode());
21856 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21860 if (Subtarget->hasSSE3() &&
21861 (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
21862 bool Lo = Mask.equals(0, 0, 2, 2);
21863 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21864 MVT ShuffleVT = MVT::v4f32;
21865 if (Depth == 1 && Root->getOpcode() == Shuffle)
21866 return false; // Nothing to do!
21867 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21868 DCI.AddToWorklist(Op.getNode());
21869 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21870 DCI.AddToWorklist(Op.getNode());
21871 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21875 if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
21876 bool Lo = Mask.equals(0, 0, 1, 1);
21877 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21878 MVT ShuffleVT = MVT::v4f32;
21879 if (Depth == 1 && Root->getOpcode() == Shuffle)
21880 return false; // Nothing to do!
21881 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21882 DCI.AddToWorklist(Op.getNode());
21883 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21884 DCI.AddToWorklist(Op.getNode());
21885 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21891 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21892 // variants as none of these have single-instruction variants that are
21893 // superior to the UNPCK formulation.
21894 if (!FloatDomain &&
21895 (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
21896 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
21897 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
21898 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
21900 bool Lo = Mask[0] == 0;
21901 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21902 if (Depth == 1 && Root->getOpcode() == Shuffle)
21903 return false; // Nothing to do!
21905 switch (Mask.size()) {
21907 ShuffleVT = MVT::v8i16;
21910 ShuffleVT = MVT::v16i8;
21913 llvm_unreachable("Impossible mask size!");
21915 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21916 DCI.AddToWorklist(Op.getNode());
21917 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21918 DCI.AddToWorklist(Op.getNode());
21919 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21924 // Don't try to re-form single instruction chains under any circumstances now
21925 // that we've done encoding canonicalization for them.
21929 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21930 // can replace them with a single PSHUFB instruction profitably. Intel's
21931 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21932 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21933 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21934 SmallVector<SDValue, 16> PSHUFBMask;
21935 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
21936 int Ratio = 16 / Mask.size();
21937 for (unsigned i = 0; i < 16; ++i) {
21938 if (Mask[i / Ratio] == SM_SentinelUndef) {
21939 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21942 int M = Mask[i / Ratio] != SM_SentinelZero
21943 ? Ratio * Mask[i / Ratio] + i % Ratio
21945 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
21947 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
21948 DCI.AddToWorklist(Op.getNode());
21949 SDValue PSHUFBMaskOp =
21950 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
21951 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21952 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
21953 DCI.AddToWorklist(Op.getNode());
21954 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21959 // Failed to find any combines.
21963 /// \brief Fully generic combining of x86 shuffle instructions.
21965 /// This should be the last combine run over the x86 shuffle instructions. Once
21966 /// they have been fully optimized, this will recursively consider all chains
21967 /// of single-use shuffle instructions, build a generic model of the cumulative
21968 /// shuffle operation, and check for simpler instructions which implement this
21969 /// operation. We use this primarily for two purposes:
21971 /// 1) Collapse generic shuffles to specialized single instructions when
21972 /// equivalent. In most cases, this is just an encoding size win, but
21973 /// sometimes we will collapse multiple generic shuffles into a single
21974 /// special-purpose shuffle.
21975 /// 2) Look for sequences of shuffle instructions with 3 or more total
21976 /// instructions, and replace them with the slightly more expensive SSSE3
21977 /// PSHUFB instruction if available. We do this as the last combining step
21978 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21979 /// a suitable short sequence of other instructions. The PHUFB will either
21980 /// use a register or have to read from memory and so is slightly (but only
21981 /// slightly) more expensive than the other shuffle instructions.
21983 /// Because this is inherently a quadratic operation (for each shuffle in
21984 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21985 /// This should never be an issue in practice as the shuffle lowering doesn't
21986 /// produce sequences of more than 8 instructions.
21988 /// FIXME: We will currently miss some cases where the redundant shuffling
21989 /// would simplify under the threshold for PSHUFB formation because of
21990 /// combine-ordering. To fix this, we should do the redundant instruction
21991 /// combining in this recursive walk.
21992 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21993 ArrayRef<int> RootMask,
21994 int Depth, bool HasPSHUFB,
21996 TargetLowering::DAGCombinerInfo &DCI,
21997 const X86Subtarget *Subtarget) {
21998 // Bound the depth of our recursive combine because this is ultimately
21999 // quadratic in nature.
22003 // Directly rip through bitcasts to find the underlying operand.
22004 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22005 Op = Op.getOperand(0);
22007 MVT VT = Op.getSimpleValueType();
22008 if (!VT.isVector())
22009 return false; // Bail if we hit a non-vector.
22010 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
22011 // version should be added.
22012 if (VT.getSizeInBits() != 128)
22015 assert(Root.getSimpleValueType().isVector() &&
22016 "Shuffles operate on vector types!");
22017 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22018 "Can only combine shuffles of the same vector register size.");
22020 if (!isTargetShuffle(Op.getOpcode()))
22022 SmallVector<int, 16> OpMask;
22024 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22025 // We only can combine unary shuffles which we can decode the mask for.
22026 if (!HaveMask || !IsUnary)
22029 assert(VT.getVectorNumElements() == OpMask.size() &&
22030 "Different mask size from vector size!");
22031 assert(((RootMask.size() > OpMask.size() &&
22032 RootMask.size() % OpMask.size() == 0) ||
22033 (OpMask.size() > RootMask.size() &&
22034 OpMask.size() % RootMask.size() == 0) ||
22035 OpMask.size() == RootMask.size()) &&
22036 "The smaller number of elements must divide the larger.");
22037 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22038 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22039 assert(((RootRatio == 1 && OpRatio == 1) ||
22040 (RootRatio == 1) != (OpRatio == 1)) &&
22041 "Must not have a ratio for both incoming and op masks!");
22043 SmallVector<int, 16> Mask;
22044 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22046 // Merge this shuffle operation's mask into our accumulated mask. Note that
22047 // this shuffle's mask will be the first applied to the input, followed by the
22048 // root mask to get us all the way to the root value arrangement. The reason
22049 // for this order is that we are recursing up the operation chain.
22050 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22051 int RootIdx = i / RootRatio;
22052 if (RootMask[RootIdx] < 0) {
22053 // This is a zero or undef lane, we're done.
22054 Mask.push_back(RootMask[RootIdx]);
22058 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22059 int OpIdx = RootMaskedIdx / OpRatio;
22060 if (OpMask[OpIdx] < 0) {
22061 // The incoming lanes are zero or undef, it doesn't matter which ones we
22063 Mask.push_back(OpMask[OpIdx]);
22067 // Ok, we have non-zero lanes, map them through.
22068 Mask.push_back(OpMask[OpIdx] * OpRatio +
22069 RootMaskedIdx % OpRatio);
22072 // See if we can recurse into the operand to combine more things.
22073 switch (Op.getOpcode()) {
22074 case X86ISD::PSHUFB:
22076 case X86ISD::PSHUFD:
22077 case X86ISD::PSHUFHW:
22078 case X86ISD::PSHUFLW:
22079 if (Op.getOperand(0).hasOneUse() &&
22080 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22081 HasPSHUFB, DAG, DCI, Subtarget))
22085 case X86ISD::UNPCKL:
22086 case X86ISD::UNPCKH:
22087 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22088 // We can't check for single use, we have to check that this shuffle is the only user.
22089 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22090 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22091 HasPSHUFB, DAG, DCI, Subtarget))
22096 // Minor canonicalization of the accumulated shuffle mask to make it easier
22097 // to match below. All this does is detect masks with squential pairs of
22098 // elements, and shrink them to the half-width mask. It does this in a loop
22099 // so it will reduce the size of the mask to the minimal width mask which
22100 // performs an equivalent shuffle.
22101 SmallVector<int, 16> WidenedMask;
22102 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22103 Mask = std::move(WidenedMask);
22104 WidenedMask.clear();
22107 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22111 /// \brief Get the PSHUF-style mask from PSHUF node.
22113 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22114 /// PSHUF-style masks that can be reused with such instructions.
22115 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22116 SmallVector<int, 4> Mask;
22118 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
22122 switch (N.getOpcode()) {
22123 case X86ISD::PSHUFD:
22125 case X86ISD::PSHUFLW:
22128 case X86ISD::PSHUFHW:
22129 Mask.erase(Mask.begin(), Mask.begin() + 4);
22130 for (int &M : Mask)
22134 llvm_unreachable("No valid shuffle instruction found!");
22138 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22140 /// We walk up the chain and look for a combinable shuffle, skipping over
22141 /// shuffles that we could hoist this shuffle's transformation past without
22142 /// altering anything.
22144 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22146 TargetLowering::DAGCombinerInfo &DCI) {
22147 assert(N.getOpcode() == X86ISD::PSHUFD &&
22148 "Called with something other than an x86 128-bit half shuffle!");
22151 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22152 // of the shuffles in the chain so that we can form a fresh chain to replace
22154 SmallVector<SDValue, 8> Chain;
22155 SDValue V = N.getOperand(0);
22156 for (; V.hasOneUse(); V = V.getOperand(0)) {
22157 switch (V.getOpcode()) {
22159 return SDValue(); // Nothing combined!
22162 // Skip bitcasts as we always know the type for the target specific
22166 case X86ISD::PSHUFD:
22167 // Found another dword shuffle.
22170 case X86ISD::PSHUFLW:
22171 // Check that the low words (being shuffled) are the identity in the
22172 // dword shuffle, and the high words are self-contained.
22173 if (Mask[0] != 0 || Mask[1] != 1 ||
22174 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22177 Chain.push_back(V);
22180 case X86ISD::PSHUFHW:
22181 // Check that the high words (being shuffled) are the identity in the
22182 // dword shuffle, and the low words are self-contained.
22183 if (Mask[2] != 2 || Mask[3] != 3 ||
22184 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22187 Chain.push_back(V);
22190 case X86ISD::UNPCKL:
22191 case X86ISD::UNPCKH:
22192 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22193 // shuffle into a preceding word shuffle.
22194 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
22197 // Search for a half-shuffle which we can combine with.
22198 unsigned CombineOp =
22199 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22200 if (V.getOperand(0) != V.getOperand(1) ||
22201 !V->isOnlyUserOf(V.getOperand(0).getNode()))
22203 Chain.push_back(V);
22204 V = V.getOperand(0);
22206 switch (V.getOpcode()) {
22208 return SDValue(); // Nothing to combine.
22210 case X86ISD::PSHUFLW:
22211 case X86ISD::PSHUFHW:
22212 if (V.getOpcode() == CombineOp)
22215 Chain.push_back(V);
22219 V = V.getOperand(0);
22223 } while (V.hasOneUse());
22226 // Break out of the loop if we break out of the switch.
22230 if (!V.hasOneUse())
22231 // We fell out of the loop without finding a viable combining instruction.
22234 // Merge this node's mask and our incoming mask.
22235 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22236 for (int &M : Mask)
22238 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22239 getV4X86ShuffleImm8ForMask(Mask, DAG));
22241 // Rebuild the chain around this new shuffle.
22242 while (!Chain.empty()) {
22243 SDValue W = Chain.pop_back_val();
22245 if (V.getValueType() != W.getOperand(0).getValueType())
22246 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
22248 switch (W.getOpcode()) {
22250 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22252 case X86ISD::UNPCKL:
22253 case X86ISD::UNPCKH:
22254 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22257 case X86ISD::PSHUFD:
22258 case X86ISD::PSHUFLW:
22259 case X86ISD::PSHUFHW:
22260 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22264 if (V.getValueType() != N.getValueType())
22265 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
22267 // Return the new chain to replace N.
22271 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22273 /// We walk up the chain, skipping shuffles of the other half and looking
22274 /// through shuffles which switch halves trying to find a shuffle of the same
22275 /// pair of dwords.
22276 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22278 TargetLowering::DAGCombinerInfo &DCI) {
22280 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22281 "Called with something other than an x86 128-bit half shuffle!");
22283 unsigned CombineOpcode = N.getOpcode();
22285 // Walk up a single-use chain looking for a combinable shuffle.
22286 SDValue V = N.getOperand(0);
22287 for (; V.hasOneUse(); V = V.getOperand(0)) {
22288 switch (V.getOpcode()) {
22290 return false; // Nothing combined!
22293 // Skip bitcasts as we always know the type for the target specific
22297 case X86ISD::PSHUFLW:
22298 case X86ISD::PSHUFHW:
22299 if (V.getOpcode() == CombineOpcode)
22302 // Other-half shuffles are no-ops.
22305 // Break out of the loop if we break out of the switch.
22309 if (!V.hasOneUse())
22310 // We fell out of the loop without finding a viable combining instruction.
22313 // Combine away the bottom node as its shuffle will be accumulated into
22314 // a preceding shuffle.
22315 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22317 // Record the old value.
22320 // Merge this node's mask and our incoming mask (adjusted to account for all
22321 // the pshufd instructions encountered).
22322 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22323 for (int &M : Mask)
22325 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22326 getV4X86ShuffleImm8ForMask(Mask, DAG));
22328 // Check that the shuffles didn't cancel each other out. If not, we need to
22329 // combine to the new one.
22331 // Replace the combinable shuffle with the combined one, updating all users
22332 // so that we re-evaluate the chain here.
22333 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22338 /// \brief Try to combine x86 target specific shuffles.
22339 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22340 TargetLowering::DAGCombinerInfo &DCI,
22341 const X86Subtarget *Subtarget) {
22343 MVT VT = N.getSimpleValueType();
22344 SmallVector<int, 4> Mask;
22346 switch (N.getOpcode()) {
22347 case X86ISD::PSHUFD:
22348 case X86ISD::PSHUFLW:
22349 case X86ISD::PSHUFHW:
22350 Mask = getPSHUFShuffleMask(N);
22351 assert(Mask.size() == 4);
22357 // Nuke no-op shuffles that show up after combining.
22358 if (isNoopShuffleMask(Mask))
22359 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22361 // Look for simplifications involving one or two shuffle instructions.
22362 SDValue V = N.getOperand(0);
22363 switch (N.getOpcode()) {
22366 case X86ISD::PSHUFLW:
22367 case X86ISD::PSHUFHW:
22368 assert(VT == MVT::v8i16);
22371 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22372 return SDValue(); // We combined away this shuffle, so we're done.
22374 // See if this reduces to a PSHUFD which is no more expensive and can
22375 // combine with more operations. Note that it has to at least flip the
22376 // dwords as otherwise it would have been removed as a no-op.
22377 if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
22378 int DMask[] = {0, 1, 2, 3};
22379 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22380 DMask[DOffset + 0] = DOffset + 1;
22381 DMask[DOffset + 1] = DOffset + 0;
22382 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
22383 DCI.AddToWorklist(V.getNode());
22384 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
22385 getV4X86ShuffleImm8ForMask(DMask, DAG));
22386 DCI.AddToWorklist(V.getNode());
22387 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
22390 // Look for shuffle patterns which can be implemented as a single unpack.
22391 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22392 // only works when we have a PSHUFD followed by two half-shuffles.
22393 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22394 (V.getOpcode() == X86ISD::PSHUFLW ||
22395 V.getOpcode() == X86ISD::PSHUFHW) &&
22396 V.getOpcode() != N.getOpcode() &&
22398 SDValue D = V.getOperand(0);
22399 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22400 D = D.getOperand(0);
22401 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22402 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22403 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22404 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22405 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22407 for (int i = 0; i < 4; ++i) {
22408 WordMask[i + NOffset] = Mask[i] + NOffset;
22409 WordMask[i + VOffset] = VMask[i] + VOffset;
22411 // Map the word mask through the DWord mask.
22413 for (int i = 0; i < 8; ++i)
22414 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22415 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
22416 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
22417 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
22418 std::begin(UnpackLoMask)) ||
22419 std::equal(std::begin(MappedMask), std::end(MappedMask),
22420 std::begin(UnpackHiMask))) {
22421 // We can replace all three shuffles with an unpack.
22422 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
22423 DCI.AddToWorklist(V.getNode());
22424 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22426 DL, MVT::v8i16, V, V);
22433 case X86ISD::PSHUFD:
22434 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22443 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22445 /// We combine this directly on the abstract vector shuffle nodes so it is
22446 /// easier to generically match. We also insert dummy vector shuffle nodes for
22447 /// the operands which explicitly discard the lanes which are unused by this
22448 /// operation to try to flow through the rest of the combiner the fact that
22449 /// they're unused.
22450 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22452 EVT VT = N->getValueType(0);
22454 // We only handle target-independent shuffles.
22455 // FIXME: It would be easy and harmless to use the target shuffle mask
22456 // extraction tool to support more.
22457 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22460 auto *SVN = cast<ShuffleVectorSDNode>(N);
22461 ArrayRef<int> Mask = SVN->getMask();
22462 SDValue V1 = N->getOperand(0);
22463 SDValue V2 = N->getOperand(1);
22465 // We require the first shuffle operand to be the SUB node, and the second to
22466 // be the ADD node.
22467 // FIXME: We should support the commuted patterns.
22468 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22471 // If there are other uses of these operations we can't fold them.
22472 if (!V1->hasOneUse() || !V2->hasOneUse())
22475 // Ensure that both operations have the same operands. Note that we can
22476 // commute the FADD operands.
22477 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22478 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22479 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22482 // We're looking for blends between FADD and FSUB nodes. We insist on these
22483 // nodes being lined up in a specific expected pattern.
22484 if (!(isShuffleEquivalent(Mask, 0, 3) ||
22485 isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
22486 isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
22489 // Only specific types are legal at this point, assert so we notice if and
22490 // when these change.
22491 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22492 VT == MVT::v4f64) &&
22493 "Unknown vector type encountered!");
22495 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22498 /// PerformShuffleCombine - Performs several different shuffle combines.
22499 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22500 TargetLowering::DAGCombinerInfo &DCI,
22501 const X86Subtarget *Subtarget) {
22503 SDValue N0 = N->getOperand(0);
22504 SDValue N1 = N->getOperand(1);
22505 EVT VT = N->getValueType(0);
22507 // Don't create instructions with illegal types after legalize types has run.
22508 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22509 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22512 // If we have legalized the vector types, look for blends of FADD and FSUB
22513 // nodes that we can fuse into an ADDSUB node.
22514 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22515 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22518 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22519 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22520 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22521 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22523 // During Type Legalization, when promoting illegal vector types,
22524 // the backend might introduce new shuffle dag nodes and bitcasts.
22526 // This code performs the following transformation:
22527 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22528 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22530 // We do this only if both the bitcast and the BINOP dag nodes have
22531 // one use. Also, perform this transformation only if the new binary
22532 // operation is legal. This is to avoid introducing dag nodes that
22533 // potentially need to be further expanded (or custom lowered) into a
22534 // less optimal sequence of dag nodes.
22535 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22536 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22537 N0.getOpcode() == ISD::BITCAST) {
22538 SDValue BC0 = N0.getOperand(0);
22539 EVT SVT = BC0.getValueType();
22540 unsigned Opcode = BC0.getOpcode();
22541 unsigned NumElts = VT.getVectorNumElements();
22543 if (BC0.hasOneUse() && SVT.isVector() &&
22544 SVT.getVectorNumElements() * 2 == NumElts &&
22545 TLI.isOperationLegal(Opcode, VT)) {
22546 bool CanFold = false;
22558 unsigned SVTNumElts = SVT.getVectorNumElements();
22559 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22560 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22561 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22562 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22563 CanFold = SVOp->getMaskElt(i) < 0;
22566 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
22567 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
22568 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22569 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22574 // Only handle 128 wide vector from here on.
22575 if (!VT.is128BitVector())
22578 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22579 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22580 // consecutive, non-overlapping, and in the right order.
22581 SmallVector<SDValue, 16> Elts;
22582 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22583 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22585 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
22589 if (isTargetShuffle(N->getOpcode())) {
22591 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22592 if (Shuffle.getNode())
22595 // Try recursively combining arbitrary sequences of x86 shuffle
22596 // instructions into higher-order shuffles. We do this after combining
22597 // specific PSHUF instruction sequences into their minimal form so that we
22598 // can evaluate how many specialized shuffle instructions are involved in
22599 // a particular chain.
22600 SmallVector<int, 1> NonceMask; // Just a placeholder.
22601 NonceMask.push_back(0);
22602 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22603 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22605 return SDValue(); // This routine will use CombineTo to replace N.
22611 /// PerformTruncateCombine - Converts truncate operation to
22612 /// a sequence of vector shuffle operations.
22613 /// It is possible when we truncate 256-bit vector to 128-bit vector
22614 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22615 TargetLowering::DAGCombinerInfo &DCI,
22616 const X86Subtarget *Subtarget) {
22620 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22621 /// specific shuffle of a load can be folded into a single element load.
22622 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22623 /// shuffles have been custom lowered so we need to handle those here.
22624 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22625 TargetLowering::DAGCombinerInfo &DCI) {
22626 if (DCI.isBeforeLegalizeOps())
22629 SDValue InVec = N->getOperand(0);
22630 SDValue EltNo = N->getOperand(1);
22632 if (!isa<ConstantSDNode>(EltNo))
22635 EVT OriginalVT = InVec.getValueType();
22637 if (InVec.getOpcode() == ISD::BITCAST) {
22638 // Don't duplicate a load with other uses.
22639 if (!InVec.hasOneUse())
22641 EVT BCVT = InVec.getOperand(0).getValueType();
22642 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22644 InVec = InVec.getOperand(0);
22647 EVT CurrentVT = InVec.getValueType();
22649 if (!isTargetShuffle(InVec.getOpcode()))
22652 // Don't duplicate a load with other uses.
22653 if (!InVec.hasOneUse())
22656 SmallVector<int, 16> ShuffleMask;
22658 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22659 ShuffleMask, UnaryShuffle))
22662 // Select the input vector, guarding against out of range extract vector.
22663 unsigned NumElems = CurrentVT.getVectorNumElements();
22664 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22665 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22666 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22667 : InVec.getOperand(1);
22669 // If inputs to shuffle are the same for both ops, then allow 2 uses
22670 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22672 if (LdNode.getOpcode() == ISD::BITCAST) {
22673 // Don't duplicate a load with other uses.
22674 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22677 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22678 LdNode = LdNode.getOperand(0);
22681 if (!ISD::isNormalLoad(LdNode.getNode()))
22684 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22686 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22689 EVT EltVT = N->getValueType(0);
22690 // If there's a bitcast before the shuffle, check if the load type and
22691 // alignment is valid.
22692 unsigned Align = LN0->getAlignment();
22693 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22694 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
22695 EltVT.getTypeForEVT(*DAG.getContext()));
22697 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22700 // All checks match so transform back to vector_shuffle so that DAG combiner
22701 // can finish the job
22704 // Create shuffle node taking into account the case that its a unary shuffle
22705 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22706 : InVec.getOperand(1);
22707 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22708 InVec.getOperand(0), Shuffle,
22710 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
22711 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22715 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22716 /// generation and convert it from being a bunch of shuffles and extracts
22717 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22718 /// storing the value and loading scalars back, while for x64 we should
22719 /// use 64-bit extracts and shifts.
22720 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22721 TargetLowering::DAGCombinerInfo &DCI) {
22722 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
22723 if (NewOp.getNode())
22726 SDValue InputVector = N->getOperand(0);
22728 // Detect whether we are trying to convert from mmx to i32 and the bitcast
22729 // from mmx to v2i32 has a single usage.
22730 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
22731 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
22732 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
22733 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22734 N->getValueType(0),
22735 InputVector.getNode()->getOperand(0));
22737 // Only operate on vectors of 4 elements, where the alternative shuffling
22738 // gets to be more expensive.
22739 if (InputVector.getValueType() != MVT::v4i32)
22742 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22743 // single use which is a sign-extend or zero-extend, and all elements are
22745 SmallVector<SDNode *, 4> Uses;
22746 unsigned ExtractedElements = 0;
22747 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22748 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22749 if (UI.getUse().getResNo() != InputVector.getResNo())
22752 SDNode *Extract = *UI;
22753 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22756 if (Extract->getValueType(0) != MVT::i32)
22758 if (!Extract->hasOneUse())
22760 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22761 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22763 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22766 // Record which element was extracted.
22767 ExtractedElements |=
22768 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22770 Uses.push_back(Extract);
22773 // If not all the elements were used, this may not be worthwhile.
22774 if (ExtractedElements != 15)
22777 // Ok, we've now decided to do the transformation.
22778 // If 64-bit shifts are legal, use the extract-shift sequence,
22779 // otherwise bounce the vector off the cache.
22780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22782 SDLoc dl(InputVector);
22784 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22785 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
22786 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
22787 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22788 DAG.getConstant(0, VecIdxTy));
22789 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22790 DAG.getConstant(1, VecIdxTy));
22792 SDValue ShAmt = DAG.getConstant(32,
22793 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
22794 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22795 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22796 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22797 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22798 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22799 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22801 // Store the value to a temporary stack slot.
22802 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22803 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22804 MachinePointerInfo(), false, false, 0);
22806 EVT ElementType = InputVector.getValueType().getVectorElementType();
22807 unsigned EltSize = ElementType.getSizeInBits() / 8;
22809 // Replace each use (extract) with a load of the appropriate element.
22810 for (unsigned i = 0; i < 4; ++i) {
22811 uint64_t Offset = EltSize * i;
22812 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
22814 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
22815 StackPtr, OffsetVal);
22817 // Load the scalar.
22818 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22819 ScalarAddr, MachinePointerInfo(),
22820 false, false, false, 0);
22825 // Replace the extracts
22826 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22827 UE = Uses.end(); UI != UE; ++UI) {
22828 SDNode *Extract = *UI;
22830 SDValue Idx = Extract->getOperand(1);
22831 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22832 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22835 // The replacement was made in place; don't return anything.
22839 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22840 static std::pair<unsigned, bool>
22841 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22842 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22843 if (!VT.isVector())
22844 return std::make_pair(0, false);
22846 bool NeedSplit = false;
22847 switch (VT.getSimpleVT().SimpleTy) {
22848 default: return std::make_pair(0, false);
22851 if (!Subtarget->hasVLX())
22852 return std::make_pair(0, false);
22856 if (!Subtarget->hasBWI())
22857 return std::make_pair(0, false);
22861 if (!Subtarget->hasAVX512())
22862 return std::make_pair(0, false);
22867 if (!Subtarget->hasAVX2())
22869 if (!Subtarget->hasAVX())
22870 return std::make_pair(0, false);
22875 if (!Subtarget->hasSSE2())
22876 return std::make_pair(0, false);
22879 // SSE2 has only a small subset of the operations.
22880 bool hasUnsigned = Subtarget->hasSSE41() ||
22881 (Subtarget->hasSSE2() && VT == MVT::v16i8);
22882 bool hasSigned = Subtarget->hasSSE41() ||
22883 (Subtarget->hasSSE2() && VT == MVT::v8i16);
22885 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22888 // Check for x CC y ? x : y.
22889 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22890 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22895 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22898 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22901 Opc = hasSigned ? X86ISD::SMIN : 0; break;
22904 Opc = hasSigned ? X86ISD::SMAX : 0; break;
22906 // Check for x CC y ? y : x -- a min/max with reversed arms.
22907 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22908 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22913 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22916 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22919 Opc = hasSigned ? X86ISD::SMAX : 0; break;
22922 Opc = hasSigned ? X86ISD::SMIN : 0; break;
22926 return std::make_pair(Opc, NeedSplit);
22930 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22931 const X86Subtarget *Subtarget) {
22933 SDValue Cond = N->getOperand(0);
22934 SDValue LHS = N->getOperand(1);
22935 SDValue RHS = N->getOperand(2);
22937 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22938 SDValue CondSrc = Cond->getOperand(0);
22939 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22940 Cond = CondSrc->getOperand(0);
22943 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22946 // A vselect where all conditions and data are constants can be optimized into
22947 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22948 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22949 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22952 unsigned MaskValue = 0;
22953 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22956 MVT VT = N->getSimpleValueType(0);
22957 unsigned NumElems = VT.getVectorNumElements();
22958 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22959 for (unsigned i = 0; i < NumElems; ++i) {
22960 // Be sure we emit undef where we can.
22961 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22962 ShuffleMask[i] = -1;
22964 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22967 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22968 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22970 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22973 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22975 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22976 TargetLowering::DAGCombinerInfo &DCI,
22977 const X86Subtarget *Subtarget) {
22979 SDValue Cond = N->getOperand(0);
22980 // Get the LHS/RHS of the select.
22981 SDValue LHS = N->getOperand(1);
22982 SDValue RHS = N->getOperand(2);
22983 EVT VT = LHS.getValueType();
22984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22986 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22987 // instructions match the semantics of the common C idiom x<y?x:y but not
22988 // x<=y?x:y, because of how they handle negative zero (which can be
22989 // ignored in unsafe-math mode).
22990 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22991 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
22992 (Subtarget->hasSSE2() ||
22993 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22994 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22996 unsigned Opcode = 0;
22997 // Check for x CC y ? x : y.
22998 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22999 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23003 // Converting this to a min would handle NaNs incorrectly, and swapping
23004 // the operands would cause it to handle comparisons between positive
23005 // and negative zero incorrectly.
23006 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23007 if (!DAG.getTarget().Options.UnsafeFPMath &&
23008 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23010 std::swap(LHS, RHS);
23012 Opcode = X86ISD::FMIN;
23015 // Converting this to a min would handle comparisons between positive
23016 // and negative zero incorrectly.
23017 if (!DAG.getTarget().Options.UnsafeFPMath &&
23018 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23020 Opcode = X86ISD::FMIN;
23023 // Converting this to a min would handle both negative zeros and NaNs
23024 // incorrectly, but we can swap the operands to fix both.
23025 std::swap(LHS, RHS);
23029 Opcode = X86ISD::FMIN;
23033 // Converting this to a max would handle comparisons between positive
23034 // and negative zero incorrectly.
23035 if (!DAG.getTarget().Options.UnsafeFPMath &&
23036 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23038 Opcode = X86ISD::FMAX;
23041 // Converting this to a max would handle NaNs incorrectly, and swapping
23042 // the operands would cause it to handle comparisons between positive
23043 // and negative zero incorrectly.
23044 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23045 if (!DAG.getTarget().Options.UnsafeFPMath &&
23046 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23048 std::swap(LHS, RHS);
23050 Opcode = X86ISD::FMAX;
23053 // Converting this to a max would handle both negative zeros and NaNs
23054 // incorrectly, but we can swap the operands to fix both.
23055 std::swap(LHS, RHS);
23059 Opcode = X86ISD::FMAX;
23062 // Check for x CC y ? y : x -- a min/max with reversed arms.
23063 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23064 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23068 // Converting this to a min would handle comparisons between positive
23069 // and negative zero incorrectly, and swapping the operands would
23070 // cause it to handle NaNs incorrectly.
23071 if (!DAG.getTarget().Options.UnsafeFPMath &&
23072 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23073 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23075 std::swap(LHS, RHS);
23077 Opcode = X86ISD::FMIN;
23080 // Converting this to a min would handle NaNs incorrectly.
23081 if (!DAG.getTarget().Options.UnsafeFPMath &&
23082 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23084 Opcode = X86ISD::FMIN;
23087 // Converting this to a min would handle both negative zeros and NaNs
23088 // incorrectly, but we can swap the operands to fix both.
23089 std::swap(LHS, RHS);
23093 Opcode = X86ISD::FMIN;
23097 // Converting this to a max would handle NaNs incorrectly.
23098 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23100 Opcode = X86ISD::FMAX;
23103 // Converting this to a max would handle comparisons between positive
23104 // and negative zero incorrectly, and swapping the operands would
23105 // cause it to handle NaNs incorrectly.
23106 if (!DAG.getTarget().Options.UnsafeFPMath &&
23107 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23108 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23110 std::swap(LHS, RHS);
23112 Opcode = X86ISD::FMAX;
23115 // Converting this to a max would handle both negative zeros and NaNs
23116 // incorrectly, but we can swap the operands to fix both.
23117 std::swap(LHS, RHS);
23121 Opcode = X86ISD::FMAX;
23127 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23130 EVT CondVT = Cond.getValueType();
23131 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23132 CondVT.getVectorElementType() == MVT::i1) {
23133 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23134 // lowering on KNL. In this case we convert it to
23135 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23136 // The same situation for all 128 and 256-bit vectors of i8 and i16.
23137 // Since SKX these selects have a proper lowering.
23138 EVT OpVT = LHS.getValueType();
23139 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23140 (OpVT.getVectorElementType() == MVT::i8 ||
23141 OpVT.getVectorElementType() == MVT::i16) &&
23142 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23143 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23144 DCI.AddToWorklist(Cond.getNode());
23145 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23148 // If this is a select between two integer constants, try to do some
23150 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23151 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23152 // Don't do this for crazy integer types.
23153 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23154 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23155 // so that TrueC (the true value) is larger than FalseC.
23156 bool NeedsCondInvert = false;
23158 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23159 // Efficiently invertible.
23160 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
23161 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
23162 isa<ConstantSDNode>(Cond.getOperand(1))))) {
23163 NeedsCondInvert = true;
23164 std::swap(TrueC, FalseC);
23167 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
23168 if (FalseC->getAPIntValue() == 0 &&
23169 TrueC->getAPIntValue().isPowerOf2()) {
23170 if (NeedsCondInvert) // Invert the condition if needed.
23171 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23172 DAG.getConstant(1, Cond.getValueType()));
23174 // Zero extend the condition if needed.
23175 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23177 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23178 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23179 DAG.getConstant(ShAmt, MVT::i8));
23182 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23183 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23184 if (NeedsCondInvert) // Invert the condition if needed.
23185 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23186 DAG.getConstant(1, Cond.getValueType()));
23188 // Zero extend the condition if needed.
23189 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23190 FalseC->getValueType(0), Cond);
23191 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23192 SDValue(FalseC, 0));
23195 // Optimize cases that will turn into an LEA instruction. This requires
23196 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23197 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23198 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23199 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23201 bool isFastMultiplier = false;
23203 switch ((unsigned char)Diff) {
23205 case 1: // result = add base, cond
23206 case 2: // result = lea base( , cond*2)
23207 case 3: // result = lea base(cond, cond*2)
23208 case 4: // result = lea base( , cond*4)
23209 case 5: // result = lea base(cond, cond*4)
23210 case 8: // result = lea base( , cond*8)
23211 case 9: // result = lea base(cond, cond*8)
23212 isFastMultiplier = true;
23217 if (isFastMultiplier) {
23218 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23219 if (NeedsCondInvert) // Invert the condition if needed.
23220 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23221 DAG.getConstant(1, Cond.getValueType()));
23223 // Zero extend the condition if needed.
23224 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23226 // Scale the condition by the difference.
23228 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23229 DAG.getConstant(Diff, Cond.getValueType()));
23231 // Add the base if non-zero.
23232 if (FalseC->getAPIntValue() != 0)
23233 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23234 SDValue(FalseC, 0));
23241 // Canonicalize max and min:
23242 // (x > y) ? x : y -> (x >= y) ? x : y
23243 // (x < y) ? x : y -> (x <= y) ? x : y
23244 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23245 // the need for an extra compare
23246 // against zero. e.g.
23247 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23249 // testl %edi, %edi
23251 // cmovgl %edi, %eax
23255 // cmovsl %eax, %edi
23256 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23257 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23258 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23259 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23264 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23265 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23266 Cond.getOperand(0), Cond.getOperand(1), NewCC);
23267 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23272 // Early exit check
23273 if (!TLI.isTypeLegal(VT))
23276 // Match VSELECTs into subs with unsigned saturation.
23277 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23278 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23279 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23280 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23281 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23283 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23284 // left side invert the predicate to simplify logic below.
23286 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23288 CC = ISD::getSetCCInverse(CC, true);
23289 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23293 if (Other.getNode() && Other->getNumOperands() == 2 &&
23294 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23295 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23296 SDValue CondRHS = Cond->getOperand(1);
23298 // Look for a general sub with unsigned saturation first.
23299 // x >= y ? x-y : 0 --> subus x, y
23300 // x > y ? x-y : 0 --> subus x, y
23301 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23302 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23303 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23305 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23306 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23307 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23308 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23309 // If the RHS is a constant we have to reverse the const
23310 // canonicalization.
23311 // x > C-1 ? x+-C : 0 --> subus x, C
23312 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23313 CondRHSConst->getAPIntValue() ==
23314 (-OpRHSConst->getAPIntValue() - 1))
23315 return DAG.getNode(
23316 X86ISD::SUBUS, DL, VT, OpLHS,
23317 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
23319 // Another special case: If C was a sign bit, the sub has been
23320 // canonicalized into a xor.
23321 // FIXME: Would it be better to use computeKnownBits to determine
23322 // whether it's safe to decanonicalize the xor?
23323 // x s< 0 ? x^C : 0 --> subus x, C
23324 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23325 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23326 OpRHSConst->getAPIntValue().isSignBit())
23327 // Note that we have to rebuild the RHS constant here to ensure we
23328 // don't rely on particular values of undef lanes.
23329 return DAG.getNode(
23330 X86ISD::SUBUS, DL, VT, OpLHS,
23331 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
23336 // Try to match a min/max vector operation.
23337 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
23338 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
23339 unsigned Opc = ret.first;
23340 bool NeedSplit = ret.second;
23342 if (Opc && NeedSplit) {
23343 unsigned NumElems = VT.getVectorNumElements();
23344 // Extract the LHS vectors
23345 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
23346 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
23348 // Extract the RHS vectors
23349 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
23350 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
23352 // Create min/max for each subvector
23353 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
23354 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
23356 // Merge the result
23357 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
23359 return DAG.getNode(Opc, DL, VT, LHS, RHS);
23362 // Simplify vector selection if condition value type matches vselect
23364 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23365 assert(Cond.getValueType().isVector() &&
23366 "vector select expects a vector selector!");
23368 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23369 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23371 // Try invert the condition if true value is not all 1s and false value
23373 if (!TValIsAllOnes && !FValIsAllZeros &&
23374 // Check if the selector will be produced by CMPP*/PCMP*
23375 Cond.getOpcode() == ISD::SETCC &&
23376 // Check if SETCC has already been promoted
23377 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
23378 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23379 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23381 if (TValIsAllZeros || FValIsAllOnes) {
23382 SDValue CC = Cond.getOperand(2);
23383 ISD::CondCode NewCC =
23384 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23385 Cond.getOperand(0).getValueType().isInteger());
23386 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23387 std::swap(LHS, RHS);
23388 TValIsAllOnes = FValIsAllOnes;
23389 FValIsAllZeros = TValIsAllZeros;
23393 if (TValIsAllOnes || FValIsAllZeros) {
23396 if (TValIsAllOnes && FValIsAllZeros)
23398 else if (TValIsAllOnes)
23399 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
23400 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
23401 else if (FValIsAllZeros)
23402 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23403 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
23405 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
23409 // If we know that this node is legal then we know that it is going to be
23410 // matched by one of the SSE/AVX BLEND instructions. These instructions only
23411 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
23412 // to simplify previous instructions.
23413 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23414 !DCI.isBeforeLegalize() &&
23415 // We explicitly check against v8i16 and v16i16 because, although
23416 // they're marked as Custom, they might only be legal when Cond is a
23417 // build_vector of constants. This will be taken care in a later
23419 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
23420 VT != MVT::v8i16) &&
23421 // Don't optimize vector of constants. Those are handled by
23422 // the generic code and all the bits must be properly set for
23423 // the generic optimizer.
23424 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23425 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23427 // Don't optimize vector selects that map to mask-registers.
23431 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23432 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23434 APInt KnownZero, KnownOne;
23435 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23436 DCI.isBeforeLegalizeOps());
23437 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23438 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23440 // If we changed the computation somewhere in the DAG, this change
23441 // will affect all users of Cond.
23442 // Make sure it is fine and update all the nodes so that we do not
23443 // use the generic VSELECT anymore. Otherwise, we may perform
23444 // wrong optimizations as we messed up with the actual expectation
23445 // for the vector boolean values.
23446 if (Cond != TLO.Old) {
23447 // Check all uses of that condition operand to check whether it will be
23448 // consumed by non-BLEND instructions, which may depend on all bits are
23450 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23452 if (I->getOpcode() != ISD::VSELECT)
23453 // TODO: Add other opcodes eventually lowered into BLEND.
23456 // Update all the users of the condition, before committing the change,
23457 // so that the VSELECT optimizations that expect the correct vector
23458 // boolean value will not be triggered.
23459 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23461 DAG.ReplaceAllUsesOfValueWith(
23463 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23464 Cond, I->getOperand(1), I->getOperand(2)));
23465 DCI.CommitTargetLoweringOpt(TLO);
23468 // At this point, only Cond is changed. Change the condition
23469 // just for N to keep the opportunity to optimize all other
23470 // users their own way.
23471 DAG.ReplaceAllUsesOfValueWith(
23473 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23474 TLO.New, N->getOperand(1), N->getOperand(2)));
23479 // We should generate an X86ISD::BLENDI from a vselect if its argument
23480 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23481 // constants. This specific pattern gets generated when we split a
23482 // selector for a 512 bit vector in a machine without AVX512 (but with
23483 // 256-bit vectors), during legalization:
23485 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23487 // Iff we find this pattern and the build_vectors are built from
23488 // constants, we translate the vselect into a shuffle_vector that we
23489 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23490 if ((N->getOpcode() == ISD::VSELECT ||
23491 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23492 !DCI.isBeforeLegalize()) {
23493 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23494 if (Shuffle.getNode())
23501 // Check whether a boolean test is testing a boolean value generated by
23502 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23505 // Simplify the following patterns:
23506 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23507 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23508 // to (Op EFLAGS Cond)
23510 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23511 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23512 // to (Op EFLAGS !Cond)
23514 // where Op could be BRCOND or CMOV.
23516 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23517 // Quit if not CMP and SUB with its value result used.
23518 if (Cmp.getOpcode() != X86ISD::CMP &&
23519 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23522 // Quit if not used as a boolean value.
23523 if (CC != X86::COND_E && CC != X86::COND_NE)
23526 // Check CMP operands. One of them should be 0 or 1 and the other should be
23527 // an SetCC or extended from it.
23528 SDValue Op1 = Cmp.getOperand(0);
23529 SDValue Op2 = Cmp.getOperand(1);
23532 const ConstantSDNode* C = nullptr;
23533 bool needOppositeCond = (CC == X86::COND_E);
23534 bool checkAgainstTrue = false; // Is it a comparison against 1?
23536 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23538 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23540 else // Quit if all operands are not constants.
23543 if (C->getZExtValue() == 1) {
23544 needOppositeCond = !needOppositeCond;
23545 checkAgainstTrue = true;
23546 } else if (C->getZExtValue() != 0)
23547 // Quit if the constant is neither 0 or 1.
23550 bool truncatedToBoolWithAnd = false;
23551 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23552 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23553 SetCC.getOpcode() == ISD::TRUNCATE ||
23554 SetCC.getOpcode() == ISD::AND) {
23555 if (SetCC.getOpcode() == ISD::AND) {
23557 ConstantSDNode *CS;
23558 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23559 CS->getZExtValue() == 1)
23561 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23562 CS->getZExtValue() == 1)
23566 SetCC = SetCC.getOperand(OpIdx);
23567 truncatedToBoolWithAnd = true;
23569 SetCC = SetCC.getOperand(0);
23572 switch (SetCC.getOpcode()) {
23573 case X86ISD::SETCC_CARRY:
23574 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23575 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23576 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23577 // truncated to i1 using 'and'.
23578 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23580 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23581 "Invalid use of SETCC_CARRY!");
23583 case X86ISD::SETCC:
23584 // Set the condition code or opposite one if necessary.
23585 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23586 if (needOppositeCond)
23587 CC = X86::GetOppositeBranchCondition(CC);
23588 return SetCC.getOperand(1);
23589 case X86ISD::CMOV: {
23590 // Check whether false/true value has canonical one, i.e. 0 or 1.
23591 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23592 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23593 // Quit if true value is not a constant.
23596 // Quit if false value is not a constant.
23598 SDValue Op = SetCC.getOperand(0);
23599 // Skip 'zext' or 'trunc' node.
23600 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23601 Op.getOpcode() == ISD::TRUNCATE)
23602 Op = Op.getOperand(0);
23603 // A special case for rdrand/rdseed, where 0 is set if false cond is
23605 if ((Op.getOpcode() != X86ISD::RDRAND &&
23606 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23609 // Quit if false value is not the constant 0 or 1.
23610 bool FValIsFalse = true;
23611 if (FVal && FVal->getZExtValue() != 0) {
23612 if (FVal->getZExtValue() != 1)
23614 // If FVal is 1, opposite cond is needed.
23615 needOppositeCond = !needOppositeCond;
23616 FValIsFalse = false;
23618 // Quit if TVal is not the constant opposite of FVal.
23619 if (FValIsFalse && TVal->getZExtValue() != 1)
23621 if (!FValIsFalse && TVal->getZExtValue() != 0)
23623 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23624 if (needOppositeCond)
23625 CC = X86::GetOppositeBranchCondition(CC);
23626 return SetCC.getOperand(3);
23633 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23634 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23635 TargetLowering::DAGCombinerInfo &DCI,
23636 const X86Subtarget *Subtarget) {
23639 // If the flag operand isn't dead, don't touch this CMOV.
23640 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23643 SDValue FalseOp = N->getOperand(0);
23644 SDValue TrueOp = N->getOperand(1);
23645 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23646 SDValue Cond = N->getOperand(3);
23648 if (CC == X86::COND_E || CC == X86::COND_NE) {
23649 switch (Cond.getOpcode()) {
23653 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23654 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23655 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23661 Flags = checkBoolTestSetCCCombine(Cond, CC);
23662 if (Flags.getNode() &&
23663 // Extra check as FCMOV only supports a subset of X86 cond.
23664 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23665 SDValue Ops[] = { FalseOp, TrueOp,
23666 DAG.getConstant(CC, MVT::i8), Flags };
23667 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23670 // If this is a select between two integer constants, try to do some
23671 // optimizations. Note that the operands are ordered the opposite of SELECT
23673 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23674 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23675 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23676 // larger than FalseC (the false value).
23677 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23678 CC = X86::GetOppositeBranchCondition(CC);
23679 std::swap(TrueC, FalseC);
23680 std::swap(TrueOp, FalseOp);
23683 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23684 // This is efficient for any integer data type (including i8/i16) and
23686 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23687 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23688 DAG.getConstant(CC, MVT::i8), Cond);
23690 // Zero extend the condition if needed.
23691 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23693 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23694 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23695 DAG.getConstant(ShAmt, MVT::i8));
23696 if (N->getNumValues() == 2) // Dead flag value?
23697 return DCI.CombineTo(N, Cond, SDValue());
23701 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23702 // for any integer data type, including i8/i16.
23703 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23704 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23705 DAG.getConstant(CC, MVT::i8), Cond);
23707 // Zero extend the condition if needed.
23708 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23709 FalseC->getValueType(0), Cond);
23710 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23711 SDValue(FalseC, 0));
23713 if (N->getNumValues() == 2) // Dead flag value?
23714 return DCI.CombineTo(N, Cond, SDValue());
23718 // Optimize cases that will turn into an LEA instruction. This requires
23719 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23720 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23721 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23722 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23724 bool isFastMultiplier = false;
23726 switch ((unsigned char)Diff) {
23728 case 1: // result = add base, cond
23729 case 2: // result = lea base( , cond*2)
23730 case 3: // result = lea base(cond, cond*2)
23731 case 4: // result = lea base( , cond*4)
23732 case 5: // result = lea base(cond, cond*4)
23733 case 8: // result = lea base( , cond*8)
23734 case 9: // result = lea base(cond, cond*8)
23735 isFastMultiplier = true;
23740 if (isFastMultiplier) {
23741 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23742 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23743 DAG.getConstant(CC, MVT::i8), Cond);
23744 // Zero extend the condition if needed.
23745 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23747 // Scale the condition by the difference.
23749 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23750 DAG.getConstant(Diff, Cond.getValueType()));
23752 // Add the base if non-zero.
23753 if (FalseC->getAPIntValue() != 0)
23754 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23755 SDValue(FalseC, 0));
23756 if (N->getNumValues() == 2) // Dead flag value?
23757 return DCI.CombineTo(N, Cond, SDValue());
23764 // Handle these cases:
23765 // (select (x != c), e, c) -> select (x != c), e, x),
23766 // (select (x == c), c, e) -> select (x == c), x, e)
23767 // where the c is an integer constant, and the "select" is the combination
23768 // of CMOV and CMP.
23770 // The rationale for this change is that the conditional-move from a constant
23771 // needs two instructions, however, conditional-move from a register needs
23772 // only one instruction.
23774 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23775 // some instruction-combining opportunities. This opt needs to be
23776 // postponed as late as possible.
23778 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23779 // the DCI.xxxx conditions are provided to postpone the optimization as
23780 // late as possible.
23782 ConstantSDNode *CmpAgainst = nullptr;
23783 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23784 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23785 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23787 if (CC == X86::COND_NE &&
23788 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23789 CC = X86::GetOppositeBranchCondition(CC);
23790 std::swap(TrueOp, FalseOp);
23793 if (CC == X86::COND_E &&
23794 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23795 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23796 DAG.getConstant(CC, MVT::i8), Cond };
23797 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23805 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23806 const X86Subtarget *Subtarget) {
23807 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23809 default: return SDValue();
23810 // SSE/AVX/AVX2 blend intrinsics.
23811 case Intrinsic::x86_avx2_pblendvb:
23812 case Intrinsic::x86_avx2_pblendw:
23813 case Intrinsic::x86_avx2_pblendd_128:
23814 case Intrinsic::x86_avx2_pblendd_256:
23815 // Don't try to simplify this intrinsic if we don't have AVX2.
23816 if (!Subtarget->hasAVX2())
23819 case Intrinsic::x86_avx_blend_pd_256:
23820 case Intrinsic::x86_avx_blend_ps_256:
23821 case Intrinsic::x86_avx_blendv_pd_256:
23822 case Intrinsic::x86_avx_blendv_ps_256:
23823 // Don't try to simplify this intrinsic if we don't have AVX.
23824 if (!Subtarget->hasAVX())
23827 case Intrinsic::x86_sse41_pblendw:
23828 case Intrinsic::x86_sse41_blendpd:
23829 case Intrinsic::x86_sse41_blendps:
23830 case Intrinsic::x86_sse41_blendvps:
23831 case Intrinsic::x86_sse41_blendvpd:
23832 case Intrinsic::x86_sse41_pblendvb: {
23833 SDValue Op0 = N->getOperand(1);
23834 SDValue Op1 = N->getOperand(2);
23835 SDValue Mask = N->getOperand(3);
23837 // Don't try to simplify this intrinsic if we don't have SSE4.1.
23838 if (!Subtarget->hasSSE41())
23841 // fold (blend A, A, Mask) -> A
23844 // fold (blend A, B, allZeros) -> A
23845 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23847 // fold (blend A, B, allOnes) -> B
23848 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23851 // Simplify the case where the mask is a constant i32 value.
23852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23853 if (C->isNullValue())
23855 if (C->isAllOnesValue())
23862 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23863 case Intrinsic::x86_sse2_psrai_w:
23864 case Intrinsic::x86_sse2_psrai_d:
23865 case Intrinsic::x86_avx2_psrai_w:
23866 case Intrinsic::x86_avx2_psrai_d:
23867 case Intrinsic::x86_sse2_psra_w:
23868 case Intrinsic::x86_sse2_psra_d:
23869 case Intrinsic::x86_avx2_psra_w:
23870 case Intrinsic::x86_avx2_psra_d: {
23871 SDValue Op0 = N->getOperand(1);
23872 SDValue Op1 = N->getOperand(2);
23873 EVT VT = Op0.getValueType();
23874 assert(VT.isVector() && "Expected a vector type!");
23876 if (isa<BuildVectorSDNode>(Op1))
23877 Op1 = Op1.getOperand(0);
23879 if (!isa<ConstantSDNode>(Op1))
23882 EVT SVT = VT.getVectorElementType();
23883 unsigned SVTBits = SVT.getSizeInBits();
23885 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23886 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23887 uint64_t ShAmt = C.getZExtValue();
23889 // Don't try to convert this shift into a ISD::SRA if the shift
23890 // count is bigger than or equal to the element size.
23891 if (ShAmt >= SVTBits)
23894 // Trivial case: if the shift count is zero, then fold this
23895 // into the first operand.
23899 // Replace this packed shift intrinsic with a target independent
23901 SDValue Splat = DAG.getConstant(C, VT);
23902 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
23907 /// PerformMulCombine - Optimize a single multiply with constant into two
23908 /// in order to implement it with two cheaper instructions, e.g.
23909 /// LEA + SHL, LEA + LEA.
23910 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23911 TargetLowering::DAGCombinerInfo &DCI) {
23912 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23915 EVT VT = N->getValueType(0);
23916 if (VT != MVT::i64)
23919 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23922 uint64_t MulAmt = C->getZExtValue();
23923 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23926 uint64_t MulAmt1 = 0;
23927 uint64_t MulAmt2 = 0;
23928 if ((MulAmt % 9) == 0) {
23930 MulAmt2 = MulAmt / 9;
23931 } else if ((MulAmt % 5) == 0) {
23933 MulAmt2 = MulAmt / 5;
23934 } else if ((MulAmt % 3) == 0) {
23936 MulAmt2 = MulAmt / 3;
23939 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23942 if (isPowerOf2_64(MulAmt2) &&
23943 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23944 // If second multiplifer is pow2, issue it first. We want the multiply by
23945 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23947 std::swap(MulAmt1, MulAmt2);
23950 if (isPowerOf2_64(MulAmt1))
23951 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23952 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
23954 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23955 DAG.getConstant(MulAmt1, VT));
23957 if (isPowerOf2_64(MulAmt2))
23958 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23959 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
23961 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23962 DAG.getConstant(MulAmt2, VT));
23964 // Do not add new nodes to DAG combiner worklist.
23965 DCI.CombineTo(N, NewMul, false);
23970 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23971 SDValue N0 = N->getOperand(0);
23972 SDValue N1 = N->getOperand(1);
23973 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23974 EVT VT = N0.getValueType();
23976 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23977 // since the result of setcc_c is all zero's or all ones.
23978 if (VT.isInteger() && !VT.isVector() &&
23979 N1C && N0.getOpcode() == ISD::AND &&
23980 N0.getOperand(1).getOpcode() == ISD::Constant) {
23981 SDValue N00 = N0.getOperand(0);
23982 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23983 ((N00.getOpcode() == ISD::ANY_EXTEND ||
23984 N00.getOpcode() == ISD::ZERO_EXTEND) &&
23985 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23986 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23987 APInt ShAmt = N1C->getAPIntValue();
23988 Mask = Mask.shl(ShAmt);
23990 return DAG.getNode(ISD::AND, SDLoc(N), VT,
23991 N00, DAG.getConstant(Mask, VT));
23995 // Hardware support for vector shifts is sparse which makes us scalarize the
23996 // vector operations in many cases. Also, on sandybridge ADD is faster than
23998 // (shl V, 1) -> add V,V
23999 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24000 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24001 assert(N0.getValueType().isVector() && "Invalid vector shift type");
24002 // We shift all of the values by one. In many cases we do not have
24003 // hardware support for this operation. This is better expressed as an ADD
24005 if (N1SplatC->getZExtValue() == 1)
24006 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24012 /// \brief Returns a vector of 0s if the node in input is a vector logical
24013 /// shift by a constant amount which is known to be bigger than or equal
24014 /// to the vector element size in bits.
24015 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24016 const X86Subtarget *Subtarget) {
24017 EVT VT = N->getValueType(0);
24019 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24020 (!Subtarget->hasInt256() ||
24021 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24024 SDValue Amt = N->getOperand(1);
24026 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24027 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24028 APInt ShiftAmt = AmtSplat->getAPIntValue();
24029 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24031 // SSE2/AVX2 logical shifts always return a vector of 0s
24032 // if the shift amount is bigger than or equal to
24033 // the element size. The constant shift amount will be
24034 // encoded as a 8-bit immediate.
24035 if (ShiftAmt.trunc(8).uge(MaxAmount))
24036 return getZeroVector(VT, Subtarget, DAG, DL);
24042 /// PerformShiftCombine - Combine shifts.
24043 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24044 TargetLowering::DAGCombinerInfo &DCI,
24045 const X86Subtarget *Subtarget) {
24046 if (N->getOpcode() == ISD::SHL) {
24047 SDValue V = PerformSHLCombine(N, DAG);
24048 if (V.getNode()) return V;
24051 if (N->getOpcode() != ISD::SRA) {
24052 // Try to fold this logical shift into a zero vector.
24053 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
24054 if (V.getNode()) return V;
24060 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
24061 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24062 // and friends. Likewise for OR -> CMPNEQSS.
24063 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24064 TargetLowering::DAGCombinerInfo &DCI,
24065 const X86Subtarget *Subtarget) {
24068 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24069 // we're requiring SSE2 for both.
24070 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24071 SDValue N0 = N->getOperand(0);
24072 SDValue N1 = N->getOperand(1);
24073 SDValue CMP0 = N0->getOperand(1);
24074 SDValue CMP1 = N1->getOperand(1);
24077 // The SETCCs should both refer to the same CMP.
24078 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24081 SDValue CMP00 = CMP0->getOperand(0);
24082 SDValue CMP01 = CMP0->getOperand(1);
24083 EVT VT = CMP00.getValueType();
24085 if (VT == MVT::f32 || VT == MVT::f64) {
24086 bool ExpectingFlags = false;
24087 // Check for any users that want flags:
24088 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24089 !ExpectingFlags && UI != UE; ++UI)
24090 switch (UI->getOpcode()) {
24095 ExpectingFlags = true;
24097 case ISD::CopyToReg:
24098 case ISD::SIGN_EXTEND:
24099 case ISD::ZERO_EXTEND:
24100 case ISD::ANY_EXTEND:
24104 if (!ExpectingFlags) {
24105 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24106 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24108 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24109 X86::CondCode tmp = cc0;
24114 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
24115 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24116 // FIXME: need symbolic constants for these magic numbers.
24117 // See X86ATTInstPrinter.cpp:printSSECC().
24118 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24119 if (Subtarget->hasAVX512()) {
24120 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24121 CMP01, DAG.getConstant(x86cc, MVT::i8));
24122 if (N->getValueType(0) != MVT::i1)
24123 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24127 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24128 CMP00.getValueType(), CMP00, CMP01,
24129 DAG.getConstant(x86cc, MVT::i8));
24131 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24132 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24134 if (is64BitFP && !Subtarget->is64Bit()) {
24135 // On a 32-bit target, we cannot bitcast the 64-bit float to a
24136 // 64-bit integer, since that's not a legal type. Since
24137 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24138 // bits, but can do this little dance to extract the lowest 32 bits
24139 // and work with those going forward.
24140 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24142 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
24144 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24145 Vector32, DAG.getIntPtrConstant(0));
24149 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
24150 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24151 DAG.getConstant(1, IntVT));
24152 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
24153 return OneBitOfTruth;
24161 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24162 /// so it can be folded inside ANDNP.
24163 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24164 EVT VT = N->getValueType(0);
24166 // Match direct AllOnes for 128 and 256-bit vectors
24167 if (ISD::isBuildVectorAllOnes(N))
24170 // Look through a bit convert.
24171 if (N->getOpcode() == ISD::BITCAST)
24172 N = N->getOperand(0).getNode();
24174 // Sometimes the operand may come from a insert_subvector building a 256-bit
24176 if (VT.is256BitVector() &&
24177 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24178 SDValue V1 = N->getOperand(0);
24179 SDValue V2 = N->getOperand(1);
24181 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24182 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24183 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24184 ISD::isBuildVectorAllOnes(V2.getNode()))
24191 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24192 // register. In most cases we actually compare or select YMM-sized registers
24193 // and mixing the two types creates horrible code. This method optimizes
24194 // some of the transition sequences.
24195 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24196 TargetLowering::DAGCombinerInfo &DCI,
24197 const X86Subtarget *Subtarget) {
24198 EVT VT = N->getValueType(0);
24199 if (!VT.is256BitVector())
24202 assert((N->getOpcode() == ISD::ANY_EXTEND ||
24203 N->getOpcode() == ISD::ZERO_EXTEND ||
24204 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24206 SDValue Narrow = N->getOperand(0);
24207 EVT NarrowVT = Narrow->getValueType(0);
24208 if (!NarrowVT.is128BitVector())
24211 if (Narrow->getOpcode() != ISD::XOR &&
24212 Narrow->getOpcode() != ISD::AND &&
24213 Narrow->getOpcode() != ISD::OR)
24216 SDValue N0 = Narrow->getOperand(0);
24217 SDValue N1 = Narrow->getOperand(1);
24220 // The Left side has to be a trunc.
24221 if (N0.getOpcode() != ISD::TRUNCATE)
24224 // The type of the truncated inputs.
24225 EVT WideVT = N0->getOperand(0)->getValueType(0);
24229 // The right side has to be a 'trunc' or a constant vector.
24230 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24231 ConstantSDNode *RHSConstSplat = nullptr;
24232 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24233 RHSConstSplat = RHSBV->getConstantSplatNode();
24234 if (!RHSTrunc && !RHSConstSplat)
24237 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24239 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24242 // Set N0 and N1 to hold the inputs to the new wide operation.
24243 N0 = N0->getOperand(0);
24244 if (RHSConstSplat) {
24245 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24246 SDValue(RHSConstSplat, 0));
24247 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24248 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24249 } else if (RHSTrunc) {
24250 N1 = N1->getOperand(0);
24253 // Generate the wide operation.
24254 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24255 unsigned Opcode = N->getOpcode();
24257 case ISD::ANY_EXTEND:
24259 case ISD::ZERO_EXTEND: {
24260 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24261 APInt Mask = APInt::getAllOnesValue(InBits);
24262 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24263 return DAG.getNode(ISD::AND, DL, VT,
24264 Op, DAG.getConstant(Mask, VT));
24266 case ISD::SIGN_EXTEND:
24267 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24268 Op, DAG.getValueType(NarrowVT));
24270 llvm_unreachable("Unexpected opcode");
24274 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24275 TargetLowering::DAGCombinerInfo &DCI,
24276 const X86Subtarget *Subtarget) {
24277 EVT VT = N->getValueType(0);
24278 if (DCI.isBeforeLegalizeOps())
24281 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24285 // Create BEXTR instructions
24286 // BEXTR is ((X >> imm) & (2**size-1))
24287 if (VT == MVT::i32 || VT == MVT::i64) {
24288 SDValue N0 = N->getOperand(0);
24289 SDValue N1 = N->getOperand(1);
24292 // Check for BEXTR.
24293 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24294 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24295 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24296 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24297 if (MaskNode && ShiftNode) {
24298 uint64_t Mask = MaskNode->getZExtValue();
24299 uint64_t Shift = ShiftNode->getZExtValue();
24300 if (isMask_64(Mask)) {
24301 uint64_t MaskSize = CountPopulation_64(Mask);
24302 if (Shift + MaskSize <= VT.getSizeInBits())
24303 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24304 DAG.getConstant(Shift | (MaskSize << 8), VT));
24312 // Want to form ANDNP nodes:
24313 // 1) In the hopes of then easily combining them with OR and AND nodes
24314 // to form PBLEND/PSIGN.
24315 // 2) To match ANDN packed intrinsics
24316 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24319 SDValue N0 = N->getOperand(0);
24320 SDValue N1 = N->getOperand(1);
24323 // Check LHS for vnot
24324 if (N0.getOpcode() == ISD::XOR &&
24325 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24326 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24327 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24329 // Check RHS for vnot
24330 if (N1.getOpcode() == ISD::XOR &&
24331 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24332 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24333 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24338 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24339 TargetLowering::DAGCombinerInfo &DCI,
24340 const X86Subtarget *Subtarget) {
24341 if (DCI.isBeforeLegalizeOps())
24344 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24348 SDValue N0 = N->getOperand(0);
24349 SDValue N1 = N->getOperand(1);
24350 EVT VT = N->getValueType(0);
24352 // look for psign/blend
24353 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24354 if (!Subtarget->hasSSSE3() ||
24355 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24358 // Canonicalize pandn to RHS
24359 if (N0.getOpcode() == X86ISD::ANDNP)
24361 // or (and (m, y), (pandn m, x))
24362 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24363 SDValue Mask = N1.getOperand(0);
24364 SDValue X = N1.getOperand(1);
24366 if (N0.getOperand(0) == Mask)
24367 Y = N0.getOperand(1);
24368 if (N0.getOperand(1) == Mask)
24369 Y = N0.getOperand(0);
24371 // Check to see if the mask appeared in both the AND and ANDNP and
24375 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24376 // Look through mask bitcast.
24377 if (Mask.getOpcode() == ISD::BITCAST)
24378 Mask = Mask.getOperand(0);
24379 if (X.getOpcode() == ISD::BITCAST)
24380 X = X.getOperand(0);
24381 if (Y.getOpcode() == ISD::BITCAST)
24382 Y = Y.getOperand(0);
24384 EVT MaskVT = Mask.getValueType();
24386 // Validate that the Mask operand is a vector sra node.
24387 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24388 // there is no psrai.b
24389 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24390 unsigned SraAmt = ~0;
24391 if (Mask.getOpcode() == ISD::SRA) {
24392 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24393 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24394 SraAmt = AmtConst->getZExtValue();
24395 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24396 SDValue SraC = Mask.getOperand(1);
24397 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24399 if ((SraAmt + 1) != EltBits)
24404 // Now we know we at least have a plendvb with the mask val. See if
24405 // we can form a psignb/w/d.
24406 // psign = x.type == y.type == mask.type && y = sub(0, x);
24407 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24408 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24409 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24410 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24411 "Unsupported VT for PSIGN");
24412 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24413 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24415 // PBLENDVB only available on SSE 4.1
24416 if (!Subtarget->hasSSE41())
24419 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24421 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
24422 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
24423 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
24424 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24425 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24429 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24432 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24433 MachineFunction &MF = DAG.getMachineFunction();
24434 bool OptForSize = MF.getFunction()->getAttributes().
24435 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
24437 // SHLD/SHRD instructions have lower register pressure, but on some
24438 // platforms they have higher latency than the equivalent
24439 // series of shifts/or that would otherwise be generated.
24440 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24441 // have higher latencies and we are not optimizing for size.
24442 if (!OptForSize && Subtarget->isSHLDSlow())
24445 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24447 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24449 if (!N0.hasOneUse() || !N1.hasOneUse())
24452 SDValue ShAmt0 = N0.getOperand(1);
24453 if (ShAmt0.getValueType() != MVT::i8)
24455 SDValue ShAmt1 = N1.getOperand(1);
24456 if (ShAmt1.getValueType() != MVT::i8)
24458 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24459 ShAmt0 = ShAmt0.getOperand(0);
24460 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24461 ShAmt1 = ShAmt1.getOperand(0);
24464 unsigned Opc = X86ISD::SHLD;
24465 SDValue Op0 = N0.getOperand(0);
24466 SDValue Op1 = N1.getOperand(0);
24467 if (ShAmt0.getOpcode() == ISD::SUB) {
24468 Opc = X86ISD::SHRD;
24469 std::swap(Op0, Op1);
24470 std::swap(ShAmt0, ShAmt1);
24473 unsigned Bits = VT.getSizeInBits();
24474 if (ShAmt1.getOpcode() == ISD::SUB) {
24475 SDValue Sum = ShAmt1.getOperand(0);
24476 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24477 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24478 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24479 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24480 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24481 return DAG.getNode(Opc, DL, VT,
24483 DAG.getNode(ISD::TRUNCATE, DL,
24486 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24487 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24489 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24490 return DAG.getNode(Opc, DL, VT,
24491 N0.getOperand(0), N1.getOperand(0),
24492 DAG.getNode(ISD::TRUNCATE, DL,
24499 // Generate NEG and CMOV for integer abs.
24500 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24501 EVT VT = N->getValueType(0);
24503 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24504 // 8-bit integer abs to NEG and CMOV.
24505 if (VT.isInteger() && VT.getSizeInBits() == 8)
24508 SDValue N0 = N->getOperand(0);
24509 SDValue N1 = N->getOperand(1);
24512 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24513 // and change it to SUB and CMOV.
24514 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24515 N0.getOpcode() == ISD::ADD &&
24516 N0.getOperand(1) == N1 &&
24517 N1.getOpcode() == ISD::SRA &&
24518 N1.getOperand(0) == N0.getOperand(0))
24519 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24520 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24521 // Generate SUB & CMOV.
24522 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24523 DAG.getConstant(0, VT), N0.getOperand(0));
24525 SDValue Ops[] = { N0.getOperand(0), Neg,
24526 DAG.getConstant(X86::COND_GE, MVT::i8),
24527 SDValue(Neg.getNode(), 1) };
24528 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24533 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24534 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24535 TargetLowering::DAGCombinerInfo &DCI,
24536 const X86Subtarget *Subtarget) {
24537 if (DCI.isBeforeLegalizeOps())
24540 if (Subtarget->hasCMov()) {
24541 SDValue RV = performIntegerAbsCombine(N, DAG);
24549 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24550 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24551 TargetLowering::DAGCombinerInfo &DCI,
24552 const X86Subtarget *Subtarget) {
24553 LoadSDNode *Ld = cast<LoadSDNode>(N);
24554 EVT RegVT = Ld->getValueType(0);
24555 EVT MemVT = Ld->getMemoryVT();
24557 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24559 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24560 // into two 16-byte operations.
24561 ISD::LoadExtType Ext = Ld->getExtensionType();
24562 unsigned Alignment = Ld->getAlignment();
24563 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24564 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24565 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24566 unsigned NumElems = RegVT.getVectorNumElements();
24570 SDValue Ptr = Ld->getBasePtr();
24571 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24573 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24575 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24576 Ld->getPointerInfo(), Ld->isVolatile(),
24577 Ld->isNonTemporal(), Ld->isInvariant(),
24579 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24580 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24581 Ld->getPointerInfo(), Ld->isVolatile(),
24582 Ld->isNonTemporal(), Ld->isInvariant(),
24583 std::min(16U, Alignment));
24584 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24586 Load2.getValue(1));
24588 SDValue NewVec = DAG.getUNDEF(RegVT);
24589 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24590 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24591 return DCI.CombineTo(N, NewVec, TF, true);
24597 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24598 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24599 const X86Subtarget *Subtarget) {
24600 StoreSDNode *St = cast<StoreSDNode>(N);
24601 EVT VT = St->getValue().getValueType();
24602 EVT StVT = St->getMemoryVT();
24604 SDValue StoredVal = St->getOperand(1);
24605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24607 // If we are saving a concatenation of two XMM registers and 32-byte stores
24608 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24609 unsigned Alignment = St->getAlignment();
24610 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24611 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24612 StVT == VT && !IsAligned) {
24613 unsigned NumElems = VT.getVectorNumElements();
24617 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24618 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24620 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
24621 SDValue Ptr0 = St->getBasePtr();
24622 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24624 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24625 St->getPointerInfo(), St->isVolatile(),
24626 St->isNonTemporal(), Alignment);
24627 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24628 St->getPointerInfo(), St->isVolatile(),
24629 St->isNonTemporal(),
24630 std::min(16U, Alignment));
24631 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24634 // Optimize trunc store (of multiple scalars) to shuffle and store.
24635 // First, pack all of the elements in one place. Next, store to memory
24636 // in fewer chunks.
24637 if (St->isTruncatingStore() && VT.isVector()) {
24638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24639 unsigned NumElems = VT.getVectorNumElements();
24640 assert(StVT != VT && "Cannot truncate to the same type");
24641 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24642 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24644 // From, To sizes and ElemCount must be pow of two
24645 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24646 // We are going to use the original vector elt for storing.
24647 // Accumulated smaller vector elements must be a multiple of the store size.
24648 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24650 unsigned SizeRatio = FromSz / ToSz;
24652 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24654 // Create a type on which we perform the shuffle
24655 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24656 StVT.getScalarType(), NumElems*SizeRatio);
24658 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24660 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
24661 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24662 for (unsigned i = 0; i != NumElems; ++i)
24663 ShuffleVec[i] = i * SizeRatio;
24665 // Can't shuffle using an illegal type.
24666 if (!TLI.isTypeLegal(WideVecVT))
24669 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24670 DAG.getUNDEF(WideVecVT),
24672 // At this point all of the data is stored at the bottom of the
24673 // register. We now need to save it to mem.
24675 // Find the largest store unit
24676 MVT StoreType = MVT::i8;
24677 for (MVT Tp : MVT::integer_valuetypes()) {
24678 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24682 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24683 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24684 (64 <= NumElems * ToSz))
24685 StoreType = MVT::f64;
24687 // Bitcast the original vector into a vector of store-size units
24688 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24689 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24690 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24691 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
24692 SmallVector<SDValue, 8> Chains;
24693 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
24694 TLI.getPointerTy());
24695 SDValue Ptr = St->getBasePtr();
24697 // Perform one or more big stores into memory.
24698 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24699 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24700 StoreType, ShuffWide,
24701 DAG.getIntPtrConstant(i));
24702 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24703 St->getPointerInfo(), St->isVolatile(),
24704 St->isNonTemporal(), St->getAlignment());
24705 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24706 Chains.push_back(Ch);
24709 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24712 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24713 // the FP state in cases where an emms may be missing.
24714 // A preferable solution to the general problem is to figure out the right
24715 // places to insert EMMS. This qualifies as a quick hack.
24717 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24718 if (VT.getSizeInBits() != 64)
24721 const Function *F = DAG.getMachineFunction().getFunction();
24722 bool NoImplicitFloatOps = F->getAttributes().
24723 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
24724 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
24725 && Subtarget->hasSSE2();
24726 if ((VT.isVector() ||
24727 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24728 isa<LoadSDNode>(St->getValue()) &&
24729 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24730 St->getChain().hasOneUse() && !St->isVolatile()) {
24731 SDNode* LdVal = St->getValue().getNode();
24732 LoadSDNode *Ld = nullptr;
24733 int TokenFactorIndex = -1;
24734 SmallVector<SDValue, 8> Ops;
24735 SDNode* ChainVal = St->getChain().getNode();
24736 // Must be a store of a load. We currently handle two cases: the load
24737 // is a direct child, and it's under an intervening TokenFactor. It is
24738 // possible to dig deeper under nested TokenFactors.
24739 if (ChainVal == LdVal)
24740 Ld = cast<LoadSDNode>(St->getChain());
24741 else if (St->getValue().hasOneUse() &&
24742 ChainVal->getOpcode() == ISD::TokenFactor) {
24743 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24744 if (ChainVal->getOperand(i).getNode() == LdVal) {
24745 TokenFactorIndex = i;
24746 Ld = cast<LoadSDNode>(St->getValue());
24748 Ops.push_back(ChainVal->getOperand(i));
24752 if (!Ld || !ISD::isNormalLoad(Ld))
24755 // If this is not the MMX case, i.e. we are just turning i64 load/store
24756 // into f64 load/store, avoid the transformation if there are multiple
24757 // uses of the loaded value.
24758 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24763 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24764 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24766 if (Subtarget->is64Bit() || F64IsLegal) {
24767 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24768 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24769 Ld->getPointerInfo(), Ld->isVolatile(),
24770 Ld->isNonTemporal(), Ld->isInvariant(),
24771 Ld->getAlignment());
24772 SDValue NewChain = NewLd.getValue(1);
24773 if (TokenFactorIndex != -1) {
24774 Ops.push_back(NewChain);
24775 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24777 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24778 St->getPointerInfo(),
24779 St->isVolatile(), St->isNonTemporal(),
24780 St->getAlignment());
24783 // Otherwise, lower to two pairs of 32-bit loads / stores.
24784 SDValue LoAddr = Ld->getBasePtr();
24785 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24786 DAG.getConstant(4, MVT::i32));
24788 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24789 Ld->getPointerInfo(),
24790 Ld->isVolatile(), Ld->isNonTemporal(),
24791 Ld->isInvariant(), Ld->getAlignment());
24792 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24793 Ld->getPointerInfo().getWithOffset(4),
24794 Ld->isVolatile(), Ld->isNonTemporal(),
24796 MinAlign(Ld->getAlignment(), 4));
24798 SDValue NewChain = LoLd.getValue(1);
24799 if (TokenFactorIndex != -1) {
24800 Ops.push_back(LoLd);
24801 Ops.push_back(HiLd);
24802 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24805 LoAddr = St->getBasePtr();
24806 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24807 DAG.getConstant(4, MVT::i32));
24809 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24810 St->getPointerInfo(),
24811 St->isVolatile(), St->isNonTemporal(),
24812 St->getAlignment());
24813 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24814 St->getPointerInfo().getWithOffset(4),
24816 St->isNonTemporal(),
24817 MinAlign(St->getAlignment(), 4));
24818 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24823 /// Return 'true' if this vector operation is "horizontal"
24824 /// and return the operands for the horizontal operation in LHS and RHS. A
24825 /// horizontal operation performs the binary operation on successive elements
24826 /// of its first operand, then on successive elements of its second operand,
24827 /// returning the resulting values in a vector. For example, if
24828 /// A = < float a0, float a1, float a2, float a3 >
24830 /// B = < float b0, float b1, float b2, float b3 >
24831 /// then the result of doing a horizontal operation on A and B is
24832 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24833 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24834 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24835 /// set to A, RHS to B, and the routine returns 'true'.
24836 /// Note that the binary operation should have the property that if one of the
24837 /// operands is UNDEF then the result is UNDEF.
24838 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24839 // Look for the following pattern: if
24840 // A = < float a0, float a1, float a2, float a3 >
24841 // B = < float b0, float b1, float b2, float b3 >
24843 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24844 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24845 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24846 // which is A horizontal-op B.
24848 // At least one of the operands should be a vector shuffle.
24849 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24850 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24853 MVT VT = LHS.getSimpleValueType();
24855 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24856 "Unsupported vector type for horizontal add/sub");
24858 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24859 // operate independently on 128-bit lanes.
24860 unsigned NumElts = VT.getVectorNumElements();
24861 unsigned NumLanes = VT.getSizeInBits()/128;
24862 unsigned NumLaneElts = NumElts / NumLanes;
24863 assert((NumLaneElts % 2 == 0) &&
24864 "Vector type should have an even number of elements in each lane");
24865 unsigned HalfLaneElts = NumLaneElts/2;
24867 // View LHS in the form
24868 // LHS = VECTOR_SHUFFLE A, B, LMask
24869 // If LHS is not a shuffle then pretend it is the shuffle
24870 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24871 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24874 SmallVector<int, 16> LMask(NumElts);
24875 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24876 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24877 A = LHS.getOperand(0);
24878 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24879 B = LHS.getOperand(1);
24880 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24881 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24883 if (LHS.getOpcode() != ISD::UNDEF)
24885 for (unsigned i = 0; i != NumElts; ++i)
24889 // Likewise, view RHS in the form
24890 // RHS = VECTOR_SHUFFLE C, D, RMask
24892 SmallVector<int, 16> RMask(NumElts);
24893 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24894 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24895 C = RHS.getOperand(0);
24896 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24897 D = RHS.getOperand(1);
24898 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24899 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24901 if (RHS.getOpcode() != ISD::UNDEF)
24903 for (unsigned i = 0; i != NumElts; ++i)
24907 // Check that the shuffles are both shuffling the same vectors.
24908 if (!(A == C && B == D) && !(A == D && B == C))
24911 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24912 if (!A.getNode() && !B.getNode())
24915 // If A and B occur in reverse order in RHS, then "swap" them (which means
24916 // rewriting the mask).
24918 CommuteVectorShuffleMask(RMask, NumElts);
24920 // At this point LHS and RHS are equivalent to
24921 // LHS = VECTOR_SHUFFLE A, B, LMask
24922 // RHS = VECTOR_SHUFFLE A, B, RMask
24923 // Check that the masks correspond to performing a horizontal operation.
24924 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24925 for (unsigned i = 0; i != NumLaneElts; ++i) {
24926 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24928 // Ignore any UNDEF components.
24929 if (LIdx < 0 || RIdx < 0 ||
24930 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24931 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24934 // Check that successive elements are being operated on. If not, this is
24935 // not a horizontal operation.
24936 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24937 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24938 if (!(LIdx == Index && RIdx == Index + 1) &&
24939 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24944 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24945 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24949 /// Do target-specific dag combines on floating point adds.
24950 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24951 const X86Subtarget *Subtarget) {
24952 EVT VT = N->getValueType(0);
24953 SDValue LHS = N->getOperand(0);
24954 SDValue RHS = N->getOperand(1);
24956 // Try to synthesize horizontal adds from adds of shuffles.
24957 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24958 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24959 isHorizontalBinOp(LHS, RHS, true))
24960 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24964 /// Do target-specific dag combines on floating point subs.
24965 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24966 const X86Subtarget *Subtarget) {
24967 EVT VT = N->getValueType(0);
24968 SDValue LHS = N->getOperand(0);
24969 SDValue RHS = N->getOperand(1);
24971 // Try to synthesize horizontal subs from subs of shuffles.
24972 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24973 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24974 isHorizontalBinOp(LHS, RHS, false))
24975 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24979 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24980 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24981 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24982 // F[X]OR(0.0, x) -> x
24983 // F[X]OR(x, 0.0) -> x
24984 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24985 if (C->getValueAPF().isPosZero())
24986 return N->getOperand(1);
24987 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24988 if (C->getValueAPF().isPosZero())
24989 return N->getOperand(0);
24993 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24994 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24995 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24997 // Only perform optimizations if UnsafeMath is used.
24998 if (!DAG.getTarget().Options.UnsafeFPMath)
25001 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25002 // into FMINC and FMAXC, which are Commutative operations.
25003 unsigned NewOp = 0;
25004 switch (N->getOpcode()) {
25005 default: llvm_unreachable("unknown opcode");
25006 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
25007 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
25010 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25011 N->getOperand(0), N->getOperand(1));
25014 /// Do target-specific dag combines on X86ISD::FAND nodes.
25015 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25016 // FAND(0.0, x) -> 0.0
25017 // FAND(x, 0.0) -> 0.0
25018 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25019 if (C->getValueAPF().isPosZero())
25020 return N->getOperand(0);
25021 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25022 if (C->getValueAPF().isPosZero())
25023 return N->getOperand(1);
25027 /// Do target-specific dag combines on X86ISD::FANDN nodes
25028 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25029 // FANDN(x, 0.0) -> 0.0
25030 // FANDN(0.0, x) -> x
25031 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25032 if (C->getValueAPF().isPosZero())
25033 return N->getOperand(1);
25034 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25035 if (C->getValueAPF().isPosZero())
25036 return N->getOperand(1);
25040 static SDValue PerformBTCombine(SDNode *N,
25042 TargetLowering::DAGCombinerInfo &DCI) {
25043 // BT ignores high bits in the bit index operand.
25044 SDValue Op1 = N->getOperand(1);
25045 if (Op1.hasOneUse()) {
25046 unsigned BitWidth = Op1.getValueSizeInBits();
25047 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25048 APInt KnownZero, KnownOne;
25049 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25050 !DCI.isBeforeLegalizeOps());
25051 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25052 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25053 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25054 DCI.CommitTargetLoweringOpt(TLO);
25059 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25060 SDValue Op = N->getOperand(0);
25061 if (Op.getOpcode() == ISD::BITCAST)
25062 Op = Op.getOperand(0);
25063 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25064 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25065 VT.getVectorElementType().getSizeInBits() ==
25066 OpVT.getVectorElementType().getSizeInBits()) {
25067 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25072 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25073 const X86Subtarget *Subtarget) {
25074 EVT VT = N->getValueType(0);
25075 if (!VT.isVector())
25078 SDValue N0 = N->getOperand(0);
25079 SDValue N1 = N->getOperand(1);
25080 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25083 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25084 // both SSE and AVX2 since there is no sign-extended shift right
25085 // operation on a vector with 64-bit elements.
25086 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25087 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25088 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25089 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25090 SDValue N00 = N0.getOperand(0);
25092 // EXTLOAD has a better solution on AVX2,
25093 // it may be replaced with X86ISD::VSEXT node.
25094 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25095 if (!ISD::isNormalLoad(N00.getNode()))
25098 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25099 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25101 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25107 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25108 TargetLowering::DAGCombinerInfo &DCI,
25109 const X86Subtarget *Subtarget) {
25110 SDValue N0 = N->getOperand(0);
25111 EVT VT = N->getValueType(0);
25113 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25114 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25115 // This exposes the sext to the sdivrem lowering, so that it directly extends
25116 // from AH (which we otherwise need to do contortions to access).
25117 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25118 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
25120 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25121 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
25122 N0.getOperand(0), N0.getOperand(1));
25123 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25124 return R.getValue(1);
25127 if (!DCI.isBeforeLegalizeOps())
25130 if (!Subtarget->hasFp256())
25133 if (VT.isVector() && VT.getSizeInBits() == 256) {
25134 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25142 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25143 const X86Subtarget* Subtarget) {
25145 EVT VT = N->getValueType(0);
25147 // Let legalize expand this if it isn't a legal type yet.
25148 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25151 EVT ScalarVT = VT.getScalarType();
25152 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25153 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
25156 SDValue A = N->getOperand(0);
25157 SDValue B = N->getOperand(1);
25158 SDValue C = N->getOperand(2);
25160 bool NegA = (A.getOpcode() == ISD::FNEG);
25161 bool NegB = (B.getOpcode() == ISD::FNEG);
25162 bool NegC = (C.getOpcode() == ISD::FNEG);
25164 // Negative multiplication when NegA xor NegB
25165 bool NegMul = (NegA != NegB);
25167 A = A.getOperand(0);
25169 B = B.getOperand(0);
25171 C = C.getOperand(0);
25175 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25177 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25179 return DAG.getNode(Opcode, dl, VT, A, B, C);
25182 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25183 TargetLowering::DAGCombinerInfo &DCI,
25184 const X86Subtarget *Subtarget) {
25185 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25186 // (and (i32 x86isd::setcc_carry), 1)
25187 // This eliminates the zext. This transformation is necessary because
25188 // ISD::SETCC is always legalized to i8.
25190 SDValue N0 = N->getOperand(0);
25191 EVT VT = N->getValueType(0);
25193 if (N0.getOpcode() == ISD::AND &&
25195 N0.getOperand(0).hasOneUse()) {
25196 SDValue N00 = N0.getOperand(0);
25197 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25198 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25199 if (!C || C->getZExtValue() != 1)
25201 return DAG.getNode(ISD::AND, dl, VT,
25202 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25203 N00.getOperand(0), N00.getOperand(1)),
25204 DAG.getConstant(1, VT));
25208 if (N0.getOpcode() == ISD::TRUNCATE &&
25210 N0.getOperand(0).hasOneUse()) {
25211 SDValue N00 = N0.getOperand(0);
25212 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25213 return DAG.getNode(ISD::AND, dl, VT,
25214 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25215 N00.getOperand(0), N00.getOperand(1)),
25216 DAG.getConstant(1, VT));
25219 if (VT.is256BitVector()) {
25220 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25225 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25226 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25227 // This exposes the zext to the udivrem lowering, so that it directly extends
25228 // from AH (which we otherwise need to do contortions to access).
25229 if (N0.getOpcode() == ISD::UDIVREM &&
25230 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25231 (VT == MVT::i32 || VT == MVT::i64)) {
25232 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25233 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25234 N0.getOperand(0), N0.getOperand(1));
25235 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25236 return R.getValue(1);
25242 // Optimize x == -y --> x+y == 0
25243 // x != -y --> x+y != 0
25244 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25245 const X86Subtarget* Subtarget) {
25246 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25247 SDValue LHS = N->getOperand(0);
25248 SDValue RHS = N->getOperand(1);
25249 EVT VT = N->getValueType(0);
25252 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25254 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25255 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25256 LHS.getValueType(), RHS, LHS.getOperand(1));
25257 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25258 addV, DAG.getConstant(0, addV.getValueType()), CC);
25260 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25261 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25262 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25263 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25264 RHS.getValueType(), LHS, RHS.getOperand(1));
25265 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25266 addV, DAG.getConstant(0, addV.getValueType()), CC);
25269 if (VT.getScalarType() == MVT::i1) {
25270 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25271 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25272 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
25273 if (!IsSEXT0 && !IsVZero0)
25275 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
25276 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25277 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25279 if (!IsSEXT1 && !IsVZero1)
25282 if (IsSEXT0 && IsVZero1) {
25283 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
25284 if (CC == ISD::SETEQ)
25285 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25286 return LHS.getOperand(0);
25288 if (IsSEXT1 && IsVZero0) {
25289 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
25290 if (CC == ISD::SETEQ)
25291 return DAG.getNOT(DL, RHS.getOperand(0), VT);
25292 return RHS.getOperand(0);
25299 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25300 const X86Subtarget *Subtarget) {
25302 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25303 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25304 "X86insertps is only defined for v4x32");
25306 SDValue Ld = N->getOperand(1);
25307 if (MayFoldLoad(Ld)) {
25308 // Extract the countS bits from the immediate so we can get the proper
25309 // address when narrowing the vector load to a specific element.
25310 // When the second source op is a memory address, interps doesn't use
25311 // countS and just gets an f32 from that address.
25312 unsigned DestIndex =
25313 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25314 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25318 // Create this as a scalar to vector to match the instruction pattern.
25319 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25320 // countS bits are ignored when loading from memory on insertps, which
25321 // means we don't need to explicitly set them to 0.
25322 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25323 LoadScalarToVector, N->getOperand(2));
25326 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25327 // as "sbb reg,reg", since it can be extended without zext and produces
25328 // an all-ones bit which is more useful than 0/1 in some cases.
25329 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25332 return DAG.getNode(ISD::AND, DL, VT,
25333 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25334 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
25335 DAG.getConstant(1, VT));
25336 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25337 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25338 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25339 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
25342 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25343 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25344 TargetLowering::DAGCombinerInfo &DCI,
25345 const X86Subtarget *Subtarget) {
25347 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25348 SDValue EFLAGS = N->getOperand(1);
25350 if (CC == X86::COND_A) {
25351 // Try to convert COND_A into COND_B in an attempt to facilitate
25352 // materializing "setb reg".
25354 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25355 // cannot take an immediate as its first operand.
25357 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25358 EFLAGS.getValueType().isInteger() &&
25359 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25360 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25361 EFLAGS.getNode()->getVTList(),
25362 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25363 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25364 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25368 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25369 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25371 if (CC == X86::COND_B)
25372 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25376 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25377 if (Flags.getNode()) {
25378 SDValue Cond = DAG.getConstant(CC, MVT::i8);
25379 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25385 // Optimize branch condition evaluation.
25387 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25388 TargetLowering::DAGCombinerInfo &DCI,
25389 const X86Subtarget *Subtarget) {
25391 SDValue Chain = N->getOperand(0);
25392 SDValue Dest = N->getOperand(1);
25393 SDValue EFLAGS = N->getOperand(3);
25394 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25398 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25399 if (Flags.getNode()) {
25400 SDValue Cond = DAG.getConstant(CC, MVT::i8);
25401 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25408 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25409 SelectionDAG &DAG) {
25410 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25411 // optimize away operation when it's from a constant.
25413 // The general transformation is:
25414 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25415 // AND(VECTOR_CMP(x,y), constant2)
25416 // constant2 = UNARYOP(constant)
25418 // Early exit if this isn't a vector operation, the operand of the
25419 // unary operation isn't a bitwise AND, or if the sizes of the operations
25420 // aren't the same.
25421 EVT VT = N->getValueType(0);
25422 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25423 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25424 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25427 // Now check that the other operand of the AND is a constant. We could
25428 // make the transformation for non-constant splats as well, but it's unclear
25429 // that would be a benefit as it would not eliminate any operations, just
25430 // perform one more step in scalar code before moving to the vector unit.
25431 if (BuildVectorSDNode *BV =
25432 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25433 // Bail out if the vector isn't a constant.
25434 if (!BV->isConstant())
25437 // Everything checks out. Build up the new and improved node.
25439 EVT IntVT = BV->getValueType(0);
25440 // Create a new constant of the appropriate type for the transformed
25442 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25443 // The AND node needs bitcasts to/from an integer vector type around it.
25444 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
25445 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25446 N->getOperand(0)->getOperand(0), MaskConst);
25447 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
25454 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25455 const X86TargetLowering *XTLI) {
25456 // First try to optimize away the conversion entirely when it's
25457 // conditionally from a constant. Vectors only.
25458 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
25459 if (Res != SDValue())
25462 // Now move on to more general possibilities.
25463 SDValue Op0 = N->getOperand(0);
25464 EVT InVT = Op0->getValueType(0);
25466 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
25467 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
25469 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
25470 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25471 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
25474 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25475 // a 32-bit target where SSE doesn't support i64->FP operations.
25476 if (Op0.getOpcode() == ISD::LOAD) {
25477 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25478 EVT VT = Ld->getValueType(0);
25479 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
25480 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25481 !XTLI->getSubtarget()->is64Bit() &&
25483 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
25484 Ld->getChain(), Op0, DAG);
25485 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25492 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25493 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25494 X86TargetLowering::DAGCombinerInfo &DCI) {
25495 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25496 // the result is either zero or one (depending on the input carry bit).
25497 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25498 if (X86::isZeroNode(N->getOperand(0)) &&
25499 X86::isZeroNode(N->getOperand(1)) &&
25500 // We don't have a good way to replace an EFLAGS use, so only do this when
25502 SDValue(N, 1).use_empty()) {
25504 EVT VT = N->getValueType(0);
25505 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
25506 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25507 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25508 DAG.getConstant(X86::COND_B,MVT::i8),
25510 DAG.getConstant(1, VT));
25511 return DCI.CombineTo(N, Res1, CarryOut);
25517 // fold (add Y, (sete X, 0)) -> adc 0, Y
25518 // (add Y, (setne X, 0)) -> sbb -1, Y
25519 // (sub (sete X, 0), Y) -> sbb 0, Y
25520 // (sub (setne X, 0), Y) -> adc -1, Y
25521 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25524 // Look through ZExts.
25525 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25526 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25529 SDValue SetCC = Ext.getOperand(0);
25530 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25533 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25534 if (CC != X86::COND_E && CC != X86::COND_NE)
25537 SDValue Cmp = SetCC.getOperand(1);
25538 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25539 !X86::isZeroNode(Cmp.getOperand(1)) ||
25540 !Cmp.getOperand(0).getValueType().isInteger())
25543 SDValue CmpOp0 = Cmp.getOperand(0);
25544 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25545 DAG.getConstant(1, CmpOp0.getValueType()));
25547 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25548 if (CC == X86::COND_NE)
25549 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25550 DL, OtherVal.getValueType(), OtherVal,
25551 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
25552 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25553 DL, OtherVal.getValueType(), OtherVal,
25554 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
25557 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25558 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25559 const X86Subtarget *Subtarget) {
25560 EVT VT = N->getValueType(0);
25561 SDValue Op0 = N->getOperand(0);
25562 SDValue Op1 = N->getOperand(1);
25564 // Try to synthesize horizontal adds from adds of shuffles.
25565 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25566 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25567 isHorizontalBinOp(Op0, Op1, true))
25568 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25570 return OptimizeConditionalInDecrement(N, DAG);
25573 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25574 const X86Subtarget *Subtarget) {
25575 SDValue Op0 = N->getOperand(0);
25576 SDValue Op1 = N->getOperand(1);
25578 // X86 can't encode an immediate LHS of a sub. See if we can push the
25579 // negation into a preceding instruction.
25580 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25581 // If the RHS of the sub is a XOR with one use and a constant, invert the
25582 // immediate. Then add one to the LHS of the sub so we can turn
25583 // X-Y -> X+~Y+1, saving one register.
25584 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25585 isa<ConstantSDNode>(Op1.getOperand(1))) {
25586 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25587 EVT VT = Op0.getValueType();
25588 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25590 DAG.getConstant(~XorC, VT));
25591 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25592 DAG.getConstant(C->getAPIntValue()+1, VT));
25596 // Try to synthesize horizontal adds from adds of shuffles.
25597 EVT VT = N->getValueType(0);
25598 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25599 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25600 isHorizontalBinOp(Op0, Op1, true))
25601 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25603 return OptimizeConditionalInDecrement(N, DAG);
25606 /// performVZEXTCombine - Performs build vector combines
25607 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25608 TargetLowering::DAGCombinerInfo &DCI,
25609 const X86Subtarget *Subtarget) {
25611 MVT VT = N->getSimpleValueType(0);
25612 SDValue Op = N->getOperand(0);
25613 MVT OpVT = Op.getSimpleValueType();
25614 MVT OpEltVT = OpVT.getVectorElementType();
25615 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25617 // (vzext (bitcast (vzext (x)) -> (vzext x)
25619 while (V.getOpcode() == ISD::BITCAST)
25620 V = V.getOperand(0);
25622 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25623 MVT InnerVT = V.getSimpleValueType();
25624 MVT InnerEltVT = InnerVT.getVectorElementType();
25626 // If the element sizes match exactly, we can just do one larger vzext. This
25627 // is always an exact type match as vzext operates on integer types.
25628 if (OpEltVT == InnerEltVT) {
25629 assert(OpVT == InnerVT && "Types must match for vzext!");
25630 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25633 // The only other way we can combine them is if only a single element of the
25634 // inner vzext is used in the input to the outer vzext.
25635 if (InnerEltVT.getSizeInBits() < InputBits)
25638 // In this case, the inner vzext is completely dead because we're going to
25639 // only look at bits inside of the low element. Just do the outer vzext on
25640 // a bitcast of the input to the inner.
25641 return DAG.getNode(X86ISD::VZEXT, DL, VT,
25642 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
25645 // Check if we can bypass extracting and re-inserting an element of an input
25646 // vector. Essentialy:
25647 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25648 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25649 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25650 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25651 SDValue ExtractedV = V.getOperand(0);
25652 SDValue OrigV = ExtractedV.getOperand(0);
25653 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25654 if (ExtractIdx->getZExtValue() == 0) {
25655 MVT OrigVT = OrigV.getSimpleValueType();
25656 // Extract a subvector if necessary...
25657 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25658 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25659 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25660 OrigVT.getVectorNumElements() / Ratio);
25661 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25662 DAG.getIntPtrConstant(0));
25664 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
25665 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25672 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25673 DAGCombinerInfo &DCI) const {
25674 SelectionDAG &DAG = DCI.DAG;
25675 switch (N->getOpcode()) {
25677 case ISD::EXTRACT_VECTOR_ELT:
25678 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25681 case X86ISD::SHRUNKBLEND:
25682 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25683 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25684 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25685 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25686 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25687 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25690 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25691 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25692 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25693 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25694 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25695 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25696 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
25697 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25698 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25700 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25702 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25703 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25704 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25705 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25706 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25707 case ISD::ANY_EXTEND:
25708 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25709 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25710 case ISD::SIGN_EXTEND_INREG:
25711 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25712 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
25713 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25714 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25715 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25716 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25717 case X86ISD::SHUFP: // Handle all target specific shuffles
25718 case X86ISD::PALIGNR:
25719 case X86ISD::UNPCKH:
25720 case X86ISD::UNPCKL:
25721 case X86ISD::MOVHLPS:
25722 case X86ISD::MOVLHPS:
25723 case X86ISD::PSHUFB:
25724 case X86ISD::PSHUFD:
25725 case X86ISD::PSHUFHW:
25726 case X86ISD::PSHUFLW:
25727 case X86ISD::MOVSS:
25728 case X86ISD::MOVSD:
25729 case X86ISD::VPERMILPI:
25730 case X86ISD::VPERM2X128:
25731 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25732 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25733 case ISD::INTRINSIC_WO_CHAIN:
25734 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25735 case X86ISD::INSERTPS:
25736 return PerformINSERTPSCombine(N, DAG, Subtarget);
25737 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
25743 /// isTypeDesirableForOp - Return true if the target has native support for
25744 /// the specified value type and it is 'desirable' to use the type for the
25745 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25746 /// instruction encodings are longer and some i16 instructions are slow.
25747 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25748 if (!isTypeLegal(VT))
25750 if (VT != MVT::i16)
25757 case ISD::SIGN_EXTEND:
25758 case ISD::ZERO_EXTEND:
25759 case ISD::ANY_EXTEND:
25772 /// IsDesirableToPromoteOp - This method query the target whether it is
25773 /// beneficial for dag combiner to promote the specified node. If true, it
25774 /// should return the desired promotion type by reference.
25775 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25776 EVT VT = Op.getValueType();
25777 if (VT != MVT::i16)
25780 bool Promote = false;
25781 bool Commute = false;
25782 switch (Op.getOpcode()) {
25785 LoadSDNode *LD = cast<LoadSDNode>(Op);
25786 // If the non-extending load has a single use and it's not live out, then it
25787 // might be folded.
25788 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25789 Op.hasOneUse()*/) {
25790 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25791 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25792 // The only case where we'd want to promote LOAD (rather then it being
25793 // promoted as an operand is when it's only use is liveout.
25794 if (UI->getOpcode() != ISD::CopyToReg)
25801 case ISD::SIGN_EXTEND:
25802 case ISD::ZERO_EXTEND:
25803 case ISD::ANY_EXTEND:
25808 SDValue N0 = Op.getOperand(0);
25809 // Look out for (store (shl (load), x)).
25810 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25823 SDValue N0 = Op.getOperand(0);
25824 SDValue N1 = Op.getOperand(1);
25825 if (!Commute && MayFoldLoad(N1))
25827 // Avoid disabling potential load folding opportunities.
25828 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25830 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25840 //===----------------------------------------------------------------------===//
25841 // X86 Inline Assembly Support
25842 //===----------------------------------------------------------------------===//
25845 // Helper to match a string separated by whitespace.
25846 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
25847 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
25849 for (unsigned i = 0, e = args.size(); i != e; ++i) {
25850 StringRef piece(*args[i]);
25851 if (!s.startswith(piece)) // Check if the piece matches.
25854 s = s.substr(piece.size());
25855 StringRef::size_type pos = s.find_first_not_of(" \t");
25856 if (pos == 0) // We matched a prefix.
25864 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
25867 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25869 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25870 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25871 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25872 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25874 if (AsmPieces.size() == 3)
25876 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25883 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25884 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25886 std::string AsmStr = IA->getAsmString();
25888 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25889 if (!Ty || Ty->getBitWidth() % 16 != 0)
25892 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25893 SmallVector<StringRef, 4> AsmPieces;
25894 SplitString(AsmStr, AsmPieces, ";\n");
25896 switch (AsmPieces.size()) {
25897 default: return false;
25899 // FIXME: this should verify that we are targeting a 486 or better. If not,
25900 // we will turn this bswap into something that will be lowered to logical
25901 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25902 // lower so don't worry about this.
25904 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
25905 matchAsm(AsmPieces[0], "bswapl", "$0") ||
25906 matchAsm(AsmPieces[0], "bswapq", "$0") ||
25907 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
25908 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
25909 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
25910 // No need to check constraints, nothing other than the equivalent of
25911 // "=r,0" would be valid here.
25912 return IntrinsicLowering::LowerToByteSwap(CI);
25915 // rorw $$8, ${0:w} --> llvm.bswap.i16
25916 if (CI->getType()->isIntegerTy(16) &&
25917 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25918 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
25919 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
25921 const std::string &ConstraintsStr = IA->getConstraintString();
25922 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25923 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25924 if (clobbersFlagRegisters(AsmPieces))
25925 return IntrinsicLowering::LowerToByteSwap(CI);
25929 if (CI->getType()->isIntegerTy(32) &&
25930 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25931 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
25932 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
25933 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
25935 const std::string &ConstraintsStr = IA->getConstraintString();
25936 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25937 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25938 if (clobbersFlagRegisters(AsmPieces))
25939 return IntrinsicLowering::LowerToByteSwap(CI);
25942 if (CI->getType()->isIntegerTy(64)) {
25943 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25944 if (Constraints.size() >= 2 &&
25945 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25946 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25947 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
25948 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
25949 matchAsm(AsmPieces[1], "bswap", "%edx") &&
25950 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
25951 return IntrinsicLowering::LowerToByteSwap(CI);
25959 /// getConstraintType - Given a constraint letter, return the type of
25960 /// constraint it is for this target.
25961 X86TargetLowering::ConstraintType
25962 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
25963 if (Constraint.size() == 1) {
25964 switch (Constraint[0]) {
25975 return C_RegisterClass;
25999 return TargetLowering::getConstraintType(Constraint);
26002 /// Examine constraint type and operand type and determine a weight value.
26003 /// This object must already have been set up with the operand type
26004 /// and the current alternative constraint selected.
26005 TargetLowering::ConstraintWeight
26006 X86TargetLowering::getSingleConstraintMatchWeight(
26007 AsmOperandInfo &info, const char *constraint) const {
26008 ConstraintWeight weight = CW_Invalid;
26009 Value *CallOperandVal = info.CallOperandVal;
26010 // If we don't have a value, we can't do a match,
26011 // but allow it at the lowest weight.
26012 if (!CallOperandVal)
26014 Type *type = CallOperandVal->getType();
26015 // Look at the constraint type.
26016 switch (*constraint) {
26018 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26029 if (CallOperandVal->getType()->isIntegerTy())
26030 weight = CW_SpecificReg;
26035 if (type->isFloatingPointTy())
26036 weight = CW_SpecificReg;
26039 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26040 weight = CW_SpecificReg;
26044 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26045 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26046 weight = CW_Register;
26049 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26050 if (C->getZExtValue() <= 31)
26051 weight = CW_Constant;
26055 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26056 if (C->getZExtValue() <= 63)
26057 weight = CW_Constant;
26061 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26062 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26063 weight = CW_Constant;
26067 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26068 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26069 weight = CW_Constant;
26073 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26074 if (C->getZExtValue() <= 3)
26075 weight = CW_Constant;
26079 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26080 if (C->getZExtValue() <= 0xff)
26081 weight = CW_Constant;
26086 if (dyn_cast<ConstantFP>(CallOperandVal)) {
26087 weight = CW_Constant;
26091 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26092 if ((C->getSExtValue() >= -0x80000000LL) &&
26093 (C->getSExtValue() <= 0x7fffffffLL))
26094 weight = CW_Constant;
26098 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26099 if (C->getZExtValue() <= 0xffffffff)
26100 weight = CW_Constant;
26107 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26108 /// with another that has more specific requirements based on the type of the
26109 /// corresponding operand.
26110 const char *X86TargetLowering::
26111 LowerXConstraint(EVT ConstraintVT) const {
26112 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26113 // 'f' like normal targets.
26114 if (ConstraintVT.isFloatingPoint()) {
26115 if (Subtarget->hasSSE2())
26117 if (Subtarget->hasSSE1())
26121 return TargetLowering::LowerXConstraint(ConstraintVT);
26124 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26125 /// vector. If it is invalid, don't add anything to Ops.
26126 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26127 std::string &Constraint,
26128 std::vector<SDValue>&Ops,
26129 SelectionDAG &DAG) const {
26132 // Only support length 1 constraints for now.
26133 if (Constraint.length() > 1) return;
26135 char ConstraintLetter = Constraint[0];
26136 switch (ConstraintLetter) {
26139 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26140 if (C->getZExtValue() <= 31) {
26141 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26147 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26148 if (C->getZExtValue() <= 63) {
26149 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26155 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26156 if (isInt<8>(C->getSExtValue())) {
26157 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26164 if (C->getZExtValue() <= 255) {
26165 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26171 // 32-bit signed value
26172 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26173 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26174 C->getSExtValue())) {
26175 // Widen to 64 bits here to get it sign extended.
26176 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
26179 // FIXME gcc accepts some relocatable values here too, but only in certain
26180 // memory models; it's complicated.
26185 // 32-bit unsigned value
26186 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26187 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26188 C->getZExtValue())) {
26189 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26193 // FIXME gcc accepts some relocatable values here too, but only in certain
26194 // memory models; it's complicated.
26198 // Literal immediates are always ok.
26199 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26200 // Widen to 64 bits here to get it sign extended.
26201 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
26205 // In any sort of PIC mode addresses need to be computed at runtime by
26206 // adding in a register or some sort of table lookup. These can't
26207 // be used as immediates.
26208 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26211 // If we are in non-pic codegen mode, we allow the address of a global (with
26212 // an optional displacement) to be used with 'i'.
26213 GlobalAddressSDNode *GA = nullptr;
26214 int64_t Offset = 0;
26216 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26218 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26219 Offset += GA->getOffset();
26221 } else if (Op.getOpcode() == ISD::ADD) {
26222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26223 Offset += C->getZExtValue();
26224 Op = Op.getOperand(0);
26227 } else if (Op.getOpcode() == ISD::SUB) {
26228 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26229 Offset += -C->getZExtValue();
26230 Op = Op.getOperand(0);
26235 // Otherwise, this isn't something we can handle, reject it.
26239 const GlobalValue *GV = GA->getGlobal();
26240 // If we require an extra load to get this address, as in PIC mode, we
26241 // can't accept it.
26242 if (isGlobalStubReference(
26243 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26246 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26247 GA->getValueType(0), Offset);
26252 if (Result.getNode()) {
26253 Ops.push_back(Result);
26256 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26259 std::pair<unsigned, const TargetRegisterClass*>
26260 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
26262 // First, see if this is a constraint that directly corresponds to an LLVM
26264 if (Constraint.size() == 1) {
26265 // GCC Constraint Letters
26266 switch (Constraint[0]) {
26268 // TODO: Slight differences here in allocation order and leaving
26269 // RIP in the class. Do they matter any more here than they do
26270 // in the normal allocation?
26271 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26272 if (Subtarget->is64Bit()) {
26273 if (VT == MVT::i32 || VT == MVT::f32)
26274 return std::make_pair(0U, &X86::GR32RegClass);
26275 if (VT == MVT::i16)
26276 return std::make_pair(0U, &X86::GR16RegClass);
26277 if (VT == MVT::i8 || VT == MVT::i1)
26278 return std::make_pair(0U, &X86::GR8RegClass);
26279 if (VT == MVT::i64 || VT == MVT::f64)
26280 return std::make_pair(0U, &X86::GR64RegClass);
26283 // 32-bit fallthrough
26284 case 'Q': // Q_REGS
26285 if (VT == MVT::i32 || VT == MVT::f32)
26286 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26287 if (VT == MVT::i16)
26288 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26289 if (VT == MVT::i8 || VT == MVT::i1)
26290 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26291 if (VT == MVT::i64)
26292 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26294 case 'r': // GENERAL_REGS
26295 case 'l': // INDEX_REGS
26296 if (VT == MVT::i8 || VT == MVT::i1)
26297 return std::make_pair(0U, &X86::GR8RegClass);
26298 if (VT == MVT::i16)
26299 return std::make_pair(0U, &X86::GR16RegClass);
26300 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26301 return std::make_pair(0U, &X86::GR32RegClass);
26302 return std::make_pair(0U, &X86::GR64RegClass);
26303 case 'R': // LEGACY_REGS
26304 if (VT == MVT::i8 || VT == MVT::i1)
26305 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26306 if (VT == MVT::i16)
26307 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26308 if (VT == MVT::i32 || !Subtarget->is64Bit())
26309 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26310 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26311 case 'f': // FP Stack registers.
26312 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26313 // value to the correct fpstack register class.
26314 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26315 return std::make_pair(0U, &X86::RFP32RegClass);
26316 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26317 return std::make_pair(0U, &X86::RFP64RegClass);
26318 return std::make_pair(0U, &X86::RFP80RegClass);
26319 case 'y': // MMX_REGS if MMX allowed.
26320 if (!Subtarget->hasMMX()) break;
26321 return std::make_pair(0U, &X86::VR64RegClass);
26322 case 'Y': // SSE_REGS if SSE2 allowed
26323 if (!Subtarget->hasSSE2()) break;
26325 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26326 if (!Subtarget->hasSSE1()) break;
26328 switch (VT.SimpleTy) {
26330 // Scalar SSE types.
26333 return std::make_pair(0U, &X86::FR32RegClass);
26336 return std::make_pair(0U, &X86::FR64RegClass);
26344 return std::make_pair(0U, &X86::VR128RegClass);
26352 return std::make_pair(0U, &X86::VR256RegClass);
26357 return std::make_pair(0U, &X86::VR512RegClass);
26363 // Use the default implementation in TargetLowering to convert the register
26364 // constraint into a member of a register class.
26365 std::pair<unsigned, const TargetRegisterClass*> Res;
26366 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
26368 // Not found as a standard register?
26370 // Map st(0) -> st(7) -> ST0
26371 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26372 tolower(Constraint[1]) == 's' &&
26373 tolower(Constraint[2]) == 't' &&
26374 Constraint[3] == '(' &&
26375 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26376 Constraint[5] == ')' &&
26377 Constraint[6] == '}') {
26379 Res.first = X86::FP0+Constraint[4]-'0';
26380 Res.second = &X86::RFP80RegClass;
26384 // GCC allows "st(0)" to be called just plain "st".
26385 if (StringRef("{st}").equals_lower(Constraint)) {
26386 Res.first = X86::FP0;
26387 Res.second = &X86::RFP80RegClass;
26392 if (StringRef("{flags}").equals_lower(Constraint)) {
26393 Res.first = X86::EFLAGS;
26394 Res.second = &X86::CCRRegClass;
26398 // 'A' means EAX + EDX.
26399 if (Constraint == "A") {
26400 Res.first = X86::EAX;
26401 Res.second = &X86::GR32_ADRegClass;
26407 // Otherwise, check to see if this is a register class of the wrong value
26408 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26409 // turn into {ax},{dx}.
26410 if (Res.second->hasType(VT))
26411 return Res; // Correct type already, nothing to do.
26413 // All of the single-register GCC register classes map their values onto
26414 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
26415 // really want an 8-bit or 32-bit register, map to the appropriate register
26416 // class and return the appropriate register.
26417 if (Res.second == &X86::GR16RegClass) {
26418 if (VT == MVT::i8 || VT == MVT::i1) {
26419 unsigned DestReg = 0;
26420 switch (Res.first) {
26422 case X86::AX: DestReg = X86::AL; break;
26423 case X86::DX: DestReg = X86::DL; break;
26424 case X86::CX: DestReg = X86::CL; break;
26425 case X86::BX: DestReg = X86::BL; break;
26428 Res.first = DestReg;
26429 Res.second = &X86::GR8RegClass;
26431 } else if (VT == MVT::i32 || VT == MVT::f32) {
26432 unsigned DestReg = 0;
26433 switch (Res.first) {
26435 case X86::AX: DestReg = X86::EAX; break;
26436 case X86::DX: DestReg = X86::EDX; break;
26437 case X86::CX: DestReg = X86::ECX; break;
26438 case X86::BX: DestReg = X86::EBX; break;
26439 case X86::SI: DestReg = X86::ESI; break;
26440 case X86::DI: DestReg = X86::EDI; break;
26441 case X86::BP: DestReg = X86::EBP; break;
26442 case X86::SP: DestReg = X86::ESP; break;
26445 Res.first = DestReg;
26446 Res.second = &X86::GR32RegClass;
26448 } else if (VT == MVT::i64 || VT == MVT::f64) {
26449 unsigned DestReg = 0;
26450 switch (Res.first) {
26452 case X86::AX: DestReg = X86::RAX; break;
26453 case X86::DX: DestReg = X86::RDX; break;
26454 case X86::CX: DestReg = X86::RCX; break;
26455 case X86::BX: DestReg = X86::RBX; break;
26456 case X86::SI: DestReg = X86::RSI; break;
26457 case X86::DI: DestReg = X86::RDI; break;
26458 case X86::BP: DestReg = X86::RBP; break;
26459 case X86::SP: DestReg = X86::RSP; break;
26462 Res.first = DestReg;
26463 Res.second = &X86::GR64RegClass;
26466 } else if (Res.second == &X86::FR32RegClass ||
26467 Res.second == &X86::FR64RegClass ||
26468 Res.second == &X86::VR128RegClass ||
26469 Res.second == &X86::VR256RegClass ||
26470 Res.second == &X86::FR32XRegClass ||
26471 Res.second == &X86::FR64XRegClass ||
26472 Res.second == &X86::VR128XRegClass ||
26473 Res.second == &X86::VR256XRegClass ||
26474 Res.second == &X86::VR512RegClass) {
26475 // Handle references to XMM physical registers that got mapped into the
26476 // wrong class. This can happen with constraints like {xmm0} where the
26477 // target independent register mapper will just pick the first match it can
26478 // find, ignoring the required type.
26480 if (VT == MVT::f32 || VT == MVT::i32)
26481 Res.second = &X86::FR32RegClass;
26482 else if (VT == MVT::f64 || VT == MVT::i64)
26483 Res.second = &X86::FR64RegClass;
26484 else if (X86::VR128RegClass.hasType(VT))
26485 Res.second = &X86::VR128RegClass;
26486 else if (X86::VR256RegClass.hasType(VT))
26487 Res.second = &X86::VR256RegClass;
26488 else if (X86::VR512RegClass.hasType(VT))
26489 Res.second = &X86::VR512RegClass;
26495 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26497 // Scaling factors are not free at all.
26498 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26499 // will take 2 allocations in the out of order engine instead of 1
26500 // for plain addressing mode, i.e. inst (reg1).
26502 // vaddps (%rsi,%drx), %ymm0, %ymm1
26503 // Requires two allocations (one for the load, one for the computation)
26505 // vaddps (%rsi), %ymm0, %ymm1
26506 // Requires just 1 allocation, i.e., freeing allocations for other operations
26507 // and having less micro operations to execute.
26509 // For some X86 architectures, this is even worse because for instance for
26510 // stores, the complex addressing mode forces the instruction to use the
26511 // "load" ports instead of the dedicated "store" port.
26512 // E.g., on Haswell:
26513 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26514 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26515 if (isLegalAddressingMode(AM, Ty))
26516 // Scale represents reg2 * scale, thus account for 1
26517 // as soon as we use a second register.
26518 return AM.Scale != 0;
26522 bool X86TargetLowering::isTargetFTOL() const {
26523 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();