1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/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<int> ReciprocalEstimateRefinementSteps(
70 "x86-recip-refinement-steps", cl::init(1),
71 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
72 "result of the hardware reciprocal estimate instruction."),
75 // Forward declarations.
76 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
79 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
80 SelectionDAG &DAG, SDLoc dl,
81 unsigned vectorWidth) {
82 assert((vectorWidth == 128 || vectorWidth == 256) &&
83 "Unsupported vector width");
84 EVT VT = Vec.getValueType();
85 EVT ElVT = VT.getVectorElementType();
86 unsigned Factor = VT.getSizeInBits()/vectorWidth;
87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88 VT.getVectorNumElements()/Factor);
90 // Extract from UNDEF is UNDEF.
91 if (Vec.getOpcode() == ISD::UNDEF)
92 return DAG.getUNDEF(ResultVT);
94 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
95 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
97 // This is the index of the first element of the vectorWidth-bit chunk
99 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
102 // If the input is a buildvector just emit a smaller one.
103 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
104 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
105 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
108 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
109 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119 SelectionDAG &DAG, SDLoc dl) {
120 assert((Vec.getValueType().is256BitVector() ||
121 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127 SelectionDAG &DAG, SDLoc dl) {
128 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133 unsigned IdxVal, SelectionDAG &DAG,
134 SDLoc dl, unsigned vectorWidth) {
135 assert((vectorWidth == 128 || vectorWidth == 256) &&
136 "Unsupported vector width");
137 // Inserting UNDEF is Result
138 if (Vec.getOpcode() == ISD::UNDEF)
140 EVT VT = Vec.getValueType();
141 EVT ElVT = VT.getVectorElementType();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant vectorWidth bits.
145 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147 // This is the index of the first element of the vectorWidth-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
156 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference. Idx is an index in the 128 bits
160 /// we want. It need not be aligned to a 128-bit boundary. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
163 SelectionDAG &DAG,SDLoc dl) {
164 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
165 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
168 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
169 SelectionDAG &DAG, SDLoc dl) {
170 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
171 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
175 /// instructions. This is used because creating CONCAT_VECTOR nodes of
176 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
177 /// large BUILD_VECTORS.
178 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
179 unsigned NumElems, SelectionDAG &DAG,
181 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
182 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
186 unsigned NumElems, SelectionDAG &DAG,
188 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
189 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
193 const X86Subtarget &STI)
194 : TargetLowering(TM), Subtarget(&STI) {
195 X86ScalarSSEf64 = Subtarget->hasSSE2();
196 X86ScalarSSEf32 = Subtarget->hasSSE1();
197 TD = getDataLayout();
199 // Set up the TargetLowering object.
200 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
202 // X86 is weird. It always uses i8 for shift amounts and setcc results.
203 setBooleanContents(ZeroOrOneBooleanContent);
204 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
205 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
207 // For 64-bit, since we have so many registers, use the ILP scheduler.
208 // For 32-bit, use the register pressure specific scheduling.
209 // For Atom, always use ILP scheduling.
210 if (Subtarget->isAtom())
211 setSchedulingPreference(Sched::ILP);
212 else if (Subtarget->is64Bit())
213 setSchedulingPreference(Sched::ILP);
215 setSchedulingPreference(Sched::RegPressure);
216 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
217 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
219 // Bypass expensive divides on Atom when compiling with O2.
220 if (TM.getOptLevel() >= CodeGenOpt::Default) {
221 if (Subtarget->hasSlowDivide32())
222 addBypassSlowDiv(32, 8);
223 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
224 addBypassSlowDiv(64, 16);
227 if (Subtarget->isTargetKnownWindowsMSVC()) {
228 // Setup Windows compiler runtime calls.
229 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
230 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
231 setLibcallName(RTLIB::SREM_I64, "_allrem");
232 setLibcallName(RTLIB::UREM_I64, "_aullrem");
233 setLibcallName(RTLIB::MUL_I64, "_allmul");
234 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
235 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
236 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
237 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
238 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
240 // The _ftol2 runtime function has an unusual calling conv, which
241 // is modeled by a special pseudo-instruction.
242 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
243 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
244 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
245 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
248 if (Subtarget->isTargetDarwin()) {
249 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
250 setUseUnderscoreSetJmp(false);
251 setUseUnderscoreLongJmp(false);
252 } else if (Subtarget->isTargetWindowsGNU()) {
253 // MS runtime is weird: it exports _setjmp, but longjmp!
254 setUseUnderscoreSetJmp(true);
255 setUseUnderscoreLongJmp(false);
257 setUseUnderscoreSetJmp(true);
258 setUseUnderscoreLongJmp(true);
261 // Set up the register classes.
262 addRegisterClass(MVT::i8, &X86::GR8RegClass);
263 addRegisterClass(MVT::i16, &X86::GR16RegClass);
264 addRegisterClass(MVT::i32, &X86::GR32RegClass);
265 if (Subtarget->is64Bit())
266 addRegisterClass(MVT::i64, &X86::GR64RegClass);
268 for (MVT VT : MVT::integer_valuetypes())
269 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
271 // We don't accept any truncstore of integer registers.
272 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
273 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
274 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
275 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
276 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
277 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
279 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
281 // SETOEQ and SETUNE require checking two conditions.
282 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
283 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
284 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
285 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
286 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
287 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
289 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
291 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
292 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
293 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
295 if (Subtarget->is64Bit()) {
296 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
297 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
298 } else if (!TM.Options.UseSoftFloat) {
299 // We have an algorithm for SSE2->double, and we turn this into a
300 // 64-bit FILD followed by conditional FADD for other targets.
301 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
302 // We have an algorithm for SSE2, and we turn this into a 64-bit
303 // FILD for other targets.
304 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
307 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
309 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
310 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
312 if (!TM.Options.UseSoftFloat) {
313 // SSE has no i16 to fp conversion, only i32
314 if (X86ScalarSSEf32) {
315 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
316 // f32 and f64 cases are Legal, f80 case is not
317 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
319 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
320 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
323 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
324 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
327 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
328 // are Legal, f80 is custom lowered.
329 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
330 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
332 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
334 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
335 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
342 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
343 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
346 // Handle FP_TO_UINT by promoting the destination to a larger signed
348 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
349 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
350 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
352 if (Subtarget->is64Bit()) {
353 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
354 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
355 } else if (!TM.Options.UseSoftFloat) {
356 // Since AVX is a superset of SSE3, only check for SSE here.
357 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
358 // Expand FP_TO_UINT into a select.
359 // FIXME: We would like to use a Custom expander here eventually to do
360 // the optimal thing for SSE vs. the default expansion in the legalizer.
361 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
363 // With SSE3 we can use fisttpll to convert to a signed i64; without
364 // SSE, we're stuck with a fistpll.
365 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
368 if (isTargetFTOL()) {
369 // Use the _ftol2 runtime function, which has a pseudo-instruction
370 // to handle its weird calling convention.
371 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
374 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
375 if (!X86ScalarSSEf64) {
376 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
377 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
378 if (Subtarget->is64Bit()) {
379 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
380 // Without SSE, i64->f64 goes through memory.
381 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
385 // Scalar integer divide and remainder are lowered to use operations that
386 // produce two results, to match the available instructions. This exposes
387 // the two-result form to trivial CSE, which is able to combine x/y and x%y
388 // into a single instruction.
390 // Scalar integer multiply-high is also lowered to use two-result
391 // operations, to match the available instructions. However, plain multiply
392 // (low) operations are left as Legal, as there are single-result
393 // instructions for this in x86. Using the two-result multiply instructions
394 // when both high and low results are needed must be arranged by dagcombine.
395 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
397 setOperationAction(ISD::MULHS, VT, Expand);
398 setOperationAction(ISD::MULHU, VT, Expand);
399 setOperationAction(ISD::SDIV, VT, Expand);
400 setOperationAction(ISD::UDIV, VT, Expand);
401 setOperationAction(ISD::SREM, VT, Expand);
402 setOperationAction(ISD::UREM, VT, Expand);
404 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
405 setOperationAction(ISD::ADDC, VT, Custom);
406 setOperationAction(ISD::ADDE, VT, Custom);
407 setOperationAction(ISD::SUBC, VT, Custom);
408 setOperationAction(ISD::SUBE, VT, Custom);
411 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
412 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
413 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
414 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
415 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
416 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
417 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
418 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
419 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
420 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
421 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
422 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
423 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
424 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
425 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
426 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
427 if (Subtarget->is64Bit())
428 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
429 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
430 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
431 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
432 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
433 setOperationAction(ISD::FREM , MVT::f32 , Expand);
434 setOperationAction(ISD::FREM , MVT::f64 , Expand);
435 setOperationAction(ISD::FREM , MVT::f80 , Expand);
436 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
438 // Promote the i8 variants and force them on up to i32 which has a shorter
440 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
441 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
442 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
443 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
444 if (Subtarget->hasBMI()) {
445 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
446 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
447 if (Subtarget->is64Bit())
448 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
450 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
451 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
452 if (Subtarget->is64Bit())
453 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
456 if (Subtarget->hasLZCNT()) {
457 // When promoting the i8 variants, force them to i32 for a shorter
459 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
461 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
462 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
463 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
464 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
469 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
470 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
471 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
474 if (Subtarget->is64Bit()) {
475 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
480 // Special handling for half-precision floating point conversions.
481 // If we don't have F16C support, then lower half float conversions
482 // into library calls.
483 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
484 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
485 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
488 // There's never any support for operations beyond MVT::f32.
489 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
490 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
491 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
492 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
494 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
495 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
496 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
497 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
498 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
499 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
501 if (Subtarget->hasPOPCNT()) {
502 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
504 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
505 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
506 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
507 if (Subtarget->is64Bit())
508 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
511 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
513 if (!Subtarget->hasMOVBE())
514 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
516 // These should be promoted to a larger select which is supported.
517 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
518 // X86 wants to expand cmov itself.
519 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
520 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
521 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
523 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
524 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
527 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
529 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
530 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
531 if (Subtarget->is64Bit()) {
532 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
533 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
535 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
536 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
537 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
538 // support continuation, user-level threading, and etc.. As a result, no
539 // other SjLj exception interfaces are implemented and please don't build
540 // your own exception handling based on them.
541 // LLVM/Clang supports zero-cost DWARF exception handling.
542 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
543 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
546 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
547 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
548 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
549 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
550 if (Subtarget->is64Bit())
551 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
552 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
553 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
554 if (Subtarget->is64Bit()) {
555 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
556 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
557 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
558 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
559 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
561 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
562 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
565 if (Subtarget->is64Bit()) {
566 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
567 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
568 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
571 if (Subtarget->hasSSE1())
572 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
574 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
576 // Expand certain atomics
577 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
579 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
580 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
581 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
584 if (Subtarget->hasCmpxchg16b()) {
585 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
588 // FIXME - use subtarget debug flags
589 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
590 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
591 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
594 if (Subtarget->is64Bit()) {
595 setExceptionPointerRegister(X86::RAX);
596 setExceptionSelectorRegister(X86::RDX);
598 setExceptionPointerRegister(X86::EAX);
599 setExceptionSelectorRegister(X86::EDX);
601 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
602 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
604 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
605 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
607 setOperationAction(ISD::TRAP, MVT::Other, Legal);
608 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
610 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
611 setOperationAction(ISD::VASTART , MVT::Other, Custom);
612 setOperationAction(ISD::VAEND , MVT::Other, Expand);
613 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
614 // TargetInfo::X86_64ABIBuiltinVaList
615 setOperationAction(ISD::VAARG , MVT::Other, Custom);
616 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
618 // TargetInfo::CharPtrBuiltinVaList
619 setOperationAction(ISD::VAARG , MVT::Other, Expand);
620 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
623 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
624 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
626 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
628 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
629 // f32 and f64 use SSE.
630 // Set up the FP register classes.
631 addRegisterClass(MVT::f32, &X86::FR32RegClass);
632 addRegisterClass(MVT::f64, &X86::FR64RegClass);
634 // Use ANDPD to simulate FABS.
635 setOperationAction(ISD::FABS , MVT::f64, Custom);
636 setOperationAction(ISD::FABS , MVT::f32, Custom);
638 // Use XORP to simulate FNEG.
639 setOperationAction(ISD::FNEG , MVT::f64, Custom);
640 setOperationAction(ISD::FNEG , MVT::f32, Custom);
642 // Use ANDPD and ORPD to simulate FCOPYSIGN.
643 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
644 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
646 // Lower this to FGETSIGNx86 plus an AND.
647 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
648 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
650 // We don't support sin/cos/fmod
651 setOperationAction(ISD::FSIN , MVT::f64, Expand);
652 setOperationAction(ISD::FCOS , MVT::f64, Expand);
653 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
654 setOperationAction(ISD::FSIN , MVT::f32, Expand);
655 setOperationAction(ISD::FCOS , MVT::f32, Expand);
656 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
658 // Expand FP immediates into loads from the stack, except for the special
660 addLegalFPImmediate(APFloat(+0.0)); // xorpd
661 addLegalFPImmediate(APFloat(+0.0f)); // xorps
662 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
663 // Use SSE for f32, x87 for f64.
664 // Set up the FP register classes.
665 addRegisterClass(MVT::f32, &X86::FR32RegClass);
666 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
668 // Use ANDPS to simulate FABS.
669 setOperationAction(ISD::FABS , MVT::f32, Custom);
671 // Use XORP to simulate FNEG.
672 setOperationAction(ISD::FNEG , MVT::f32, Custom);
674 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
676 // Use ANDPS and ORPS to simulate FCOPYSIGN.
677 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
678 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
680 // We don't support sin/cos/fmod
681 setOperationAction(ISD::FSIN , MVT::f32, Expand);
682 setOperationAction(ISD::FCOS , MVT::f32, Expand);
683 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
685 // Special cases we handle for FP constants.
686 addLegalFPImmediate(APFloat(+0.0f)); // xorps
687 addLegalFPImmediate(APFloat(+0.0)); // FLD0
688 addLegalFPImmediate(APFloat(+1.0)); // FLD1
689 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
690 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
692 if (!TM.Options.UnsafeFPMath) {
693 setOperationAction(ISD::FSIN , MVT::f64, Expand);
694 setOperationAction(ISD::FCOS , MVT::f64, Expand);
695 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
697 } else if (!TM.Options.UseSoftFloat) {
698 // f32 and f64 in x87.
699 // Set up the FP register classes.
700 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
701 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
703 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
704 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
705 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
706 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
708 if (!TM.Options.UnsafeFPMath) {
709 setOperationAction(ISD::FSIN , MVT::f64, Expand);
710 setOperationAction(ISD::FSIN , MVT::f32, Expand);
711 setOperationAction(ISD::FCOS , MVT::f64, Expand);
712 setOperationAction(ISD::FCOS , MVT::f32, Expand);
713 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
714 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
716 addLegalFPImmediate(APFloat(+0.0)); // FLD0
717 addLegalFPImmediate(APFloat(+1.0)); // FLD1
718 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
719 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
720 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
721 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
722 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
723 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
726 // We don't support FMA.
727 setOperationAction(ISD::FMA, MVT::f64, Expand);
728 setOperationAction(ISD::FMA, MVT::f32, Expand);
730 // Long double always uses X87.
731 if (!TM.Options.UseSoftFloat) {
732 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
733 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
734 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
736 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
737 addLegalFPImmediate(TmpFlt); // FLD0
739 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
742 APFloat TmpFlt2(+1.0);
743 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
745 addLegalFPImmediate(TmpFlt2); // FLD1
746 TmpFlt2.changeSign();
747 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
750 if (!TM.Options.UnsafeFPMath) {
751 setOperationAction(ISD::FSIN , MVT::f80, Expand);
752 setOperationAction(ISD::FCOS , MVT::f80, Expand);
753 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
756 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
757 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
758 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
759 setOperationAction(ISD::FRINT, MVT::f80, Expand);
760 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
761 setOperationAction(ISD::FMA, MVT::f80, Expand);
764 // Always use a library call for pow.
765 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
766 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
767 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
769 setOperationAction(ISD::FLOG, MVT::f80, Expand);
770 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
771 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
772 setOperationAction(ISD::FEXP, MVT::f80, Expand);
773 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
774 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
775 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
777 // First set operation action for all vector types to either promote
778 // (for widening) or expand (for scalarization). Then we will selectively
779 // turn on ones that can be effectively codegen'd.
780 for (MVT VT : MVT::vector_valuetypes()) {
781 setOperationAction(ISD::ADD , VT, Expand);
782 setOperationAction(ISD::SUB , VT, Expand);
783 setOperationAction(ISD::FADD, VT, Expand);
784 setOperationAction(ISD::FNEG, VT, Expand);
785 setOperationAction(ISD::FSUB, VT, Expand);
786 setOperationAction(ISD::MUL , VT, Expand);
787 setOperationAction(ISD::FMUL, VT, Expand);
788 setOperationAction(ISD::SDIV, VT, Expand);
789 setOperationAction(ISD::UDIV, VT, Expand);
790 setOperationAction(ISD::FDIV, VT, Expand);
791 setOperationAction(ISD::SREM, VT, Expand);
792 setOperationAction(ISD::UREM, VT, Expand);
793 setOperationAction(ISD::LOAD, VT, Expand);
794 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
796 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
797 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
798 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
799 setOperationAction(ISD::FABS, VT, Expand);
800 setOperationAction(ISD::FSIN, VT, Expand);
801 setOperationAction(ISD::FSINCOS, VT, Expand);
802 setOperationAction(ISD::FCOS, VT, Expand);
803 setOperationAction(ISD::FSINCOS, VT, Expand);
804 setOperationAction(ISD::FREM, VT, Expand);
805 setOperationAction(ISD::FMA, VT, Expand);
806 setOperationAction(ISD::FPOWI, VT, Expand);
807 setOperationAction(ISD::FSQRT, VT, Expand);
808 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
809 setOperationAction(ISD::FFLOOR, VT, Expand);
810 setOperationAction(ISD::FCEIL, VT, Expand);
811 setOperationAction(ISD::FTRUNC, VT, Expand);
812 setOperationAction(ISD::FRINT, VT, Expand);
813 setOperationAction(ISD::FNEARBYINT, VT, Expand);
814 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
815 setOperationAction(ISD::MULHS, VT, Expand);
816 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
817 setOperationAction(ISD::MULHU, VT, Expand);
818 setOperationAction(ISD::SDIVREM, VT, Expand);
819 setOperationAction(ISD::UDIVREM, VT, Expand);
820 setOperationAction(ISD::FPOW, VT, Expand);
821 setOperationAction(ISD::CTPOP, VT, Expand);
822 setOperationAction(ISD::CTTZ, VT, Expand);
823 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
824 setOperationAction(ISD::CTLZ, VT, Expand);
825 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
826 setOperationAction(ISD::SHL, VT, Expand);
827 setOperationAction(ISD::SRA, VT, Expand);
828 setOperationAction(ISD::SRL, VT, Expand);
829 setOperationAction(ISD::ROTL, VT, Expand);
830 setOperationAction(ISD::ROTR, VT, Expand);
831 setOperationAction(ISD::BSWAP, VT, Expand);
832 setOperationAction(ISD::SETCC, VT, Expand);
833 setOperationAction(ISD::FLOG, VT, Expand);
834 setOperationAction(ISD::FLOG2, VT, Expand);
835 setOperationAction(ISD::FLOG10, VT, Expand);
836 setOperationAction(ISD::FEXP, VT, Expand);
837 setOperationAction(ISD::FEXP2, VT, Expand);
838 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
839 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
840 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
841 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
842 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
843 setOperationAction(ISD::TRUNCATE, VT, Expand);
844 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
845 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
846 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
847 setOperationAction(ISD::VSELECT, VT, Expand);
848 setOperationAction(ISD::SELECT_CC, VT, Expand);
849 for (MVT InnerVT : MVT::vector_valuetypes()) {
850 setTruncStoreAction(InnerVT, VT, Expand);
852 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
853 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
855 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
856 // types, we have to deal with them whether we ask for Expansion or not.
857 // Setting Expand causes its own optimisation problems though, so leave
859 if (VT.getVectorElementType() == MVT::i1)
860 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
864 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
865 // with -msoft-float, disable use of MMX as well.
866 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
867 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
868 // No operations on x86mmx supported, everything uses intrinsics.
871 // MMX-sized vectors (other than x86mmx) are expected to be expanded
872 // into smaller operations.
873 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
874 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
875 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
876 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
877 setOperationAction(ISD::AND, MVT::v8i8, Expand);
878 setOperationAction(ISD::AND, MVT::v4i16, Expand);
879 setOperationAction(ISD::AND, MVT::v2i32, Expand);
880 setOperationAction(ISD::AND, MVT::v1i64, Expand);
881 setOperationAction(ISD::OR, MVT::v8i8, Expand);
882 setOperationAction(ISD::OR, MVT::v4i16, Expand);
883 setOperationAction(ISD::OR, MVT::v2i32, Expand);
884 setOperationAction(ISD::OR, MVT::v1i64, Expand);
885 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
886 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
887 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
888 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
889 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
890 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
891 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
892 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
893 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
894 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
895 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
896 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
897 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
898 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
899 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
900 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
901 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
903 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
904 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
906 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
907 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
908 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
909 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
910 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
911 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
912 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
913 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
914 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
916 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
918 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
919 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
922 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
923 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
925 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
926 // registers cannot be used even for integer operations.
927 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
928 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
929 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
930 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
932 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
933 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
934 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
935 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
936 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
937 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
938 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
939 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
940 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
941 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
942 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
943 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
944 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
945 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
946 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
947 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
948 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
949 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
950 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
951 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
952 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
953 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
955 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
956 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
957 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
958 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
960 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
961 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
966 // Only provide customized ctpop vector bit twiddling for vector types we
967 // know to perform better than using the popcnt instructions on each vector
968 // element. If popcnt isn't supported, always provide the custom version.
969 if (!Subtarget->hasPOPCNT()) {
970 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
971 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
974 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
975 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
976 MVT VT = (MVT::SimpleValueType)i;
977 // Do not attempt to custom lower non-power-of-2 vectors
978 if (!isPowerOf2_32(VT.getVectorNumElements()))
980 // Do not attempt to custom lower non-128-bit vectors
981 if (!VT.is128BitVector())
983 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
984 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
985 setOperationAction(ISD::VSELECT, VT, Custom);
986 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
989 // We support custom legalizing of sext and anyext loads for specific
990 // memory vector types which we can load as a scalar (or sequence of
991 // scalars) and extend in-register to a legal 128-bit vector type. For sext
992 // loads these must work with a single scalar load.
993 for (MVT VT : MVT::integer_vector_valuetypes()) {
994 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
995 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
996 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
997 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
998 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
999 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
1000 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
1001 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
1002 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
1005 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1006 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1007 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1008 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1009 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1010 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1014 if (Subtarget->is64Bit()) {
1015 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1019 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1020 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1021 MVT VT = (MVT::SimpleValueType)i;
1023 // Do not attempt to promote non-128-bit vectors
1024 if (!VT.is128BitVector())
1027 setOperationAction(ISD::AND, VT, Promote);
1028 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1029 setOperationAction(ISD::OR, VT, Promote);
1030 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1031 setOperationAction(ISD::XOR, VT, Promote);
1032 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1033 setOperationAction(ISD::LOAD, VT, Promote);
1034 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1035 setOperationAction(ISD::SELECT, VT, Promote);
1036 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1039 // Custom lower v2i64 and v2f64 selects.
1040 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1041 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1042 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1043 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1045 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1046 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1048 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1049 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1050 // As there is no 64-bit GPR available, we need build a special custom
1051 // sequence to convert from v2i32 to v2f32.
1052 if (!Subtarget->is64Bit())
1053 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1055 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1056 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1058 for (MVT VT : MVT::fp_vector_valuetypes())
1059 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1061 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1062 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1063 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1066 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1067 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1068 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1069 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1070 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1071 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1072 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1073 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1074 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1075 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1076 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1078 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1079 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1080 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1081 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1082 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1083 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1084 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1085 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1086 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1087 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1089 // FIXME: Do we need to handle scalar-to-vector here?
1090 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1092 // We directly match byte blends in the backend as they match the VSELECT
1094 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1096 // SSE41 brings specific instructions for doing vector sign extend even in
1097 // cases where we don't have SRA.
1098 for (MVT VT : MVT::integer_vector_valuetypes()) {
1099 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1100 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1101 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1104 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1105 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1106 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1107 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1108 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1109 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1110 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1112 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1113 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1114 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1115 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1116 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1117 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1119 // i8 and i16 vectors are custom because the source register and source
1120 // source memory operand types are not the same width. f32 vectors are
1121 // custom since the immediate controlling the insert encodes additional
1123 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1124 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1125 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1126 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1128 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1129 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1130 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1131 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1133 // FIXME: these should be Legal, but that's only for the case where
1134 // the index is constant. For now custom expand to deal with that.
1135 if (Subtarget->is64Bit()) {
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1137 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1141 if (Subtarget->hasSSE2()) {
1142 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1143 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1145 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1146 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1148 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1149 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1151 // In the customized shift lowering, the legal cases in AVX2 will be
1153 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1154 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1156 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1157 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1159 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1162 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1163 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1164 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1165 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1166 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1167 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1168 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1170 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1171 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1172 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1174 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1175 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1176 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1177 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1178 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1179 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1180 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1181 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1182 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1183 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1184 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1185 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1187 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1188 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1189 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1190 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1191 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1192 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1193 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1194 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1195 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1196 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1197 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1198 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1200 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1201 // even though v8i16 is a legal type.
1202 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1203 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1204 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1206 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1207 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1208 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1210 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1211 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1213 for (MVT VT : MVT::fp_vector_valuetypes())
1214 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1216 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1217 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1219 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1220 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1222 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1223 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1225 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1226 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1227 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1228 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1230 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1231 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1232 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1234 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1235 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1236 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1237 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1238 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1239 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1240 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1241 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1242 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1243 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1244 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1245 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1247 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1248 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1249 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1250 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1251 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1252 setOperationAction(ISD::FMA, MVT::f32, Legal);
1253 setOperationAction(ISD::FMA, MVT::f64, Legal);
1256 if (Subtarget->hasInt256()) {
1257 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1258 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1259 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1260 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1262 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1263 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1264 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1265 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1267 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1268 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1269 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1270 // Don't lower v32i8 because there is no 128-bit byte mul
1272 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1273 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1274 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1275 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1277 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1278 // when we have a 256bit-wide blend with immediate.
1279 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1281 // Only provide customized ctpop vector bit twiddling for vector types we
1282 // know to perform better than using the popcnt instructions on each
1283 // vector element. If popcnt isn't supported, always provide the custom
1285 if (!Subtarget->hasPOPCNT())
1286 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1288 // Custom CTPOP always performs better on natively supported v8i32
1289 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1291 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1292 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1293 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1294 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1295 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1296 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1297 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1299 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1300 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1301 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1302 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1303 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1304 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1306 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1307 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1308 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1309 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1311 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1312 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1313 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1314 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1316 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1317 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1318 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1319 // Don't lower v32i8 because there is no 128-bit byte mul
1322 // In the customized shift lowering, the legal cases in AVX2 will be
1324 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1325 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1327 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1328 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1330 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1332 // Custom lower several nodes for 256-bit types.
1333 for (MVT VT : MVT::vector_valuetypes()) {
1334 if (VT.getScalarSizeInBits() >= 32) {
1335 setOperationAction(ISD::MLOAD, VT, Legal);
1336 setOperationAction(ISD::MSTORE, VT, Legal);
1338 // Extract subvector is special because the value type
1339 // (result) is 128-bit but the source is 256-bit wide.
1340 if (VT.is128BitVector()) {
1341 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1343 // Do not attempt to custom lower other non-256-bit vectors
1344 if (!VT.is256BitVector())
1347 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1348 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1349 setOperationAction(ISD::VSELECT, VT, Custom);
1350 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1352 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1353 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1354 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1357 if (Subtarget->hasInt256())
1358 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1361 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1362 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1363 MVT VT = (MVT::SimpleValueType)i;
1365 // Do not attempt to promote non-256-bit vectors
1366 if (!VT.is256BitVector())
1369 setOperationAction(ISD::AND, VT, Promote);
1370 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1371 setOperationAction(ISD::OR, VT, Promote);
1372 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1373 setOperationAction(ISD::XOR, VT, Promote);
1374 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1375 setOperationAction(ISD::LOAD, VT, Promote);
1376 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1377 setOperationAction(ISD::SELECT, VT, Promote);
1378 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1382 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1383 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1384 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1385 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1386 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1388 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1389 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1390 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1392 for (MVT VT : MVT::fp_vector_valuetypes())
1393 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1395 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1396 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1397 setOperationAction(ISD::XOR, MVT::i1, Legal);
1398 setOperationAction(ISD::OR, MVT::i1, Legal);
1399 setOperationAction(ISD::AND, MVT::i1, Legal);
1400 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1401 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1402 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1403 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1404 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1406 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1407 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1408 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1409 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1410 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1411 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1413 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1414 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1415 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1416 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1417 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1418 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1419 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1420 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1422 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1423 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1424 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1425 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1426 if (Subtarget->is64Bit()) {
1427 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1428 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1429 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1430 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1432 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1433 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1434 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1435 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1436 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1437 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1438 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1439 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1440 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1441 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1442 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1443 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1444 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1445 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1447 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1448 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1449 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1450 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1451 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1452 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1453 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1454 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1455 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1456 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1457 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1458 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1459 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1461 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1462 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1463 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1464 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1465 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1466 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1467 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1468 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1469 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1470 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1473 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1474 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1475 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1476 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1477 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1479 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1480 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1482 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1484 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1485 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1486 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1487 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1488 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1489 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1490 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1491 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1492 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1494 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1495 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1497 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1498 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1500 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1502 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1503 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1505 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1506 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1508 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1509 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1511 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1512 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1513 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1514 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1515 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1516 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1518 if (Subtarget->hasCDI()) {
1519 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1520 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1523 // Custom lower several nodes.
1524 for (MVT VT : MVT::vector_valuetypes()) {
1525 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1526 // Extract subvector is special because the value type
1527 // (result) is 256/128-bit but the source is 512-bit wide.
1528 if (VT.is128BitVector() || VT.is256BitVector()) {
1529 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1531 if (VT.getVectorElementType() == MVT::i1)
1532 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1534 // Do not attempt to custom lower other non-512-bit vectors
1535 if (!VT.is512BitVector())
1538 if ( EltSize >= 32) {
1539 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1540 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1541 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1542 setOperationAction(ISD::VSELECT, VT, Legal);
1543 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1544 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1545 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1546 setOperationAction(ISD::MLOAD, VT, Legal);
1547 setOperationAction(ISD::MSTORE, VT, Legal);
1550 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1551 MVT VT = (MVT::SimpleValueType)i;
1553 // Do not attempt to promote non-512-bit vectors.
1554 if (!VT.is512BitVector())
1557 setOperationAction(ISD::SELECT, VT, Promote);
1558 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1562 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1563 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1564 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1566 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1567 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1569 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1570 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1571 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1572 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1573 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1574 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1575 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1576 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1577 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1579 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1580 const MVT VT = (MVT::SimpleValueType)i;
1582 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1584 // Do not attempt to promote non-512-bit vectors.
1585 if (!VT.is512BitVector())
1589 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1590 setOperationAction(ISD::VSELECT, VT, Legal);
1595 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1596 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1597 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1599 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1600 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1601 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Legal);
1603 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1604 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1605 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1606 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1607 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1608 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1611 // We want to custom lower some of our intrinsics.
1612 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1613 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1614 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1615 if (!Subtarget->is64Bit())
1616 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1618 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1619 // handle type legalization for these operations here.
1621 // FIXME: We really should do custom legalization for addition and
1622 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1623 // than generic legalization for 64-bit multiplication-with-overflow, though.
1624 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1625 // Add/Sub/Mul with overflow operations are custom lowered.
1627 setOperationAction(ISD::SADDO, VT, Custom);
1628 setOperationAction(ISD::UADDO, VT, Custom);
1629 setOperationAction(ISD::SSUBO, VT, Custom);
1630 setOperationAction(ISD::USUBO, VT, Custom);
1631 setOperationAction(ISD::SMULO, VT, Custom);
1632 setOperationAction(ISD::UMULO, VT, Custom);
1636 if (!Subtarget->is64Bit()) {
1637 // These libcalls are not available in 32-bit.
1638 setLibcallName(RTLIB::SHL_I128, nullptr);
1639 setLibcallName(RTLIB::SRL_I128, nullptr);
1640 setLibcallName(RTLIB::SRA_I128, nullptr);
1643 // Combine sin / cos into one node or libcall if possible.
1644 if (Subtarget->hasSinCos()) {
1645 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1646 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1647 if (Subtarget->isTargetDarwin()) {
1648 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1649 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1650 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1651 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1655 if (Subtarget->isTargetWin64()) {
1656 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1657 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1658 setOperationAction(ISD::SREM, MVT::i128, Custom);
1659 setOperationAction(ISD::UREM, MVT::i128, Custom);
1660 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1661 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1664 // We have target-specific dag combine patterns for the following nodes:
1665 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1666 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1667 setTargetDAGCombine(ISD::BITCAST);
1668 setTargetDAGCombine(ISD::VSELECT);
1669 setTargetDAGCombine(ISD::SELECT);
1670 setTargetDAGCombine(ISD::SHL);
1671 setTargetDAGCombine(ISD::SRA);
1672 setTargetDAGCombine(ISD::SRL);
1673 setTargetDAGCombine(ISD::OR);
1674 setTargetDAGCombine(ISD::AND);
1675 setTargetDAGCombine(ISD::ADD);
1676 setTargetDAGCombine(ISD::FADD);
1677 setTargetDAGCombine(ISD::FSUB);
1678 setTargetDAGCombine(ISD::FMA);
1679 setTargetDAGCombine(ISD::SUB);
1680 setTargetDAGCombine(ISD::LOAD);
1681 setTargetDAGCombine(ISD::MLOAD);
1682 setTargetDAGCombine(ISD::STORE);
1683 setTargetDAGCombine(ISD::MSTORE);
1684 setTargetDAGCombine(ISD::ZERO_EXTEND);
1685 setTargetDAGCombine(ISD::ANY_EXTEND);
1686 setTargetDAGCombine(ISD::SIGN_EXTEND);
1687 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1688 setTargetDAGCombine(ISD::TRUNCATE);
1689 setTargetDAGCombine(ISD::SINT_TO_FP);
1690 setTargetDAGCombine(ISD::SETCC);
1691 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1692 setTargetDAGCombine(ISD::BUILD_VECTOR);
1693 setTargetDAGCombine(ISD::MUL);
1694 setTargetDAGCombine(ISD::XOR);
1696 computeRegisterProperties(Subtarget->getRegisterInfo());
1698 // On Darwin, -Os means optimize for size without hurting performance,
1699 // do not reduce the limit.
1700 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1701 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1702 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1703 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1704 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1705 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1706 setPrefLoopAlignment(4); // 2^4 bytes.
1708 // Predictable cmov don't hurt on atom because it's in-order.
1709 PredictableSelectIsExpensive = !Subtarget->isAtom();
1710 EnableExtLdPromotion = true;
1711 setPrefFunctionAlignment(4); // 2^4 bytes.
1713 verifyIntrinsicTables();
1716 // This has so far only been implemented for 64-bit MachO.
1717 bool X86TargetLowering::useLoadStackGuardNode() const {
1718 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1721 TargetLoweringBase::LegalizeTypeAction
1722 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1723 if (ExperimentalVectorWideningLegalization &&
1724 VT.getVectorNumElements() != 1 &&
1725 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1726 return TypeWidenVector;
1728 return TargetLoweringBase::getPreferredVectorAction(VT);
1731 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1733 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1735 const unsigned NumElts = VT.getVectorNumElements();
1736 const EVT EltVT = VT.getVectorElementType();
1737 if (VT.is512BitVector()) {
1738 if (Subtarget->hasAVX512())
1739 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1740 EltVT == MVT::f32 || EltVT == MVT::f64)
1742 case 8: return MVT::v8i1;
1743 case 16: return MVT::v16i1;
1745 if (Subtarget->hasBWI())
1746 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1748 case 32: return MVT::v32i1;
1749 case 64: return MVT::v64i1;
1753 if (VT.is256BitVector() || VT.is128BitVector()) {
1754 if (Subtarget->hasVLX())
1755 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1756 EltVT == MVT::f32 || EltVT == MVT::f64)
1758 case 2: return MVT::v2i1;
1759 case 4: return MVT::v4i1;
1760 case 8: return MVT::v8i1;
1762 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1763 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1765 case 8: return MVT::v8i1;
1766 case 16: return MVT::v16i1;
1767 case 32: return MVT::v32i1;
1771 return VT.changeVectorElementTypeToInteger();
1774 /// Helper for getByValTypeAlignment to determine
1775 /// the desired ByVal argument alignment.
1776 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1779 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1780 if (VTy->getBitWidth() == 128)
1782 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1783 unsigned EltAlign = 0;
1784 getMaxByValAlign(ATy->getElementType(), EltAlign);
1785 if (EltAlign > MaxAlign)
1786 MaxAlign = EltAlign;
1787 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1788 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1789 unsigned EltAlign = 0;
1790 getMaxByValAlign(STy->getElementType(i), EltAlign);
1791 if (EltAlign > MaxAlign)
1792 MaxAlign = EltAlign;
1799 /// Return the desired alignment for ByVal aggregate
1800 /// function arguments in the caller parameter area. For X86, aggregates
1801 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1802 /// are at 4-byte boundaries.
1803 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1804 if (Subtarget->is64Bit()) {
1805 // Max of 8 and alignment of type.
1806 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1813 if (Subtarget->hasSSE1())
1814 getMaxByValAlign(Ty, Align);
1818 /// Returns the target specific optimal type for load
1819 /// and store operations as a result of memset, memcpy, and memmove
1820 /// lowering. If DstAlign is zero that means it's safe to destination
1821 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1822 /// means there isn't a need to check it against alignment requirement,
1823 /// probably because the source does not need to be loaded. If 'IsMemset' is
1824 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1825 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1826 /// source is constant so it does not need to be loaded.
1827 /// It returns EVT::Other if the type should be determined using generic
1828 /// target-independent logic.
1830 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1831 unsigned DstAlign, unsigned SrcAlign,
1832 bool IsMemset, bool ZeroMemset,
1834 MachineFunction &MF) const {
1835 const Function *F = MF.getFunction();
1836 if ((!IsMemset || ZeroMemset) &&
1837 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1839 (Subtarget->isUnalignedMemAccessFast() ||
1840 ((DstAlign == 0 || DstAlign >= 16) &&
1841 (SrcAlign == 0 || SrcAlign >= 16)))) {
1843 if (Subtarget->hasInt256())
1845 if (Subtarget->hasFp256())
1848 if (Subtarget->hasSSE2())
1850 if (Subtarget->hasSSE1())
1852 } else if (!MemcpyStrSrc && Size >= 8 &&
1853 !Subtarget->is64Bit() &&
1854 Subtarget->hasSSE2()) {
1855 // Do not use f64 to lower memcpy if source is string constant. It's
1856 // better to use i32 to avoid the loads.
1860 if (Subtarget->is64Bit() && Size >= 8)
1865 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1867 return X86ScalarSSEf32;
1868 else if (VT == MVT::f64)
1869 return X86ScalarSSEf64;
1874 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1879 *Fast = Subtarget->isUnalignedMemAccessFast();
1883 /// Return the entry encoding for a jump table in the
1884 /// current function. The returned value is a member of the
1885 /// MachineJumpTableInfo::JTEntryKind enum.
1886 unsigned X86TargetLowering::getJumpTableEncoding() const {
1887 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1889 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1890 Subtarget->isPICStyleGOT())
1891 return MachineJumpTableInfo::EK_Custom32;
1893 // Otherwise, use the normal jump table encoding heuristics.
1894 return TargetLowering::getJumpTableEncoding();
1898 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1899 const MachineBasicBlock *MBB,
1900 unsigned uid,MCContext &Ctx) const{
1901 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1902 Subtarget->isPICStyleGOT());
1903 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1905 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1906 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1909 /// Returns relocation base for the given PIC jumptable.
1910 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1911 SelectionDAG &DAG) const {
1912 if (!Subtarget->is64Bit())
1913 // This doesn't have SDLoc associated with it, but is not really the
1914 // same as a Register.
1915 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1919 /// This returns the relocation base for the given PIC jumptable,
1920 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1921 const MCExpr *X86TargetLowering::
1922 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1923 MCContext &Ctx) const {
1924 // X86-64 uses RIP relative addressing based on the jump table label.
1925 if (Subtarget->isPICStyleRIPRel())
1926 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1928 // Otherwise, the reference is relative to the PIC base.
1929 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1932 std::pair<const TargetRegisterClass *, uint8_t>
1933 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1935 const TargetRegisterClass *RRC = nullptr;
1937 switch (VT.SimpleTy) {
1939 return TargetLowering::findRepresentativeClass(TRI, VT);
1940 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1941 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1944 RRC = &X86::VR64RegClass;
1946 case MVT::f32: case MVT::f64:
1947 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1948 case MVT::v4f32: case MVT::v2f64:
1949 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1951 RRC = &X86::VR128RegClass;
1954 return std::make_pair(RRC, Cost);
1957 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1958 unsigned &Offset) const {
1959 if (!Subtarget->isTargetLinux())
1962 if (Subtarget->is64Bit()) {
1963 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1965 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1977 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1978 unsigned DestAS) const {
1979 assert(SrcAS != DestAS && "Expected different address spaces!");
1981 return SrcAS < 256 && DestAS < 256;
1984 //===----------------------------------------------------------------------===//
1985 // Return Value Calling Convention Implementation
1986 //===----------------------------------------------------------------------===//
1988 #include "X86GenCallingConv.inc"
1991 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1992 MachineFunction &MF, bool isVarArg,
1993 const SmallVectorImpl<ISD::OutputArg> &Outs,
1994 LLVMContext &Context) const {
1995 SmallVector<CCValAssign, 16> RVLocs;
1996 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1997 return CCInfo.CheckReturn(Outs, RetCC_X86);
2000 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2001 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2006 X86TargetLowering::LowerReturn(SDValue Chain,
2007 CallingConv::ID CallConv, bool isVarArg,
2008 const SmallVectorImpl<ISD::OutputArg> &Outs,
2009 const SmallVectorImpl<SDValue> &OutVals,
2010 SDLoc dl, SelectionDAG &DAG) const {
2011 MachineFunction &MF = DAG.getMachineFunction();
2012 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2014 SmallVector<CCValAssign, 16> RVLocs;
2015 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2016 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2019 SmallVector<SDValue, 6> RetOps;
2020 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2021 // Operand #1 = Bytes To Pop
2022 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2025 // Copy the result values into the output registers.
2026 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2027 CCValAssign &VA = RVLocs[i];
2028 assert(VA.isRegLoc() && "Can only return in registers!");
2029 SDValue ValToCopy = OutVals[i];
2030 EVT ValVT = ValToCopy.getValueType();
2032 // Promote values to the appropriate types.
2033 if (VA.getLocInfo() == CCValAssign::SExt)
2034 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2035 else if (VA.getLocInfo() == CCValAssign::ZExt)
2036 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2037 else if (VA.getLocInfo() == CCValAssign::AExt)
2038 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2039 else if (VA.getLocInfo() == CCValAssign::BCvt)
2040 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2042 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2043 "Unexpected FP-extend for return value.");
2045 // If this is x86-64, and we disabled SSE, we can't return FP values,
2046 // or SSE or MMX vectors.
2047 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2048 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2049 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2050 report_fatal_error("SSE register return with SSE disabled");
2052 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2053 // llvm-gcc has never done it right and no one has noticed, so this
2054 // should be OK for now.
2055 if (ValVT == MVT::f64 &&
2056 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2057 report_fatal_error("SSE2 register return with SSE2 disabled");
2059 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2060 // the RET instruction and handled by the FP Stackifier.
2061 if (VA.getLocReg() == X86::FP0 ||
2062 VA.getLocReg() == X86::FP1) {
2063 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2064 // change the value to the FP stack register class.
2065 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2066 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2067 RetOps.push_back(ValToCopy);
2068 // Don't emit a copytoreg.
2072 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2073 // which is returned in RAX / RDX.
2074 if (Subtarget->is64Bit()) {
2075 if (ValVT == MVT::x86mmx) {
2076 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2077 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2078 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2080 // If we don't have SSE2 available, convert to v4f32 so the generated
2081 // register is legal.
2082 if (!Subtarget->hasSSE2())
2083 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2088 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2089 Flag = Chain.getValue(1);
2090 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2093 // The x86-64 ABIs require that for returning structs by value we copy
2094 // the sret argument into %rax/%eax (depending on ABI) for the return.
2095 // Win32 requires us to put the sret argument to %eax as well.
2096 // We saved the argument into a virtual register in the entry block,
2097 // so now we copy the value out and into %rax/%eax.
2099 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2100 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2101 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2102 // either case FuncInfo->setSRetReturnReg() will have been called.
2103 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2104 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2105 "No need for an sret register");
2106 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2109 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2110 X86::RAX : X86::EAX;
2111 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2112 Flag = Chain.getValue(1);
2114 // RAX/EAX now acts like a return value.
2115 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2118 RetOps[0] = Chain; // Update chain.
2120 // Add the flag if we have it.
2122 RetOps.push_back(Flag);
2124 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2127 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2128 if (N->getNumValues() != 1)
2130 if (!N->hasNUsesOfValue(1, 0))
2133 SDValue TCChain = Chain;
2134 SDNode *Copy = *N->use_begin();
2135 if (Copy->getOpcode() == ISD::CopyToReg) {
2136 // If the copy has a glue operand, we conservatively assume it isn't safe to
2137 // perform a tail call.
2138 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2140 TCChain = Copy->getOperand(0);
2141 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2144 bool HasRet = false;
2145 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2147 if (UI->getOpcode() != X86ISD::RET_FLAG)
2149 // If we are returning more than one value, we can definitely
2150 // not make a tail call see PR19530
2151 if (UI->getNumOperands() > 4)
2153 if (UI->getNumOperands() == 4 &&
2154 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2167 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2168 ISD::NodeType ExtendKind) const {
2170 // TODO: Is this also valid on 32-bit?
2171 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2172 ReturnMVT = MVT::i8;
2174 ReturnMVT = MVT::i32;
2176 EVT MinVT = getRegisterType(Context, ReturnMVT);
2177 return VT.bitsLT(MinVT) ? MinVT : VT;
2180 /// Lower the result values of a call into the
2181 /// appropriate copies out of appropriate physical registers.
2184 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2185 CallingConv::ID CallConv, bool isVarArg,
2186 const SmallVectorImpl<ISD::InputArg> &Ins,
2187 SDLoc dl, SelectionDAG &DAG,
2188 SmallVectorImpl<SDValue> &InVals) const {
2190 // Assign locations to each value returned by this call.
2191 SmallVector<CCValAssign, 16> RVLocs;
2192 bool Is64Bit = Subtarget->is64Bit();
2193 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2195 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2197 // Copy all of the result registers out of their specified physreg.
2198 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2199 CCValAssign &VA = RVLocs[i];
2200 EVT CopyVT = VA.getValVT();
2202 // If this is x86-64, and we disabled SSE, we can't return FP values
2203 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2204 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2205 report_fatal_error("SSE register return with SSE disabled");
2208 // If we prefer to use the value in xmm registers, copy it out as f80 and
2209 // use a truncate to move it from fp stack reg to xmm reg.
2210 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2211 isScalarFPTypeInSSEReg(VA.getValVT()))
2214 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2215 CopyVT, InFlag).getValue(1);
2216 SDValue Val = Chain.getValue(0);
2218 if (CopyVT != VA.getValVT())
2219 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2220 // This truncation won't change the value.
2221 DAG.getIntPtrConstant(1));
2223 InFlag = Chain.getValue(2);
2224 InVals.push_back(Val);
2230 //===----------------------------------------------------------------------===//
2231 // C & StdCall & Fast Calling Convention implementation
2232 //===----------------------------------------------------------------------===//
2233 // StdCall calling convention seems to be standard for many Windows' API
2234 // routines and around. It differs from C calling convention just a little:
2235 // callee should clean up the stack, not caller. Symbols should be also
2236 // decorated in some fancy way :) It doesn't support any vector arguments.
2237 // For info on fast calling convention see Fast Calling Convention (tail call)
2238 // implementation LowerX86_32FastCCCallTo.
2240 /// CallIsStructReturn - Determines whether a call uses struct return
2242 enum StructReturnType {
2247 static StructReturnType
2248 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2250 return NotStructReturn;
2252 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2253 if (!Flags.isSRet())
2254 return NotStructReturn;
2255 if (Flags.isInReg())
2256 return RegStructReturn;
2257 return StackStructReturn;
2260 /// Determines whether a function uses struct return semantics.
2261 static StructReturnType
2262 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2264 return NotStructReturn;
2266 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2267 if (!Flags.isSRet())
2268 return NotStructReturn;
2269 if (Flags.isInReg())
2270 return RegStructReturn;
2271 return StackStructReturn;
2274 /// Make a copy of an aggregate at address specified by "Src" to address
2275 /// "Dst" with size and alignment information specified by the specific
2276 /// parameter attribute. The copy will be passed as a byval function parameter.
2278 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2279 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2281 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2283 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2284 /*isVolatile*/false, /*AlwaysInline=*/true,
2285 MachinePointerInfo(), MachinePointerInfo());
2288 /// Return true if the calling convention is one that
2289 /// supports tail call optimization.
2290 static bool IsTailCallConvention(CallingConv::ID CC) {
2291 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2292 CC == CallingConv::HiPE);
2295 /// \brief Return true if the calling convention is a C calling convention.
2296 static bool IsCCallConvention(CallingConv::ID CC) {
2297 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2298 CC == CallingConv::X86_64_SysV);
2301 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2302 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2306 CallingConv::ID CalleeCC = CS.getCallingConv();
2307 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2313 /// Return true if the function is being made into
2314 /// a tailcall target by changing its ABI.
2315 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2316 bool GuaranteedTailCallOpt) {
2317 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2321 X86TargetLowering::LowerMemArgument(SDValue Chain,
2322 CallingConv::ID CallConv,
2323 const SmallVectorImpl<ISD::InputArg> &Ins,
2324 SDLoc dl, SelectionDAG &DAG,
2325 const CCValAssign &VA,
2326 MachineFrameInfo *MFI,
2328 // Create the nodes corresponding to a load from this parameter slot.
2329 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2330 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2331 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2332 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2335 // If value is passed by pointer we have address passed instead of the value
2337 if (VA.getLocInfo() == CCValAssign::Indirect)
2338 ValVT = VA.getLocVT();
2340 ValVT = VA.getValVT();
2342 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2343 // changed with more analysis.
2344 // In case of tail call optimization mark all arguments mutable. Since they
2345 // could be overwritten by lowering of arguments in case of a tail call.
2346 if (Flags.isByVal()) {
2347 unsigned Bytes = Flags.getByValSize();
2348 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2349 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2350 return DAG.getFrameIndex(FI, getPointerTy());
2352 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2353 VA.getLocMemOffset(), isImmutable);
2354 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2355 return DAG.getLoad(ValVT, dl, Chain, FIN,
2356 MachinePointerInfo::getFixedStack(FI),
2357 false, false, false, 0);
2361 // FIXME: Get this from tablegen.
2362 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2363 const X86Subtarget *Subtarget) {
2364 assert(Subtarget->is64Bit());
2366 if (Subtarget->isCallingConvWin64(CallConv)) {
2367 static const MCPhysReg GPR64ArgRegsWin64[] = {
2368 X86::RCX, X86::RDX, X86::R8, X86::R9
2370 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2373 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2374 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2376 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2379 // FIXME: Get this from tablegen.
2380 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2381 CallingConv::ID CallConv,
2382 const X86Subtarget *Subtarget) {
2383 assert(Subtarget->is64Bit());
2384 if (Subtarget->isCallingConvWin64(CallConv)) {
2385 // The XMM registers which might contain var arg parameters are shadowed
2386 // in their paired GPR. So we only need to save the GPR to their home
2388 // TODO: __vectorcall will change this.
2392 const Function *Fn = MF.getFunction();
2393 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2394 assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2395 "SSE register cannot be used when SSE is disabled!");
2396 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2397 !Subtarget->hasSSE1())
2398 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2402 static const MCPhysReg XMMArgRegs64Bit[] = {
2403 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2404 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2406 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2410 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2411 CallingConv::ID CallConv,
2413 const SmallVectorImpl<ISD::InputArg> &Ins,
2416 SmallVectorImpl<SDValue> &InVals)
2418 MachineFunction &MF = DAG.getMachineFunction();
2419 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2421 const Function* Fn = MF.getFunction();
2422 if (Fn->hasExternalLinkage() &&
2423 Subtarget->isTargetCygMing() &&
2424 Fn->getName() == "main")
2425 FuncInfo->setForceFramePointer(true);
2427 MachineFrameInfo *MFI = MF.getFrameInfo();
2428 bool Is64Bit = Subtarget->is64Bit();
2429 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2431 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2432 "Var args not supported with calling convention fastcc, ghc or hipe");
2434 // Assign locations to all of the incoming arguments.
2435 SmallVector<CCValAssign, 16> ArgLocs;
2436 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2438 // Allocate shadow area for Win64
2440 CCInfo.AllocateStack(32, 8);
2442 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2444 unsigned LastVal = ~0U;
2446 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2447 CCValAssign &VA = ArgLocs[i];
2448 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2450 assert(VA.getValNo() != LastVal &&
2451 "Don't support value assigned to multiple locs yet");
2453 LastVal = VA.getValNo();
2455 if (VA.isRegLoc()) {
2456 EVT RegVT = VA.getLocVT();
2457 const TargetRegisterClass *RC;
2458 if (RegVT == MVT::i32)
2459 RC = &X86::GR32RegClass;
2460 else if (Is64Bit && RegVT == MVT::i64)
2461 RC = &X86::GR64RegClass;
2462 else if (RegVT == MVT::f32)
2463 RC = &X86::FR32RegClass;
2464 else if (RegVT == MVT::f64)
2465 RC = &X86::FR64RegClass;
2466 else if (RegVT.is512BitVector())
2467 RC = &X86::VR512RegClass;
2468 else if (RegVT.is256BitVector())
2469 RC = &X86::VR256RegClass;
2470 else if (RegVT.is128BitVector())
2471 RC = &X86::VR128RegClass;
2472 else if (RegVT == MVT::x86mmx)
2473 RC = &X86::VR64RegClass;
2474 else if (RegVT == MVT::i1)
2475 RC = &X86::VK1RegClass;
2476 else if (RegVT == MVT::v8i1)
2477 RC = &X86::VK8RegClass;
2478 else if (RegVT == MVT::v16i1)
2479 RC = &X86::VK16RegClass;
2480 else if (RegVT == MVT::v32i1)
2481 RC = &X86::VK32RegClass;
2482 else if (RegVT == MVT::v64i1)
2483 RC = &X86::VK64RegClass;
2485 llvm_unreachable("Unknown argument type!");
2487 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2488 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2490 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2491 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2493 if (VA.getLocInfo() == CCValAssign::SExt)
2494 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2495 DAG.getValueType(VA.getValVT()));
2496 else if (VA.getLocInfo() == CCValAssign::ZExt)
2497 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2498 DAG.getValueType(VA.getValVT()));
2499 else if (VA.getLocInfo() == CCValAssign::BCvt)
2500 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2502 if (VA.isExtInLoc()) {
2503 // Handle MMX values passed in XMM regs.
2504 if (RegVT.isVector())
2505 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2507 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2510 assert(VA.isMemLoc());
2511 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2514 // If value is passed via pointer - do a load.
2515 if (VA.getLocInfo() == CCValAssign::Indirect)
2516 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2517 MachinePointerInfo(), false, false, false, 0);
2519 InVals.push_back(ArgValue);
2522 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2523 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2524 // The x86-64 ABIs require that for returning structs by value we copy
2525 // the sret argument into %rax/%eax (depending on ABI) for the return.
2526 // Win32 requires us to put the sret argument to %eax as well.
2527 // Save the argument into a virtual register so that we can access it
2528 // from the return points.
2529 if (Ins[i].Flags.isSRet()) {
2530 unsigned Reg = FuncInfo->getSRetReturnReg();
2532 MVT PtrTy = getPointerTy();
2533 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2534 FuncInfo->setSRetReturnReg(Reg);
2536 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2537 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2543 unsigned StackSize = CCInfo.getNextStackOffset();
2544 // Align stack specially for tail calls.
2545 if (FuncIsMadeTailCallSafe(CallConv,
2546 MF.getTarget().Options.GuaranteedTailCallOpt))
2547 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2549 // If the function takes variable number of arguments, make a frame index for
2550 // the start of the first vararg value... for expansion of llvm.va_start. We
2551 // can skip this if there are no va_start calls.
2552 if (MFI->hasVAStart() &&
2553 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2554 CallConv != CallingConv::X86_ThisCall))) {
2555 FuncInfo->setVarArgsFrameIndex(
2556 MFI->CreateFixedObject(1, StackSize, true));
2559 // Figure out if XMM registers are in use.
2560 assert(!(MF.getTarget().Options.UseSoftFloat &&
2561 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2562 "SSE register cannot be used when SSE is disabled!");
2564 // 64-bit calling conventions support varargs and register parameters, so we
2565 // have to do extra work to spill them in the prologue.
2566 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2567 // Find the first unallocated argument registers.
2568 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2569 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2570 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2571 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2572 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2573 "SSE register cannot be used when SSE is disabled!");
2575 // Gather all the live in physical registers.
2576 SmallVector<SDValue, 6> LiveGPRs;
2577 SmallVector<SDValue, 8> LiveXMMRegs;
2579 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2580 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2582 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2584 if (!ArgXMMs.empty()) {
2585 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2586 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2587 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2588 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2589 LiveXMMRegs.push_back(
2590 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2595 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2596 // Get to the caller-allocated home save location. Add 8 to account
2597 // for the return address.
2598 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2599 FuncInfo->setRegSaveFrameIndex(
2600 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2601 // Fixup to set vararg frame on shadow area (4 x i64).
2603 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2605 // For X86-64, if there are vararg parameters that are passed via
2606 // registers, then we must store them to their spots on the stack so
2607 // they may be loaded by deferencing the result of va_next.
2608 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2609 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2610 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2611 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2614 // Store the integer parameter registers.
2615 SmallVector<SDValue, 8> MemOps;
2616 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2618 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2619 for (SDValue Val : LiveGPRs) {
2620 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2621 DAG.getIntPtrConstant(Offset));
2623 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2624 MachinePointerInfo::getFixedStack(
2625 FuncInfo->getRegSaveFrameIndex(), Offset),
2627 MemOps.push_back(Store);
2631 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2632 // Now store the XMM (fp + vector) parameter registers.
2633 SmallVector<SDValue, 12> SaveXMMOps;
2634 SaveXMMOps.push_back(Chain);
2635 SaveXMMOps.push_back(ALVal);
2636 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2637 FuncInfo->getRegSaveFrameIndex()));
2638 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2639 FuncInfo->getVarArgsFPOffset()));
2640 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2642 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2643 MVT::Other, SaveXMMOps));
2646 if (!MemOps.empty())
2647 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2650 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2651 // Find the largest legal vector type.
2652 MVT VecVT = MVT::Other;
2653 // FIXME: Only some x86_32 calling conventions support AVX512.
2654 if (Subtarget->hasAVX512() &&
2655 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2656 CallConv == CallingConv::Intel_OCL_BI)))
2657 VecVT = MVT::v16f32;
2658 else if (Subtarget->hasAVX())
2660 else if (Subtarget->hasSSE2())
2663 // We forward some GPRs and some vector types.
2664 SmallVector<MVT, 2> RegParmTypes;
2665 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2666 RegParmTypes.push_back(IntVT);
2667 if (VecVT != MVT::Other)
2668 RegParmTypes.push_back(VecVT);
2670 // Compute the set of forwarded registers. The rest are scratch.
2671 SmallVectorImpl<ForwardedRegister> &Forwards =
2672 FuncInfo->getForwardedMustTailRegParms();
2673 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2675 // Conservatively forward AL on x86_64, since it might be used for varargs.
2676 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2677 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2678 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2681 // Copy all forwards from physical to virtual registers.
2682 for (ForwardedRegister &F : Forwards) {
2683 // FIXME: Can we use a less constrained schedule?
2684 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2685 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2686 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2690 // Some CCs need callee pop.
2691 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2692 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2693 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2695 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2696 // If this is an sret function, the return should pop the hidden pointer.
2697 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2698 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2699 argsAreStructReturn(Ins) == StackStructReturn)
2700 FuncInfo->setBytesToPopOnReturn(4);
2704 // RegSaveFrameIndex is X86-64 only.
2705 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2706 if (CallConv == CallingConv::X86_FastCall ||
2707 CallConv == CallingConv::X86_ThisCall)
2708 // fastcc functions can't have varargs.
2709 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2712 FuncInfo->setArgumentStackSize(StackSize);
2718 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2719 SDValue StackPtr, SDValue Arg,
2720 SDLoc dl, SelectionDAG &DAG,
2721 const CCValAssign &VA,
2722 ISD::ArgFlagsTy Flags) const {
2723 unsigned LocMemOffset = VA.getLocMemOffset();
2724 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2725 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2726 if (Flags.isByVal())
2727 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2729 return DAG.getStore(Chain, dl, Arg, PtrOff,
2730 MachinePointerInfo::getStack(LocMemOffset),
2734 /// Emit a load of return address if tail call
2735 /// optimization is performed and it is required.
2737 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2738 SDValue &OutRetAddr, SDValue Chain,
2739 bool IsTailCall, bool Is64Bit,
2740 int FPDiff, SDLoc dl) const {
2741 // Adjust the Return address stack slot.
2742 EVT VT = getPointerTy();
2743 OutRetAddr = getReturnAddressFrameIndex(DAG);
2745 // Load the "old" Return address.
2746 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2747 false, false, false, 0);
2748 return SDValue(OutRetAddr.getNode(), 1);
2751 /// Emit a store of the return address if tail call
2752 /// optimization is performed and it is required (FPDiff!=0).
2753 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2754 SDValue Chain, SDValue RetAddrFrIdx,
2755 EVT PtrVT, unsigned SlotSize,
2756 int FPDiff, SDLoc dl) {
2757 // Store the return address to the appropriate stack slot.
2758 if (!FPDiff) return Chain;
2759 // Calculate the new stack slot for the return address.
2760 int NewReturnAddrFI =
2761 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2763 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2764 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2765 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2771 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2772 SmallVectorImpl<SDValue> &InVals) const {
2773 SelectionDAG &DAG = CLI.DAG;
2775 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2776 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2777 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2778 SDValue Chain = CLI.Chain;
2779 SDValue Callee = CLI.Callee;
2780 CallingConv::ID CallConv = CLI.CallConv;
2781 bool &isTailCall = CLI.IsTailCall;
2782 bool isVarArg = CLI.IsVarArg;
2784 MachineFunction &MF = DAG.getMachineFunction();
2785 bool Is64Bit = Subtarget->is64Bit();
2786 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2787 StructReturnType SR = callIsStructReturn(Outs);
2788 bool IsSibcall = false;
2789 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2791 if (MF.getTarget().Options.DisableTailCalls)
2794 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2796 // Force this to be a tail call. The verifier rules are enough to ensure
2797 // that we can lower this successfully without moving the return address
2800 } else if (isTailCall) {
2801 // Check if it's really possible to do a tail call.
2802 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2803 isVarArg, SR != NotStructReturn,
2804 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2805 Outs, OutVals, Ins, DAG);
2807 // Sibcalls are automatically detected tailcalls which do not require
2809 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2816 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2817 "Var args not supported with calling convention fastcc, ghc or hipe");
2819 // Analyze operands of the call, assigning locations to each operand.
2820 SmallVector<CCValAssign, 16> ArgLocs;
2821 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2823 // Allocate shadow area for Win64
2825 CCInfo.AllocateStack(32, 8);
2827 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2829 // Get a count of how many bytes are to be pushed on the stack.
2830 unsigned NumBytes = CCInfo.getNextStackOffset();
2832 // This is a sibcall. The memory operands are available in caller's
2833 // own caller's stack.
2835 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2836 IsTailCallConvention(CallConv))
2837 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2840 if (isTailCall && !IsSibcall && !IsMustTail) {
2841 // Lower arguments at fp - stackoffset + fpdiff.
2842 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2844 FPDiff = NumBytesCallerPushed - NumBytes;
2846 // Set the delta of movement of the returnaddr stackslot.
2847 // But only set if delta is greater than previous delta.
2848 if (FPDiff < X86Info->getTCReturnAddrDelta())
2849 X86Info->setTCReturnAddrDelta(FPDiff);
2852 unsigned NumBytesToPush = NumBytes;
2853 unsigned NumBytesToPop = NumBytes;
2855 // If we have an inalloca argument, all stack space has already been allocated
2856 // for us and be right at the top of the stack. We don't support multiple
2857 // arguments passed in memory when using inalloca.
2858 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2860 if (!ArgLocs.back().isMemLoc())
2861 report_fatal_error("cannot use inalloca attribute on a register "
2863 if (ArgLocs.back().getLocMemOffset() != 0)
2864 report_fatal_error("any parameter with the inalloca attribute must be "
2865 "the only memory argument");
2869 Chain = DAG.getCALLSEQ_START(
2870 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2872 SDValue RetAddrFrIdx;
2873 // Load return address for tail calls.
2874 if (isTailCall && FPDiff)
2875 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2876 Is64Bit, FPDiff, dl);
2878 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2879 SmallVector<SDValue, 8> MemOpChains;
2882 // Walk the register/memloc assignments, inserting copies/loads. In the case
2883 // of tail call optimization arguments are handle later.
2884 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2885 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2886 // Skip inalloca arguments, they have already been written.
2887 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2888 if (Flags.isInAlloca())
2891 CCValAssign &VA = ArgLocs[i];
2892 EVT RegVT = VA.getLocVT();
2893 SDValue Arg = OutVals[i];
2894 bool isByVal = Flags.isByVal();
2896 // Promote the value if needed.
2897 switch (VA.getLocInfo()) {
2898 default: llvm_unreachable("Unknown loc info!");
2899 case CCValAssign::Full: break;
2900 case CCValAssign::SExt:
2901 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2903 case CCValAssign::ZExt:
2904 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2906 case CCValAssign::AExt:
2907 if (RegVT.is128BitVector()) {
2908 // Special case: passing MMX values in XMM registers.
2909 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2910 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2911 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2913 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2915 case CCValAssign::BCvt:
2916 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2918 case CCValAssign::Indirect: {
2919 // Store the argument.
2920 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2921 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2922 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2923 MachinePointerInfo::getFixedStack(FI),
2930 if (VA.isRegLoc()) {
2931 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2932 if (isVarArg && IsWin64) {
2933 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2934 // shadow reg if callee is a varargs function.
2935 unsigned ShadowReg = 0;
2936 switch (VA.getLocReg()) {
2937 case X86::XMM0: ShadowReg = X86::RCX; break;
2938 case X86::XMM1: ShadowReg = X86::RDX; break;
2939 case X86::XMM2: ShadowReg = X86::R8; break;
2940 case X86::XMM3: ShadowReg = X86::R9; break;
2943 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2945 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2946 assert(VA.isMemLoc());
2947 if (!StackPtr.getNode())
2948 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2950 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2951 dl, DAG, VA, Flags));
2955 if (!MemOpChains.empty())
2956 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2958 if (Subtarget->isPICStyleGOT()) {
2959 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2962 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2963 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2965 // If we are tail calling and generating PIC/GOT style code load the
2966 // address of the callee into ECX. The value in ecx is used as target of
2967 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2968 // for tail calls on PIC/GOT architectures. Normally we would just put the
2969 // address of GOT into ebx and then call target@PLT. But for tail calls
2970 // ebx would be restored (since ebx is callee saved) before jumping to the
2973 // Note: The actual moving to ECX is done further down.
2974 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2975 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2976 !G->getGlobal()->hasProtectedVisibility())
2977 Callee = LowerGlobalAddress(Callee, DAG);
2978 else if (isa<ExternalSymbolSDNode>(Callee))
2979 Callee = LowerExternalSymbol(Callee, DAG);
2983 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2984 // From AMD64 ABI document:
2985 // For calls that may call functions that use varargs or stdargs
2986 // (prototype-less calls or calls to functions containing ellipsis (...) in
2987 // the declaration) %al is used as hidden argument to specify the number
2988 // of SSE registers used. The contents of %al do not need to match exactly
2989 // the number of registers, but must be an ubound on the number of SSE
2990 // registers used and is in the range 0 - 8 inclusive.
2992 // Count the number of XMM registers allocated.
2993 static const MCPhysReg XMMArgRegs[] = {
2994 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2995 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2997 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2998 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2999 && "SSE registers cannot be used when SSE is disabled");
3001 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3002 DAG.getConstant(NumXMMRegs, MVT::i8)));
3005 if (isVarArg && IsMustTail) {
3006 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3007 for (const auto &F : Forwards) {
3008 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3009 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3013 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3014 // don't need this because the eligibility check rejects calls that require
3015 // shuffling arguments passed in memory.
3016 if (!IsSibcall && isTailCall) {
3017 // Force all the incoming stack arguments to be loaded from the stack
3018 // before any new outgoing arguments are stored to the stack, because the
3019 // outgoing stack slots may alias the incoming argument stack slots, and
3020 // the alias isn't otherwise explicit. This is slightly more conservative
3021 // than necessary, because it means that each store effectively depends
3022 // on every argument instead of just those arguments it would clobber.
3023 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3025 SmallVector<SDValue, 8> MemOpChains2;
3028 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3029 CCValAssign &VA = ArgLocs[i];
3032 assert(VA.isMemLoc());
3033 SDValue Arg = OutVals[i];
3034 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3035 // Skip inalloca arguments. They don't require any work.
3036 if (Flags.isInAlloca())
3038 // Create frame index.
3039 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3040 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3041 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3042 FIN = DAG.getFrameIndex(FI, getPointerTy());
3044 if (Flags.isByVal()) {
3045 // Copy relative to framepointer.
3046 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3047 if (!StackPtr.getNode())
3048 StackPtr = DAG.getCopyFromReg(Chain, dl,
3049 RegInfo->getStackRegister(),
3051 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3053 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3057 // Store relative to framepointer.
3058 MemOpChains2.push_back(
3059 DAG.getStore(ArgChain, dl, Arg, FIN,
3060 MachinePointerInfo::getFixedStack(FI),
3065 if (!MemOpChains2.empty())
3066 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3068 // Store the return address to the appropriate stack slot.
3069 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3070 getPointerTy(), RegInfo->getSlotSize(),
3074 // Build a sequence of copy-to-reg nodes chained together with token chain
3075 // and flag operands which copy the outgoing args into registers.
3077 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3078 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3079 RegsToPass[i].second, InFlag);
3080 InFlag = Chain.getValue(1);
3083 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3084 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3085 // In the 64-bit large code model, we have to make all calls
3086 // through a register, since the call instruction's 32-bit
3087 // pc-relative offset may not be large enough to hold the whole
3089 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3090 // If the callee is a GlobalAddress node (quite common, every direct call
3091 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3093 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3095 // We should use extra load for direct calls to dllimported functions in
3097 const GlobalValue *GV = G->getGlobal();
3098 if (!GV->hasDLLImportStorageClass()) {
3099 unsigned char OpFlags = 0;
3100 bool ExtraLoad = false;
3101 unsigned WrapperKind = ISD::DELETED_NODE;
3103 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3104 // external symbols most go through the PLT in PIC mode. If the symbol
3105 // has hidden or protected visibility, or if it is static or local, then
3106 // we don't need to use the PLT - we can directly call it.
3107 if (Subtarget->isTargetELF() &&
3108 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3109 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3110 OpFlags = X86II::MO_PLT;
3111 } else if (Subtarget->isPICStyleStubAny() &&
3112 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3113 (!Subtarget->getTargetTriple().isMacOSX() ||
3114 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3115 // PC-relative references to external symbols should go through $stub,
3116 // unless we're building with the leopard linker or later, which
3117 // automatically synthesizes these stubs.
3118 OpFlags = X86II::MO_DARWIN_STUB;
3119 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3120 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3121 // If the function is marked as non-lazy, generate an indirect call
3122 // which loads from the GOT directly. This avoids runtime overhead
3123 // at the cost of eager binding (and one extra byte of encoding).
3124 OpFlags = X86II::MO_GOTPCREL;
3125 WrapperKind = X86ISD::WrapperRIP;
3129 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3130 G->getOffset(), OpFlags);
3132 // Add a wrapper if needed.
3133 if (WrapperKind != ISD::DELETED_NODE)
3134 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3135 // Add extra indirection if needed.
3137 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3138 MachinePointerInfo::getGOT(),
3139 false, false, false, 0);
3141 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3142 unsigned char OpFlags = 0;
3144 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3145 // external symbols should go through the PLT.
3146 if (Subtarget->isTargetELF() &&
3147 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3148 OpFlags = X86II::MO_PLT;
3149 } else if (Subtarget->isPICStyleStubAny() &&
3150 (!Subtarget->getTargetTriple().isMacOSX() ||
3151 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3152 // PC-relative references to external symbols should go through $stub,
3153 // unless we're building with the leopard linker or later, which
3154 // automatically synthesizes these stubs.
3155 OpFlags = X86II::MO_DARWIN_STUB;
3158 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3160 } else if (Subtarget->isTarget64BitILP32() &&
3161 Callee->getValueType(0) == MVT::i32) {
3162 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3163 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3166 // Returns a chain & a flag for retval copy to use.
3167 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3168 SmallVector<SDValue, 8> Ops;
3170 if (!IsSibcall && isTailCall) {
3171 Chain = DAG.getCALLSEQ_END(Chain,
3172 DAG.getIntPtrConstant(NumBytesToPop, true),
3173 DAG.getIntPtrConstant(0, true), InFlag, dl);
3174 InFlag = Chain.getValue(1);
3177 Ops.push_back(Chain);
3178 Ops.push_back(Callee);
3181 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3183 // Add argument registers to the end of the list so that they are known live
3185 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3186 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3187 RegsToPass[i].second.getValueType()));
3189 // Add a register mask operand representing the call-preserved registers.
3190 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3191 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3192 assert(Mask && "Missing call preserved mask for calling convention");
3193 Ops.push_back(DAG.getRegisterMask(Mask));
3195 if (InFlag.getNode())
3196 Ops.push_back(InFlag);
3200 //// If this is the first return lowered for this function, add the regs
3201 //// to the liveout set for the function.
3202 // This isn't right, although it's probably harmless on x86; liveouts
3203 // should be computed from returns not tail calls. Consider a void
3204 // function making a tail call to a function returning int.
3205 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3208 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3209 InFlag = Chain.getValue(1);
3211 // Create the CALLSEQ_END node.
3212 unsigned NumBytesForCalleeToPop;
3213 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3214 DAG.getTarget().Options.GuaranteedTailCallOpt))
3215 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3216 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3217 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3218 SR == StackStructReturn)
3219 // If this is a call to a struct-return function, the callee
3220 // pops the hidden struct pointer, so we have to push it back.
3221 // This is common for Darwin/X86, Linux & Mingw32 targets.
3222 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3223 NumBytesForCalleeToPop = 4;
3225 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3227 // Returns a flag for retval copy to use.
3229 Chain = DAG.getCALLSEQ_END(Chain,
3230 DAG.getIntPtrConstant(NumBytesToPop, true),
3231 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3234 InFlag = Chain.getValue(1);
3237 // Handle result values, copying them out of physregs into vregs that we
3239 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3240 Ins, dl, DAG, InVals);
3243 //===----------------------------------------------------------------------===//
3244 // Fast Calling Convention (tail call) implementation
3245 //===----------------------------------------------------------------------===//
3247 // Like std call, callee cleans arguments, convention except that ECX is
3248 // reserved for storing the tail called function address. Only 2 registers are
3249 // free for argument passing (inreg). Tail call optimization is performed
3251 // * tailcallopt is enabled
3252 // * caller/callee are fastcc
3253 // On X86_64 architecture with GOT-style position independent code only local
3254 // (within module) calls are supported at the moment.
3255 // To keep the stack aligned according to platform abi the function
3256 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3257 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3258 // If a tail called function callee has more arguments than the caller the
3259 // caller needs to make sure that there is room to move the RETADDR to. This is
3260 // achieved by reserving an area the size of the argument delta right after the
3261 // original RETADDR, but before the saved framepointer or the spilled registers
3262 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3274 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3275 /// for a 16 byte align requirement.
3277 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3278 SelectionDAG& DAG) const {
3279 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3280 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3281 unsigned StackAlignment = TFI.getStackAlignment();
3282 uint64_t AlignMask = StackAlignment - 1;
3283 int64_t Offset = StackSize;
3284 unsigned SlotSize = RegInfo->getSlotSize();
3285 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3286 // Number smaller than 12 so just add the difference.
3287 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3289 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3290 Offset = ((~AlignMask) & Offset) + StackAlignment +
3291 (StackAlignment-SlotSize);
3296 /// MatchingStackOffset - Return true if the given stack call argument is
3297 /// already available in the same position (relatively) of the caller's
3298 /// incoming argument stack.
3300 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3301 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3302 const X86InstrInfo *TII) {
3303 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3305 if (Arg.getOpcode() == ISD::CopyFromReg) {
3306 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3307 if (!TargetRegisterInfo::isVirtualRegister(VR))
3309 MachineInstr *Def = MRI->getVRegDef(VR);
3312 if (!Flags.isByVal()) {
3313 if (!TII->isLoadFromStackSlot(Def, FI))
3316 unsigned Opcode = Def->getOpcode();
3317 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3318 Opcode == X86::LEA64_32r) &&
3319 Def->getOperand(1).isFI()) {
3320 FI = Def->getOperand(1).getIndex();
3321 Bytes = Flags.getByValSize();
3325 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3326 if (Flags.isByVal())
3327 // ByVal argument is passed in as a pointer but it's now being
3328 // dereferenced. e.g.
3329 // define @foo(%struct.X* %A) {
3330 // tail call @bar(%struct.X* byval %A)
3333 SDValue Ptr = Ld->getBasePtr();
3334 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3337 FI = FINode->getIndex();
3338 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3339 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3340 FI = FINode->getIndex();
3341 Bytes = Flags.getByValSize();
3345 assert(FI != INT_MAX);
3346 if (!MFI->isFixedObjectIndex(FI))
3348 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3351 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3352 /// for tail call optimization. Targets which want to do tail call
3353 /// optimization should implement this function.
3355 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3356 CallingConv::ID CalleeCC,
3358 bool isCalleeStructRet,
3359 bool isCallerStructRet,
3361 const SmallVectorImpl<ISD::OutputArg> &Outs,
3362 const SmallVectorImpl<SDValue> &OutVals,
3363 const SmallVectorImpl<ISD::InputArg> &Ins,
3364 SelectionDAG &DAG) const {
3365 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3368 // If -tailcallopt is specified, make fastcc functions tail-callable.
3369 const MachineFunction &MF = DAG.getMachineFunction();
3370 const Function *CallerF = MF.getFunction();
3372 // If the function return type is x86_fp80 and the callee return type is not,
3373 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3374 // perform a tailcall optimization here.
3375 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3378 CallingConv::ID CallerCC = CallerF->getCallingConv();
3379 bool CCMatch = CallerCC == CalleeCC;
3380 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3381 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3383 // Win64 functions have extra shadow space for argument homing. Don't do the
3384 // sibcall if the caller and callee have mismatched expectations for this
3386 if (IsCalleeWin64 != IsCallerWin64)
3389 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3390 if (IsTailCallConvention(CalleeCC) && CCMatch)
3395 // Look for obvious safe cases to perform tail call optimization that do not
3396 // require ABI changes. This is what gcc calls sibcall.
3398 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3399 // emit a special epilogue.
3400 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3401 if (RegInfo->needsStackRealignment(MF))
3404 // Also avoid sibcall optimization if either caller or callee uses struct
3405 // return semantics.
3406 if (isCalleeStructRet || isCallerStructRet)
3409 // An stdcall/thiscall caller is expected to clean up its arguments; the
3410 // callee isn't going to do that.
3411 // FIXME: this is more restrictive than needed. We could produce a tailcall
3412 // when the stack adjustment matches. For example, with a thiscall that takes
3413 // only one argument.
3414 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3415 CallerCC == CallingConv::X86_ThisCall))
3418 // Do not sibcall optimize vararg calls unless all arguments are passed via
3420 if (isVarArg && !Outs.empty()) {
3422 // Optimizing for varargs on Win64 is unlikely to be safe without
3423 // additional testing.
3424 if (IsCalleeWin64 || IsCallerWin64)
3427 SmallVector<CCValAssign, 16> ArgLocs;
3428 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3431 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3432 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3433 if (!ArgLocs[i].isRegLoc())
3437 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3438 // stack. Therefore, if it's not used by the call it is not safe to optimize
3439 // this into a sibcall.
3440 bool Unused = false;
3441 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3448 SmallVector<CCValAssign, 16> RVLocs;
3449 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3451 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3452 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3453 CCValAssign &VA = RVLocs[i];
3454 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3459 // If the calling conventions do not match, then we'd better make sure the
3460 // results are returned in the same way as what the caller expects.
3462 SmallVector<CCValAssign, 16> RVLocs1;
3463 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3465 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3467 SmallVector<CCValAssign, 16> RVLocs2;
3468 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3470 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3472 if (RVLocs1.size() != RVLocs2.size())
3474 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3475 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3477 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3479 if (RVLocs1[i].isRegLoc()) {
3480 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3483 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3489 // If the callee takes no arguments then go on to check the results of the
3491 if (!Outs.empty()) {
3492 // Check if stack adjustment is needed. For now, do not do this if any
3493 // argument is passed on the stack.
3494 SmallVector<CCValAssign, 16> ArgLocs;
3495 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3498 // Allocate shadow area for Win64
3500 CCInfo.AllocateStack(32, 8);
3502 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3503 if (CCInfo.getNextStackOffset()) {
3504 MachineFunction &MF = DAG.getMachineFunction();
3505 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3508 // Check if the arguments are already laid out in the right way as
3509 // the caller's fixed stack objects.
3510 MachineFrameInfo *MFI = MF.getFrameInfo();
3511 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3512 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3513 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3514 CCValAssign &VA = ArgLocs[i];
3515 SDValue Arg = OutVals[i];
3516 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3517 if (VA.getLocInfo() == CCValAssign::Indirect)
3519 if (!VA.isRegLoc()) {
3520 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3527 // If the tailcall address may be in a register, then make sure it's
3528 // possible to register allocate for it. In 32-bit, the call address can
3529 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3530 // callee-saved registers are restored. These happen to be the same
3531 // registers used to pass 'inreg' arguments so watch out for those.
3532 if (!Subtarget->is64Bit() &&
3533 ((!isa<GlobalAddressSDNode>(Callee) &&
3534 !isa<ExternalSymbolSDNode>(Callee)) ||
3535 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3536 unsigned NumInRegs = 0;
3537 // In PIC we need an extra register to formulate the address computation
3539 unsigned MaxInRegs =
3540 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3542 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3543 CCValAssign &VA = ArgLocs[i];
3546 unsigned Reg = VA.getLocReg();
3549 case X86::EAX: case X86::EDX: case X86::ECX:
3550 if (++NumInRegs == MaxInRegs)
3562 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3563 const TargetLibraryInfo *libInfo) const {
3564 return X86::createFastISel(funcInfo, libInfo);
3567 //===----------------------------------------------------------------------===//
3568 // Other Lowering Hooks
3569 //===----------------------------------------------------------------------===//
3571 static bool MayFoldLoad(SDValue Op) {
3572 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3575 static bool MayFoldIntoStore(SDValue Op) {
3576 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3579 static bool isTargetShuffle(unsigned Opcode) {
3581 default: return false;
3582 case X86ISD::BLENDI:
3583 case X86ISD::PSHUFB:
3584 case X86ISD::PSHUFD:
3585 case X86ISD::PSHUFHW:
3586 case X86ISD::PSHUFLW:
3588 case X86ISD::PALIGNR:
3589 case X86ISD::MOVLHPS:
3590 case X86ISD::MOVLHPD:
3591 case X86ISD::MOVHLPS:
3592 case X86ISD::MOVLPS:
3593 case X86ISD::MOVLPD:
3594 case X86ISD::MOVSHDUP:
3595 case X86ISD::MOVSLDUP:
3596 case X86ISD::MOVDDUP:
3599 case X86ISD::UNPCKL:
3600 case X86ISD::UNPCKH:
3601 case X86ISD::VPERMILPI:
3602 case X86ISD::VPERM2X128:
3603 case X86ISD::VPERMI:
3608 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3609 SDValue V1, unsigned TargetMask,
3610 SelectionDAG &DAG) {
3612 default: llvm_unreachable("Unknown x86 shuffle node");
3613 case X86ISD::PSHUFD:
3614 case X86ISD::PSHUFHW:
3615 case X86ISD::PSHUFLW:
3616 case X86ISD::VPERMILPI:
3617 case X86ISD::VPERMI:
3618 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3622 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3623 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3625 default: llvm_unreachable("Unknown x86 shuffle node");
3626 case X86ISD::MOVLHPS:
3627 case X86ISD::MOVLHPD:
3628 case X86ISD::MOVHLPS:
3629 case X86ISD::MOVLPS:
3630 case X86ISD::MOVLPD:
3633 case X86ISD::UNPCKL:
3634 case X86ISD::UNPCKH:
3635 return DAG.getNode(Opc, dl, VT, V1, V2);
3639 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3640 MachineFunction &MF = DAG.getMachineFunction();
3641 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3642 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3643 int ReturnAddrIndex = FuncInfo->getRAIndex();
3645 if (ReturnAddrIndex == 0) {
3646 // Set up a frame object for the return address.
3647 unsigned SlotSize = RegInfo->getSlotSize();
3648 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3651 FuncInfo->setRAIndex(ReturnAddrIndex);
3654 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3657 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3658 bool hasSymbolicDisplacement) {
3659 // Offset should fit into 32 bit immediate field.
3660 if (!isInt<32>(Offset))
3663 // If we don't have a symbolic displacement - we don't have any extra
3665 if (!hasSymbolicDisplacement)
3668 // FIXME: Some tweaks might be needed for medium code model.
3669 if (M != CodeModel::Small && M != CodeModel::Kernel)
3672 // For small code model we assume that latest object is 16MB before end of 31
3673 // bits boundary. We may also accept pretty large negative constants knowing
3674 // that all objects are in the positive half of address space.
3675 if (M == CodeModel::Small && Offset < 16*1024*1024)
3678 // For kernel code model we know that all object resist in the negative half
3679 // of 32bits address space. We may not accept negative offsets, since they may
3680 // be just off and we may accept pretty large positive ones.
3681 if (M == CodeModel::Kernel && Offset >= 0)
3687 /// isCalleePop - Determines whether the callee is required to pop its
3688 /// own arguments. Callee pop is necessary to support tail calls.
3689 bool X86::isCalleePop(CallingConv::ID CallingConv,
3690 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3691 switch (CallingConv) {
3694 case CallingConv::X86_StdCall:
3695 case CallingConv::X86_FastCall:
3696 case CallingConv::X86_ThisCall:
3698 case CallingConv::Fast:
3699 case CallingConv::GHC:
3700 case CallingConv::HiPE:
3707 /// \brief Return true if the condition is an unsigned comparison operation.
3708 static bool isX86CCUnsigned(unsigned X86CC) {
3710 default: llvm_unreachable("Invalid integer condition!");
3711 case X86::COND_E: return true;
3712 case X86::COND_G: return false;
3713 case X86::COND_GE: return false;
3714 case X86::COND_L: return false;
3715 case X86::COND_LE: return false;
3716 case X86::COND_NE: return true;
3717 case X86::COND_B: return true;
3718 case X86::COND_A: return true;
3719 case X86::COND_BE: return true;
3720 case X86::COND_AE: return true;
3722 llvm_unreachable("covered switch fell through?!");
3725 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3726 /// specific condition code, returning the condition code and the LHS/RHS of the
3727 /// comparison to make.
3728 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3729 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3731 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3732 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3733 // X > -1 -> X == 0, jump !sign.
3734 RHS = DAG.getConstant(0, RHS.getValueType());
3735 return X86::COND_NS;
3737 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3738 // X < 0 -> X == 0, jump on sign.
3741 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3743 RHS = DAG.getConstant(0, RHS.getValueType());
3744 return X86::COND_LE;
3748 switch (SetCCOpcode) {
3749 default: llvm_unreachable("Invalid integer condition!");
3750 case ISD::SETEQ: return X86::COND_E;
3751 case ISD::SETGT: return X86::COND_G;
3752 case ISD::SETGE: return X86::COND_GE;
3753 case ISD::SETLT: return X86::COND_L;
3754 case ISD::SETLE: return X86::COND_LE;
3755 case ISD::SETNE: return X86::COND_NE;
3756 case ISD::SETULT: return X86::COND_B;
3757 case ISD::SETUGT: return X86::COND_A;
3758 case ISD::SETULE: return X86::COND_BE;
3759 case ISD::SETUGE: return X86::COND_AE;
3763 // First determine if it is required or is profitable to flip the operands.
3765 // If LHS is a foldable load, but RHS is not, flip the condition.
3766 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3767 !ISD::isNON_EXTLoad(RHS.getNode())) {
3768 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3769 std::swap(LHS, RHS);
3772 switch (SetCCOpcode) {
3778 std::swap(LHS, RHS);
3782 // On a floating point condition, the flags are set as follows:
3784 // 0 | 0 | 0 | X > Y
3785 // 0 | 0 | 1 | X < Y
3786 // 1 | 0 | 0 | X == Y
3787 // 1 | 1 | 1 | unordered
3788 switch (SetCCOpcode) {
3789 default: llvm_unreachable("Condcode should be pre-legalized away");
3791 case ISD::SETEQ: return X86::COND_E;
3792 case ISD::SETOLT: // flipped
3794 case ISD::SETGT: return X86::COND_A;
3795 case ISD::SETOLE: // flipped
3797 case ISD::SETGE: return X86::COND_AE;
3798 case ISD::SETUGT: // flipped
3800 case ISD::SETLT: return X86::COND_B;
3801 case ISD::SETUGE: // flipped
3803 case ISD::SETLE: return X86::COND_BE;
3805 case ISD::SETNE: return X86::COND_NE;
3806 case ISD::SETUO: return X86::COND_P;
3807 case ISD::SETO: return X86::COND_NP;
3809 case ISD::SETUNE: return X86::COND_INVALID;
3813 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3814 /// code. Current x86 isa includes the following FP cmov instructions:
3815 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3816 static bool hasFPCMov(unsigned X86CC) {
3832 /// isFPImmLegal - Returns true if the target can instruction select the
3833 /// specified FP immediate natively. If false, the legalizer will
3834 /// materialize the FP immediate as a load from a constant pool.
3835 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3836 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3837 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3843 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3844 ISD::LoadExtType ExtTy,
3846 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3847 // relocation target a movq or addq instruction: don't let the load shrink.
3848 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3849 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3850 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3851 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3855 /// \brief Returns true if it is beneficial to convert a load of a constant
3856 /// to just the constant itself.
3857 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3859 assert(Ty->isIntegerTy());
3861 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3862 if (BitSize == 0 || BitSize > 64)
3867 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3868 unsigned Index) const {
3869 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3872 return (Index == 0 || Index == ResVT.getVectorNumElements());
3875 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3876 // Speculate cttz only if we can directly use TZCNT.
3877 return Subtarget->hasBMI();
3880 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3881 // Speculate ctlz only if we can directly use LZCNT.
3882 return Subtarget->hasLZCNT();
3885 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3886 /// the specified range (L, H].
3887 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3888 return (Val < 0) || (Val >= Low && Val < Hi);
3891 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3892 /// specified value.
3893 static bool isUndefOrEqual(int Val, int CmpVal) {
3894 return (Val < 0 || Val == CmpVal);
3897 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3898 /// from position Pos and ending in Pos+Size, falls within the specified
3899 /// sequential range (Low, Low+Size]. or is undef.
3900 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3901 unsigned Pos, unsigned Size, int Low) {
3902 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3903 if (!isUndefOrEqual(Mask[i], Low))
3908 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3909 /// the two vector operands have swapped position.
3910 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3911 unsigned NumElems) {
3912 for (unsigned i = 0; i != NumElems; ++i) {
3916 else if (idx < (int)NumElems)
3917 Mask[i] = idx + NumElems;
3919 Mask[i] = idx - NumElems;
3923 /// isVEXTRACTIndex - Return true if the specified
3924 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3925 /// suitable for instruction that extract 128 or 256 bit vectors
3926 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3927 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3928 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3931 // The index should be aligned on a vecWidth-bit boundary.
3933 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3935 MVT VT = N->getSimpleValueType(0);
3936 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3937 bool Result = (Index * ElSize) % vecWidth == 0;
3942 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3943 /// operand specifies a subvector insert that is suitable for input to
3944 /// insertion of 128 or 256-bit subvectors
3945 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3946 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3947 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3949 // The index should be aligned on a vecWidth-bit boundary.
3951 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3953 MVT VT = N->getSimpleValueType(0);
3954 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3955 bool Result = (Index * ElSize) % vecWidth == 0;
3960 bool X86::isVINSERT128Index(SDNode *N) {
3961 return isVINSERTIndex(N, 128);
3964 bool X86::isVINSERT256Index(SDNode *N) {
3965 return isVINSERTIndex(N, 256);
3968 bool X86::isVEXTRACT128Index(SDNode *N) {
3969 return isVEXTRACTIndex(N, 128);
3972 bool X86::isVEXTRACT256Index(SDNode *N) {
3973 return isVEXTRACTIndex(N, 256);
3976 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3977 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3978 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3979 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3982 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3984 MVT VecVT = N->getOperand(0).getSimpleValueType();
3985 MVT ElVT = VecVT.getVectorElementType();
3987 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3988 return Index / NumElemsPerChunk;
3991 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3992 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3993 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3994 llvm_unreachable("Illegal insert subvector for VINSERT");
3997 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3999 MVT VecVT = N->getSimpleValueType(0);
4000 MVT ElVT = VecVT.getVectorElementType();
4002 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4003 return Index / NumElemsPerChunk;
4006 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4007 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4008 /// and VINSERTI128 instructions.
4009 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4010 return getExtractVEXTRACTImmediate(N, 128);
4013 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4014 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4015 /// and VINSERTI64x4 instructions.
4016 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4017 return getExtractVEXTRACTImmediate(N, 256);
4020 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4021 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4022 /// and VINSERTI128 instructions.
4023 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4024 return getInsertVINSERTImmediate(N, 128);
4027 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4028 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4029 /// and VINSERTI64x4 instructions.
4030 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4031 return getInsertVINSERTImmediate(N, 256);
4034 /// isZero - Returns true if Elt is a constant integer zero
4035 static bool isZero(SDValue V) {
4036 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4037 return C && C->isNullValue();
4040 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4042 bool X86::isZeroNode(SDValue Elt) {
4045 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4046 return CFP->getValueAPF().isPosZero();
4050 /// getZeroVector - Returns a vector of specified type with all zero elements.
4052 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4053 SelectionDAG &DAG, SDLoc dl) {
4054 assert(VT.isVector() && "Expected a vector type");
4056 // Always build SSE zero vectors as <4 x i32> bitcasted
4057 // to their dest type. This ensures they get CSE'd.
4059 if (VT.is128BitVector()) { // SSE
4060 if (Subtarget->hasSSE2()) { // SSE2
4061 SDValue Cst = DAG.getConstant(0, MVT::i32);
4062 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4064 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4065 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4067 } else if (VT.is256BitVector()) { // AVX
4068 if (Subtarget->hasInt256()) { // AVX2
4069 SDValue Cst = DAG.getConstant(0, MVT::i32);
4070 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4071 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4073 // 256-bit logic and arithmetic instructions in AVX are all
4074 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4075 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4076 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4077 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4079 } else if (VT.is512BitVector()) { // AVX-512
4080 SDValue Cst = DAG.getConstant(0, MVT::i32);
4081 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4082 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4083 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4084 } else if (VT.getScalarType() == MVT::i1) {
4085 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4086 SDValue Cst = DAG.getConstant(0, MVT::i1);
4087 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4088 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4090 llvm_unreachable("Unexpected vector type");
4092 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4095 /// getOnesVector - Returns a vector of specified type with all bits set.
4096 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4097 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4098 /// Then bitcast to their original type, ensuring they get CSE'd.
4099 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4101 assert(VT.isVector() && "Expected a vector type");
4103 SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4105 if (VT.is256BitVector()) {
4106 if (HasInt256) { // AVX2
4107 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4108 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4110 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4111 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4113 } else if (VT.is128BitVector()) {
4114 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4116 llvm_unreachable("Unexpected vector type");
4118 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4121 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4122 /// operation of specified width.
4123 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4125 unsigned NumElems = VT.getVectorNumElements();
4126 SmallVector<int, 8> Mask;
4127 Mask.push_back(NumElems);
4128 for (unsigned i = 1; i != NumElems; ++i)
4130 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4133 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4134 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4136 unsigned NumElems = VT.getVectorNumElements();
4137 SmallVector<int, 8> Mask;
4138 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4140 Mask.push_back(i + NumElems);
4142 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4145 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4146 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4148 unsigned NumElems = VT.getVectorNumElements();
4149 SmallVector<int, 8> Mask;
4150 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4151 Mask.push_back(i + Half);
4152 Mask.push_back(i + NumElems + Half);
4154 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4157 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4158 /// vector of zero or undef vector. This produces a shuffle where the low
4159 /// element of V2 is swizzled into the zero/undef vector, landing at element
4160 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4161 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4163 const X86Subtarget *Subtarget,
4164 SelectionDAG &DAG) {
4165 MVT VT = V2.getSimpleValueType();
4167 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4168 unsigned NumElems = VT.getVectorNumElements();
4169 SmallVector<int, 16> MaskVec;
4170 for (unsigned i = 0; i != NumElems; ++i)
4171 // If this is the insertion idx, put the low elt of V2 here.
4172 MaskVec.push_back(i == Idx ? NumElems : i);
4173 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4176 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4177 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4178 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4179 /// shuffles which use a single input multiple times, and in those cases it will
4180 /// adjust the mask to only have indices within that single input.
4181 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4182 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4183 unsigned NumElems = VT.getVectorNumElements();
4187 bool IsFakeUnary = false;
4188 switch(N->getOpcode()) {
4189 case X86ISD::BLENDI:
4190 ImmN = N->getOperand(N->getNumOperands()-1);
4191 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4194 ImmN = N->getOperand(N->getNumOperands()-1);
4195 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4196 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4198 case X86ISD::UNPCKH:
4199 DecodeUNPCKHMask(VT, Mask);
4200 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4202 case X86ISD::UNPCKL:
4203 DecodeUNPCKLMask(VT, Mask);
4204 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4206 case X86ISD::MOVHLPS:
4207 DecodeMOVHLPSMask(NumElems, Mask);
4208 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4210 case X86ISD::MOVLHPS:
4211 DecodeMOVLHPSMask(NumElems, Mask);
4212 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4214 case X86ISD::PALIGNR:
4215 ImmN = N->getOperand(N->getNumOperands()-1);
4216 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4218 case X86ISD::PSHUFD:
4219 case X86ISD::VPERMILPI:
4220 ImmN = N->getOperand(N->getNumOperands()-1);
4221 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4224 case X86ISD::PSHUFHW:
4225 ImmN = N->getOperand(N->getNumOperands()-1);
4226 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4229 case X86ISD::PSHUFLW:
4230 ImmN = N->getOperand(N->getNumOperands()-1);
4231 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4234 case X86ISD::PSHUFB: {
4236 SDValue MaskNode = N->getOperand(1);
4237 while (MaskNode->getOpcode() == ISD::BITCAST)
4238 MaskNode = MaskNode->getOperand(0);
4240 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4241 // If we have a build-vector, then things are easy.
4242 EVT VT = MaskNode.getValueType();
4243 assert(VT.isVector() &&
4244 "Can't produce a non-vector with a build_vector!");
4245 if (!VT.isInteger())
4248 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4250 SmallVector<uint64_t, 32> RawMask;
4251 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4252 SDValue Op = MaskNode->getOperand(i);
4253 if (Op->getOpcode() == ISD::UNDEF) {
4254 RawMask.push_back((uint64_t)SM_SentinelUndef);
4257 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4260 APInt MaskElement = CN->getAPIntValue();
4262 // We now have to decode the element which could be any integer size and
4263 // extract each byte of it.
4264 for (int j = 0; j < NumBytesPerElement; ++j) {
4265 // Note that this is x86 and so always little endian: the low byte is
4266 // the first byte of the mask.
4267 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4268 MaskElement = MaskElement.lshr(8);
4271 DecodePSHUFBMask(RawMask, Mask);
4275 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4279 SDValue Ptr = MaskLoad->getBasePtr();
4280 if (Ptr->getOpcode() == X86ISD::Wrapper)
4281 Ptr = Ptr->getOperand(0);
4283 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4284 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4287 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4288 DecodePSHUFBMask(C, Mask);
4296 case X86ISD::VPERMI:
4297 ImmN = N->getOperand(N->getNumOperands()-1);
4298 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4303 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4305 case X86ISD::VPERM2X128:
4306 ImmN = N->getOperand(N->getNumOperands()-1);
4307 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308 if (Mask.empty()) return false;
4310 case X86ISD::MOVSLDUP:
4311 DecodeMOVSLDUPMask(VT, Mask);
4314 case X86ISD::MOVSHDUP:
4315 DecodeMOVSHDUPMask(VT, Mask);
4318 case X86ISD::MOVDDUP:
4319 DecodeMOVDDUPMask(VT, Mask);
4322 case X86ISD::MOVLHPD:
4323 case X86ISD::MOVLPD:
4324 case X86ISD::MOVLPS:
4325 // Not yet implemented
4327 default: llvm_unreachable("unknown target shuffle node");
4330 // If we have a fake unary shuffle, the shuffle mask is spread across two
4331 // inputs that are actually the same node. Re-map the mask to always point
4332 // into the first input.
4335 if (M >= (int)Mask.size())
4341 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4342 /// element of the result of the vector shuffle.
4343 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4346 return SDValue(); // Limit search depth.
4348 SDValue V = SDValue(N, 0);
4349 EVT VT = V.getValueType();
4350 unsigned Opcode = V.getOpcode();
4352 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4353 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4354 int Elt = SV->getMaskElt(Index);
4357 return DAG.getUNDEF(VT.getVectorElementType());
4359 unsigned NumElems = VT.getVectorNumElements();
4360 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4361 : SV->getOperand(1);
4362 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4365 // Recurse into target specific vector shuffles to find scalars.
4366 if (isTargetShuffle(Opcode)) {
4367 MVT ShufVT = V.getSimpleValueType();
4368 unsigned NumElems = ShufVT.getVectorNumElements();
4369 SmallVector<int, 16> ShuffleMask;
4372 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4375 int Elt = ShuffleMask[Index];
4377 return DAG.getUNDEF(ShufVT.getVectorElementType());
4379 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4381 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4385 // Actual nodes that may contain scalar elements
4386 if (Opcode == ISD::BITCAST) {
4387 V = V.getOperand(0);
4388 EVT SrcVT = V.getValueType();
4389 unsigned NumElems = VT.getVectorNumElements();
4391 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4395 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4396 return (Index == 0) ? V.getOperand(0)
4397 : DAG.getUNDEF(VT.getVectorElementType());
4399 if (V.getOpcode() == ISD::BUILD_VECTOR)
4400 return V.getOperand(Index);
4405 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4407 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4408 unsigned NumNonZero, unsigned NumZero,
4410 const X86Subtarget* Subtarget,
4411 const TargetLowering &TLI) {
4418 for (unsigned i = 0; i < 16; ++i) {
4419 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4420 if (ThisIsNonZero && First) {
4422 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4424 V = DAG.getUNDEF(MVT::v8i16);
4429 SDValue ThisElt, LastElt;
4430 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4431 if (LastIsNonZero) {
4432 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4433 MVT::i16, Op.getOperand(i-1));
4435 if (ThisIsNonZero) {
4436 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4437 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4438 ThisElt, DAG.getConstant(8, MVT::i8));
4440 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4444 if (ThisElt.getNode())
4445 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4446 DAG.getIntPtrConstant(i/2));
4450 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4453 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4455 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4456 unsigned NumNonZero, unsigned NumZero,
4458 const X86Subtarget* Subtarget,
4459 const TargetLowering &TLI) {
4466 for (unsigned i = 0; i < 8; ++i) {
4467 bool isNonZero = (NonZeros & (1 << i)) != 0;
4471 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4473 V = DAG.getUNDEF(MVT::v8i16);
4476 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4477 MVT::v8i16, V, Op.getOperand(i),
4478 DAG.getIntPtrConstant(i));
4485 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4486 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4487 const X86Subtarget *Subtarget,
4488 const TargetLowering &TLI) {
4489 // Find all zeroable elements.
4490 std::bitset<4> Zeroable;
4491 for (int i=0; i < 4; ++i) {
4492 SDValue Elt = Op->getOperand(i);
4493 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4495 assert(Zeroable.size() - Zeroable.count() > 1 &&
4496 "We expect at least two non-zero elements!");
4498 // We only know how to deal with build_vector nodes where elements are either
4499 // zeroable or extract_vector_elt with constant index.
4500 SDValue FirstNonZero;
4501 unsigned FirstNonZeroIdx;
4502 for (unsigned i=0; i < 4; ++i) {
4505 SDValue Elt = Op->getOperand(i);
4506 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4507 !isa<ConstantSDNode>(Elt.getOperand(1)))
4509 // Make sure that this node is extracting from a 128-bit vector.
4510 MVT VT = Elt.getOperand(0).getSimpleValueType();
4511 if (!VT.is128BitVector())
4513 if (!FirstNonZero.getNode()) {
4515 FirstNonZeroIdx = i;
4519 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4520 SDValue V1 = FirstNonZero.getOperand(0);
4521 MVT VT = V1.getSimpleValueType();
4523 // See if this build_vector can be lowered as a blend with zero.
4525 unsigned EltMaskIdx, EltIdx;
4527 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4528 if (Zeroable[EltIdx]) {
4529 // The zero vector will be on the right hand side.
4530 Mask[EltIdx] = EltIdx+4;
4534 Elt = Op->getOperand(EltIdx);
4535 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4536 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4537 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4539 Mask[EltIdx] = EltIdx;
4543 // Let the shuffle legalizer deal with blend operations.
4544 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4545 if (V1.getSimpleValueType() != VT)
4546 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4547 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4550 // See if we can lower this build_vector to a INSERTPS.
4551 if (!Subtarget->hasSSE41())
4554 SDValue V2 = Elt.getOperand(0);
4555 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4558 bool CanFold = true;
4559 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4563 SDValue Current = Op->getOperand(i);
4564 SDValue SrcVector = Current->getOperand(0);
4567 CanFold = SrcVector == V1 &&
4568 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4574 assert(V1.getNode() && "Expected at least two non-zero elements!");
4575 if (V1.getSimpleValueType() != MVT::v4f32)
4576 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4577 if (V2.getSimpleValueType() != MVT::v4f32)
4578 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4580 // Ok, we can emit an INSERTPS instruction.
4581 unsigned ZMask = Zeroable.to_ulong();
4583 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4584 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4585 SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4586 DAG.getIntPtrConstant(InsertPSMask));
4587 return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4590 /// Return a vector logical shift node.
4591 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4592 unsigned NumBits, SelectionDAG &DAG,
4593 const TargetLowering &TLI, SDLoc dl) {
4594 assert(VT.is128BitVector() && "Unknown type for VShift");
4595 MVT ShVT = MVT::v2i64;
4596 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4597 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4598 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4599 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4600 SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4601 return DAG.getNode(ISD::BITCAST, dl, VT,
4602 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4606 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4608 // Check if the scalar load can be widened into a vector load. And if
4609 // the address is "base + cst" see if the cst can be "absorbed" into
4610 // the shuffle mask.
4611 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4612 SDValue Ptr = LD->getBasePtr();
4613 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4615 EVT PVT = LD->getValueType(0);
4616 if (PVT != MVT::i32 && PVT != MVT::f32)
4621 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4622 FI = FINode->getIndex();
4624 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4625 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4626 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4627 Offset = Ptr.getConstantOperandVal(1);
4628 Ptr = Ptr.getOperand(0);
4633 // FIXME: 256-bit vector instructions don't require a strict alignment,
4634 // improve this code to support it better.
4635 unsigned RequiredAlign = VT.getSizeInBits()/8;
4636 SDValue Chain = LD->getChain();
4637 // Make sure the stack object alignment is at least 16 or 32.
4638 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4639 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4640 if (MFI->isFixedObjectIndex(FI)) {
4641 // Can't change the alignment. FIXME: It's possible to compute
4642 // the exact stack offset and reference FI + adjust offset instead.
4643 // If someone *really* cares about this. That's the way to implement it.
4646 MFI->setObjectAlignment(FI, RequiredAlign);
4650 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4651 // Ptr + (Offset & ~15).
4654 if ((Offset % RequiredAlign) & 3)
4656 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4658 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4659 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4661 int EltNo = (Offset - StartOffset) >> 2;
4662 unsigned NumElems = VT.getVectorNumElements();
4664 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4665 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4666 LD->getPointerInfo().getWithOffset(StartOffset),
4667 false, false, false, 0);
4669 SmallVector<int, 8> Mask(NumElems, EltNo);
4671 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4677 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4678 /// elements can be replaced by a single large load which has the same value as
4679 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4681 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4683 /// FIXME: we'd also like to handle the case where the last elements are zero
4684 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4685 /// There's even a handy isZeroNode for that purpose.
4686 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4687 SDLoc &DL, SelectionDAG &DAG,
4688 bool isAfterLegalize) {
4689 unsigned NumElems = Elts.size();
4691 LoadSDNode *LDBase = nullptr;
4692 unsigned LastLoadedElt = -1U;
4694 // For each element in the initializer, see if we've found a load or an undef.
4695 // If we don't find an initial load element, or later load elements are
4696 // non-consecutive, bail out.
4697 for (unsigned i = 0; i < NumElems; ++i) {
4698 SDValue Elt = Elts[i];
4699 // Look through a bitcast.
4700 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4701 Elt = Elt.getOperand(0);
4702 if (!Elt.getNode() ||
4703 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4706 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4708 LDBase = cast<LoadSDNode>(Elt.getNode());
4712 if (Elt.getOpcode() == ISD::UNDEF)
4715 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4716 EVT LdVT = Elt.getValueType();
4717 // Each loaded element must be the correct fractional portion of the
4718 // requested vector load.
4719 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4721 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4726 // If we have found an entire vector of loads and undefs, then return a large
4727 // load of the entire vector width starting at the base pointer. If we found
4728 // consecutive loads for the low half, generate a vzext_load node.
4729 if (LastLoadedElt == NumElems - 1) {
4730 assert(LDBase && "Did not find base load for merging consecutive loads");
4731 EVT EltVT = LDBase->getValueType(0);
4732 // Ensure that the input vector size for the merged loads matches the
4733 // cumulative size of the input elements.
4734 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4737 if (isAfterLegalize &&
4738 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4741 SDValue NewLd = SDValue();
4743 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4744 LDBase->getPointerInfo(), LDBase->isVolatile(),
4745 LDBase->isNonTemporal(), LDBase->isInvariant(),
4746 LDBase->getAlignment());
4748 if (LDBase->hasAnyUseOfValue(1)) {
4749 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4751 SDValue(NewLd.getNode(), 1));
4752 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4753 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4754 SDValue(NewLd.getNode(), 1));
4760 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4761 //of a v4i32 / v4f32. It's probably worth generalizing.
4762 EVT EltVT = VT.getVectorElementType();
4763 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4764 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4765 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4766 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4768 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4769 LDBase->getPointerInfo(),
4770 LDBase->getAlignment(),
4771 false/*isVolatile*/, true/*ReadMem*/,
4774 // Make sure the newly-created LOAD is in the same position as LDBase in
4775 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4776 // update uses of LDBase's output chain to use the TokenFactor.
4777 if (LDBase->hasAnyUseOfValue(1)) {
4778 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4779 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4780 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4781 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4782 SDValue(ResNode.getNode(), 1));
4785 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4790 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4791 /// to generate a splat value for the following cases:
4792 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4793 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4794 /// a scalar load, or a constant.
4795 /// The VBROADCAST node is returned when a pattern is found,
4796 /// or SDValue() otherwise.
4797 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4798 SelectionDAG &DAG) {
4799 // VBROADCAST requires AVX.
4800 // TODO: Splats could be generated for non-AVX CPUs using SSE
4801 // instructions, but there's less potential gain for only 128-bit vectors.
4802 if (!Subtarget->hasAVX())
4805 MVT VT = Op.getSimpleValueType();
4808 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4809 "Unsupported vector type for broadcast.");
4814 switch (Op.getOpcode()) {
4816 // Unknown pattern found.
4819 case ISD::BUILD_VECTOR: {
4820 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4821 BitVector UndefElements;
4822 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4824 // We need a splat of a single value to use broadcast, and it doesn't
4825 // make any sense if the value is only in one element of the vector.
4826 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4830 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4831 Ld.getOpcode() == ISD::ConstantFP);
4833 // Make sure that all of the users of a non-constant load are from the
4834 // BUILD_VECTOR node.
4835 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4840 case ISD::VECTOR_SHUFFLE: {
4841 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4843 // Shuffles must have a splat mask where the first element is
4845 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4848 SDValue Sc = Op.getOperand(0);
4849 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4850 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4852 if (!Subtarget->hasInt256())
4855 // Use the register form of the broadcast instruction available on AVX2.
4856 if (VT.getSizeInBits() >= 256)
4857 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4858 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4861 Ld = Sc.getOperand(0);
4862 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4863 Ld.getOpcode() == ISD::ConstantFP);
4865 // The scalar_to_vector node and the suspected
4866 // load node must have exactly one user.
4867 // Constants may have multiple users.
4869 // AVX-512 has register version of the broadcast
4870 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4871 Ld.getValueType().getSizeInBits() >= 32;
4872 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4879 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4880 bool IsGE256 = (VT.getSizeInBits() >= 256);
4882 // When optimizing for size, generate up to 5 extra bytes for a broadcast
4883 // instruction to save 8 or more bytes of constant pool data.
4884 // TODO: If multiple splats are generated to load the same constant,
4885 // it may be detrimental to overall size. There needs to be a way to detect
4886 // that condition to know if this is truly a size win.
4887 const Function *F = DAG.getMachineFunction().getFunction();
4888 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4890 // Handle broadcasting a single constant scalar from the constant pool
4892 // On Sandybridge (no AVX2), it is still better to load a constant vector
4893 // from the constant pool and not to broadcast it from a scalar.
4894 // But override that restriction when optimizing for size.
4895 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4896 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4897 EVT CVT = Ld.getValueType();
4898 assert(!CVT.isVector() && "Must not broadcast a vector type");
4900 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4901 // For size optimization, also splat v2f64 and v2i64, and for size opt
4902 // with AVX2, also splat i8 and i16.
4903 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4904 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4905 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4906 const Constant *C = nullptr;
4907 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4908 C = CI->getConstantIntValue();
4909 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4910 C = CF->getConstantFPValue();
4912 assert(C && "Invalid constant type");
4914 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4915 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4916 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4917 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4918 MachinePointerInfo::getConstantPool(),
4919 false, false, false, Alignment);
4921 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4925 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4927 // Handle AVX2 in-register broadcasts.
4928 if (!IsLoad && Subtarget->hasInt256() &&
4929 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4930 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4932 // The scalar source must be a normal load.
4936 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4937 (Subtarget->hasVLX() && ScalarSize == 64))
4938 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4940 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4941 // double since there is no vbroadcastsd xmm
4942 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4943 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4944 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4947 // Unsupported broadcast.
4951 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4952 /// underlying vector and index.
4954 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4956 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4958 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4959 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4962 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4964 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4966 // (extract_vector_elt (vector_shuffle<2,u,u,u>
4967 // (extract_subvector (v8f32 %vreg0), Constant<4>),
4970 // In this case the vector is the extract_subvector expression and the index
4971 // is 2, as specified by the shuffle.
4972 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4973 SDValue ShuffleVec = SVOp->getOperand(0);
4974 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4975 assert(ShuffleVecVT.getVectorElementType() ==
4976 ExtractedFromVec.getSimpleValueType().getVectorElementType());
4978 int ShuffleIdx = SVOp->getMaskElt(Idx);
4979 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4980 ExtractedFromVec = ShuffleVec;
4986 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4987 MVT VT = Op.getSimpleValueType();
4989 // Skip if insert_vec_elt is not supported.
4990 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4991 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4995 unsigned NumElems = Op.getNumOperands();
4999 SmallVector<unsigned, 4> InsertIndices;
5000 SmallVector<int, 8> Mask(NumElems, -1);
5002 for (unsigned i = 0; i != NumElems; ++i) {
5003 unsigned Opc = Op.getOperand(i).getOpcode();
5005 if (Opc == ISD::UNDEF)
5008 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5009 // Quit if more than 1 elements need inserting.
5010 if (InsertIndices.size() > 1)
5013 InsertIndices.push_back(i);
5017 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5018 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5019 // Quit if non-constant index.
5020 if (!isa<ConstantSDNode>(ExtIdx))
5022 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5024 // Quit if extracted from vector of different type.
5025 if (ExtractedFromVec.getValueType() != VT)
5028 if (!VecIn1.getNode())
5029 VecIn1 = ExtractedFromVec;
5030 else if (VecIn1 != ExtractedFromVec) {
5031 if (!VecIn2.getNode())
5032 VecIn2 = ExtractedFromVec;
5033 else if (VecIn2 != ExtractedFromVec)
5034 // Quit if more than 2 vectors to shuffle
5038 if (ExtractedFromVec == VecIn1)
5040 else if (ExtractedFromVec == VecIn2)
5041 Mask[i] = Idx + NumElems;
5044 if (!VecIn1.getNode())
5047 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5048 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5049 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5050 unsigned Idx = InsertIndices[i];
5051 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5052 DAG.getIntPtrConstant(Idx));
5058 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5060 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5062 MVT VT = Op.getSimpleValueType();
5063 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5064 "Unexpected type in LowerBUILD_VECTORvXi1!");
5067 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5068 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5069 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5070 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5073 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5074 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5075 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5076 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5079 bool AllContants = true;
5080 uint64_t Immediate = 0;
5081 int NonConstIdx = -1;
5082 bool IsSplat = true;
5083 unsigned NumNonConsts = 0;
5084 unsigned NumConsts = 0;
5085 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5086 SDValue In = Op.getOperand(idx);
5087 if (In.getOpcode() == ISD::UNDEF)
5089 if (!isa<ConstantSDNode>(In)) {
5090 AllContants = false;
5095 if (cast<ConstantSDNode>(In)->getZExtValue())
5096 Immediate |= (1ULL << idx);
5098 if (In != Op.getOperand(0))
5103 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5104 DAG.getConstant(Immediate, MVT::i16));
5105 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5106 DAG.getIntPtrConstant(0));
5109 if (NumNonConsts == 1 && NonConstIdx != 0) {
5112 SDValue VecAsImm = DAG.getConstant(Immediate,
5113 MVT::getIntegerVT(VT.getSizeInBits()));
5114 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5117 DstVec = DAG.getUNDEF(VT);
5118 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5119 Op.getOperand(NonConstIdx),
5120 DAG.getIntPtrConstant(NonConstIdx));
5122 if (!IsSplat && (NonConstIdx != 0))
5123 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5124 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5127 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5128 DAG.getConstant(-1, SelectVT),
5129 DAG.getConstant(0, SelectVT));
5131 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5132 DAG.getConstant((Immediate | 1), SelectVT),
5133 DAG.getConstant(Immediate, SelectVT));
5134 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5137 /// \brief Return true if \p N implements a horizontal binop and return the
5138 /// operands for the horizontal binop into V0 and V1.
5140 /// This is a helper function of PerformBUILD_VECTORCombine.
5141 /// This function checks that the build_vector \p N in input implements a
5142 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5143 /// operation to match.
5144 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5145 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5146 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5149 /// This function only analyzes elements of \p N whose indices are
5150 /// in range [BaseIdx, LastIdx).
5151 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5153 unsigned BaseIdx, unsigned LastIdx,
5154 SDValue &V0, SDValue &V1) {
5155 EVT VT = N->getValueType(0);
5157 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5158 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5159 "Invalid Vector in input!");
5161 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5162 bool CanFold = true;
5163 unsigned ExpectedVExtractIdx = BaseIdx;
5164 unsigned NumElts = LastIdx - BaseIdx;
5165 V0 = DAG.getUNDEF(VT);
5166 V1 = DAG.getUNDEF(VT);
5168 // Check if N implements a horizontal binop.
5169 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5170 SDValue Op = N->getOperand(i + BaseIdx);
5173 if (Op->getOpcode() == ISD::UNDEF) {
5174 // Update the expected vector extract index.
5175 if (i * 2 == NumElts)
5176 ExpectedVExtractIdx = BaseIdx;
5177 ExpectedVExtractIdx += 2;
5181 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5186 SDValue Op0 = Op.getOperand(0);
5187 SDValue Op1 = Op.getOperand(1);
5189 // Try to match the following pattern:
5190 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5191 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5192 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5193 Op0.getOperand(0) == Op1.getOperand(0) &&
5194 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5195 isa<ConstantSDNode>(Op1.getOperand(1)));
5199 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5200 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5202 if (i * 2 < NumElts) {
5203 if (V0.getOpcode() == ISD::UNDEF)
5204 V0 = Op0.getOperand(0);
5206 if (V1.getOpcode() == ISD::UNDEF)
5207 V1 = Op0.getOperand(0);
5208 if (i * 2 == NumElts)
5209 ExpectedVExtractIdx = BaseIdx;
5212 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5213 if (I0 == ExpectedVExtractIdx)
5214 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5215 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5216 // Try to match the following dag sequence:
5217 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5218 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5222 ExpectedVExtractIdx += 2;
5228 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5229 /// a concat_vector.
5231 /// This is a helper function of PerformBUILD_VECTORCombine.
5232 /// This function expects two 256-bit vectors called V0 and V1.
5233 /// At first, each vector is split into two separate 128-bit vectors.
5234 /// Then, the resulting 128-bit vectors are used to implement two
5235 /// horizontal binary operations.
5237 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5239 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5240 /// the two new horizontal binop.
5241 /// When Mode is set, the first horizontal binop dag node would take as input
5242 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5243 /// horizontal binop dag node would take as input the lower 128-bit of V1
5244 /// and the upper 128-bit of V1.
5246 /// HADD V0_LO, V0_HI
5247 /// HADD V1_LO, V1_HI
5249 /// Otherwise, the first horizontal binop dag node takes as input the lower
5250 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5251 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5253 /// HADD V0_LO, V1_LO
5254 /// HADD V0_HI, V1_HI
5256 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5257 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5258 /// the upper 128-bits of the result.
5259 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5260 SDLoc DL, SelectionDAG &DAG,
5261 unsigned X86Opcode, bool Mode,
5262 bool isUndefLO, bool isUndefHI) {
5263 EVT VT = V0.getValueType();
5264 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5265 "Invalid nodes in input!");
5267 unsigned NumElts = VT.getVectorNumElements();
5268 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5269 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5270 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5271 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5272 EVT NewVT = V0_LO.getValueType();
5274 SDValue LO = DAG.getUNDEF(NewVT);
5275 SDValue HI = DAG.getUNDEF(NewVT);
5278 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5279 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5280 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5281 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5282 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5284 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5285 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5286 V1_LO->getOpcode() != ISD::UNDEF))
5287 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5289 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5290 V1_HI->getOpcode() != ISD::UNDEF))
5291 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5294 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5297 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5298 /// sequence of 'vadd + vsub + blendi'.
5299 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5300 const X86Subtarget *Subtarget) {
5302 EVT VT = BV->getValueType(0);
5303 unsigned NumElts = VT.getVectorNumElements();
5304 SDValue InVec0 = DAG.getUNDEF(VT);
5305 SDValue InVec1 = DAG.getUNDEF(VT);
5307 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5308 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5310 // Odd-numbered elements in the input build vector are obtained from
5311 // adding two integer/float elements.
5312 // Even-numbered elements in the input build vector are obtained from
5313 // subtracting two integer/float elements.
5314 unsigned ExpectedOpcode = ISD::FSUB;
5315 unsigned NextExpectedOpcode = ISD::FADD;
5316 bool AddFound = false;
5317 bool SubFound = false;
5319 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5320 SDValue Op = BV->getOperand(i);
5322 // Skip 'undef' values.
5323 unsigned Opcode = Op.getOpcode();
5324 if (Opcode == ISD::UNDEF) {
5325 std::swap(ExpectedOpcode, NextExpectedOpcode);
5329 // Early exit if we found an unexpected opcode.
5330 if (Opcode != ExpectedOpcode)
5333 SDValue Op0 = Op.getOperand(0);
5334 SDValue Op1 = Op.getOperand(1);
5336 // Try to match the following pattern:
5337 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5338 // Early exit if we cannot match that sequence.
5339 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5340 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5341 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5342 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5343 Op0.getOperand(1) != Op1.getOperand(1))
5346 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5350 // We found a valid add/sub node. Update the information accordingly.
5356 // Update InVec0 and InVec1.
5357 if (InVec0.getOpcode() == ISD::UNDEF)
5358 InVec0 = Op0.getOperand(0);
5359 if (InVec1.getOpcode() == ISD::UNDEF)
5360 InVec1 = Op1.getOperand(0);
5362 // Make sure that operands in input to each add/sub node always
5363 // come from a same pair of vectors.
5364 if (InVec0 != Op0.getOperand(0)) {
5365 if (ExpectedOpcode == ISD::FSUB)
5368 // FADD is commutable. Try to commute the operands
5369 // and then test again.
5370 std::swap(Op0, Op1);
5371 if (InVec0 != Op0.getOperand(0))
5375 if (InVec1 != Op1.getOperand(0))
5378 // Update the pair of expected opcodes.
5379 std::swap(ExpectedOpcode, NextExpectedOpcode);
5382 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5383 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5384 InVec1.getOpcode() != ISD::UNDEF)
5385 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5390 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5391 const X86Subtarget *Subtarget) {
5393 EVT VT = N->getValueType(0);
5394 unsigned NumElts = VT.getVectorNumElements();
5395 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5396 SDValue InVec0, InVec1;
5398 // Try to match an ADDSUB.
5399 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5400 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5401 SDValue Value = matchAddSub(BV, DAG, Subtarget);
5402 if (Value.getNode())
5406 // Try to match horizontal ADD/SUB.
5407 unsigned NumUndefsLO = 0;
5408 unsigned NumUndefsHI = 0;
5409 unsigned Half = NumElts/2;
5411 // Count the number of UNDEF operands in the build_vector in input.
5412 for (unsigned i = 0, e = Half; i != e; ++i)
5413 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5416 for (unsigned i = Half, e = NumElts; i != e; ++i)
5417 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5420 // Early exit if this is either a build_vector of all UNDEFs or all the
5421 // operands but one are UNDEF.
5422 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5425 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5426 // Try to match an SSE3 float HADD/HSUB.
5427 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5428 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5430 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5431 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5432 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5433 // Try to match an SSSE3 integer HADD/HSUB.
5434 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5435 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5437 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5438 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5441 if (!Subtarget->hasAVX())
5444 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5445 // Try to match an AVX horizontal add/sub of packed single/double
5446 // precision floating point values from 256-bit vectors.
5447 SDValue InVec2, InVec3;
5448 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5449 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5450 ((InVec0.getOpcode() == ISD::UNDEF ||
5451 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5452 ((InVec1.getOpcode() == ISD::UNDEF ||
5453 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5454 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5456 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5457 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5458 ((InVec0.getOpcode() == ISD::UNDEF ||
5459 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5460 ((InVec1.getOpcode() == ISD::UNDEF ||
5461 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5462 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5463 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5464 // Try to match an AVX2 horizontal add/sub of signed integers.
5465 SDValue InVec2, InVec3;
5467 bool CanFold = true;
5469 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5470 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5471 ((InVec0.getOpcode() == ISD::UNDEF ||
5472 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5473 ((InVec1.getOpcode() == ISD::UNDEF ||
5474 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5475 X86Opcode = X86ISD::HADD;
5476 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5477 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5478 ((InVec0.getOpcode() == ISD::UNDEF ||
5479 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5480 ((InVec1.getOpcode() == ISD::UNDEF ||
5481 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5482 X86Opcode = X86ISD::HSUB;
5487 // Fold this build_vector into a single horizontal add/sub.
5488 // Do this only if the target has AVX2.
5489 if (Subtarget->hasAVX2())
5490 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5492 // Do not try to expand this build_vector into a pair of horizontal
5493 // add/sub if we can emit a pair of scalar add/sub.
5494 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5497 // Convert this build_vector into a pair of horizontal binop followed by
5499 bool isUndefLO = NumUndefsLO == Half;
5500 bool isUndefHI = NumUndefsHI == Half;
5501 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5502 isUndefLO, isUndefHI);
5506 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5507 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5509 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5510 X86Opcode = X86ISD::HADD;
5511 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5512 X86Opcode = X86ISD::HSUB;
5513 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5514 X86Opcode = X86ISD::FHADD;
5515 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5516 X86Opcode = X86ISD::FHSUB;
5520 // Don't try to expand this build_vector into a pair of horizontal add/sub
5521 // if we can simply emit a pair of scalar add/sub.
5522 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5525 // Convert this build_vector into two horizontal add/sub followed by
5527 bool isUndefLO = NumUndefsLO == Half;
5528 bool isUndefHI = NumUndefsHI == Half;
5529 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5530 isUndefLO, isUndefHI);
5537 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5540 MVT VT = Op.getSimpleValueType();
5541 MVT ExtVT = VT.getVectorElementType();
5542 unsigned NumElems = Op.getNumOperands();
5544 // Generate vectors for predicate vectors.
5545 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5546 return LowerBUILD_VECTORvXi1(Op, DAG);
5548 // Vectors containing all zeros can be matched by pxor and xorps later
5549 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5550 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5551 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5552 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5555 return getZeroVector(VT, Subtarget, DAG, dl);
5558 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5559 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5560 // vpcmpeqd on 256-bit vectors.
5561 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5562 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5565 if (!VT.is512BitVector())
5566 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5569 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5570 if (Broadcast.getNode())
5573 unsigned EVTBits = ExtVT.getSizeInBits();
5575 unsigned NumZero = 0;
5576 unsigned NumNonZero = 0;
5577 unsigned NonZeros = 0;
5578 bool IsAllConstants = true;
5579 SmallSet<SDValue, 8> Values;
5580 for (unsigned i = 0; i < NumElems; ++i) {
5581 SDValue Elt = Op.getOperand(i);
5582 if (Elt.getOpcode() == ISD::UNDEF)
5585 if (Elt.getOpcode() != ISD::Constant &&
5586 Elt.getOpcode() != ISD::ConstantFP)
5587 IsAllConstants = false;
5588 if (X86::isZeroNode(Elt))
5591 NonZeros |= (1 << i);
5596 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5597 if (NumNonZero == 0)
5598 return DAG.getUNDEF(VT);
5600 // Special case for single non-zero, non-undef, element.
5601 if (NumNonZero == 1) {
5602 unsigned Idx = countTrailingZeros(NonZeros);
5603 SDValue Item = Op.getOperand(Idx);
5605 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5606 // the value are obviously zero, truncate the value to i32 and do the
5607 // insertion that way. Only do this if the value is non-constant or if the
5608 // value is a constant being inserted into element 0. It is cheaper to do
5609 // a constant pool load than it is to do a movd + shuffle.
5610 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5611 (!IsAllConstants || Idx == 0)) {
5612 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5614 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5615 EVT VecVT = MVT::v4i32;
5617 // Truncate the value (which may itself be a constant) to i32, and
5618 // convert it to a vector with movd (S2V+shuffle to zero extend).
5619 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5620 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5622 ISD::BITCAST, dl, VT,
5623 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5627 // If we have a constant or non-constant insertion into the low element of
5628 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5629 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5630 // depending on what the source datatype is.
5633 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5635 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5636 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5637 if (VT.is256BitVector() || VT.is512BitVector()) {
5638 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5639 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5640 Item, DAG.getIntPtrConstant(0));
5642 assert(VT.is128BitVector() && "Expected an SSE value type!");
5643 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5644 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5645 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5648 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5649 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5650 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5651 if (VT.is256BitVector()) {
5652 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5653 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5655 assert(VT.is128BitVector() && "Expected an SSE value type!");
5656 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5658 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5662 // Is it a vector logical left shift?
5663 if (NumElems == 2 && Idx == 1 &&
5664 X86::isZeroNode(Op.getOperand(0)) &&
5665 !X86::isZeroNode(Op.getOperand(1))) {
5666 unsigned NumBits = VT.getSizeInBits();
5667 return getVShift(true, VT,
5668 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5669 VT, Op.getOperand(1)),
5670 NumBits/2, DAG, *this, dl);
5673 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5676 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5677 // is a non-constant being inserted into an element other than the low one,
5678 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5679 // movd/movss) to move this into the low element, then shuffle it into
5681 if (EVTBits == 32) {
5682 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5683 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5687 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5688 if (Values.size() == 1) {
5689 if (EVTBits == 32) {
5690 // Instead of a shuffle like this:
5691 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5692 // Check if it's possible to issue this instead.
5693 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5694 unsigned Idx = countTrailingZeros(NonZeros);
5695 SDValue Item = Op.getOperand(Idx);
5696 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5697 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5702 // A vector full of immediates; various special cases are already
5703 // handled, so this is best done with a single constant-pool load.
5707 // For AVX-length vectors, see if we can use a vector load to get all of the
5708 // elements, otherwise build the individual 128-bit pieces and use
5709 // shuffles to put them in place.
5710 if (VT.is256BitVector() || VT.is512BitVector()) {
5711 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5713 // Check for a build vector of consecutive loads.
5714 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5717 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5719 // Build both the lower and upper subvector.
5720 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5721 makeArrayRef(&V[0], NumElems/2));
5722 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5723 makeArrayRef(&V[NumElems / 2], NumElems/2));
5725 // Recreate the wider vector with the lower and upper part.
5726 if (VT.is256BitVector())
5727 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5728 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5731 // Let legalizer expand 2-wide build_vectors.
5732 if (EVTBits == 64) {
5733 if (NumNonZero == 1) {
5734 // One half is zero or undef.
5735 unsigned Idx = countTrailingZeros(NonZeros);
5736 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5737 Op.getOperand(Idx));
5738 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5743 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5744 if (EVTBits == 8 && NumElems == 16) {
5745 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5747 if (V.getNode()) return V;
5750 if (EVTBits == 16 && NumElems == 8) {
5751 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5753 if (V.getNode()) return V;
5756 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5757 if (EVTBits == 32 && NumElems == 4) {
5758 SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5763 // If element VT is == 32 bits, turn it into a number of shuffles.
5764 SmallVector<SDValue, 8> V(NumElems);
5765 if (NumElems == 4 && NumZero > 0) {
5766 for (unsigned i = 0; i < 4; ++i) {
5767 bool isZero = !(NonZeros & (1 << i));
5769 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5771 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5774 for (unsigned i = 0; i < 2; ++i) {
5775 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5778 V[i] = V[i*2]; // Must be a zero vector.
5781 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5784 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5787 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5792 bool Reverse1 = (NonZeros & 0x3) == 2;
5793 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5797 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5798 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5800 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5803 if (Values.size() > 1 && VT.is128BitVector()) {
5804 // Check for a build vector of consecutive loads.
5805 for (unsigned i = 0; i < NumElems; ++i)
5806 V[i] = Op.getOperand(i);
5808 // Check for elements which are consecutive loads.
5809 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5813 // Check for a build vector from mostly shuffle plus few inserting.
5814 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5818 // For SSE 4.1, use insertps to put the high elements into the low element.
5819 if (Subtarget->hasSSE41()) {
5821 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5822 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5824 Result = DAG.getUNDEF(VT);
5826 for (unsigned i = 1; i < NumElems; ++i) {
5827 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5828 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5829 Op.getOperand(i), DAG.getIntPtrConstant(i));
5834 // Otherwise, expand into a number of unpckl*, start by extending each of
5835 // our (non-undef) elements to the full vector width with the element in the
5836 // bottom slot of the vector (which generates no code for SSE).
5837 for (unsigned i = 0; i < NumElems; ++i) {
5838 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5839 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5841 V[i] = DAG.getUNDEF(VT);
5844 // Next, we iteratively mix elements, e.g. for v4f32:
5845 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5846 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5847 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5848 unsigned EltStride = NumElems >> 1;
5849 while (EltStride != 0) {
5850 for (unsigned i = 0; i < EltStride; ++i) {
5851 // If V[i+EltStride] is undef and this is the first round of mixing,
5852 // then it is safe to just drop this shuffle: V[i] is already in the
5853 // right place, the one element (since it's the first round) being
5854 // inserted as undef can be dropped. This isn't safe for successive
5855 // rounds because they will permute elements within both vectors.
5856 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5857 EltStride == NumElems/2)
5860 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5869 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5870 // to create 256-bit vectors from two other 128-bit ones.
5871 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5873 MVT ResVT = Op.getSimpleValueType();
5875 assert((ResVT.is256BitVector() ||
5876 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5878 SDValue V1 = Op.getOperand(0);
5879 SDValue V2 = Op.getOperand(1);
5880 unsigned NumElems = ResVT.getVectorNumElements();
5881 if(ResVT.is256BitVector())
5882 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5884 if (Op.getNumOperands() == 4) {
5885 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5886 ResVT.getVectorNumElements()/2);
5887 SDValue V3 = Op.getOperand(2);
5888 SDValue V4 = Op.getOperand(3);
5889 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5890 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5892 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5895 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5896 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
5897 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5898 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5899 Op.getNumOperands() == 4)));
5901 // AVX can use the vinsertf128 instruction to create 256-bit vectors
5902 // from two other 128-bit ones.
5904 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5905 return LowerAVXCONCAT_VECTORS(Op, DAG);
5909 //===----------------------------------------------------------------------===//
5910 // Vector shuffle lowering
5912 // This is an experimental code path for lowering vector shuffles on x86. It is
5913 // designed to handle arbitrary vector shuffles and blends, gracefully
5914 // degrading performance as necessary. It works hard to recognize idiomatic
5915 // shuffles and lower them to optimal instruction patterns without leaving
5916 // a framework that allows reasonably efficient handling of all vector shuffle
5918 //===----------------------------------------------------------------------===//
5920 /// \brief Tiny helper function to identify a no-op mask.
5922 /// This is a somewhat boring predicate function. It checks whether the mask
5923 /// array input, which is assumed to be a single-input shuffle mask of the kind
5924 /// used by the X86 shuffle instructions (not a fully general
5925 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5926 /// in-place shuffle are 'no-op's.
5927 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5928 for (int i = 0, Size = Mask.size(); i < Size; ++i)
5929 if (Mask[i] != -1 && Mask[i] != i)
5934 /// \brief Helper function to classify a mask as a single-input mask.
5936 /// This isn't a generic single-input test because in the vector shuffle
5937 /// lowering we canonicalize single inputs to be the first input operand. This
5938 /// means we can more quickly test for a single input by only checking whether
5939 /// an input from the second operand exists. We also assume that the size of
5940 /// mask corresponds to the size of the input vectors which isn't true in the
5941 /// fully general case.
5942 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5944 if (M >= (int)Mask.size())
5949 /// \brief Test whether there are elements crossing 128-bit lanes in this
5952 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5953 /// and we routinely test for these.
5954 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5955 int LaneSize = 128 / VT.getScalarSizeInBits();
5956 int Size = Mask.size();
5957 for (int i = 0; i < Size; ++i)
5958 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5963 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5965 /// This checks a shuffle mask to see if it is performing the same
5966 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5967 /// that it is also not lane-crossing. It may however involve a blend from the
5968 /// same lane of a second vector.
5970 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5971 /// non-trivial to compute in the face of undef lanes. The representation is
5972 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5973 /// entries from both V1 and V2 inputs to the wider mask.
5975 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5976 SmallVectorImpl<int> &RepeatedMask) {
5977 int LaneSize = 128 / VT.getScalarSizeInBits();
5978 RepeatedMask.resize(LaneSize, -1);
5979 int Size = Mask.size();
5980 for (int i = 0; i < Size; ++i) {
5983 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
5984 // This entry crosses lanes, so there is no way to model this shuffle.
5987 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
5988 if (RepeatedMask[i % LaneSize] == -1)
5989 // This is the first non-undef entry in this slot of a 128-bit lane.
5990 RepeatedMask[i % LaneSize] =
5991 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
5992 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
5993 // Found a mismatch with the repeated mask.
5999 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6002 /// This is a fast way to test a shuffle mask against a fixed pattern:
6004 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6006 /// It returns true if the mask is exactly as wide as the argument list, and
6007 /// each element of the mask is either -1 (signifying undef) or the value given
6008 /// in the argument.
6009 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6010 ArrayRef<int> ExpectedMask) {
6011 if (Mask.size() != ExpectedMask.size())
6014 int Size = Mask.size();
6016 // If the values are build vectors, we can look through them to find
6017 // equivalent inputs that make the shuffles equivalent.
6018 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6019 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6021 for (int i = 0; i < Size; ++i)
6022 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6023 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6024 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6025 if (!MaskBV || !ExpectedBV ||
6026 MaskBV->getOperand(Mask[i] % Size) !=
6027 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6034 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6036 /// This helper function produces an 8-bit shuffle immediate corresponding to
6037 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6038 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6041 /// NB: We rely heavily on "undef" masks preserving the input lane.
6042 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6043 SelectionDAG &DAG) {
6044 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6045 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6046 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6047 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6048 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6051 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6052 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6053 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6054 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6055 return DAG.getConstant(Imm, MVT::i8);
6058 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6060 /// This is used as a fallback approach when first class blend instructions are
6061 /// unavailable. Currently it is only suitable for integer vectors, but could
6062 /// be generalized for floating point vectors if desirable.
6063 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6064 SDValue V2, ArrayRef<int> Mask,
6065 SelectionDAG &DAG) {
6066 assert(VT.isInteger() && "Only supports integer vector types!");
6067 MVT EltVT = VT.getScalarType();
6068 int NumEltBits = EltVT.getSizeInBits();
6069 SDValue Zero = DAG.getConstant(0, EltVT);
6070 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6071 SmallVector<SDValue, 16> MaskOps;
6072 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6073 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6074 return SDValue(); // Shuffled input!
6075 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6078 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6079 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6080 // We have to cast V2 around.
6081 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6082 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6083 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6084 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6085 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6086 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6089 /// \brief Try to emit a blend instruction for a shuffle.
6091 /// This doesn't do any checks for the availability of instructions for blending
6092 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6093 /// be matched in the backend with the type given. What it does check for is
6094 /// that the shuffle mask is in fact a blend.
6095 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6096 SDValue V2, ArrayRef<int> Mask,
6097 const X86Subtarget *Subtarget,
6098 SelectionDAG &DAG) {
6099 unsigned BlendMask = 0;
6100 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6101 if (Mask[i] >= Size) {
6102 if (Mask[i] != i + Size)
6103 return SDValue(); // Shuffled V2 input!
6104 BlendMask |= 1u << i;
6107 if (Mask[i] >= 0 && Mask[i] != i)
6108 return SDValue(); // Shuffled V1 input!
6110 switch (VT.SimpleTy) {
6115 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6116 DAG.getConstant(BlendMask, MVT::i8));
6120 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6124 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6125 // that instruction.
6126 if (Subtarget->hasAVX2()) {
6127 // Scale the blend by the number of 32-bit dwords per element.
6128 int Scale = VT.getScalarSizeInBits() / 32;
6130 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6131 if (Mask[i] >= Size)
6132 for (int j = 0; j < Scale; ++j)
6133 BlendMask |= 1u << (i * Scale + j);
6135 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6136 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6137 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6138 return DAG.getNode(ISD::BITCAST, DL, VT,
6139 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6140 DAG.getConstant(BlendMask, MVT::i8)));
6144 // For integer shuffles we need to expand the mask and cast the inputs to
6145 // v8i16s prior to blending.
6146 int Scale = 8 / VT.getVectorNumElements();
6148 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6149 if (Mask[i] >= Size)
6150 for (int j = 0; j < Scale; ++j)
6151 BlendMask |= 1u << (i * Scale + j);
6153 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6154 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6155 return DAG.getNode(ISD::BITCAST, DL, VT,
6156 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6157 DAG.getConstant(BlendMask, MVT::i8)));
6161 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6162 SmallVector<int, 8> RepeatedMask;
6163 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6164 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6165 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6167 for (int i = 0; i < 8; ++i)
6168 if (RepeatedMask[i] >= 16)
6169 BlendMask |= 1u << i;
6170 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6171 DAG.getConstant(BlendMask, MVT::i8));
6177 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6178 "256-bit byte-blends require AVX2 support!");
6180 // Scale the blend by the number of bytes per element.
6181 int Scale = VT.getScalarSizeInBits() / 8;
6183 // This form of blend is always done on bytes. Compute the byte vector
6185 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6187 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6188 // mix of LLVM's code generator and the x86 backend. We tell the code
6189 // generator that boolean values in the elements of an x86 vector register
6190 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6191 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6192 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6193 // of the element (the remaining are ignored) and 0 in that high bit would
6194 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6195 // the LLVM model for boolean values in vector elements gets the relevant
6196 // bit set, it is set backwards and over constrained relative to x86's
6198 SmallVector<SDValue, 32> VSELECTMask;
6199 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6200 for (int j = 0; j < Scale; ++j)
6201 VSELECTMask.push_back(
6202 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6203 : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6205 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6206 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6208 ISD::BITCAST, DL, VT,
6209 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6210 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6215 llvm_unreachable("Not a supported integer vector type!");
6219 /// \brief Try to lower as a blend of elements from two inputs followed by
6220 /// a single-input permutation.
6222 /// This matches the pattern where we can blend elements from two inputs and
6223 /// then reduce the shuffle to a single-input permutation.
6224 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6227 SelectionDAG &DAG) {
6228 // We build up the blend mask while checking whether a blend is a viable way
6229 // to reduce the shuffle.
6230 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6231 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6233 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6237 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6239 if (BlendMask[Mask[i] % Size] == -1)
6240 BlendMask[Mask[i] % Size] = Mask[i];
6241 else if (BlendMask[Mask[i] % Size] != Mask[i])
6242 return SDValue(); // Can't blend in the needed input!
6244 PermuteMask[i] = Mask[i] % Size;
6247 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6248 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6251 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6252 /// blends and permutes.
6254 /// This matches the extremely common pattern for handling combined
6255 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6256 /// operations. It will try to pick the best arrangement of shuffles and
6258 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6262 SelectionDAG &DAG) {
6263 // Shuffle the input elements into the desired positions in V1 and V2 and
6264 // blend them together.
6265 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6266 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6267 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6268 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6269 if (Mask[i] >= 0 && Mask[i] < Size) {
6270 V1Mask[i] = Mask[i];
6272 } else if (Mask[i] >= Size) {
6273 V2Mask[i] = Mask[i] - Size;
6274 BlendMask[i] = i + Size;
6277 // Try to lower with the simpler initial blend strategy unless one of the
6278 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6279 // shuffle may be able to fold with a load or other benefit. However, when
6280 // we'll have to do 2x as many shuffles in order to achieve this, blending
6281 // first is a better strategy.
6282 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6283 if (SDValue BlendPerm =
6284 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6287 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6288 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6289 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6292 /// \brief Try to lower a vector shuffle as a byte rotation.
6294 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6295 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6296 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6297 /// try to generically lower a vector shuffle through such an pattern. It
6298 /// does not check for the profitability of lowering either as PALIGNR or
6299 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6300 /// This matches shuffle vectors that look like:
6302 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6304 /// Essentially it concatenates V1 and V2, shifts right by some number of
6305 /// elements, and takes the low elements as the result. Note that while this is
6306 /// specified as a *right shift* because x86 is little-endian, it is a *left
6307 /// rotate* of the vector lanes.
6308 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6311 const X86Subtarget *Subtarget,
6312 SelectionDAG &DAG) {
6313 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6315 int NumElts = Mask.size();
6316 int NumLanes = VT.getSizeInBits() / 128;
6317 int NumLaneElts = NumElts / NumLanes;
6319 // We need to detect various ways of spelling a rotation:
6320 // [11, 12, 13, 14, 15, 0, 1, 2]
6321 // [-1, 12, 13, 14, -1, -1, 1, -1]
6322 // [-1, -1, -1, -1, -1, -1, 1, 2]
6323 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6324 // [-1, 4, 5, 6, -1, -1, 9, -1]
6325 // [-1, 4, 5, 6, -1, -1, -1, -1]
6328 for (int l = 0; l < NumElts; l += NumLaneElts) {
6329 for (int i = 0; i < NumLaneElts; ++i) {
6330 if (Mask[l + i] == -1)
6332 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6334 // Get the mod-Size index and lane correct it.
6335 int LaneIdx = (Mask[l + i] % NumElts) - l;
6336 // Make sure it was in this lane.
6337 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6340 // Determine where a rotated vector would have started.
6341 int StartIdx = i - LaneIdx;
6343 // The identity rotation isn't interesting, stop.
6346 // If we found the tail of a vector the rotation must be the missing
6347 // front. If we found the head of a vector, it must be how much of the
6349 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6352 Rotation = CandidateRotation;
6353 else if (Rotation != CandidateRotation)
6354 // The rotations don't match, so we can't match this mask.
6357 // Compute which value this mask is pointing at.
6358 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6360 // Compute which of the two target values this index should be assigned
6361 // to. This reflects whether the high elements are remaining or the low
6362 // elements are remaining.
6363 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6365 // Either set up this value if we've not encountered it before, or check
6366 // that it remains consistent.
6369 else if (TargetV != MaskV)
6370 // This may be a rotation, but it pulls from the inputs in some
6371 // unsupported interleaving.
6376 // Check that we successfully analyzed the mask, and normalize the results.
6377 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6378 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6384 // The actual rotate instruction rotates bytes, so we need to scale the
6385 // rotation based on how many bytes are in the vector lane.
6386 int Scale = 16 / NumLaneElts;
6388 // SSSE3 targets can use the palignr instruction.
6389 if (Subtarget->hasSSSE3()) {
6390 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6391 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6392 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6393 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6395 return DAG.getNode(ISD::BITCAST, DL, VT,
6396 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6397 DAG.getConstant(Rotation * Scale, MVT::i8)));
6400 assert(VT.getSizeInBits() == 128 &&
6401 "Rotate-based lowering only supports 128-bit lowering!");
6402 assert(Mask.size() <= 16 &&
6403 "Can shuffle at most 16 bytes in a 128-bit vector!");
6405 // Default SSE2 implementation
6406 int LoByteShift = 16 - Rotation * Scale;
6407 int HiByteShift = Rotation * Scale;
6409 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6410 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6411 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6413 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6414 DAG.getConstant(LoByteShift, MVT::i8));
6415 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6416 DAG.getConstant(HiByteShift, MVT::i8));
6417 return DAG.getNode(ISD::BITCAST, DL, VT,
6418 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6421 /// \brief Compute whether each element of a shuffle is zeroable.
6423 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6424 /// Either it is an undef element in the shuffle mask, the element of the input
6425 /// referenced is undef, or the element of the input referenced is known to be
6426 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6427 /// as many lanes with this technique as possible to simplify the remaining
6429 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6430 SDValue V1, SDValue V2) {
6431 SmallBitVector Zeroable(Mask.size(), false);
6433 while (V1.getOpcode() == ISD::BITCAST)
6434 V1 = V1->getOperand(0);
6435 while (V2.getOpcode() == ISD::BITCAST)
6436 V2 = V2->getOperand(0);
6438 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6439 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6441 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6443 // Handle the easy cases.
6444 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6449 // If this is an index into a build_vector node (which has the same number
6450 // of elements), dig out the input value and use it.
6451 SDValue V = M < Size ? V1 : V2;
6452 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6455 SDValue Input = V.getOperand(M % Size);
6456 // The UNDEF opcode check really should be dead code here, but not quite
6457 // worth asserting on (it isn't invalid, just unexpected).
6458 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6465 /// \brief Try to emit a bitmask instruction for a shuffle.
6467 /// This handles cases where we can model a blend exactly as a bitmask due to
6468 /// one of the inputs being zeroable.
6469 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6470 SDValue V2, ArrayRef<int> Mask,
6471 SelectionDAG &DAG) {
6472 MVT EltVT = VT.getScalarType();
6473 int NumEltBits = EltVT.getSizeInBits();
6474 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6475 SDValue Zero = DAG.getConstant(0, IntEltVT);
6476 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6477 if (EltVT.isFloatingPoint()) {
6478 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6479 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6481 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6482 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6484 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6487 if (Mask[i] % Size != i)
6488 return SDValue(); // Not a blend.
6490 V = Mask[i] < Size ? V1 : V2;
6491 else if (V != (Mask[i] < Size ? V1 : V2))
6492 return SDValue(); // Can only let one input through the mask.
6494 VMaskOps[i] = AllOnes;
6497 return SDValue(); // No non-zeroable elements!
6499 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6500 V = DAG.getNode(VT.isFloatingPoint()
6501 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6506 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6508 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6509 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6510 /// matches elements from one of the input vectors shuffled to the left or
6511 /// right with zeroable elements 'shifted in'. It handles both the strictly
6512 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6515 /// PSHL : (little-endian) left bit shift.
6516 /// [ zz, 0, zz, 2 ]
6517 /// [ -1, 4, zz, -1 ]
6518 /// PSRL : (little-endian) right bit shift.
6520 /// [ -1, -1, 7, zz]
6521 /// PSLLDQ : (little-endian) left byte shift
6522 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6523 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6524 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6525 /// PSRLDQ : (little-endian) right byte shift
6526 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6527 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6528 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6529 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6530 SDValue V2, ArrayRef<int> Mask,
6531 SelectionDAG &DAG) {
6532 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6534 int Size = Mask.size();
6535 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6537 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6538 for (int i = 0; i < Size; i += Scale)
6539 for (int j = 0; j < Shift; ++j)
6540 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6546 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6547 for (int i = 0; i != Size; i += Scale) {
6548 unsigned Pos = Left ? i + Shift : i;
6549 unsigned Low = Left ? i : i + Shift;
6550 unsigned Len = Scale - Shift;
6551 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6552 Low + (V == V1 ? 0 : Size)))
6556 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6557 bool ByteShift = ShiftEltBits > 64;
6558 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6559 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6560 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6562 // Normalize the scale for byte shifts to still produce an i64 element
6564 Scale = ByteShift ? Scale / 2 : Scale;
6566 // We need to round trip through the appropriate type for the shift.
6567 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6568 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6569 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6570 "Illegal integer vector type");
6571 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6573 V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6574 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6577 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6578 // keep doubling the size of the integer elements up to that. We can
6579 // then shift the elements of the integer vector by whole multiples of
6580 // their width within the elements of the larger integer vector. Test each
6581 // multiple to see if we can find a match with the moved element indices
6582 // and that the shifted in elements are all zeroable.
6583 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6584 for (int Shift = 1; Shift != Scale; ++Shift)
6585 for (bool Left : {true, false})
6586 if (CheckZeros(Shift, Scale, Left))
6587 for (SDValue V : {V1, V2})
6588 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6595 /// \brief Lower a vector shuffle as a zero or any extension.
6597 /// Given a specific number of elements, element bit width, and extension
6598 /// stride, produce either a zero or any extension based on the available
6599 /// features of the subtarget.
6600 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6601 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6602 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6603 assert(Scale > 1 && "Need a scale to extend.");
6604 int NumElements = VT.getVectorNumElements();
6605 int EltBits = VT.getScalarSizeInBits();
6606 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6607 "Only 8, 16, and 32 bit elements can be extended.");
6608 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6610 // Found a valid zext mask! Try various lowering strategies based on the
6611 // input type and available ISA extensions.
6612 if (Subtarget->hasSSE41()) {
6613 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6614 NumElements / Scale);
6615 return DAG.getNode(ISD::BITCAST, DL, VT,
6616 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6619 // For any extends we can cheat for larger element sizes and use shuffle
6620 // instructions that can fold with a load and/or copy.
6621 if (AnyExt && EltBits == 32) {
6622 int PSHUFDMask[4] = {0, -1, 1, -1};
6624 ISD::BITCAST, DL, VT,
6625 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6626 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6627 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6629 if (AnyExt && EltBits == 16 && Scale > 2) {
6630 int PSHUFDMask[4] = {0, -1, 0, -1};
6631 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6632 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6633 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6634 int PSHUFHWMask[4] = {1, -1, -1, -1};
6636 ISD::BITCAST, DL, VT,
6637 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6638 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6639 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6642 // If this would require more than 2 unpack instructions to expand, use
6643 // pshufb when available. We can only use more than 2 unpack instructions
6644 // when zero extending i8 elements which also makes it easier to use pshufb.
6645 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6646 assert(NumElements == 16 && "Unexpected byte vector width!");
6647 SDValue PSHUFBMask[16];
6648 for (int i = 0; i < 16; ++i)
6650 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6651 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6652 return DAG.getNode(ISD::BITCAST, DL, VT,
6653 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6654 DAG.getNode(ISD::BUILD_VECTOR, DL,
6655 MVT::v16i8, PSHUFBMask)));
6658 // Otherwise emit a sequence of unpacks.
6660 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6661 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6662 : getZeroVector(InputVT, Subtarget, DAG, DL);
6663 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6664 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6668 } while (Scale > 1);
6669 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6672 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6674 /// This routine will try to do everything in its power to cleverly lower
6675 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6676 /// check for the profitability of this lowering, it tries to aggressively
6677 /// match this pattern. It will use all of the micro-architectural details it
6678 /// can to emit an efficient lowering. It handles both blends with all-zero
6679 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6680 /// masking out later).
6682 /// The reason we have dedicated lowering for zext-style shuffles is that they
6683 /// are both incredibly common and often quite performance sensitive.
6684 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6685 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6686 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6687 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6689 int Bits = VT.getSizeInBits();
6690 int NumElements = VT.getVectorNumElements();
6691 assert(VT.getScalarSizeInBits() <= 32 &&
6692 "Exceeds 32-bit integer zero extension limit");
6693 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6695 // Define a helper function to check a particular ext-scale and lower to it if
6697 auto Lower = [&](int Scale) -> SDValue {
6700 for (int i = 0; i < NumElements; ++i) {
6702 continue; // Valid anywhere but doesn't tell us anything.
6703 if (i % Scale != 0) {
6704 // Each of the extended elements need to be zeroable.
6708 // We no longer are in the anyext case.
6713 // Each of the base elements needs to be consecutive indices into the
6714 // same input vector.
6715 SDValue V = Mask[i] < NumElements ? V1 : V2;
6718 else if (InputV != V)
6719 return SDValue(); // Flip-flopping inputs.
6721 if (Mask[i] % NumElements != i / Scale)
6722 return SDValue(); // Non-consecutive strided elements.
6725 // If we fail to find an input, we have a zero-shuffle which should always
6726 // have already been handled.
6727 // FIXME: Maybe handle this here in case during blending we end up with one?
6731 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6732 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6735 // The widest scale possible for extending is to a 64-bit integer.
6736 assert(Bits % 64 == 0 &&
6737 "The number of bits in a vector must be divisible by 64 on x86!");
6738 int NumExtElements = Bits / 64;
6740 // Each iteration, try extending the elements half as much, but into twice as
6742 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6743 assert(NumElements % NumExtElements == 0 &&
6744 "The input vector size must be divisible by the extended size.");
6745 if (SDValue V = Lower(NumElements / NumExtElements))
6749 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6753 // Returns one of the source operands if the shuffle can be reduced to a
6754 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6755 auto CanZExtLowHalf = [&]() {
6756 for (int i = NumElements / 2; i != NumElements; ++i)
6759 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6761 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6766 if (SDValue V = CanZExtLowHalf()) {
6767 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6768 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6769 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6772 // No viable ext lowering found.
6776 /// \brief Try to get a scalar value for a specific element of a vector.
6778 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6779 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6780 SelectionDAG &DAG) {
6781 MVT VT = V.getSimpleValueType();
6782 MVT EltVT = VT.getVectorElementType();
6783 while (V.getOpcode() == ISD::BITCAST)
6784 V = V.getOperand(0);
6785 // If the bitcasts shift the element size, we can't extract an equivalent
6787 MVT NewVT = V.getSimpleValueType();
6788 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6791 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6792 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6793 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6798 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6800 /// This is particularly important because the set of instructions varies
6801 /// significantly based on whether the operand is a load or not.
6802 static bool isShuffleFoldableLoad(SDValue V) {
6803 while (V.getOpcode() == ISD::BITCAST)
6804 V = V.getOperand(0);
6806 return ISD::isNON_EXTLoad(V.getNode());
6809 /// \brief Try to lower insertion of a single element into a zero vector.
6811 /// This is a common pattern that we have especially efficient patterns to lower
6812 /// across all subtarget feature sets.
6813 static SDValue lowerVectorShuffleAsElementInsertion(
6814 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6815 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6816 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6818 MVT EltVT = VT.getVectorElementType();
6820 int V2Index = std::find_if(Mask.begin(), Mask.end(),
6821 [&Mask](int M) { return M >= (int)Mask.size(); }) -
6823 bool IsV1Zeroable = true;
6824 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6825 if (i != V2Index && !Zeroable[i]) {
6826 IsV1Zeroable = false;
6830 // Check for a single input from a SCALAR_TO_VECTOR node.
6831 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6832 // all the smarts here sunk into that routine. However, the current
6833 // lowering of BUILD_VECTOR makes that nearly impossible until the old
6834 // vector shuffle lowering is dead.
6835 if (SDValue V2S = getScalarValueForVectorElement(
6836 V2, Mask[V2Index] - Mask.size(), DAG)) {
6837 // We need to zext the scalar if it is smaller than an i32.
6838 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6839 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6840 // Using zext to expand a narrow element won't work for non-zero
6845 // Zero-extend directly to i32.
6847 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6849 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6850 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6851 EltVT == MVT::i16) {
6852 // Either not inserting from the low element of the input or the input
6853 // element size is too small to use VZEXT_MOVL to clear the high bits.
6857 if (!IsV1Zeroable) {
6858 // If V1 can't be treated as a zero vector we have fewer options to lower
6859 // this. We can't support integer vectors or non-zero targets cheaply, and
6860 // the V1 elements can't be permuted in any way.
6861 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6862 if (!VT.isFloatingPoint() || V2Index != 0)
6864 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6865 V1Mask[V2Index] = -1;
6866 if (!isNoopShuffleMask(V1Mask))
6868 // This is essentially a special case blend operation, but if we have
6869 // general purpose blend operations, they are always faster. Bail and let
6870 // the rest of the lowering handle these as blends.
6871 if (Subtarget->hasSSE41())
6874 // Otherwise, use MOVSD or MOVSS.
6875 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6876 "Only two types of floating point element types to handle!");
6877 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6881 // This lowering only works for the low element with floating point vectors.
6882 if (VT.isFloatingPoint() && V2Index != 0)
6885 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6887 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6890 // If we have 4 or fewer lanes we can cheaply shuffle the element into
6891 // the desired position. Otherwise it is more efficient to do a vector
6892 // shift left. We know that we can do a vector shift left because all
6893 // the inputs are zero.
6894 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6895 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6896 V2Shuffle[V2Index] = 0;
6897 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6899 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6901 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6903 V2Index * EltVT.getSizeInBits()/8,
6904 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6905 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6911 /// \brief Try to lower broadcast of a single element.
6913 /// For convenience, this code also bundles all of the subtarget feature set
6914 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6915 /// a convenient way to factor it out.
6916 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6918 const X86Subtarget *Subtarget,
6919 SelectionDAG &DAG) {
6920 if (!Subtarget->hasAVX())
6922 if (VT.isInteger() && !Subtarget->hasAVX2())
6925 // Check that the mask is a broadcast.
6926 int BroadcastIdx = -1;
6928 if (M >= 0 && BroadcastIdx == -1)
6930 else if (M >= 0 && M != BroadcastIdx)
6933 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6934 "a sorted mask where the broadcast "
6937 // Go up the chain of (vector) values to try and find a scalar load that
6938 // we can combine with the broadcast.
6940 switch (V.getOpcode()) {
6941 case ISD::CONCAT_VECTORS: {
6942 int OperandSize = Mask.size() / V.getNumOperands();
6943 V = V.getOperand(BroadcastIdx / OperandSize);
6944 BroadcastIdx %= OperandSize;
6948 case ISD::INSERT_SUBVECTOR: {
6949 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6950 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6954 int BeginIdx = (int)ConstantIdx->getZExtValue();
6956 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6957 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6958 BroadcastIdx -= BeginIdx;
6969 // Check if this is a broadcast of a scalar. We special case lowering
6970 // for scalars so that we can more effectively fold with loads.
6971 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6972 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6973 V = V.getOperand(BroadcastIdx);
6975 // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6977 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6979 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6980 // We can't broadcast from a vector register w/o AVX2, and we can only
6981 // broadcast from the zero-element of a vector register.
6985 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
6988 // Check for whether we can use INSERTPS to perform the shuffle. We only use
6989 // INSERTPS when the V1 elements are already in the correct locations
6990 // because otherwise we can just always use two SHUFPS instructions which
6991 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
6992 // perform INSERTPS if a single V1 element is out of place and all V2
6993 // elements are zeroable.
6994 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
6996 SelectionDAG &DAG) {
6997 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
6998 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
6999 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7000 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7002 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7005 int V1DstIndex = -1;
7006 int V2DstIndex = -1;
7007 bool V1UsedInPlace = false;
7009 for (int i = 0; i < 4; ++i) {
7010 // Synthesize a zero mask from the zeroable elements (includes undefs).
7016 // Flag if we use any V1 inputs in place.
7018 V1UsedInPlace = true;
7022 // We can only insert a single non-zeroable element.
7023 if (V1DstIndex != -1 || V2DstIndex != -1)
7027 // V1 input out of place for insertion.
7030 // V2 input for insertion.
7035 // Don't bother if we have no (non-zeroable) element for insertion.
7036 if (V1DstIndex == -1 && V2DstIndex == -1)
7039 // Determine element insertion src/dst indices. The src index is from the
7040 // start of the inserted vector, not the start of the concatenated vector.
7041 unsigned V2SrcIndex = 0;
7042 if (V1DstIndex != -1) {
7043 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7044 // and don't use the original V2 at all.
7045 V2SrcIndex = Mask[V1DstIndex];
7046 V2DstIndex = V1DstIndex;
7049 V2SrcIndex = Mask[V2DstIndex] - 4;
7052 // If no V1 inputs are used in place, then the result is created only from
7053 // the zero mask and the V2 insertion - so remove V1 dependency.
7055 V1 = DAG.getUNDEF(MVT::v4f32);
7057 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7058 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7060 // Insert the V2 element into the desired position.
7062 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7063 DAG.getConstant(InsertPSMask, MVT::i8));
7066 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7067 /// UNPCK instruction.
7069 /// This specifically targets cases where we end up with alternating between
7070 /// the two inputs, and so can permute them into something that feeds a single
7071 /// UNPCK instruction. Note that this routine only targets integer vectors
7072 /// because for floating point vectors we have a generalized SHUFPS lowering
7073 /// strategy that handles everything that doesn't *exactly* match an unpack,
7074 /// making this clever lowering unnecessary.
7075 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7076 SDValue V2, ArrayRef<int> Mask,
7077 SelectionDAG &DAG) {
7078 assert(!VT.isFloatingPoint() &&
7079 "This routine only supports integer vectors.");
7080 assert(!isSingleInputShuffleMask(Mask) &&
7081 "This routine should only be used when blending two inputs.");
7082 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7084 int Size = Mask.size();
7086 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7087 return M >= 0 && M % Size < Size / 2;
7089 int NumHiInputs = std::count_if(
7090 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7092 bool UnpackLo = NumLoInputs >= NumHiInputs;
7094 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7095 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7096 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7098 for (int i = 0; i < Size; ++i) {
7102 // Each element of the unpack contains Scale elements from this mask.
7103 int UnpackIdx = i / Scale;
7105 // We only handle the case where V1 feeds the first slots of the unpack.
7106 // We rely on canonicalization to ensure this is the case.
7107 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7110 // Setup the mask for this input. The indexing is tricky as we have to
7111 // handle the unpack stride.
7112 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7113 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7117 // If we will have to shuffle both inputs to use the unpack, check whether
7118 // we can just unpack first and shuffle the result. If so, skip this unpack.
7119 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7120 !isNoopShuffleMask(V2Mask))
7123 // Shuffle the inputs into place.
7124 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7125 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7127 // Cast the inputs to the type we will use to unpack them.
7128 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7129 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7131 // Unpack the inputs and cast the result back to the desired type.
7132 return DAG.getNode(ISD::BITCAST, DL, VT,
7133 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7134 DL, UnpackVT, V1, V2));
7137 // We try each unpack from the largest to the smallest to try and find one
7138 // that fits this mask.
7139 int OrigNumElements = VT.getVectorNumElements();
7140 int OrigScalarSize = VT.getScalarSizeInBits();
7141 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7142 int Scale = ScalarSize / OrigScalarSize;
7143 int NumElements = OrigNumElements / Scale;
7144 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7145 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7149 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7151 if (NumLoInputs == 0 || NumHiInputs == 0) {
7152 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7153 "We have to have *some* inputs!");
7154 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7156 // FIXME: We could consider the total complexity of the permute of each
7157 // possible unpacking. Or at the least we should consider how many
7158 // half-crossings are created.
7159 // FIXME: We could consider commuting the unpacks.
7161 SmallVector<int, 32> PermMask;
7162 PermMask.assign(Size, -1);
7163 for (int i = 0; i < Size; ++i) {
7167 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7170 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7172 return DAG.getVectorShuffle(
7173 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7175 DAG.getUNDEF(VT), PermMask);
7181 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7183 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7184 /// support for floating point shuffles but not integer shuffles. These
7185 /// instructions will incur a domain crossing penalty on some chips though so
7186 /// it is better to avoid lowering through this for integer vectors where
7188 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7189 const X86Subtarget *Subtarget,
7190 SelectionDAG &DAG) {
7192 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7193 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7194 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7195 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7196 ArrayRef<int> Mask = SVOp->getMask();
7197 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7199 if (isSingleInputShuffleMask(Mask)) {
7200 // Use low duplicate instructions for masks that match their pattern.
7201 if (Subtarget->hasSSE3())
7202 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7203 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7205 // Straight shuffle of a single input vector. Simulate this by using the
7206 // single input as both of the "inputs" to this instruction..
7207 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7209 if (Subtarget->hasAVX()) {
7210 // If we have AVX, we can use VPERMILPS which will allow folding a load
7211 // into the shuffle.
7212 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7213 DAG.getConstant(SHUFPDMask, MVT::i8));
7216 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7217 DAG.getConstant(SHUFPDMask, MVT::i8));
7219 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7220 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7222 // If we have a single input, insert that into V1 if we can do so cheaply.
7223 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7224 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7225 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7227 // Try inverting the insertion since for v2 masks it is easy to do and we
7228 // can't reliably sort the mask one way or the other.
7229 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7230 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7231 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7232 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7236 // Try to use one of the special instruction patterns to handle two common
7237 // blend patterns if a zero-blend above didn't work.
7238 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7239 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7240 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7241 // We can either use a special instruction to load over the low double or
7242 // to move just the low double.
7244 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7246 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7248 if (Subtarget->hasSSE41())
7249 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7253 // Use dedicated unpack instructions for masks that match their pattern.
7254 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7255 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7256 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7257 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7259 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7260 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7261 DAG.getConstant(SHUFPDMask, MVT::i8));
7264 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7266 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7267 /// the integer unit to minimize domain crossing penalties. However, for blends
7268 /// it falls back to the floating point shuffle operation with appropriate bit
7270 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7271 const X86Subtarget *Subtarget,
7272 SelectionDAG &DAG) {
7274 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7275 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7276 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7277 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7278 ArrayRef<int> Mask = SVOp->getMask();
7279 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7281 if (isSingleInputShuffleMask(Mask)) {
7282 // Check for being able to broadcast a single element.
7283 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7284 Mask, Subtarget, DAG))
7287 // Straight shuffle of a single input vector. For everything from SSE2
7288 // onward this has a single fast instruction with no scary immediates.
7289 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7290 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7291 int WidenedMask[4] = {
7292 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7293 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7295 ISD::BITCAST, DL, MVT::v2i64,
7296 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7297 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7299 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7300 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7301 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7302 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7304 // If we have a blend of two PACKUS operations an the blend aligns with the
7305 // low and half halves, we can just merge the PACKUS operations. This is
7306 // particularly important as it lets us merge shuffles that this routine itself
7308 auto GetPackNode = [](SDValue V) {
7309 while (V.getOpcode() == ISD::BITCAST)
7310 V = V.getOperand(0);
7312 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7314 if (SDValue V1Pack = GetPackNode(V1))
7315 if (SDValue V2Pack = GetPackNode(V2))
7316 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7317 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7318 Mask[0] == 0 ? V1Pack.getOperand(0)
7319 : V1Pack.getOperand(1),
7320 Mask[1] == 2 ? V2Pack.getOperand(0)
7321 : V2Pack.getOperand(1)));
7323 // Try to use shift instructions.
7325 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7328 // When loading a scalar and then shuffling it into a vector we can often do
7329 // the insertion cheaply.
7330 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7331 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7333 // Try inverting the insertion since for v2 masks it is easy to do and we
7334 // can't reliably sort the mask one way or the other.
7335 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7336 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7337 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7340 // We have different paths for blend lowering, but they all must use the
7341 // *exact* same predicate.
7342 bool IsBlendSupported = Subtarget->hasSSE41();
7343 if (IsBlendSupported)
7344 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7348 // Use dedicated unpack instructions for masks that match their pattern.
7349 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7350 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7351 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7352 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7354 // Try to use byte rotation instructions.
7355 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7356 if (Subtarget->hasSSSE3())
7357 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7358 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7361 // If we have direct support for blends, we should lower by decomposing into
7362 // a permute. That will be faster than the domain cross.
7363 if (IsBlendSupported)
7364 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7367 // We implement this with SHUFPD which is pretty lame because it will likely
7368 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7369 // However, all the alternatives are still more cycles and newer chips don't
7370 // have this problem. It would be really nice if x86 had better shuffles here.
7371 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7372 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7373 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7374 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7377 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7379 /// This is used to disable more specialized lowerings when the shufps lowering
7380 /// will happen to be efficient.
7381 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7382 // This routine only handles 128-bit shufps.
7383 assert(Mask.size() == 4 && "Unsupported mask size!");
7385 // To lower with a single SHUFPS we need to have the low half and high half
7386 // each requiring a single input.
7387 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7389 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7395 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7397 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7398 /// It makes no assumptions about whether this is the *best* lowering, it simply
7400 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7401 ArrayRef<int> Mask, SDValue V1,
7402 SDValue V2, SelectionDAG &DAG) {
7403 SDValue LowV = V1, HighV = V2;
7404 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7407 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7409 if (NumV2Elements == 1) {
7411 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7414 // Compute the index adjacent to V2Index and in the same half by toggling
7416 int V2AdjIndex = V2Index ^ 1;
7418 if (Mask[V2AdjIndex] == -1) {
7419 // Handles all the cases where we have a single V2 element and an undef.
7420 // This will only ever happen in the high lanes because we commute the
7421 // vector otherwise.
7423 std::swap(LowV, HighV);
7424 NewMask[V2Index] -= 4;
7426 // Handle the case where the V2 element ends up adjacent to a V1 element.
7427 // To make this work, blend them together as the first step.
7428 int V1Index = V2AdjIndex;
7429 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7430 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7431 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7433 // Now proceed to reconstruct the final blend as we have the necessary
7434 // high or low half formed.
7441 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7442 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7444 } else if (NumV2Elements == 2) {
7445 if (Mask[0] < 4 && Mask[1] < 4) {
7446 // Handle the easy case where we have V1 in the low lanes and V2 in the
7450 } else if (Mask[2] < 4 && Mask[3] < 4) {
7451 // We also handle the reversed case because this utility may get called
7452 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7453 // arrange things in the right direction.
7459 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7460 // trying to place elements directly, just blend them and set up the final
7461 // shuffle to place them.
7463 // The first two blend mask elements are for V1, the second two are for
7465 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7466 Mask[2] < 4 ? Mask[2] : Mask[3],
7467 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7468 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7469 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7470 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7472 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7475 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7476 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7477 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7478 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7481 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7482 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7485 /// \brief Lower 4-lane 32-bit floating point shuffles.
7487 /// Uses instructions exclusively from the floating point unit to minimize
7488 /// domain crossing penalties, as these are sufficient to implement all v4f32
7490 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7491 const X86Subtarget *Subtarget,
7492 SelectionDAG &DAG) {
7494 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7495 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7496 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7497 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7498 ArrayRef<int> Mask = SVOp->getMask();
7499 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7502 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7504 if (NumV2Elements == 0) {
7505 // Check for being able to broadcast a single element.
7506 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7507 Mask, Subtarget, DAG))
7510 // Use even/odd duplicate instructions for masks that match their pattern.
7511 if (Subtarget->hasSSE3()) {
7512 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7513 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7514 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7515 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7518 if (Subtarget->hasAVX()) {
7519 // If we have AVX, we can use VPERMILPS which will allow folding a load
7520 // into the shuffle.
7521 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7522 getV4X86ShuffleImm8ForMask(Mask, DAG));
7525 // Otherwise, use a straight shuffle of a single input vector. We pass the
7526 // input vector to both operands to simulate this with a SHUFPS.
7527 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7528 getV4X86ShuffleImm8ForMask(Mask, DAG));
7531 // There are special ways we can lower some single-element blends. However, we
7532 // have custom ways we can lower more complex single-element blends below that
7533 // we defer to if both this and BLENDPS fail to match, so restrict this to
7534 // when the V2 input is targeting element 0 of the mask -- that is the fast
7536 if (NumV2Elements == 1 && Mask[0] >= 4)
7537 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7538 Mask, Subtarget, DAG))
7541 if (Subtarget->hasSSE41()) {
7542 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7546 // Use INSERTPS if we can complete the shuffle efficiently.
7547 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7550 if (!isSingleSHUFPSMask(Mask))
7551 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7552 DL, MVT::v4f32, V1, V2, Mask, DAG))
7556 // Use dedicated unpack instructions for masks that match their pattern.
7557 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7558 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7559 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7560 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7561 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7562 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7563 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7564 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7566 // Otherwise fall back to a SHUFPS lowering strategy.
7567 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7570 /// \brief Lower 4-lane i32 vector shuffles.
7572 /// We try to handle these with integer-domain shuffles where we can, but for
7573 /// blends we use the floating point domain blend instructions.
7574 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7575 const X86Subtarget *Subtarget,
7576 SelectionDAG &DAG) {
7578 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7579 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7580 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7581 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7582 ArrayRef<int> Mask = SVOp->getMask();
7583 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7585 // Whenever we can lower this as a zext, that instruction is strictly faster
7586 // than any alternative. It also allows us to fold memory operands into the
7587 // shuffle in many cases.
7588 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7589 Mask, Subtarget, DAG))
7593 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7595 if (NumV2Elements == 0) {
7596 // Check for being able to broadcast a single element.
7597 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7598 Mask, Subtarget, DAG))
7601 // Straight shuffle of a single input vector. For everything from SSE2
7602 // onward this has a single fast instruction with no scary immediates.
7603 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7604 // but we aren't actually going to use the UNPCK instruction because doing
7605 // so prevents folding a load into this instruction or making a copy.
7606 const int UnpackLoMask[] = {0, 0, 1, 1};
7607 const int UnpackHiMask[] = {2, 2, 3, 3};
7608 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7609 Mask = UnpackLoMask;
7610 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7611 Mask = UnpackHiMask;
7613 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7614 getV4X86ShuffleImm8ForMask(Mask, DAG));
7617 // Try to use shift instructions.
7619 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7622 // There are special ways we can lower some single-element blends.
7623 if (NumV2Elements == 1)
7624 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7625 Mask, Subtarget, DAG))
7628 // We have different paths for blend lowering, but they all must use the
7629 // *exact* same predicate.
7630 bool IsBlendSupported = Subtarget->hasSSE41();
7631 if (IsBlendSupported)
7632 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7636 if (SDValue Masked =
7637 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7640 // Use dedicated unpack instructions for masks that match their pattern.
7641 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7642 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7643 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7644 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7645 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7646 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7647 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7648 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7650 // Try to use byte rotation instructions.
7651 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7652 if (Subtarget->hasSSSE3())
7653 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7654 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7657 // If we have direct support for blends, we should lower by decomposing into
7658 // a permute. That will be faster than the domain cross.
7659 if (IsBlendSupported)
7660 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7663 // Try to lower by permuting the inputs into an unpack instruction.
7664 if (SDValue Unpack =
7665 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7668 // We implement this with SHUFPS because it can blend from two vectors.
7669 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7670 // up the inputs, bypassing domain shift penalties that we would encur if we
7671 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7673 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7674 DAG.getVectorShuffle(
7676 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7677 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7680 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7681 /// shuffle lowering, and the most complex part.
7683 /// The lowering strategy is to try to form pairs of input lanes which are
7684 /// targeted at the same half of the final vector, and then use a dword shuffle
7685 /// to place them onto the right half, and finally unpack the paired lanes into
7686 /// their final position.
7688 /// The exact breakdown of how to form these dword pairs and align them on the
7689 /// correct sides is really tricky. See the comments within the function for
7690 /// more of the details.
7692 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7693 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7694 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7695 /// vector, form the analogous 128-bit 8-element Mask.
7696 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7697 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7698 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7699 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7700 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7702 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7703 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7704 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7706 SmallVector<int, 4> LoInputs;
7707 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7708 [](int M) { return M >= 0; });
7709 std::sort(LoInputs.begin(), LoInputs.end());
7710 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7711 SmallVector<int, 4> HiInputs;
7712 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7713 [](int M) { return M >= 0; });
7714 std::sort(HiInputs.begin(), HiInputs.end());
7715 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7717 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7718 int NumHToL = LoInputs.size() - NumLToL;
7720 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7721 int NumHToH = HiInputs.size() - NumLToH;
7722 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7723 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7724 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7725 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7727 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7728 // such inputs we can swap two of the dwords across the half mark and end up
7729 // with <=2 inputs to each half in each half. Once there, we can fall through
7730 // to the generic code below. For example:
7732 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7733 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7735 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7736 // and an existing 2-into-2 on the other half. In this case we may have to
7737 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7738 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7739 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7740 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7741 // half than the one we target for fixing) will be fixed when we re-enter this
7742 // path. We will also combine away any sequence of PSHUFD instructions that
7743 // result into a single instruction. Here is an example of the tricky case:
7745 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7746 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7748 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7750 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7751 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7753 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7754 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7756 // The result is fine to be handled by the generic logic.
7757 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7758 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7759 int AOffset, int BOffset) {
7760 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7761 "Must call this with A having 3 or 1 inputs from the A half.");
7762 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7763 "Must call this with B having 1 or 3 inputs from the B half.");
7764 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7765 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7767 // Compute the index of dword with only one word among the three inputs in
7768 // a half by taking the sum of the half with three inputs and subtracting
7769 // the sum of the actual three inputs. The difference is the remaining
7772 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7773 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7774 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7775 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7776 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7777 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7778 int TripleNonInputIdx =
7779 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7780 TripleDWord = TripleNonInputIdx / 2;
7782 // We use xor with one to compute the adjacent DWord to whichever one the
7784 OneInputDWord = (OneInput / 2) ^ 1;
7786 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7787 // and BToA inputs. If there is also such a problem with the BToB and AToB
7788 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7789 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7790 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7791 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7792 // Compute how many inputs will be flipped by swapping these DWords. We
7794 // to balance this to ensure we don't form a 3-1 shuffle in the other
7796 int NumFlippedAToBInputs =
7797 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7798 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7799 int NumFlippedBToBInputs =
7800 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7801 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7802 if ((NumFlippedAToBInputs == 1 &&
7803 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7804 (NumFlippedBToBInputs == 1 &&
7805 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7806 // We choose whether to fix the A half or B half based on whether that
7807 // half has zero flipped inputs. At zero, we may not be able to fix it
7808 // with that half. We also bias towards fixing the B half because that
7809 // will more commonly be the high half, and we have to bias one way.
7810 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7811 ArrayRef<int> Inputs) {
7812 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7813 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7814 PinnedIdx ^ 1) != Inputs.end();
7815 // Determine whether the free index is in the flipped dword or the
7816 // unflipped dword based on where the pinned index is. We use this bit
7817 // in an xor to conditionally select the adjacent dword.
7818 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7819 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7820 FixFreeIdx) != Inputs.end();
7821 if (IsFixIdxInput == IsFixFreeIdxInput)
7823 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7824 FixFreeIdx) != Inputs.end();
7825 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7826 "We need to be changing the number of flipped inputs!");
7827 int PSHUFHalfMask[] = {0, 1, 2, 3};
7828 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7829 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7831 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7834 if (M != -1 && M == FixIdx)
7836 else if (M != -1 && M == FixFreeIdx)
7839 if (NumFlippedBToBInputs != 0) {
7841 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7842 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7844 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7846 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7847 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7852 int PSHUFDMask[] = {0, 1, 2, 3};
7853 PSHUFDMask[ADWord] = BDWord;
7854 PSHUFDMask[BDWord] = ADWord;
7855 V = DAG.getNode(ISD::BITCAST, DL, VT,
7856 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7857 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7858 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7860 // Adjust the mask to match the new locations of A and B.
7862 if (M != -1 && M/2 == ADWord)
7863 M = 2 * BDWord + M % 2;
7864 else if (M != -1 && M/2 == BDWord)
7865 M = 2 * ADWord + M % 2;
7867 // Recurse back into this routine to re-compute state now that this isn't
7868 // a 3 and 1 problem.
7869 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7872 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7873 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7874 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7875 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7877 // At this point there are at most two inputs to the low and high halves from
7878 // each half. That means the inputs can always be grouped into dwords and
7879 // those dwords can then be moved to the correct half with a dword shuffle.
7880 // We use at most one low and one high word shuffle to collect these paired
7881 // inputs into dwords, and finally a dword shuffle to place them.
7882 int PSHUFLMask[4] = {-1, -1, -1, -1};
7883 int PSHUFHMask[4] = {-1, -1, -1, -1};
7884 int PSHUFDMask[4] = {-1, -1, -1, -1};
7886 // First fix the masks for all the inputs that are staying in their
7887 // original halves. This will then dictate the targets of the cross-half
7889 auto fixInPlaceInputs =
7890 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7891 MutableArrayRef<int> SourceHalfMask,
7892 MutableArrayRef<int> HalfMask, int HalfOffset) {
7893 if (InPlaceInputs.empty())
7895 if (InPlaceInputs.size() == 1) {
7896 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7897 InPlaceInputs[0] - HalfOffset;
7898 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7901 if (IncomingInputs.empty()) {
7902 // Just fix all of the in place inputs.
7903 for (int Input : InPlaceInputs) {
7904 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7905 PSHUFDMask[Input / 2] = Input / 2;
7910 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7911 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7912 InPlaceInputs[0] - HalfOffset;
7913 // Put the second input next to the first so that they are packed into
7914 // a dword. We find the adjacent index by toggling the low bit.
7915 int AdjIndex = InPlaceInputs[0] ^ 1;
7916 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7917 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7918 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7920 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7921 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7923 // Now gather the cross-half inputs and place them into a free dword of
7924 // their target half.
7925 // FIXME: This operation could almost certainly be simplified dramatically to
7926 // look more like the 3-1 fixing operation.
7927 auto moveInputsToRightHalf = [&PSHUFDMask](
7928 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7929 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7930 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7932 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7933 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7935 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7937 int LowWord = Word & ~1;
7938 int HighWord = Word | 1;
7939 return isWordClobbered(SourceHalfMask, LowWord) ||
7940 isWordClobbered(SourceHalfMask, HighWord);
7943 if (IncomingInputs.empty())
7946 if (ExistingInputs.empty()) {
7947 // Map any dwords with inputs from them into the right half.
7948 for (int Input : IncomingInputs) {
7949 // If the source half mask maps over the inputs, turn those into
7950 // swaps and use the swapped lane.
7951 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7952 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7953 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7954 Input - SourceOffset;
7955 // We have to swap the uses in our half mask in one sweep.
7956 for (int &M : HalfMask)
7957 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7959 else if (M == Input)
7960 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7962 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7963 Input - SourceOffset &&
7964 "Previous placement doesn't match!");
7966 // Note that this correctly re-maps both when we do a swap and when
7967 // we observe the other side of the swap above. We rely on that to
7968 // avoid swapping the members of the input list directly.
7969 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7972 // Map the input's dword into the correct half.
7973 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7974 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7976 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7978 "Previous placement doesn't match!");
7981 // And just directly shift any other-half mask elements to be same-half
7982 // as we will have mirrored the dword containing the element into the
7983 // same position within that half.
7984 for (int &M : HalfMask)
7985 if (M >= SourceOffset && M < SourceOffset + 4) {
7986 M = M - SourceOffset + DestOffset;
7987 assert(M >= 0 && "This should never wrap below zero!");
7992 // Ensure we have the input in a viable dword of its current half. This
7993 // is particularly tricky because the original position may be clobbered
7994 // by inputs being moved and *staying* in that half.
7995 if (IncomingInputs.size() == 1) {
7996 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7997 int InputFixed = std::find(std::begin(SourceHalfMask),
7998 std::end(SourceHalfMask), -1) -
7999 std::begin(SourceHalfMask) + SourceOffset;
8000 SourceHalfMask[InputFixed - SourceOffset] =
8001 IncomingInputs[0] - SourceOffset;
8002 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8004 IncomingInputs[0] = InputFixed;
8006 } else if (IncomingInputs.size() == 2) {
8007 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8008 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8009 // We have two non-adjacent or clobbered inputs we need to extract from
8010 // the source half. To do this, we need to map them into some adjacent
8011 // dword slot in the source mask.
8012 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8013 IncomingInputs[1] - SourceOffset};
8015 // If there is a free slot in the source half mask adjacent to one of
8016 // the inputs, place the other input in it. We use (Index XOR 1) to
8017 // compute an adjacent index.
8018 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8019 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8020 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8021 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8022 InputsFixed[1] = InputsFixed[0] ^ 1;
8023 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8024 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8025 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8026 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8027 InputsFixed[0] = InputsFixed[1] ^ 1;
8028 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8029 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8030 // The two inputs are in the same DWord but it is clobbered and the
8031 // adjacent DWord isn't used at all. Move both inputs to the free
8033 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8034 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8035 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8036 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8038 // The only way we hit this point is if there is no clobbering
8039 // (because there are no off-half inputs to this half) and there is no
8040 // free slot adjacent to one of the inputs. In this case, we have to
8041 // swap an input with a non-input.
8042 for (int i = 0; i < 4; ++i)
8043 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8044 "We can't handle any clobbers here!");
8045 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8046 "Cannot have adjacent inputs here!");
8048 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8049 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8051 // We also have to update the final source mask in this case because
8052 // it may need to undo the above swap.
8053 for (int &M : FinalSourceHalfMask)
8054 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8055 M = InputsFixed[1] + SourceOffset;
8056 else if (M == InputsFixed[1] + SourceOffset)
8057 M = (InputsFixed[0] ^ 1) + SourceOffset;
8059 InputsFixed[1] = InputsFixed[0] ^ 1;
8062 // Point everything at the fixed inputs.
8063 for (int &M : HalfMask)
8064 if (M == IncomingInputs[0])
8065 M = InputsFixed[0] + SourceOffset;
8066 else if (M == IncomingInputs[1])
8067 M = InputsFixed[1] + SourceOffset;
8069 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8070 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8073 llvm_unreachable("Unhandled input size!");
8076 // Now hoist the DWord down to the right half.
8077 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8078 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8079 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8080 for (int &M : HalfMask)
8081 for (int Input : IncomingInputs)
8083 M = FreeDWord * 2 + Input % 2;
8085 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8086 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8087 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8088 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8090 // Now enact all the shuffles we've computed to move the inputs into their
8092 if (!isNoopShuffleMask(PSHUFLMask))
8093 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8094 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8095 if (!isNoopShuffleMask(PSHUFHMask))
8096 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8097 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8098 if (!isNoopShuffleMask(PSHUFDMask))
8099 V = DAG.getNode(ISD::BITCAST, DL, VT,
8100 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8101 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8102 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8104 // At this point, each half should contain all its inputs, and we can then
8105 // just shuffle them into their final position.
8106 assert(std::count_if(LoMask.begin(), LoMask.end(),
8107 [](int M) { return M >= 4; }) == 0 &&
8108 "Failed to lift all the high half inputs to the low mask!");
8109 assert(std::count_if(HiMask.begin(), HiMask.end(),
8110 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8111 "Failed to lift all the low half inputs to the high mask!");
8113 // Do a half shuffle for the low mask.
8114 if (!isNoopShuffleMask(LoMask))
8115 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8116 getV4X86ShuffleImm8ForMask(LoMask, DAG));
8118 // Do a half shuffle with the high mask after shifting its values down.
8119 for (int &M : HiMask)
8122 if (!isNoopShuffleMask(HiMask))
8123 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8124 getV4X86ShuffleImm8ForMask(HiMask, DAG));
8129 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8130 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8131 SDValue V2, ArrayRef<int> Mask,
8132 SelectionDAG &DAG, bool &V1InUse,
8134 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8140 int Size = Mask.size();
8141 int Scale = 16 / Size;
8142 for (int i = 0; i < 16; ++i) {
8143 if (Mask[i / Scale] == -1) {
8144 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8146 const int ZeroMask = 0x80;
8147 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8149 int V2Idx = Mask[i / Scale] < Size
8151 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8152 if (Zeroable[i / Scale])
8153 V1Idx = V2Idx = ZeroMask;
8154 V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8155 V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8156 V1InUse |= (ZeroMask != V1Idx);
8157 V2InUse |= (ZeroMask != V2Idx);
8162 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8163 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8164 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8166 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8167 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8168 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8170 // If we need shuffled inputs from both, blend the two.
8172 if (V1InUse && V2InUse)
8173 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8175 V = V1InUse ? V1 : V2;
8177 // Cast the result back to the correct type.
8178 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8181 /// \brief Generic lowering of 8-lane i16 shuffles.
8183 /// This handles both single-input shuffles and combined shuffle/blends with
8184 /// two inputs. The single input shuffles are immediately delegated to
8185 /// a dedicated lowering routine.
8187 /// The blends are lowered in one of three fundamental ways. If there are few
8188 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8189 /// of the input is significantly cheaper when lowered as an interleaving of
8190 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8191 /// halves of the inputs separately (making them have relatively few inputs)
8192 /// and then concatenate them.
8193 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8194 const X86Subtarget *Subtarget,
8195 SelectionDAG &DAG) {
8197 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8198 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8199 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8200 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8201 ArrayRef<int> OrigMask = SVOp->getMask();
8202 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8203 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8204 MutableArrayRef<int> Mask(MaskStorage);
8206 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8208 // Whenever we can lower this as a zext, that instruction is strictly faster
8209 // than any alternative.
8210 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8211 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8214 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8216 auto isV2 = [](int M) { return M >= 8; };
8218 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8220 if (NumV2Inputs == 0) {
8221 // Check for being able to broadcast a single element.
8222 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8223 Mask, Subtarget, DAG))
8226 // Try to use shift instructions.
8228 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8231 // Use dedicated unpack instructions for masks that match their pattern.
8232 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8233 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8234 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8235 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8237 // Try to use byte rotation instructions.
8238 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8239 Mask, Subtarget, DAG))
8242 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8246 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8247 "All single-input shuffles should be canonicalized to be V1-input "
8250 // Try to use shift instructions.
8252 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8255 // There are special ways we can lower some single-element blends.
8256 if (NumV2Inputs == 1)
8257 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8258 Mask, Subtarget, DAG))
8261 // We have different paths for blend lowering, but they all must use the
8262 // *exact* same predicate.
8263 bool IsBlendSupported = Subtarget->hasSSE41();
8264 if (IsBlendSupported)
8265 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8269 if (SDValue Masked =
8270 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8273 // Use dedicated unpack instructions for masks that match their pattern.
8274 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8275 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8276 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8277 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8279 // Try to use byte rotation instructions.
8280 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8281 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8284 if (SDValue BitBlend =
8285 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8288 if (SDValue Unpack =
8289 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8292 // If we can't directly blend but can use PSHUFB, that will be better as it
8293 // can both shuffle and set up the inefficient blend.
8294 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8295 bool V1InUse, V2InUse;
8296 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8300 // We can always bit-blend if we have to so the fallback strategy is to
8301 // decompose into single-input permutes and blends.
8302 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8306 /// \brief Check whether a compaction lowering can be done by dropping even
8307 /// elements and compute how many times even elements must be dropped.
8309 /// This handles shuffles which take every Nth element where N is a power of
8310 /// two. Example shuffle masks:
8312 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8313 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8314 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8315 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8316 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8317 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8319 /// Any of these lanes can of course be undef.
8321 /// This routine only supports N <= 3.
8322 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8325 /// \returns N above, or the number of times even elements must be dropped if
8326 /// there is such a number. Otherwise returns zero.
8327 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8328 // Figure out whether we're looping over two inputs or just one.
8329 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8331 // The modulus for the shuffle vector entries is based on whether this is
8332 // a single input or not.
8333 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8334 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8335 "We should only be called with masks with a power-of-2 size!");
8337 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8339 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8340 // and 2^3 simultaneously. This is because we may have ambiguity with
8341 // partially undef inputs.
8342 bool ViableForN[3] = {true, true, true};
8344 for (int i = 0, e = Mask.size(); i < e; ++i) {
8345 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8350 bool IsAnyViable = false;
8351 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8352 if (ViableForN[j]) {
8355 // The shuffle mask must be equal to (i * 2^N) % M.
8356 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8359 ViableForN[j] = false;
8361 // Early exit if we exhaust the possible powers of two.
8366 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8370 // Return 0 as there is no viable power of two.
8374 /// \brief Generic lowering of v16i8 shuffles.
8376 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8377 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8378 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8379 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8381 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8382 const X86Subtarget *Subtarget,
8383 SelectionDAG &DAG) {
8385 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8386 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8387 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8388 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8389 ArrayRef<int> Mask = SVOp->getMask();
8390 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8392 // Try to use shift instructions.
8394 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8397 // Try to use byte rotation instructions.
8398 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8399 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8402 // Try to use a zext lowering.
8403 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8404 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8408 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8410 // For single-input shuffles, there are some nicer lowering tricks we can use.
8411 if (NumV2Elements == 0) {
8412 // Check for being able to broadcast a single element.
8413 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8414 Mask, Subtarget, DAG))
8417 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8418 // Notably, this handles splat and partial-splat shuffles more efficiently.
8419 // However, it only makes sense if the pre-duplication shuffle simplifies
8420 // things significantly. Currently, this means we need to be able to
8421 // express the pre-duplication shuffle as an i16 shuffle.
8423 // FIXME: We should check for other patterns which can be widened into an
8424 // i16 shuffle as well.
8425 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8426 for (int i = 0; i < 16; i += 2)
8427 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8432 auto tryToWidenViaDuplication = [&]() -> SDValue {
8433 if (!canWidenViaDuplication(Mask))
8435 SmallVector<int, 4> LoInputs;
8436 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8437 [](int M) { return M >= 0 && M < 8; });
8438 std::sort(LoInputs.begin(), LoInputs.end());
8439 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8441 SmallVector<int, 4> HiInputs;
8442 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8443 [](int M) { return M >= 8; });
8444 std::sort(HiInputs.begin(), HiInputs.end());
8445 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8448 bool TargetLo = LoInputs.size() >= HiInputs.size();
8449 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8450 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8452 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8453 SmallDenseMap<int, int, 8> LaneMap;
8454 for (int I : InPlaceInputs) {
8455 PreDupI16Shuffle[I/2] = I/2;
8458 int j = TargetLo ? 0 : 4, je = j + 4;
8459 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8460 // Check if j is already a shuffle of this input. This happens when
8461 // there are two adjacent bytes after we move the low one.
8462 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8463 // If we haven't yet mapped the input, search for a slot into which
8465 while (j < je && PreDupI16Shuffle[j] != -1)
8469 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8472 // Map this input with the i16 shuffle.
8473 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8476 // Update the lane map based on the mapping we ended up with.
8477 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8480 ISD::BITCAST, DL, MVT::v16i8,
8481 DAG.getVectorShuffle(MVT::v8i16, DL,
8482 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8483 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8485 // Unpack the bytes to form the i16s that will be shuffled into place.
8486 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8487 MVT::v16i8, V1, V1);
8489 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8490 for (int i = 0; i < 16; ++i)
8491 if (Mask[i] != -1) {
8492 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8493 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8494 if (PostDupI16Shuffle[i / 2] == -1)
8495 PostDupI16Shuffle[i / 2] = MappedMask;
8497 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8498 "Conflicting entrties in the original shuffle!");
8501 ISD::BITCAST, DL, MVT::v16i8,
8502 DAG.getVectorShuffle(MVT::v8i16, DL,
8503 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8504 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8506 if (SDValue V = tryToWidenViaDuplication())
8510 // Use dedicated unpack instructions for masks that match their pattern.
8511 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8512 0, 16, 1, 17, 2, 18, 3, 19,
8514 4, 20, 5, 21, 6, 22, 7, 23}))
8515 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8516 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8517 8, 24, 9, 25, 10, 26, 11, 27,
8519 12, 28, 13, 29, 14, 30, 15, 31}))
8520 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8522 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8523 // with PSHUFB. It is important to do this before we attempt to generate any
8524 // blends but after all of the single-input lowerings. If the single input
8525 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8526 // want to preserve that and we can DAG combine any longer sequences into
8527 // a PSHUFB in the end. But once we start blending from multiple inputs,
8528 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8529 // and there are *very* few patterns that would actually be faster than the
8530 // PSHUFB approach because of its ability to zero lanes.
8532 // FIXME: The only exceptions to the above are blends which are exact
8533 // interleavings with direct instructions supporting them. We currently don't
8534 // handle those well here.
8535 if (Subtarget->hasSSSE3()) {
8536 bool V1InUse = false;
8537 bool V2InUse = false;
8539 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8540 DAG, V1InUse, V2InUse);
8542 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8543 // do so. This avoids using them to handle blends-with-zero which is
8544 // important as a single pshufb is significantly faster for that.
8545 if (V1InUse && V2InUse) {
8546 if (Subtarget->hasSSE41())
8547 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8548 Mask, Subtarget, DAG))
8551 // We can use an unpack to do the blending rather than an or in some
8552 // cases. Even though the or may be (very minorly) more efficient, we
8553 // preference this lowering because there are common cases where part of
8554 // the complexity of the shuffles goes away when we do the final blend as
8556 // FIXME: It might be worth trying to detect if the unpack-feeding
8557 // shuffles will both be pshufb, in which case we shouldn't bother with
8559 if (SDValue Unpack =
8560 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8567 // There are special ways we can lower some single-element blends.
8568 if (NumV2Elements == 1)
8569 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8570 Mask, Subtarget, DAG))
8573 if (SDValue BitBlend =
8574 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8577 // Check whether a compaction lowering can be done. This handles shuffles
8578 // which take every Nth element for some even N. See the helper function for
8581 // We special case these as they can be particularly efficiently handled with
8582 // the PACKUSB instruction on x86 and they show up in common patterns of
8583 // rearranging bytes to truncate wide elements.
8584 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8585 // NumEvenDrops is the power of two stride of the elements. Another way of
8586 // thinking about it is that we need to drop the even elements this many
8587 // times to get the original input.
8588 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8590 // First we need to zero all the dropped bytes.
8591 assert(NumEvenDrops <= 3 &&
8592 "No support for dropping even elements more than 3 times.");
8593 // We use the mask type to pick which bytes are preserved based on how many
8594 // elements are dropped.
8595 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8596 SDValue ByteClearMask =
8597 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8598 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8599 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8601 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8603 // Now pack things back together.
8604 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8605 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8606 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8607 for (int i = 1; i < NumEvenDrops; ++i) {
8608 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8609 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8615 // Handle multi-input cases by blending single-input shuffles.
8616 if (NumV2Elements > 0)
8617 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8620 // The fallback path for single-input shuffles widens this into two v8i16
8621 // vectors with unpacks, shuffles those, and then pulls them back together
8625 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8626 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8627 for (int i = 0; i < 16; ++i)
8629 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8631 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8633 SDValue VLoHalf, VHiHalf;
8634 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8635 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8637 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8638 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8639 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8640 [](int M) { return M >= 0 && M % 2 == 1; })) {
8641 // Use a mask to drop the high bytes.
8642 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8643 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8644 DAG.getConstant(0x00FF, MVT::v8i16));
8646 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8647 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8649 // Squash the masks to point directly into VLoHalf.
8650 for (int &M : LoBlendMask)
8653 for (int &M : HiBlendMask)
8657 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8658 // VHiHalf so that we can blend them as i16s.
8659 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8660 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8661 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8662 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8665 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8666 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8668 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8671 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8673 /// This routine breaks down the specific type of 128-bit shuffle and
8674 /// dispatches to the lowering routines accordingly.
8675 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8676 MVT VT, const X86Subtarget *Subtarget,
8677 SelectionDAG &DAG) {
8678 switch (VT.SimpleTy) {
8680 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8682 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8684 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8686 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8688 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8690 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8693 llvm_unreachable("Unimplemented!");
8697 /// \brief Helper function to test whether a shuffle mask could be
8698 /// simplified by widening the elements being shuffled.
8700 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8701 /// leaves it in an unspecified state.
8703 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8704 /// shuffle masks. The latter have the special property of a '-2' representing
8705 /// a zero-ed lane of a vector.
8706 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8707 SmallVectorImpl<int> &WidenedMask) {
8708 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8709 // If both elements are undef, its trivial.
8710 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8711 WidenedMask.push_back(SM_SentinelUndef);
8715 // Check for an undef mask and a mask value properly aligned to fit with
8716 // a pair of values. If we find such a case, use the non-undef mask's value.
8717 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8718 WidenedMask.push_back(Mask[i + 1] / 2);
8721 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8722 WidenedMask.push_back(Mask[i] / 2);
8726 // When zeroing, we need to spread the zeroing across both lanes to widen.
8727 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8728 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8729 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8730 WidenedMask.push_back(SM_SentinelZero);
8736 // Finally check if the two mask values are adjacent and aligned with
8738 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8739 WidenedMask.push_back(Mask[i] / 2);
8743 // Otherwise we can't safely widen the elements used in this shuffle.
8746 assert(WidenedMask.size() == Mask.size() / 2 &&
8747 "Incorrect size of mask after widening the elements!");
8752 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8754 /// This routine just extracts two subvectors, shuffles them independently, and
8755 /// then concatenates them back together. This should work effectively with all
8756 /// AVX vector shuffle types.
8757 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8758 SDValue V2, ArrayRef<int> Mask,
8759 SelectionDAG &DAG) {
8760 assert(VT.getSizeInBits() >= 256 &&
8761 "Only for 256-bit or wider vector shuffles!");
8762 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8763 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8765 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8766 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8768 int NumElements = VT.getVectorNumElements();
8769 int SplitNumElements = NumElements / 2;
8770 MVT ScalarVT = VT.getScalarType();
8771 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8773 // Rather than splitting build-vectors, just build two narrower build
8774 // vectors. This helps shuffling with splats and zeros.
8775 auto SplitVector = [&](SDValue V) {
8776 while (V.getOpcode() == ISD::BITCAST)
8777 V = V->getOperand(0);
8779 MVT OrigVT = V.getSimpleValueType();
8780 int OrigNumElements = OrigVT.getVectorNumElements();
8781 int OrigSplitNumElements = OrigNumElements / 2;
8782 MVT OrigScalarVT = OrigVT.getScalarType();
8783 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8787 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8789 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8790 DAG.getIntPtrConstant(0));
8791 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8792 DAG.getIntPtrConstant(OrigSplitNumElements));
8795 SmallVector<SDValue, 16> LoOps, HiOps;
8796 for (int i = 0; i < OrigSplitNumElements; ++i) {
8797 LoOps.push_back(BV->getOperand(i));
8798 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8800 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8801 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8803 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8804 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8807 SDValue LoV1, HiV1, LoV2, HiV2;
8808 std::tie(LoV1, HiV1) = SplitVector(V1);
8809 std::tie(LoV2, HiV2) = SplitVector(V2);
8811 // Now create two 4-way blends of these half-width vectors.
8812 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8813 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8814 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8815 for (int i = 0; i < SplitNumElements; ++i) {
8816 int M = HalfMask[i];
8817 if (M >= NumElements) {
8818 if (M >= NumElements + SplitNumElements)
8822 V2BlendMask.push_back(M - NumElements);
8823 V1BlendMask.push_back(-1);
8824 BlendMask.push_back(SplitNumElements + i);
8825 } else if (M >= 0) {
8826 if (M >= SplitNumElements)
8830 V2BlendMask.push_back(-1);
8831 V1BlendMask.push_back(M);
8832 BlendMask.push_back(i);
8834 V2BlendMask.push_back(-1);
8835 V1BlendMask.push_back(-1);
8836 BlendMask.push_back(-1);
8840 // Because the lowering happens after all combining takes place, we need to
8841 // manually combine these blend masks as much as possible so that we create
8842 // a minimal number of high-level vector shuffle nodes.
8844 // First try just blending the halves of V1 or V2.
8845 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8846 return DAG.getUNDEF(SplitVT);
8847 if (!UseLoV2 && !UseHiV2)
8848 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8849 if (!UseLoV1 && !UseHiV1)
8850 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8852 SDValue V1Blend, V2Blend;
8853 if (UseLoV1 && UseHiV1) {
8855 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8857 // We only use half of V1 so map the usage down into the final blend mask.
8858 V1Blend = UseLoV1 ? LoV1 : HiV1;
8859 for (int i = 0; i < SplitNumElements; ++i)
8860 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8861 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8863 if (UseLoV2 && UseHiV2) {
8865 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8867 // We only use half of V2 so map the usage down into the final blend mask.
8868 V2Blend = UseLoV2 ? LoV2 : HiV2;
8869 for (int i = 0; i < SplitNumElements; ++i)
8870 if (BlendMask[i] >= SplitNumElements)
8871 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8873 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8875 SDValue Lo = HalfBlend(LoMask);
8876 SDValue Hi = HalfBlend(HiMask);
8877 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8880 /// \brief Either split a vector in halves or decompose the shuffles and the
8883 /// This is provided as a good fallback for many lowerings of non-single-input
8884 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8885 /// between splitting the shuffle into 128-bit components and stitching those
8886 /// back together vs. extracting the single-input shuffles and blending those
8888 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8889 SDValue V2, ArrayRef<int> Mask,
8890 SelectionDAG &DAG) {
8891 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8892 "lower single-input shuffles as it "
8893 "could then recurse on itself.");
8894 int Size = Mask.size();
8896 // If this can be modeled as a broadcast of two elements followed by a blend,
8897 // prefer that lowering. This is especially important because broadcasts can
8898 // often fold with memory operands.
8899 auto DoBothBroadcast = [&] {
8900 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8903 if (V2BroadcastIdx == -1)
8904 V2BroadcastIdx = M - Size;
8905 else if (M - Size != V2BroadcastIdx)
8907 } else if (M >= 0) {
8908 if (V1BroadcastIdx == -1)
8910 else if (M != V1BroadcastIdx)
8915 if (DoBothBroadcast())
8916 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8919 // If the inputs all stem from a single 128-bit lane of each input, then we
8920 // split them rather than blending because the split will decompose to
8921 // unusually few instructions.
8922 int LaneCount = VT.getSizeInBits() / 128;
8923 int LaneSize = Size / LaneCount;
8924 SmallBitVector LaneInputs[2];
8925 LaneInputs[0].resize(LaneCount, false);
8926 LaneInputs[1].resize(LaneCount, false);
8927 for (int i = 0; i < Size; ++i)
8929 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8930 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8931 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8933 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8934 // that the decomposed single-input shuffles don't end up here.
8935 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8938 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8939 /// a permutation and blend of those lanes.
8941 /// This essentially blends the out-of-lane inputs to each lane into the lane
8942 /// from a permuted copy of the vector. This lowering strategy results in four
8943 /// instructions in the worst case for a single-input cross lane shuffle which
8944 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8945 /// of. Special cases for each particular shuffle pattern should be handled
8946 /// prior to trying this lowering.
8947 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8948 SDValue V1, SDValue V2,
8950 SelectionDAG &DAG) {
8951 // FIXME: This should probably be generalized for 512-bit vectors as well.
8952 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8953 int LaneSize = Mask.size() / 2;
8955 // If there are only inputs from one 128-bit lane, splitting will in fact be
8956 // less expensive. The flags track wether the given lane contains an element
8957 // that crosses to another lane.
8958 bool LaneCrossing[2] = {false, false};
8959 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8960 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8961 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8962 if (!LaneCrossing[0] || !LaneCrossing[1])
8963 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8965 if (isSingleInputShuffleMask(Mask)) {
8966 SmallVector<int, 32> FlippedBlendMask;
8967 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8968 FlippedBlendMask.push_back(
8969 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8971 : Mask[i] % LaneSize +
8972 (i / LaneSize) * LaneSize + Size));
8974 // Flip the vector, and blend the results which should now be in-lane. The
8975 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8976 // 5 for the high source. The value 3 selects the high half of source 2 and
8977 // the value 2 selects the low half of source 2. We only use source 2 to
8978 // allow folding it into a memory operand.
8979 unsigned PERMMask = 3 | 2 << 4;
8980 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
8981 V1, DAG.getConstant(PERMMask, MVT::i8));
8982 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
8985 // This now reduces to two single-input shuffles of V1 and V2 which at worst
8986 // will be handled by the above logic and a blend of the results, much like
8987 // other patterns in AVX.
8988 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8991 /// \brief Handle lowering 2-lane 128-bit shuffles.
8992 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8993 SDValue V2, ArrayRef<int> Mask,
8994 const X86Subtarget *Subtarget,
8995 SelectionDAG &DAG) {
8996 // Blends are faster and handle all the non-lane-crossing cases.
8997 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9001 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9002 VT.getVectorNumElements() / 2);
9003 // Check for patterns which can be matched with a single insert of a 128-bit
9005 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}) ||
9006 isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9007 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9008 DAG.getIntPtrConstant(0));
9009 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9010 Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9011 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9013 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9014 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9015 DAG.getIntPtrConstant(0));
9016 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9017 DAG.getIntPtrConstant(2));
9018 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9021 // Otherwise form a 128-bit permutation.
9022 // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9023 unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9024 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9025 DAG.getConstant(PermMask, MVT::i8));
9028 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9029 /// shuffling each lane.
9031 /// This will only succeed when the result of fixing the 128-bit lanes results
9032 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9033 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9034 /// the lane crosses early and then use simpler shuffles within each lane.
9036 /// FIXME: It might be worthwhile at some point to support this without
9037 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9038 /// in x86 only floating point has interesting non-repeating shuffles, and even
9039 /// those are still *marginally* more expensive.
9040 static SDValue lowerVectorShuffleByMerging128BitLanes(
9041 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9042 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9043 assert(!isSingleInputShuffleMask(Mask) &&
9044 "This is only useful with multiple inputs.");
9046 int Size = Mask.size();
9047 int LaneSize = 128 / VT.getScalarSizeInBits();
9048 int NumLanes = Size / LaneSize;
9049 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9051 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9052 // check whether the in-128-bit lane shuffles share a repeating pattern.
9053 SmallVector<int, 4> Lanes;
9054 Lanes.resize(NumLanes, -1);
9055 SmallVector<int, 4> InLaneMask;
9056 InLaneMask.resize(LaneSize, -1);
9057 for (int i = 0; i < Size; ++i) {
9061 int j = i / LaneSize;
9064 // First entry we've seen for this lane.
9065 Lanes[j] = Mask[i] / LaneSize;
9066 } else if (Lanes[j] != Mask[i] / LaneSize) {
9067 // This doesn't match the lane selected previously!
9071 // Check that within each lane we have a consistent shuffle mask.
9072 int k = i % LaneSize;
9073 if (InLaneMask[k] < 0) {
9074 InLaneMask[k] = Mask[i] % LaneSize;
9075 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9076 // This doesn't fit a repeating in-lane mask.
9081 // First shuffle the lanes into place.
9082 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9083 VT.getSizeInBits() / 64);
9084 SmallVector<int, 8> LaneMask;
9085 LaneMask.resize(NumLanes * 2, -1);
9086 for (int i = 0; i < NumLanes; ++i)
9087 if (Lanes[i] >= 0) {
9088 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9089 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9092 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9093 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9094 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9096 // Cast it back to the type we actually want.
9097 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9099 // Now do a simple shuffle that isn't lane crossing.
9100 SmallVector<int, 8> NewMask;
9101 NewMask.resize(Size, -1);
9102 for (int i = 0; i < Size; ++i)
9104 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9105 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9106 "Must not introduce lane crosses at this point!");
9108 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9111 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9114 /// This returns true if the elements from a particular input are already in the
9115 /// slot required by the given mask and require no permutation.
9116 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9117 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9118 int Size = Mask.size();
9119 for (int i = 0; i < Size; ++i)
9120 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9126 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9128 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9129 /// isn't available.
9130 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9131 const X86Subtarget *Subtarget,
9132 SelectionDAG &DAG) {
9134 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9135 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9136 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9137 ArrayRef<int> Mask = SVOp->getMask();
9138 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9140 SmallVector<int, 4> WidenedMask;
9141 if (canWidenShuffleElements(Mask, WidenedMask))
9142 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9145 if (isSingleInputShuffleMask(Mask)) {
9146 // Check for being able to broadcast a single element.
9147 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9148 Mask, Subtarget, DAG))
9151 // Use low duplicate instructions for masks that match their pattern.
9152 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9153 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9155 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9156 // Non-half-crossing single input shuffles can be lowerid with an
9157 // interleaved permutation.
9158 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9159 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9160 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9161 DAG.getConstant(VPERMILPMask, MVT::i8));
9164 // With AVX2 we have direct support for this permutation.
9165 if (Subtarget->hasAVX2())
9166 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9167 getV4X86ShuffleImm8ForMask(Mask, DAG));
9169 // Otherwise, fall back.
9170 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9174 // X86 has dedicated unpack instructions that can handle specific blend
9175 // operations: UNPCKH and UNPCKL.
9176 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9177 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9178 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9179 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9180 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9181 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9182 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9183 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9185 // If we have a single input to the zero element, insert that into V1 if we
9186 // can do so cheaply.
9188 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9189 if (NumV2Elements == 1 && Mask[0] >= 4)
9190 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9191 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9194 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9198 // Check if the blend happens to exactly fit that of SHUFPD.
9199 if ((Mask[0] == -1 || Mask[0] < 2) &&
9200 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9201 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9202 (Mask[3] == -1 || Mask[3] >= 6)) {
9203 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9204 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9205 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9206 DAG.getConstant(SHUFPDMask, MVT::i8));
9208 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9209 (Mask[1] == -1 || Mask[1] < 2) &&
9210 (Mask[2] == -1 || Mask[2] >= 6) &&
9211 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9212 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9213 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9214 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9215 DAG.getConstant(SHUFPDMask, MVT::i8));
9218 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9219 // shuffle. However, if we have AVX2 and either inputs are already in place,
9220 // we will be able to shuffle even across lanes the other input in a single
9221 // instruction so skip this pattern.
9222 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9223 isShuffleMaskInputInPlace(1, Mask))))
9224 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9225 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9228 // If we have AVX2 then we always want to lower with a blend because an v4 we
9229 // can fully permute the elements.
9230 if (Subtarget->hasAVX2())
9231 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9234 // Otherwise fall back on generic lowering.
9235 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9238 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9240 /// This routine is only called when we have AVX2 and thus a reasonable
9241 /// instruction set for v4i64 shuffling..
9242 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9243 const X86Subtarget *Subtarget,
9244 SelectionDAG &DAG) {
9246 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9247 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9248 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9249 ArrayRef<int> Mask = SVOp->getMask();
9250 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9251 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9253 SmallVector<int, 4> WidenedMask;
9254 if (canWidenShuffleElements(Mask, WidenedMask))
9255 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9258 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9262 // Check for being able to broadcast a single element.
9263 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9264 Mask, Subtarget, DAG))
9267 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9268 // use lower latency instructions that will operate on both 128-bit lanes.
9269 SmallVector<int, 2> RepeatedMask;
9270 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9271 if (isSingleInputShuffleMask(Mask)) {
9272 int PSHUFDMask[] = {-1, -1, -1, -1};
9273 for (int i = 0; i < 2; ++i)
9274 if (RepeatedMask[i] >= 0) {
9275 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9276 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9279 ISD::BITCAST, DL, MVT::v4i64,
9280 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9281 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9282 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9286 // AVX2 provides a direct instruction for permuting a single input across
9288 if (isSingleInputShuffleMask(Mask))
9289 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9290 getV4X86ShuffleImm8ForMask(Mask, DAG));
9292 // Try to use shift instructions.
9294 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9297 // Use dedicated unpack instructions for masks that match their pattern.
9298 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9299 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9300 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9301 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9302 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9303 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9304 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9305 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9307 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9308 // shuffle. However, if we have AVX2 and either inputs are already in place,
9309 // we will be able to shuffle even across lanes the other input in a single
9310 // instruction so skip this pattern.
9311 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9312 isShuffleMaskInputInPlace(1, Mask))))
9313 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9314 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9317 // Otherwise fall back on generic blend lowering.
9318 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9322 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9324 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9325 /// isn't available.
9326 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9327 const X86Subtarget *Subtarget,
9328 SelectionDAG &DAG) {
9330 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9331 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9332 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9333 ArrayRef<int> Mask = SVOp->getMask();
9334 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9336 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9340 // Check for being able to broadcast a single element.
9341 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9342 Mask, Subtarget, DAG))
9345 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9346 // options to efficiently lower the shuffle.
9347 SmallVector<int, 4> RepeatedMask;
9348 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9349 assert(RepeatedMask.size() == 4 &&
9350 "Repeated masks must be half the mask width!");
9352 // Use even/odd duplicate instructions for masks that match their pattern.
9353 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9354 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9355 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9356 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9358 if (isSingleInputShuffleMask(Mask))
9359 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9360 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9362 // Use dedicated unpack instructions for masks that match their pattern.
9363 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9364 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9365 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9366 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9367 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9368 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9369 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9370 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9372 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9373 // have already handled any direct blends. We also need to squash the
9374 // repeated mask into a simulated v4f32 mask.
9375 for (int i = 0; i < 4; ++i)
9376 if (RepeatedMask[i] >= 8)
9377 RepeatedMask[i] -= 4;
9378 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9381 // If we have a single input shuffle with different shuffle patterns in the
9382 // two 128-bit lanes use the variable mask to VPERMILPS.
9383 if (isSingleInputShuffleMask(Mask)) {
9384 SDValue VPermMask[8];
9385 for (int i = 0; i < 8; ++i)
9386 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9387 : DAG.getConstant(Mask[i], MVT::i32);
9388 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9390 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9391 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9393 if (Subtarget->hasAVX2())
9394 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9395 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9396 DAG.getNode(ISD::BUILD_VECTOR, DL,
9397 MVT::v8i32, VPermMask)),
9400 // Otherwise, fall back.
9401 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9405 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9407 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9408 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9411 // If we have AVX2 then we always want to lower with a blend because at v8 we
9412 // can fully permute the elements.
9413 if (Subtarget->hasAVX2())
9414 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9417 // Otherwise fall back on generic lowering.
9418 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9421 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9423 /// This routine is only called when we have AVX2 and thus a reasonable
9424 /// instruction set for v8i32 shuffling..
9425 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9426 const X86Subtarget *Subtarget,
9427 SelectionDAG &DAG) {
9429 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9430 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9431 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9432 ArrayRef<int> Mask = SVOp->getMask();
9433 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9434 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9436 // Whenever we can lower this as a zext, that instruction is strictly faster
9437 // than any alternative. It also allows us to fold memory operands into the
9438 // shuffle in many cases.
9439 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9440 Mask, Subtarget, DAG))
9443 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9447 // Check for being able to broadcast a single element.
9448 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9449 Mask, Subtarget, DAG))
9452 // If the shuffle mask is repeated in each 128-bit lane we can use more
9453 // efficient instructions that mirror the shuffles across the two 128-bit
9455 SmallVector<int, 4> RepeatedMask;
9456 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9457 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9458 if (isSingleInputShuffleMask(Mask))
9459 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9460 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9462 // Use dedicated unpack instructions for masks that match their pattern.
9463 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9464 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9465 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9466 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9467 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9468 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9469 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9470 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9473 // Try to use shift instructions.
9475 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9478 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9479 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9482 // If the shuffle patterns aren't repeated but it is a single input, directly
9483 // generate a cross-lane VPERMD instruction.
9484 if (isSingleInputShuffleMask(Mask)) {
9485 SDValue VPermMask[8];
9486 for (int i = 0; i < 8; ++i)
9487 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9488 : DAG.getConstant(Mask[i], MVT::i32);
9490 X86ISD::VPERMV, DL, MVT::v8i32,
9491 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9494 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9496 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9497 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9500 // Otherwise fall back on generic blend lowering.
9501 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9505 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9507 /// This routine is only called when we have AVX2 and thus a reasonable
9508 /// instruction set for v16i16 shuffling..
9509 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9510 const X86Subtarget *Subtarget,
9511 SelectionDAG &DAG) {
9513 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9514 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9515 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9516 ArrayRef<int> Mask = SVOp->getMask();
9517 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9518 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9520 // Whenever we can lower this as a zext, that instruction is strictly faster
9521 // than any alternative. It also allows us to fold memory operands into the
9522 // shuffle in many cases.
9523 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9524 Mask, Subtarget, DAG))
9527 // Check for being able to broadcast a single element.
9528 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9529 Mask, Subtarget, DAG))
9532 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9536 // Use dedicated unpack instructions for masks that match their pattern.
9537 if (isShuffleEquivalent(V1, V2, Mask,
9538 {// First 128-bit lane:
9539 0, 16, 1, 17, 2, 18, 3, 19,
9540 // Second 128-bit lane:
9541 8, 24, 9, 25, 10, 26, 11, 27}))
9542 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9543 if (isShuffleEquivalent(V1, V2, Mask,
9544 {// First 128-bit lane:
9545 4, 20, 5, 21, 6, 22, 7, 23,
9546 // Second 128-bit lane:
9547 12, 28, 13, 29, 14, 30, 15, 31}))
9548 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9550 // Try to use shift instructions.
9552 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9555 // Try to use byte rotation instructions.
9556 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9557 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9560 if (isSingleInputShuffleMask(Mask)) {
9561 // There are no generalized cross-lane shuffle operations available on i16
9563 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9564 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9567 SmallVector<int, 8> RepeatedMask;
9568 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9569 // As this is a single-input shuffle, the repeated mask should be
9570 // a strictly valid v8i16 mask that we can pass through to the v8i16
9571 // lowering to handle even the v16 case.
9572 return lowerV8I16GeneralSingleInputVectorShuffle(
9573 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9576 SDValue PSHUFBMask[32];
9577 for (int i = 0; i < 16; ++i) {
9578 if (Mask[i] == -1) {
9579 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9583 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9584 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9585 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9586 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9589 ISD::BITCAST, DL, MVT::v16i16,
9591 X86ISD::PSHUFB, DL, MVT::v32i8,
9592 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9593 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9596 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9598 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9599 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9602 // Otherwise fall back on generic lowering.
9603 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9606 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9608 /// This routine is only called when we have AVX2 and thus a reasonable
9609 /// instruction set for v32i8 shuffling..
9610 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9611 const X86Subtarget *Subtarget,
9612 SelectionDAG &DAG) {
9614 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9615 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9616 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9617 ArrayRef<int> Mask = SVOp->getMask();
9618 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9619 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9621 // Whenever we can lower this as a zext, that instruction is strictly faster
9622 // than any alternative. It also allows us to fold memory operands into the
9623 // shuffle in many cases.
9624 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9625 Mask, Subtarget, DAG))
9628 // Check for being able to broadcast a single element.
9629 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9630 Mask, Subtarget, DAG))
9633 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9637 // Use dedicated unpack instructions for masks that match their pattern.
9638 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9640 if (isShuffleEquivalent(
9642 {// First 128-bit lane:
9643 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9644 // Second 128-bit lane:
9645 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9646 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9647 if (isShuffleEquivalent(
9649 {// First 128-bit lane:
9650 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9651 // Second 128-bit lane:
9652 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9653 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9655 // Try to use shift instructions.
9657 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9660 // Try to use byte rotation instructions.
9661 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9662 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9665 if (isSingleInputShuffleMask(Mask)) {
9666 // There are no generalized cross-lane shuffle operations available on i8
9668 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9669 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9672 SDValue PSHUFBMask[32];
9673 for (int i = 0; i < 32; ++i)
9676 ? DAG.getUNDEF(MVT::i8)
9677 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9680 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9681 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9684 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9686 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9687 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9690 // Otherwise fall back on generic lowering.
9691 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9694 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9696 /// This routine either breaks down the specific type of a 256-bit x86 vector
9697 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9698 /// together based on the available instructions.
9699 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9700 MVT VT, const X86Subtarget *Subtarget,
9701 SelectionDAG &DAG) {
9703 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9704 ArrayRef<int> Mask = SVOp->getMask();
9706 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9707 // check for those subtargets here and avoid much of the subtarget querying in
9708 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9709 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9710 // floating point types there eventually, just immediately cast everything to
9711 // a float and operate entirely in that domain.
9712 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9713 int ElementBits = VT.getScalarSizeInBits();
9714 if (ElementBits < 32)
9715 // No floating point type available, decompose into 128-bit vectors.
9716 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9718 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9719 VT.getVectorNumElements());
9720 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9721 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9722 return DAG.getNode(ISD::BITCAST, DL, VT,
9723 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9726 switch (VT.SimpleTy) {
9728 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9730 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9732 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9734 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9736 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9738 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9741 llvm_unreachable("Not a valid 256-bit x86 vector type!");
9745 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9746 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9747 const X86Subtarget *Subtarget,
9748 SelectionDAG &DAG) {
9750 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9751 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9752 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9753 ArrayRef<int> Mask = SVOp->getMask();
9754 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9756 // X86 has dedicated unpack instructions that can handle specific blend
9757 // operations: UNPCKH and UNPCKL.
9758 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9759 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9760 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9761 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9763 // FIXME: Implement direct support for this type!
9764 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9767 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9768 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9769 const X86Subtarget *Subtarget,
9770 SelectionDAG &DAG) {
9772 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9773 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9774 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9775 ArrayRef<int> Mask = SVOp->getMask();
9776 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9778 // Use dedicated unpack instructions for masks that match their pattern.
9779 if (isShuffleEquivalent(V1, V2, Mask,
9780 {// First 128-bit lane.
9781 0, 16, 1, 17, 4, 20, 5, 21,
9782 // Second 128-bit lane.
9783 8, 24, 9, 25, 12, 28, 13, 29}))
9784 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9785 if (isShuffleEquivalent(V1, V2, Mask,
9786 {// First 128-bit lane.
9787 2, 18, 3, 19, 6, 22, 7, 23,
9788 // Second 128-bit lane.
9789 10, 26, 11, 27, 14, 30, 15, 31}))
9790 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9792 // FIXME: Implement direct support for this type!
9793 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9796 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9797 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9798 const X86Subtarget *Subtarget,
9799 SelectionDAG &DAG) {
9801 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9802 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9803 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9804 ArrayRef<int> Mask = SVOp->getMask();
9805 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9807 // X86 has dedicated unpack instructions that can handle specific blend
9808 // operations: UNPCKH and UNPCKL.
9809 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9810 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9811 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9812 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9814 // FIXME: Implement direct support for this type!
9815 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9818 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9819 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9820 const X86Subtarget *Subtarget,
9821 SelectionDAG &DAG) {
9823 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9824 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9825 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9826 ArrayRef<int> Mask = SVOp->getMask();
9827 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9829 // Use dedicated unpack instructions for masks that match their pattern.
9830 if (isShuffleEquivalent(V1, V2, Mask,
9831 {// First 128-bit lane.
9832 0, 16, 1, 17, 4, 20, 5, 21,
9833 // Second 128-bit lane.
9834 8, 24, 9, 25, 12, 28, 13, 29}))
9835 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9836 if (isShuffleEquivalent(V1, V2, Mask,
9837 {// First 128-bit lane.
9838 2, 18, 3, 19, 6, 22, 7, 23,
9839 // Second 128-bit lane.
9840 10, 26, 11, 27, 14, 30, 15, 31}))
9841 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9843 // FIXME: Implement direct support for this type!
9844 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9847 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9848 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9849 const X86Subtarget *Subtarget,
9850 SelectionDAG &DAG) {
9852 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9853 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9854 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9855 ArrayRef<int> Mask = SVOp->getMask();
9856 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9857 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9859 // FIXME: Implement direct support for this type!
9860 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9863 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9864 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9865 const X86Subtarget *Subtarget,
9866 SelectionDAG &DAG) {
9868 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9869 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9870 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9871 ArrayRef<int> Mask = SVOp->getMask();
9872 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9873 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9875 // FIXME: Implement direct support for this type!
9876 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9879 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9881 /// This routine either breaks down the specific type of a 512-bit x86 vector
9882 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9883 /// together based on the available instructions.
9884 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9885 MVT VT, const X86Subtarget *Subtarget,
9886 SelectionDAG &DAG) {
9888 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9889 ArrayRef<int> Mask = SVOp->getMask();
9890 assert(Subtarget->hasAVX512() &&
9891 "Cannot lower 512-bit vectors w/ basic ISA!");
9893 // Check for being able to broadcast a single element.
9894 if (SDValue Broadcast =
9895 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
9898 // Dispatch to each element type for lowering. If we don't have supprot for
9899 // specific element type shuffles at 512 bits, immediately split them and
9900 // lower them. Each lowering routine of a given type is allowed to assume that
9901 // the requisite ISA extensions for that element type are available.
9902 switch (VT.SimpleTy) {
9904 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9906 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9908 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9910 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9912 if (Subtarget->hasBWI())
9913 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9916 if (Subtarget->hasBWI())
9917 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9921 llvm_unreachable("Not a valid 512-bit x86 vector type!");
9924 // Otherwise fall back on splitting.
9925 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9928 /// \brief Top-level lowering for x86 vector shuffles.
9930 /// This handles decomposition, canonicalization, and lowering of all x86
9931 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9932 /// above in helper routines. The canonicalization attempts to widen shuffles
9933 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9934 /// s.t. only one of the two inputs needs to be tested, etc.
9935 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9936 SelectionDAG &DAG) {
9937 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9938 ArrayRef<int> Mask = SVOp->getMask();
9939 SDValue V1 = Op.getOperand(0);
9940 SDValue V2 = Op.getOperand(1);
9941 MVT VT = Op.getSimpleValueType();
9942 int NumElements = VT.getVectorNumElements();
9945 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9947 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9948 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9949 if (V1IsUndef && V2IsUndef)
9950 return DAG.getUNDEF(VT);
9952 // When we create a shuffle node we put the UNDEF node to second operand,
9953 // but in some cases the first operand may be transformed to UNDEF.
9954 // In this case we should just commute the node.
9956 return DAG.getCommutedVectorShuffle(*SVOp);
9958 // Check for non-undef masks pointing at an undef vector and make the masks
9959 // undef as well. This makes it easier to match the shuffle based solely on
9963 if (M >= NumElements) {
9964 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
9965 for (int &M : NewMask)
9966 if (M >= NumElements)
9968 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
9971 // We actually see shuffles that are entirely re-arrangements of a set of
9972 // zero inputs. This mostly happens while decomposing complex shuffles into
9973 // simple ones. Directly lower these as a buildvector of zeros.
9974 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9976 return getZeroVector(VT, Subtarget, DAG, dl);
9978 // Try to collapse shuffles into using a vector type with fewer elements but
9979 // wider element types. We cap this to not form integers or floating point
9980 // elements wider than 64 bits, but it might be interesting to form i128
9981 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
9982 SmallVector<int, 16> WidenedMask;
9983 if (VT.getScalarSizeInBits() < 64 &&
9984 canWidenShuffleElements(Mask, WidenedMask)) {
9985 MVT NewEltVT = VT.isFloatingPoint()
9986 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
9987 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
9988 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
9989 // Make sure that the new vector type is legal. For example, v2f64 isn't
9991 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
9992 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
9993 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
9994 return DAG.getNode(ISD::BITCAST, dl, VT,
9995 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
9999 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10000 for (int M : SVOp->getMask())
10002 ++NumUndefElements;
10003 else if (M < NumElements)
10008 // Commute the shuffle as needed such that more elements come from V1 than
10009 // V2. This allows us to match the shuffle pattern strictly on how many
10010 // elements come from V1 without handling the symmetric cases.
10011 if (NumV2Elements > NumV1Elements)
10012 return DAG.getCommutedVectorShuffle(*SVOp);
10014 // When the number of V1 and V2 elements are the same, try to minimize the
10015 // number of uses of V2 in the low half of the vector. When that is tied,
10016 // ensure that the sum of indices for V1 is equal to or lower than the sum
10017 // indices for V2. When those are equal, try to ensure that the number of odd
10018 // indices for V1 is lower than the number of odd indices for V2.
10019 if (NumV1Elements == NumV2Elements) {
10020 int LowV1Elements = 0, LowV2Elements = 0;
10021 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10022 if (M >= NumElements)
10026 if (LowV2Elements > LowV1Elements) {
10027 return DAG.getCommutedVectorShuffle(*SVOp);
10028 } else if (LowV2Elements == LowV1Elements) {
10029 int SumV1Indices = 0, SumV2Indices = 0;
10030 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10031 if (SVOp->getMask()[i] >= NumElements)
10033 else if (SVOp->getMask()[i] >= 0)
10035 if (SumV2Indices < SumV1Indices) {
10036 return DAG.getCommutedVectorShuffle(*SVOp);
10037 } else if (SumV2Indices == SumV1Indices) {
10038 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10039 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10040 if (SVOp->getMask()[i] >= NumElements)
10041 NumV2OddIndices += i % 2;
10042 else if (SVOp->getMask()[i] >= 0)
10043 NumV1OddIndices += i % 2;
10044 if (NumV2OddIndices < NumV1OddIndices)
10045 return DAG.getCommutedVectorShuffle(*SVOp);
10050 // For each vector width, delegate to a specialized lowering routine.
10051 if (VT.getSizeInBits() == 128)
10052 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10054 if (VT.getSizeInBits() == 256)
10055 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10057 // Force AVX-512 vectors to be scalarized for now.
10058 // FIXME: Implement AVX-512 support!
10059 if (VT.getSizeInBits() == 512)
10060 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10062 llvm_unreachable("Unimplemented!");
10065 // This function assumes its argument is a BUILD_VECTOR of constants or
10066 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10068 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10069 unsigned &MaskValue) {
10071 unsigned NumElems = BuildVector->getNumOperands();
10072 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10073 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10074 unsigned NumElemsInLane = NumElems / NumLanes;
10076 // Blend for v16i16 should be symetric for the both lanes.
10077 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10078 SDValue EltCond = BuildVector->getOperand(i);
10079 SDValue SndLaneEltCond =
10080 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10082 int Lane1Cond = -1, Lane2Cond = -1;
10083 if (isa<ConstantSDNode>(EltCond))
10084 Lane1Cond = !isZero(EltCond);
10085 if (isa<ConstantSDNode>(SndLaneEltCond))
10086 Lane2Cond = !isZero(SndLaneEltCond);
10088 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10089 // Lane1Cond != 0, means we want the first argument.
10090 // Lane1Cond == 0, means we want the second argument.
10091 // The encoding of this argument is 0 for the first argument, 1
10092 // for the second. Therefore, invert the condition.
10093 MaskValue |= !Lane1Cond << i;
10094 else if (Lane1Cond < 0)
10095 MaskValue |= !Lane2Cond << i;
10102 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10103 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10104 const X86Subtarget *Subtarget,
10105 SelectionDAG &DAG) {
10106 SDValue Cond = Op.getOperand(0);
10107 SDValue LHS = Op.getOperand(1);
10108 SDValue RHS = Op.getOperand(2);
10110 MVT VT = Op.getSimpleValueType();
10112 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10114 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10116 // Only non-legal VSELECTs reach this lowering, convert those into generic
10117 // shuffles and re-use the shuffle lowering path for blends.
10118 SmallVector<int, 32> Mask;
10119 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10120 SDValue CondElt = CondBV->getOperand(i);
10122 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10124 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10127 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10128 // A vselect where all conditions and data are constants can be optimized into
10129 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10130 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10131 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10132 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10135 // Try to lower this to a blend-style vector shuffle. This can handle all
10136 // constant condition cases.
10137 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10140 // Variable blends are only legal from SSE4.1 onward.
10141 if (!Subtarget->hasSSE41())
10144 // Only some types will be legal on some subtargets. If we can emit a legal
10145 // VSELECT-matching blend, return Op, and but if we need to expand, return
10147 switch (Op.getSimpleValueType().SimpleTy) {
10149 // Most of the vector types have blends past SSE4.1.
10153 // The byte blends for AVX vectors were introduced only in AVX2.
10154 if (Subtarget->hasAVX2())
10161 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10162 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10165 // FIXME: We should custom lower this by fixing the condition and using i8
10171 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10172 MVT VT = Op.getSimpleValueType();
10175 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10178 if (VT.getSizeInBits() == 8) {
10179 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10180 Op.getOperand(0), Op.getOperand(1));
10181 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10182 DAG.getValueType(VT));
10183 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10186 if (VT.getSizeInBits() == 16) {
10187 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10188 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10190 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10191 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10192 DAG.getNode(ISD::BITCAST, dl,
10195 Op.getOperand(1)));
10196 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10197 Op.getOperand(0), Op.getOperand(1));
10198 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10199 DAG.getValueType(VT));
10200 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10203 if (VT == MVT::f32) {
10204 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10205 // the result back to FR32 register. It's only worth matching if the
10206 // result has a single use which is a store or a bitcast to i32. And in
10207 // the case of a store, it's not worth it if the index is a constant 0,
10208 // because a MOVSSmr can be used instead, which is smaller and faster.
10209 if (!Op.hasOneUse())
10211 SDNode *User = *Op.getNode()->use_begin();
10212 if ((User->getOpcode() != ISD::STORE ||
10213 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10214 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10215 (User->getOpcode() != ISD::BITCAST ||
10216 User->getValueType(0) != MVT::i32))
10218 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10219 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10222 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10225 if (VT == MVT::i32 || VT == MVT::i64) {
10226 // ExtractPS/pextrq works with constant index.
10227 if (isa<ConstantSDNode>(Op.getOperand(1)))
10233 /// Extract one bit from mask vector, like v16i1 or v8i1.
10234 /// AVX-512 feature.
10236 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10237 SDValue Vec = Op.getOperand(0);
10239 MVT VecVT = Vec.getSimpleValueType();
10240 SDValue Idx = Op.getOperand(1);
10241 MVT EltVT = Op.getSimpleValueType();
10243 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10244 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10245 "Unexpected vector type in ExtractBitFromMaskVector");
10247 // variable index can't be handled in mask registers,
10248 // extend vector to VR512
10249 if (!isa<ConstantSDNode>(Idx)) {
10250 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10251 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10252 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10253 ExtVT.getVectorElementType(), Ext, Idx);
10254 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10257 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10258 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10259 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10260 rc = getRegClassFor(MVT::v16i1);
10261 unsigned MaxSift = rc->getSize()*8 - 1;
10262 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10263 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10264 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10265 DAG.getConstant(MaxSift, MVT::i8));
10266 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10267 DAG.getIntPtrConstant(0));
10271 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10272 SelectionDAG &DAG) const {
10274 SDValue Vec = Op.getOperand(0);
10275 MVT VecVT = Vec.getSimpleValueType();
10276 SDValue Idx = Op.getOperand(1);
10278 if (Op.getSimpleValueType() == MVT::i1)
10279 return ExtractBitFromMaskVector(Op, DAG);
10281 if (!isa<ConstantSDNode>(Idx)) {
10282 if (VecVT.is512BitVector() ||
10283 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10284 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10287 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10288 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10289 MaskEltVT.getSizeInBits());
10291 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10292 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10293 getZeroVector(MaskVT, Subtarget, DAG, dl),
10294 Idx, DAG.getConstant(0, getPointerTy()));
10295 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10296 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10297 Perm, DAG.getConstant(0, getPointerTy()));
10302 // If this is a 256-bit vector result, first extract the 128-bit vector and
10303 // then extract the element from the 128-bit vector.
10304 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10306 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10307 // Get the 128-bit vector.
10308 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10309 MVT EltVT = VecVT.getVectorElementType();
10311 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10313 //if (IdxVal >= NumElems/2)
10314 // IdxVal -= NumElems/2;
10315 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10316 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10317 DAG.getConstant(IdxVal, MVT::i32));
10320 assert(VecVT.is128BitVector() && "Unexpected vector length");
10322 if (Subtarget->hasSSE41()) {
10323 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10328 MVT VT = Op.getSimpleValueType();
10329 // TODO: handle v16i8.
10330 if (VT.getSizeInBits() == 16) {
10331 SDValue Vec = Op.getOperand(0);
10332 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10334 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10335 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10336 DAG.getNode(ISD::BITCAST, dl,
10338 Op.getOperand(1)));
10339 // Transform it so it match pextrw which produces a 32-bit result.
10340 MVT EltVT = MVT::i32;
10341 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10342 Op.getOperand(0), Op.getOperand(1));
10343 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10344 DAG.getValueType(VT));
10345 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10348 if (VT.getSizeInBits() == 32) {
10349 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10353 // SHUFPS the element to the lowest double word, then movss.
10354 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10355 MVT VVT = Op.getOperand(0).getSimpleValueType();
10356 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10357 DAG.getUNDEF(VVT), Mask);
10358 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10359 DAG.getIntPtrConstant(0));
10362 if (VT.getSizeInBits() == 64) {
10363 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10364 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10365 // to match extract_elt for f64.
10366 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10370 // UNPCKHPD the element to the lowest double word, then movsd.
10371 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10372 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10373 int Mask[2] = { 1, -1 };
10374 MVT VVT = Op.getOperand(0).getSimpleValueType();
10375 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10376 DAG.getUNDEF(VVT), Mask);
10377 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10378 DAG.getIntPtrConstant(0));
10384 /// Insert one bit to mask vector, like v16i1 or v8i1.
10385 /// AVX-512 feature.
10387 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10389 SDValue Vec = Op.getOperand(0);
10390 SDValue Elt = Op.getOperand(1);
10391 SDValue Idx = Op.getOperand(2);
10392 MVT VecVT = Vec.getSimpleValueType();
10394 if (!isa<ConstantSDNode>(Idx)) {
10395 // Non constant index. Extend source and destination,
10396 // insert element and then truncate the result.
10397 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10398 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10399 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10400 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10401 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10402 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10405 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10406 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10407 if (Vec.getOpcode() == ISD::UNDEF)
10408 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10409 DAG.getConstant(IdxVal, MVT::i8));
10410 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10411 unsigned MaxSift = rc->getSize()*8 - 1;
10412 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10413 DAG.getConstant(MaxSift, MVT::i8));
10414 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10415 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10416 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10419 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10420 SelectionDAG &DAG) const {
10421 MVT VT = Op.getSimpleValueType();
10422 MVT EltVT = VT.getVectorElementType();
10424 if (EltVT == MVT::i1)
10425 return InsertBitToMaskVector(Op, DAG);
10428 SDValue N0 = Op.getOperand(0);
10429 SDValue N1 = Op.getOperand(1);
10430 SDValue N2 = Op.getOperand(2);
10431 if (!isa<ConstantSDNode>(N2))
10433 auto *N2C = cast<ConstantSDNode>(N2);
10434 unsigned IdxVal = N2C->getZExtValue();
10436 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10437 // into that, and then insert the subvector back into the result.
10438 if (VT.is256BitVector() || VT.is512BitVector()) {
10439 // Get the desired 128-bit vector half.
10440 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10442 // Insert the element into the desired half.
10443 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10444 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10446 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10447 DAG.getConstant(IdxIn128, MVT::i32));
10449 // Insert the changed part back to the 256-bit vector
10450 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10452 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10454 if (Subtarget->hasSSE41()) {
10455 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10457 if (VT == MVT::v8i16) {
10458 Opc = X86ISD::PINSRW;
10460 assert(VT == MVT::v16i8);
10461 Opc = X86ISD::PINSRB;
10464 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10466 if (N1.getValueType() != MVT::i32)
10467 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10468 if (N2.getValueType() != MVT::i32)
10469 N2 = DAG.getIntPtrConstant(IdxVal);
10470 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10473 if (EltVT == MVT::f32) {
10474 // Bits [7:6] of the constant are the source select. This will always be
10475 // zero here. The DAG Combiner may combine an extract_elt index into
10477 // bits. For example (insert (extract, 3), 2) could be matched by
10479 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10480 // Bits [5:4] of the constant are the destination select. This is the
10481 // value of the incoming immediate.
10482 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10483 // combine either bitwise AND or insert of float 0.0 to set these bits.
10484 N2 = DAG.getIntPtrConstant(IdxVal << 4);
10485 // Create this as a scalar to vector..
10486 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10487 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10490 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10491 // PINSR* works with constant index.
10496 if (EltVT == MVT::i8)
10499 if (EltVT.getSizeInBits() == 16) {
10500 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10501 // as its second argument.
10502 if (N1.getValueType() != MVT::i32)
10503 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10504 if (N2.getValueType() != MVT::i32)
10505 N2 = DAG.getIntPtrConstant(IdxVal);
10506 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10511 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10513 MVT OpVT = Op.getSimpleValueType();
10515 // If this is a 256-bit vector result, first insert into a 128-bit
10516 // vector and then insert into the 256-bit vector.
10517 if (!OpVT.is128BitVector()) {
10518 // Insert into a 128-bit vector.
10519 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10520 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10521 OpVT.getVectorNumElements() / SizeFactor);
10523 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10525 // Insert the 128-bit vector.
10526 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10529 if (OpVT == MVT::v1i64 &&
10530 Op.getOperand(0).getValueType() == MVT::i64)
10531 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10533 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10534 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10535 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10536 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10539 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10540 // a simple subregister reference or explicit instructions to grab
10541 // upper bits of a vector.
10542 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10543 SelectionDAG &DAG) {
10545 SDValue In = Op.getOperand(0);
10546 SDValue Idx = Op.getOperand(1);
10547 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10548 MVT ResVT = Op.getSimpleValueType();
10549 MVT InVT = In.getSimpleValueType();
10551 if (Subtarget->hasFp256()) {
10552 if (ResVT.is128BitVector() &&
10553 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10554 isa<ConstantSDNode>(Idx)) {
10555 return Extract128BitVector(In, IdxVal, DAG, dl);
10557 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10558 isa<ConstantSDNode>(Idx)) {
10559 return Extract256BitVector(In, IdxVal, DAG, dl);
10565 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10566 // simple superregister reference or explicit instructions to insert
10567 // the upper bits of a vector.
10568 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10569 SelectionDAG &DAG) {
10570 if (!Subtarget->hasAVX())
10574 SDValue Vec = Op.getOperand(0);
10575 SDValue SubVec = Op.getOperand(1);
10576 SDValue Idx = Op.getOperand(2);
10578 if (!isa<ConstantSDNode>(Idx))
10581 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10582 MVT OpVT = Op.getSimpleValueType();
10583 MVT SubVecVT = SubVec.getSimpleValueType();
10585 // Fold two 16-byte subvector loads into one 32-byte load:
10586 // (insert_subvector (insert_subvector undef, (load addr), 0),
10587 // (load addr + 16), Elts/2)
10589 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10590 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10591 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10592 !Subtarget->isUnalignedMem32Slow()) {
10593 SDValue SubVec2 = Vec.getOperand(1);
10594 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10595 if (Idx2->getZExtValue() == 0) {
10596 SDValue Ops[] = { SubVec2, SubVec };
10597 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10604 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10605 SubVecVT.is128BitVector())
10606 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10608 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10609 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10614 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10615 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10616 // one of the above mentioned nodes. It has to be wrapped because otherwise
10617 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10618 // be used to form addressing mode. These wrapped nodes will be selected
10621 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10622 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10624 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10625 // global base reg.
10626 unsigned char OpFlag = 0;
10627 unsigned WrapperKind = X86ISD::Wrapper;
10628 CodeModel::Model M = DAG.getTarget().getCodeModel();
10630 if (Subtarget->isPICStyleRIPRel() &&
10631 (M == CodeModel::Small || M == CodeModel::Kernel))
10632 WrapperKind = X86ISD::WrapperRIP;
10633 else if (Subtarget->isPICStyleGOT())
10634 OpFlag = X86II::MO_GOTOFF;
10635 else if (Subtarget->isPICStyleStubPIC())
10636 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10638 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10639 CP->getAlignment(),
10640 CP->getOffset(), OpFlag);
10642 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10643 // With PIC, the address is actually $g + Offset.
10645 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10646 DAG.getNode(X86ISD::GlobalBaseReg,
10647 SDLoc(), getPointerTy()),
10654 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10655 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10657 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10658 // global base reg.
10659 unsigned char OpFlag = 0;
10660 unsigned WrapperKind = X86ISD::Wrapper;
10661 CodeModel::Model M = DAG.getTarget().getCodeModel();
10663 if (Subtarget->isPICStyleRIPRel() &&
10664 (M == CodeModel::Small || M == CodeModel::Kernel))
10665 WrapperKind = X86ISD::WrapperRIP;
10666 else if (Subtarget->isPICStyleGOT())
10667 OpFlag = X86II::MO_GOTOFF;
10668 else if (Subtarget->isPICStyleStubPIC())
10669 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10671 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10674 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10676 // With PIC, the address is actually $g + Offset.
10678 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10679 DAG.getNode(X86ISD::GlobalBaseReg,
10680 SDLoc(), getPointerTy()),
10687 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10688 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10690 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10691 // global base reg.
10692 unsigned char OpFlag = 0;
10693 unsigned WrapperKind = X86ISD::Wrapper;
10694 CodeModel::Model M = DAG.getTarget().getCodeModel();
10696 if (Subtarget->isPICStyleRIPRel() &&
10697 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10698 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10699 OpFlag = X86II::MO_GOTPCREL;
10700 WrapperKind = X86ISD::WrapperRIP;
10701 } else if (Subtarget->isPICStyleGOT()) {
10702 OpFlag = X86II::MO_GOT;
10703 } else if (Subtarget->isPICStyleStubPIC()) {
10704 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10705 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10706 OpFlag = X86II::MO_DARWIN_NONLAZY;
10709 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10712 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10714 // With PIC, the address is actually $g + Offset.
10715 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10716 !Subtarget->is64Bit()) {
10717 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10718 DAG.getNode(X86ISD::GlobalBaseReg,
10719 SDLoc(), getPointerTy()),
10723 // For symbols that require a load from a stub to get the address, emit the
10725 if (isGlobalStubReference(OpFlag))
10726 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10727 MachinePointerInfo::getGOT(), false, false, false, 0);
10733 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10734 // Create the TargetBlockAddressAddress node.
10735 unsigned char OpFlags =
10736 Subtarget->ClassifyBlockAddressReference();
10737 CodeModel::Model M = DAG.getTarget().getCodeModel();
10738 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10739 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10741 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10744 if (Subtarget->isPICStyleRIPRel() &&
10745 (M == CodeModel::Small || M == CodeModel::Kernel))
10746 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10748 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10750 // With PIC, the address is actually $g + Offset.
10751 if (isGlobalRelativeToPICBase(OpFlags)) {
10752 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10753 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10761 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10762 int64_t Offset, SelectionDAG &DAG) const {
10763 // Create the TargetGlobalAddress node, folding in the constant
10764 // offset if it is legal.
10765 unsigned char OpFlags =
10766 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10767 CodeModel::Model M = DAG.getTarget().getCodeModel();
10769 if (OpFlags == X86II::MO_NO_FLAG &&
10770 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10771 // A direct static reference to a global.
10772 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10775 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10778 if (Subtarget->isPICStyleRIPRel() &&
10779 (M == CodeModel::Small || M == CodeModel::Kernel))
10780 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10782 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10784 // With PIC, the address is actually $g + Offset.
10785 if (isGlobalRelativeToPICBase(OpFlags)) {
10786 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10787 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10791 // For globals that require a load from a stub to get the address, emit the
10793 if (isGlobalStubReference(OpFlags))
10794 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10795 MachinePointerInfo::getGOT(), false, false, false, 0);
10797 // If there was a non-zero offset that we didn't fold, create an explicit
10798 // addition for it.
10800 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10801 DAG.getConstant(Offset, getPointerTy()));
10807 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10808 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10809 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10810 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10814 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10815 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10816 unsigned char OperandFlags, bool LocalDynamic = false) {
10817 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10818 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10820 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10821 GA->getValueType(0),
10825 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10829 SDValue Ops[] = { Chain, TGA, *InFlag };
10830 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10832 SDValue Ops[] = { Chain, TGA };
10833 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10836 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10837 MFI->setAdjustsStack(true);
10838 MFI->setHasCalls(true);
10840 SDValue Flag = Chain.getValue(1);
10841 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10844 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10846 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10849 SDLoc dl(GA); // ? function entry point might be better
10850 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10851 DAG.getNode(X86ISD::GlobalBaseReg,
10852 SDLoc(), PtrVT), InFlag);
10853 InFlag = Chain.getValue(1);
10855 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10858 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10860 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10862 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10863 X86::RAX, X86II::MO_TLSGD);
10866 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10872 // Get the start address of the TLS block for this module.
10873 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10874 .getInfo<X86MachineFunctionInfo>();
10875 MFI->incNumLocalDynamicTLSAccesses();
10879 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10880 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10883 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10884 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10885 InFlag = Chain.getValue(1);
10886 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10887 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10890 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10894 unsigned char OperandFlags = X86II::MO_DTPOFF;
10895 unsigned WrapperKind = X86ISD::Wrapper;
10896 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10897 GA->getValueType(0),
10898 GA->getOffset(), OperandFlags);
10899 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10901 // Add x@dtpoff with the base.
10902 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10905 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10906 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10907 const EVT PtrVT, TLSModel::Model model,
10908 bool is64Bit, bool isPIC) {
10911 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10912 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10913 is64Bit ? 257 : 256));
10915 SDValue ThreadPointer =
10916 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10917 MachinePointerInfo(Ptr), false, false, false, 0);
10919 unsigned char OperandFlags = 0;
10920 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10922 unsigned WrapperKind = X86ISD::Wrapper;
10923 if (model == TLSModel::LocalExec) {
10924 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10925 } else if (model == TLSModel::InitialExec) {
10927 OperandFlags = X86II::MO_GOTTPOFF;
10928 WrapperKind = X86ISD::WrapperRIP;
10930 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10933 llvm_unreachable("Unexpected model");
10936 // emit "addl x@ntpoff,%eax" (local exec)
10937 // or "addl x@indntpoff,%eax" (initial exec)
10938 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10940 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10941 GA->getOffset(), OperandFlags);
10942 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10944 if (model == TLSModel::InitialExec) {
10945 if (isPIC && !is64Bit) {
10946 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10947 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10951 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10952 MachinePointerInfo::getGOT(), false, false, false, 0);
10955 // The address of the thread local variable is the add of the thread
10956 // pointer with the offset of the variable.
10957 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10961 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10963 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10964 const GlobalValue *GV = GA->getGlobal();
10966 if (Subtarget->isTargetELF()) {
10967 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10970 case TLSModel::GeneralDynamic:
10971 if (Subtarget->is64Bit())
10972 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10973 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10974 case TLSModel::LocalDynamic:
10975 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10976 Subtarget->is64Bit());
10977 case TLSModel::InitialExec:
10978 case TLSModel::LocalExec:
10979 return LowerToTLSExecModel(
10980 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10981 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10983 llvm_unreachable("Unknown TLS model.");
10986 if (Subtarget->isTargetDarwin()) {
10987 // Darwin only has one model of TLS. Lower to that.
10988 unsigned char OpFlag = 0;
10989 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10990 X86ISD::WrapperRIP : X86ISD::Wrapper;
10992 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10993 // global base reg.
10994 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10995 !Subtarget->is64Bit();
10997 OpFlag = X86II::MO_TLVP_PIC_BASE;
10999 OpFlag = X86II::MO_TLVP;
11001 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11002 GA->getValueType(0),
11003 GA->getOffset(), OpFlag);
11004 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11006 // With PIC32, the address is actually $g + Offset.
11008 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11009 DAG.getNode(X86ISD::GlobalBaseReg,
11010 SDLoc(), getPointerTy()),
11013 // Lowering the machine isd will make sure everything is in the right
11015 SDValue Chain = DAG.getEntryNode();
11016 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11017 SDValue Args[] = { Chain, Offset };
11018 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11020 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11021 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11022 MFI->setAdjustsStack(true);
11024 // And our return value (tls address) is in the standard call return value
11026 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11027 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11028 Chain.getValue(1));
11031 if (Subtarget->isTargetKnownWindowsMSVC() ||
11032 Subtarget->isTargetWindowsGNU()) {
11033 // Just use the implicit TLS architecture
11034 // Need to generate someting similar to:
11035 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11037 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11038 // mov rcx, qword [rdx+rcx*8]
11039 // mov eax, .tls$:tlsvar
11040 // [rax+rcx] contains the address
11041 // Windows 64bit: gs:0x58
11042 // Windows 32bit: fs:__tls_array
11045 SDValue Chain = DAG.getEntryNode();
11047 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11048 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11049 // use its literal value of 0x2C.
11050 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11051 ? Type::getInt8PtrTy(*DAG.getContext(),
11053 : Type::getInt32PtrTy(*DAG.getContext(),
11057 Subtarget->is64Bit()
11058 ? DAG.getIntPtrConstant(0x58)
11059 : (Subtarget->isTargetWindowsGNU()
11060 ? DAG.getIntPtrConstant(0x2C)
11061 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11063 SDValue ThreadPointer =
11064 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11065 MachinePointerInfo(Ptr), false, false, false, 0);
11067 // Load the _tls_index variable
11068 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11069 if (Subtarget->is64Bit())
11070 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11071 IDX, MachinePointerInfo(), MVT::i32,
11072 false, false, false, 0);
11074 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11075 false, false, false, 0);
11077 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11079 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11081 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11082 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11083 false, false, false, 0);
11085 // Get the offset of start of .tls section
11086 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11087 GA->getValueType(0),
11088 GA->getOffset(), X86II::MO_SECREL);
11089 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11091 // The address of the thread local variable is the add of the thread
11092 // pointer with the offset of the variable.
11093 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11096 llvm_unreachable("TLS not implemented for this target.");
11099 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11100 /// and take a 2 x i32 value to shift plus a shift amount.
11101 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11102 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11103 MVT VT = Op.getSimpleValueType();
11104 unsigned VTBits = VT.getSizeInBits();
11106 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11107 SDValue ShOpLo = Op.getOperand(0);
11108 SDValue ShOpHi = Op.getOperand(1);
11109 SDValue ShAmt = Op.getOperand(2);
11110 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11111 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11113 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11114 DAG.getConstant(VTBits - 1, MVT::i8));
11115 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11116 DAG.getConstant(VTBits - 1, MVT::i8))
11117 : DAG.getConstant(0, VT);
11119 SDValue Tmp2, Tmp3;
11120 if (Op.getOpcode() == ISD::SHL_PARTS) {
11121 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11122 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11124 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11125 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11128 // If the shift amount is larger or equal than the width of a part we can't
11129 // rely on the results of shld/shrd. Insert a test and select the appropriate
11130 // values for large shift amounts.
11131 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11132 DAG.getConstant(VTBits, MVT::i8));
11133 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11134 AndNode, DAG.getConstant(0, MVT::i8));
11137 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11138 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11139 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11141 if (Op.getOpcode() == ISD::SHL_PARTS) {
11142 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11143 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11145 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11146 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11149 SDValue Ops[2] = { Lo, Hi };
11150 return DAG.getMergeValues(Ops, dl);
11153 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11154 SelectionDAG &DAG) const {
11155 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11158 if (SrcVT.isVector()) {
11159 if (SrcVT.getVectorElementType() == MVT::i1) {
11160 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11161 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11162 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11163 Op.getOperand(0)));
11168 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11169 "Unknown SINT_TO_FP to lower!");
11171 // These are really Legal; return the operand so the caller accepts it as
11173 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11175 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11176 Subtarget->is64Bit()) {
11180 unsigned Size = SrcVT.getSizeInBits()/8;
11181 MachineFunction &MF = DAG.getMachineFunction();
11182 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11183 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11184 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11186 MachinePointerInfo::getFixedStack(SSFI),
11188 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11191 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11193 SelectionDAG &DAG) const {
11197 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11199 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11201 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11203 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11205 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11206 MachineMemOperand *MMO;
11208 int SSFI = FI->getIndex();
11210 DAG.getMachineFunction()
11211 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11212 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11214 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11215 StackSlot = StackSlot.getOperand(1);
11217 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11218 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11220 Tys, Ops, SrcVT, MMO);
11223 Chain = Result.getValue(1);
11224 SDValue InFlag = Result.getValue(2);
11226 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11227 // shouldn't be necessary except that RFP cannot be live across
11228 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11229 MachineFunction &MF = DAG.getMachineFunction();
11230 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11231 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11232 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11233 Tys = DAG.getVTList(MVT::Other);
11235 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11237 MachineMemOperand *MMO =
11238 DAG.getMachineFunction()
11239 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11240 MachineMemOperand::MOStore, SSFISize, SSFISize);
11242 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11243 Ops, Op.getValueType(), MMO);
11244 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11245 MachinePointerInfo::getFixedStack(SSFI),
11246 false, false, false, 0);
11252 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11253 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11254 SelectionDAG &DAG) const {
11255 // This algorithm is not obvious. Here it is what we're trying to output:
11258 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11259 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11261 haddpd %xmm0, %xmm0
11263 pshufd $0x4e, %xmm0, %xmm1
11269 LLVMContext *Context = DAG.getContext();
11271 // Build some magic constants.
11272 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11273 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11274 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11276 SmallVector<Constant*,2> CV1;
11278 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11279 APInt(64, 0x4330000000000000ULL))));
11281 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11282 APInt(64, 0x4530000000000000ULL))));
11283 Constant *C1 = ConstantVector::get(CV1);
11284 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11286 // Load the 64-bit value into an XMM register.
11287 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11289 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11290 MachinePointerInfo::getConstantPool(),
11291 false, false, false, 16);
11292 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11293 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11296 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11297 MachinePointerInfo::getConstantPool(),
11298 false, false, false, 16);
11299 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11300 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11303 if (Subtarget->hasSSE3()) {
11304 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11305 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11307 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11308 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11310 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11311 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11315 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11316 DAG.getIntPtrConstant(0));
11319 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11320 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11321 SelectionDAG &DAG) const {
11323 // FP constant to bias correct the final result.
11324 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11327 // Load the 32-bit value into an XMM register.
11328 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11331 // Zero out the upper parts of the register.
11332 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11334 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11335 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11336 DAG.getIntPtrConstant(0));
11338 // Or the load with the bias.
11339 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11340 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11341 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11342 MVT::v2f64, Load)),
11343 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11344 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11345 MVT::v2f64, Bias)));
11346 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11347 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11348 DAG.getIntPtrConstant(0));
11350 // Subtract the bias.
11351 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11353 // Handle final rounding.
11354 EVT DestVT = Op.getValueType();
11356 if (DestVT.bitsLT(MVT::f64))
11357 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11358 DAG.getIntPtrConstant(0));
11359 if (DestVT.bitsGT(MVT::f64))
11360 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11362 // Handle final rounding.
11366 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11367 const X86Subtarget &Subtarget) {
11368 // The algorithm is the following:
11369 // #ifdef __SSE4_1__
11370 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11371 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11372 // (uint4) 0x53000000, 0xaa);
11374 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11375 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11377 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11378 // return (float4) lo + fhi;
11381 SDValue V = Op->getOperand(0);
11382 EVT VecIntVT = V.getValueType();
11383 bool Is128 = VecIntVT == MVT::v4i32;
11384 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11385 // If we convert to something else than the supported type, e.g., to v4f64,
11387 if (VecFloatVT != Op->getValueType(0))
11390 unsigned NumElts = VecIntVT.getVectorNumElements();
11391 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11392 "Unsupported custom type");
11393 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11395 // In the #idef/#else code, we have in common:
11396 // - The vector of constants:
11402 // Create the splat vector for 0x4b000000.
11403 SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11404 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11405 CstLow, CstLow, CstLow, CstLow};
11406 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11407 makeArrayRef(&CstLowArray[0], NumElts));
11408 // Create the splat vector for 0x53000000.
11409 SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11410 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11411 CstHigh, CstHigh, CstHigh, CstHigh};
11412 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11413 makeArrayRef(&CstHighArray[0], NumElts));
11415 // Create the right shift.
11416 SDValue CstShift = DAG.getConstant(16, MVT::i32);
11417 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11418 CstShift, CstShift, CstShift, CstShift};
11419 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11420 makeArrayRef(&CstShiftArray[0], NumElts));
11421 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11424 if (Subtarget.hasSSE41()) {
11425 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11426 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11427 SDValue VecCstLowBitcast =
11428 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11429 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11430 // Low will be bitcasted right away, so do not bother bitcasting back to its
11432 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11433 VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11434 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11435 // (uint4) 0x53000000, 0xaa);
11436 SDValue VecCstHighBitcast =
11437 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11438 SDValue VecShiftBitcast =
11439 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11440 // High will be bitcasted right away, so do not bother bitcasting back to
11441 // its original type.
11442 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11443 VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11445 SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11446 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11447 CstMask, CstMask, CstMask);
11448 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11449 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11450 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11452 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11453 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11456 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11457 SDValue CstFAdd = DAG.getConstantFP(
11458 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11459 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11460 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11461 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11462 makeArrayRef(&CstFAddArray[0], NumElts));
11464 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11465 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11467 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11468 // return (float4) lo + fhi;
11469 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11470 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11473 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11474 SelectionDAG &DAG) const {
11475 SDValue N0 = Op.getOperand(0);
11476 MVT SVT = N0.getSimpleValueType();
11479 switch (SVT.SimpleTy) {
11481 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11486 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11487 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11488 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11492 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11494 llvm_unreachable(nullptr);
11497 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11498 SelectionDAG &DAG) const {
11499 SDValue N0 = Op.getOperand(0);
11502 if (Op.getValueType().isVector())
11503 return lowerUINT_TO_FP_vec(Op, DAG);
11505 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11506 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11507 // the optimization here.
11508 if (DAG.SignBitIsZero(N0))
11509 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11511 MVT SrcVT = N0.getSimpleValueType();
11512 MVT DstVT = Op.getSimpleValueType();
11513 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11514 return LowerUINT_TO_FP_i64(Op, DAG);
11515 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11516 return LowerUINT_TO_FP_i32(Op, DAG);
11517 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11520 // Make a 64-bit buffer, and use it to build an FILD.
11521 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11522 if (SrcVT == MVT::i32) {
11523 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11524 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11525 getPointerTy(), StackSlot, WordOff);
11526 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11527 StackSlot, MachinePointerInfo(),
11529 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11530 OffsetSlot, MachinePointerInfo(),
11532 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11536 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11537 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11538 StackSlot, MachinePointerInfo(),
11540 // For i64 source, we need to add the appropriate power of 2 if the input
11541 // was negative. This is the same as the optimization in
11542 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11543 // we must be careful to do the computation in x87 extended precision, not
11544 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11545 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11546 MachineMemOperand *MMO =
11547 DAG.getMachineFunction()
11548 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11549 MachineMemOperand::MOLoad, 8, 8);
11551 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11552 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11553 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11556 APInt FF(32, 0x5F800000ULL);
11558 // Check whether the sign bit is set.
11559 SDValue SignSet = DAG.getSetCC(dl,
11560 getSetCCResultType(*DAG.getContext(), MVT::i64),
11561 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11564 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11565 SDValue FudgePtr = DAG.getConstantPool(
11566 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11569 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11570 SDValue Zero = DAG.getIntPtrConstant(0);
11571 SDValue Four = DAG.getIntPtrConstant(4);
11572 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11574 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11576 // Load the value out, extending it from f32 to f80.
11577 // FIXME: Avoid the extend by constructing the right constant pool?
11578 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11579 FudgePtr, MachinePointerInfo::getConstantPool(),
11580 MVT::f32, false, false, false, 4);
11581 // Extend everything to 80 bits to force it to be done on x87.
11582 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11583 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11586 std::pair<SDValue,SDValue>
11587 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11588 bool IsSigned, bool IsReplace) const {
11591 EVT DstTy = Op.getValueType();
11593 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11594 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11598 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11599 DstTy.getSimpleVT() >= MVT::i16 &&
11600 "Unknown FP_TO_INT to lower!");
11602 // These are really Legal.
11603 if (DstTy == MVT::i32 &&
11604 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11605 return std::make_pair(SDValue(), SDValue());
11606 if (Subtarget->is64Bit() &&
11607 DstTy == MVT::i64 &&
11608 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11609 return std::make_pair(SDValue(), SDValue());
11611 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11612 // stack slot, or into the FTOL runtime function.
11613 MachineFunction &MF = DAG.getMachineFunction();
11614 unsigned MemSize = DstTy.getSizeInBits()/8;
11615 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11616 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11619 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11620 Opc = X86ISD::WIN_FTOL;
11622 switch (DstTy.getSimpleVT().SimpleTy) {
11623 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11624 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11625 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11626 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11629 SDValue Chain = DAG.getEntryNode();
11630 SDValue Value = Op.getOperand(0);
11631 EVT TheVT = Op.getOperand(0).getValueType();
11632 // FIXME This causes a redundant load/store if the SSE-class value is already
11633 // in memory, such as if it is on the callstack.
11634 if (isScalarFPTypeInSSEReg(TheVT)) {
11635 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11636 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11637 MachinePointerInfo::getFixedStack(SSFI),
11639 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11641 Chain, StackSlot, DAG.getValueType(TheVT)
11644 MachineMemOperand *MMO =
11645 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11646 MachineMemOperand::MOLoad, MemSize, MemSize);
11647 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11648 Chain = Value.getValue(1);
11649 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11650 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11653 MachineMemOperand *MMO =
11654 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11655 MachineMemOperand::MOStore, MemSize, MemSize);
11657 if (Opc != X86ISD::WIN_FTOL) {
11658 // Build the FP_TO_INT*_IN_MEM
11659 SDValue Ops[] = { Chain, Value, StackSlot };
11660 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11662 return std::make_pair(FIST, StackSlot);
11664 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11665 DAG.getVTList(MVT::Other, MVT::Glue),
11667 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11668 MVT::i32, ftol.getValue(1));
11669 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11670 MVT::i32, eax.getValue(2));
11671 SDValue Ops[] = { eax, edx };
11672 SDValue pair = IsReplace
11673 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11674 : DAG.getMergeValues(Ops, DL);
11675 return std::make_pair(pair, SDValue());
11679 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11680 const X86Subtarget *Subtarget) {
11681 MVT VT = Op->getSimpleValueType(0);
11682 SDValue In = Op->getOperand(0);
11683 MVT InVT = In.getSimpleValueType();
11686 // Optimize vectors in AVX mode:
11689 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11690 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11691 // Concat upper and lower parts.
11694 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11695 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11696 // Concat upper and lower parts.
11699 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11700 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11701 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11704 if (Subtarget->hasInt256())
11705 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11707 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11708 SDValue Undef = DAG.getUNDEF(InVT);
11709 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11710 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11711 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11713 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11714 VT.getVectorNumElements()/2);
11716 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11717 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11719 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11722 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11723 SelectionDAG &DAG) {
11724 MVT VT = Op->getSimpleValueType(0);
11725 SDValue In = Op->getOperand(0);
11726 MVT InVT = In.getSimpleValueType();
11728 unsigned int NumElts = VT.getVectorNumElements();
11729 if (NumElts != 8 && NumElts != 16)
11732 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11733 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11735 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11736 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11737 // Now we have only mask extension
11738 assert(InVT.getVectorElementType() == MVT::i1);
11739 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11740 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11741 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11742 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11743 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11744 MachinePointerInfo::getConstantPool(),
11745 false, false, false, Alignment);
11747 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11748 if (VT.is512BitVector())
11750 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11753 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11754 SelectionDAG &DAG) {
11755 if (Subtarget->hasFp256()) {
11756 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11764 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11765 SelectionDAG &DAG) {
11767 MVT VT = Op.getSimpleValueType();
11768 SDValue In = Op.getOperand(0);
11769 MVT SVT = In.getSimpleValueType();
11771 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11772 return LowerZERO_EXTEND_AVX512(Op, DAG);
11774 if (Subtarget->hasFp256()) {
11775 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11780 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11781 VT.getVectorNumElements() != SVT.getVectorNumElements());
11785 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11787 MVT VT = Op.getSimpleValueType();
11788 SDValue In = Op.getOperand(0);
11789 MVT InVT = In.getSimpleValueType();
11791 if (VT == MVT::i1) {
11792 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11793 "Invalid scalar TRUNCATE operation");
11794 if (InVT.getSizeInBits() >= 32)
11796 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11797 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11799 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11800 "Invalid TRUNCATE operation");
11802 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11803 if (VT.getVectorElementType().getSizeInBits() >=8)
11804 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11806 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11807 unsigned NumElts = InVT.getVectorNumElements();
11808 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11809 if (InVT.getSizeInBits() < 512) {
11810 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11811 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11815 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11816 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11817 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11818 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11819 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11820 MachinePointerInfo::getConstantPool(),
11821 false, false, false, Alignment);
11822 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11823 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11824 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11827 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11828 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11829 if (Subtarget->hasInt256()) {
11830 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11831 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11832 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11834 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11835 DAG.getIntPtrConstant(0));
11838 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11839 DAG.getIntPtrConstant(0));
11840 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11841 DAG.getIntPtrConstant(2));
11842 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11843 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11844 static const int ShufMask[] = {0, 2, 4, 6};
11845 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11848 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11849 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11850 if (Subtarget->hasInt256()) {
11851 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11853 SmallVector<SDValue,32> pshufbMask;
11854 for (unsigned i = 0; i < 2; ++i) {
11855 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11856 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11857 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11858 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11859 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11860 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11861 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11862 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11863 for (unsigned j = 0; j < 8; ++j)
11864 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11866 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11867 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11868 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11870 static const int ShufMask[] = {0, 2, -1, -1};
11871 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11873 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11874 DAG.getIntPtrConstant(0));
11875 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11878 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11879 DAG.getIntPtrConstant(0));
11881 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11882 DAG.getIntPtrConstant(4));
11884 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11885 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11887 // The PSHUFB mask:
11888 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11889 -1, -1, -1, -1, -1, -1, -1, -1};
11891 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11892 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11893 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11895 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11896 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11898 // The MOVLHPS Mask:
11899 static const int ShufMask2[] = {0, 1, 4, 5};
11900 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11901 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11904 // Handle truncation of V256 to V128 using shuffles.
11905 if (!VT.is128BitVector() || !InVT.is256BitVector())
11908 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11910 unsigned NumElems = VT.getVectorNumElements();
11911 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11913 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11914 // Prepare truncation shuffle mask
11915 for (unsigned i = 0; i != NumElems; ++i)
11916 MaskVec[i] = i * 2;
11917 SDValue V = DAG.getVectorShuffle(NVT, DL,
11918 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11919 DAG.getUNDEF(NVT), &MaskVec[0]);
11920 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11921 DAG.getIntPtrConstant(0));
11924 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11925 SelectionDAG &DAG) const {
11926 assert(!Op.getSimpleValueType().isVector());
11928 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11929 /*IsSigned=*/ true, /*IsReplace=*/ false);
11930 SDValue FIST = Vals.first, StackSlot = Vals.second;
11931 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11932 if (!FIST.getNode()) return Op;
11934 if (StackSlot.getNode())
11935 // Load the result.
11936 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11937 FIST, StackSlot, MachinePointerInfo(),
11938 false, false, false, 0);
11940 // The node is the result.
11944 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11945 SelectionDAG &DAG) const {
11946 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11947 /*IsSigned=*/ false, /*IsReplace=*/ false);
11948 SDValue FIST = Vals.first, StackSlot = Vals.second;
11949 assert(FIST.getNode() && "Unexpected failure");
11951 if (StackSlot.getNode())
11952 // Load the result.
11953 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11954 FIST, StackSlot, MachinePointerInfo(),
11955 false, false, false, 0);
11957 // The node is the result.
11961 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11963 MVT VT = Op.getSimpleValueType();
11964 SDValue In = Op.getOperand(0);
11965 MVT SVT = In.getSimpleValueType();
11967 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11969 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11970 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11971 In, DAG.getUNDEF(SVT)));
11974 /// The only differences between FABS and FNEG are the mask and the logic op.
11975 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
11976 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
11977 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
11978 "Wrong opcode for lowering FABS or FNEG.");
11980 bool IsFABS = (Op.getOpcode() == ISD::FABS);
11982 // If this is a FABS and it has an FNEG user, bail out to fold the combination
11983 // into an FNABS. We'll lower the FABS after that if it is still in use.
11985 for (SDNode *User : Op->uses())
11986 if (User->getOpcode() == ISD::FNEG)
11989 SDValue Op0 = Op.getOperand(0);
11990 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
11993 MVT VT = Op.getSimpleValueType();
11994 // Assume scalar op for initialization; update for vector if needed.
11995 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
11996 // generate a 16-byte vector constant and logic op even for the scalar case.
11997 // Using a 16-byte mask allows folding the load of the mask with
11998 // the logic op, so it can save (~4 bytes) on code size.
12000 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12001 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12002 // decide if we should generate a 16-byte constant mask when we only need 4 or
12003 // 8 bytes for the scalar case.
12004 if (VT.isVector()) {
12005 EltVT = VT.getVectorElementType();
12006 NumElts = VT.getVectorNumElements();
12009 unsigned EltBits = EltVT.getSizeInBits();
12010 LLVMContext *Context = DAG.getContext();
12011 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12013 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12014 Constant *C = ConstantInt::get(*Context, MaskElt);
12015 C = ConstantVector::getSplat(NumElts, C);
12016 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12017 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12018 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12019 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12020 MachinePointerInfo::getConstantPool(),
12021 false, false, false, Alignment);
12023 if (VT.isVector()) {
12024 // For a vector, cast operands to a vector type, perform the logic op,
12025 // and cast the result back to the original value type.
12026 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12027 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12028 SDValue Operand = IsFNABS ?
12029 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12030 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12031 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12032 return DAG.getNode(ISD::BITCAST, dl, VT,
12033 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12036 // If not vector, then scalar.
12037 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12038 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12039 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12042 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12043 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12044 LLVMContext *Context = DAG.getContext();
12045 SDValue Op0 = Op.getOperand(0);
12046 SDValue Op1 = Op.getOperand(1);
12048 MVT VT = Op.getSimpleValueType();
12049 MVT SrcVT = Op1.getSimpleValueType();
12051 // If second operand is smaller, extend it first.
12052 if (SrcVT.bitsLT(VT)) {
12053 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12056 // And if it is bigger, shrink it first.
12057 if (SrcVT.bitsGT(VT)) {
12058 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12062 // At this point the operands and the result should have the same
12063 // type, and that won't be f80 since that is not custom lowered.
12065 const fltSemantics &Sem =
12066 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12067 const unsigned SizeInBits = VT.getSizeInBits();
12069 SmallVector<Constant *, 4> CV(
12070 VT == MVT::f64 ? 2 : 4,
12071 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12073 // First, clear all bits but the sign bit from the second operand (sign).
12074 CV[0] = ConstantFP::get(*Context,
12075 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12076 Constant *C = ConstantVector::get(CV);
12077 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12078 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12079 MachinePointerInfo::getConstantPool(),
12080 false, false, false, 16);
12081 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12083 // Next, clear the sign bit from the first operand (magnitude).
12084 // If it's a constant, we can clear it here.
12085 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12086 APFloat APF = Op0CN->getValueAPF();
12087 // If the magnitude is a positive zero, the sign bit alone is enough.
12088 if (APF.isPosZero())
12091 CV[0] = ConstantFP::get(*Context, APF);
12093 CV[0] = ConstantFP::get(
12095 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12097 C = ConstantVector::get(CV);
12098 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12099 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12100 MachinePointerInfo::getConstantPool(),
12101 false, false, false, 16);
12102 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12103 if (!isa<ConstantFPSDNode>(Op0))
12104 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12106 // OR the magnitude value with the sign bit.
12107 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12110 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12111 SDValue N0 = Op.getOperand(0);
12113 MVT VT = Op.getSimpleValueType();
12115 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12116 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12117 DAG.getConstant(1, VT));
12118 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12121 // Check whether an OR'd tree is PTEST-able.
12122 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12123 SelectionDAG &DAG) {
12124 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12126 if (!Subtarget->hasSSE41())
12129 if (!Op->hasOneUse())
12132 SDNode *N = Op.getNode();
12135 SmallVector<SDValue, 8> Opnds;
12136 DenseMap<SDValue, unsigned> VecInMap;
12137 SmallVector<SDValue, 8> VecIns;
12138 EVT VT = MVT::Other;
12140 // Recognize a special case where a vector is casted into wide integer to
12142 Opnds.push_back(N->getOperand(0));
12143 Opnds.push_back(N->getOperand(1));
12145 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12146 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12147 // BFS traverse all OR'd operands.
12148 if (I->getOpcode() == ISD::OR) {
12149 Opnds.push_back(I->getOperand(0));
12150 Opnds.push_back(I->getOperand(1));
12151 // Re-evaluate the number of nodes to be traversed.
12152 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12156 // Quit if a non-EXTRACT_VECTOR_ELT
12157 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12160 // Quit if without a constant index.
12161 SDValue Idx = I->getOperand(1);
12162 if (!isa<ConstantSDNode>(Idx))
12165 SDValue ExtractedFromVec = I->getOperand(0);
12166 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12167 if (M == VecInMap.end()) {
12168 VT = ExtractedFromVec.getValueType();
12169 // Quit if not 128/256-bit vector.
12170 if (!VT.is128BitVector() && !VT.is256BitVector())
12172 // Quit if not the same type.
12173 if (VecInMap.begin() != VecInMap.end() &&
12174 VT != VecInMap.begin()->first.getValueType())
12176 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12177 VecIns.push_back(ExtractedFromVec);
12179 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12182 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12183 "Not extracted from 128-/256-bit vector.");
12185 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12187 for (DenseMap<SDValue, unsigned>::const_iterator
12188 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12189 // Quit if not all elements are used.
12190 if (I->second != FullMask)
12194 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12196 // Cast all vectors into TestVT for PTEST.
12197 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12198 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12200 // If more than one full vectors are evaluated, OR them first before PTEST.
12201 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12202 // Each iteration will OR 2 nodes and append the result until there is only
12203 // 1 node left, i.e. the final OR'd value of all vectors.
12204 SDValue LHS = VecIns[Slot];
12205 SDValue RHS = VecIns[Slot + 1];
12206 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12209 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12210 VecIns.back(), VecIns.back());
12213 /// \brief return true if \c Op has a use that doesn't just read flags.
12214 static bool hasNonFlagsUse(SDValue Op) {
12215 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12217 SDNode *User = *UI;
12218 unsigned UOpNo = UI.getOperandNo();
12219 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12220 // Look pass truncate.
12221 UOpNo = User->use_begin().getOperandNo();
12222 User = *User->use_begin();
12225 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12226 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12232 /// Emit nodes that will be selected as "test Op0,Op0", or something
12234 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12235 SelectionDAG &DAG) const {
12236 if (Op.getValueType() == MVT::i1) {
12237 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12238 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12239 DAG.getConstant(0, MVT::i8));
12241 // CF and OF aren't always set the way we want. Determine which
12242 // of these we need.
12243 bool NeedCF = false;
12244 bool NeedOF = false;
12247 case X86::COND_A: case X86::COND_AE:
12248 case X86::COND_B: case X86::COND_BE:
12251 case X86::COND_G: case X86::COND_GE:
12252 case X86::COND_L: case X86::COND_LE:
12253 case X86::COND_O: case X86::COND_NO: {
12254 // Check if we really need to set the
12255 // Overflow flag. If NoSignedWrap is present
12256 // that is not actually needed.
12257 switch (Op->getOpcode()) {
12262 const BinaryWithFlagsSDNode *BinNode =
12263 cast<BinaryWithFlagsSDNode>(Op.getNode());
12264 if (BinNode->hasNoSignedWrap())
12274 // See if we can use the EFLAGS value from the operand instead of
12275 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12276 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12277 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12278 // Emit a CMP with 0, which is the TEST pattern.
12279 //if (Op.getValueType() == MVT::i1)
12280 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12281 // DAG.getConstant(0, MVT::i1));
12282 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12283 DAG.getConstant(0, Op.getValueType()));
12285 unsigned Opcode = 0;
12286 unsigned NumOperands = 0;
12288 // Truncate operations may prevent the merge of the SETCC instruction
12289 // and the arithmetic instruction before it. Attempt to truncate the operands
12290 // of the arithmetic instruction and use a reduced bit-width instruction.
12291 bool NeedTruncation = false;
12292 SDValue ArithOp = Op;
12293 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12294 SDValue Arith = Op->getOperand(0);
12295 // Both the trunc and the arithmetic op need to have one user each.
12296 if (Arith->hasOneUse())
12297 switch (Arith.getOpcode()) {
12304 NeedTruncation = true;
12310 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12311 // which may be the result of a CAST. We use the variable 'Op', which is the
12312 // non-casted variable when we check for possible users.
12313 switch (ArithOp.getOpcode()) {
12315 // Due to an isel shortcoming, be conservative if this add is likely to be
12316 // selected as part of a load-modify-store instruction. When the root node
12317 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12318 // uses of other nodes in the match, such as the ADD in this case. This
12319 // leads to the ADD being left around and reselected, with the result being
12320 // two adds in the output. Alas, even if none our users are stores, that
12321 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12322 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12323 // climbing the DAG back to the root, and it doesn't seem to be worth the
12325 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12326 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12327 if (UI->getOpcode() != ISD::CopyToReg &&
12328 UI->getOpcode() != ISD::SETCC &&
12329 UI->getOpcode() != ISD::STORE)
12332 if (ConstantSDNode *C =
12333 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12334 // An add of one will be selected as an INC.
12335 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12336 Opcode = X86ISD::INC;
12341 // An add of negative one (subtract of one) will be selected as a DEC.
12342 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12343 Opcode = X86ISD::DEC;
12349 // Otherwise use a regular EFLAGS-setting add.
12350 Opcode = X86ISD::ADD;
12355 // If we have a constant logical shift that's only used in a comparison
12356 // against zero turn it into an equivalent AND. This allows turning it into
12357 // a TEST instruction later.
12358 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12359 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12360 EVT VT = Op.getValueType();
12361 unsigned BitWidth = VT.getSizeInBits();
12362 unsigned ShAmt = Op->getConstantOperandVal(1);
12363 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12365 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12366 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12367 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12368 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12370 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12371 DAG.getConstant(Mask, VT));
12372 DAG.ReplaceAllUsesWith(Op, New);
12378 // If the primary and result isn't used, don't bother using X86ISD::AND,
12379 // because a TEST instruction will be better.
12380 if (!hasNonFlagsUse(Op))
12386 // Due to the ISEL shortcoming noted above, be conservative if this op is
12387 // likely to be selected as part of a load-modify-store instruction.
12388 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12389 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12390 if (UI->getOpcode() == ISD::STORE)
12393 // Otherwise use a regular EFLAGS-setting instruction.
12394 switch (ArithOp.getOpcode()) {
12395 default: llvm_unreachable("unexpected operator!");
12396 case ISD::SUB: Opcode = X86ISD::SUB; break;
12397 case ISD::XOR: Opcode = X86ISD::XOR; break;
12398 case ISD::AND: Opcode = X86ISD::AND; break;
12400 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12401 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12402 if (EFLAGS.getNode())
12405 Opcode = X86ISD::OR;
12419 return SDValue(Op.getNode(), 1);
12425 // If we found that truncation is beneficial, perform the truncation and
12427 if (NeedTruncation) {
12428 EVT VT = Op.getValueType();
12429 SDValue WideVal = Op->getOperand(0);
12430 EVT WideVT = WideVal.getValueType();
12431 unsigned ConvertedOp = 0;
12432 // Use a target machine opcode to prevent further DAGCombine
12433 // optimizations that may separate the arithmetic operations
12434 // from the setcc node.
12435 switch (WideVal.getOpcode()) {
12437 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12438 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12439 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12440 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12441 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12445 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12446 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12447 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12448 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12449 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12455 // Emit a CMP with 0, which is the TEST pattern.
12456 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12457 DAG.getConstant(0, Op.getValueType()));
12459 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12460 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12462 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12463 DAG.ReplaceAllUsesWith(Op, New);
12464 return SDValue(New.getNode(), 1);
12467 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12469 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12470 SDLoc dl, SelectionDAG &DAG) const {
12471 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12472 if (C->getAPIntValue() == 0)
12473 return EmitTest(Op0, X86CC, dl, DAG);
12475 if (Op0.getValueType() == MVT::i1)
12476 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12479 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12480 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12481 // Do the comparison at i32 if it's smaller, besides the Atom case.
12482 // This avoids subregister aliasing issues. Keep the smaller reference
12483 // if we're optimizing for size, however, as that'll allow better folding
12484 // of memory operations.
12485 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12486 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12487 Attribute::MinSize) &&
12488 !Subtarget->isAtom()) {
12489 unsigned ExtendOp =
12490 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12491 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12492 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12494 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12495 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12496 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12498 return SDValue(Sub.getNode(), 1);
12500 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12503 /// Convert a comparison if required by the subtarget.
12504 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12505 SelectionDAG &DAG) const {
12506 // If the subtarget does not support the FUCOMI instruction, floating-point
12507 // comparisons have to be converted.
12508 if (Subtarget->hasCMov() ||
12509 Cmp.getOpcode() != X86ISD::CMP ||
12510 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12511 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12514 // The instruction selector will select an FUCOM instruction instead of
12515 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12516 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12517 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12519 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12520 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12521 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12522 DAG.getConstant(8, MVT::i8));
12523 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12524 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12527 /// The minimum architected relative accuracy is 2^-12. We need one
12528 /// Newton-Raphson step to have a good float result (24 bits of precision).
12529 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12530 DAGCombinerInfo &DCI,
12531 unsigned &RefinementSteps,
12532 bool &UseOneConstNR) const {
12533 // FIXME: We should use instruction latency models to calculate the cost of
12534 // each potential sequence, but this is very hard to do reliably because
12535 // at least Intel's Core* chips have variable timing based on the number of
12536 // significant digits in the divisor and/or sqrt operand.
12537 if (!Subtarget->useSqrtEst())
12540 EVT VT = Op.getValueType();
12542 // SSE1 has rsqrtss and rsqrtps.
12543 // TODO: Add support for AVX512 (v16f32).
12544 // It is likely not profitable to do this for f64 because a double-precision
12545 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12546 // instructions: convert to single, rsqrtss, convert back to double, refine
12547 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12548 // along with FMA, this could be a throughput win.
12549 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12550 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12551 RefinementSteps = 1;
12552 UseOneConstNR = false;
12553 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12558 /// The minimum architected relative accuracy is 2^-12. We need one
12559 /// Newton-Raphson step to have a good float result (24 bits of precision).
12560 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12561 DAGCombinerInfo &DCI,
12562 unsigned &RefinementSteps) const {
12563 // FIXME: We should use instruction latency models to calculate the cost of
12564 // each potential sequence, but this is very hard to do reliably because
12565 // at least Intel's Core* chips have variable timing based on the number of
12566 // significant digits in the divisor.
12567 if (!Subtarget->useReciprocalEst())
12570 EVT VT = Op.getValueType();
12572 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12573 // TODO: Add support for AVX512 (v16f32).
12574 // It is likely not profitable to do this for f64 because a double-precision
12575 // reciprocal estimate with refinement on x86 prior to FMA requires
12576 // 15 instructions: convert to single, rcpss, convert back to double, refine
12577 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12578 // along with FMA, this could be a throughput win.
12579 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12580 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12581 RefinementSteps = ReciprocalEstimateRefinementSteps;
12582 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12587 static bool isAllOnes(SDValue V) {
12588 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12589 return C && C->isAllOnesValue();
12592 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12593 /// if it's possible.
12594 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12595 SDLoc dl, SelectionDAG &DAG) const {
12596 SDValue Op0 = And.getOperand(0);
12597 SDValue Op1 = And.getOperand(1);
12598 if (Op0.getOpcode() == ISD::TRUNCATE)
12599 Op0 = Op0.getOperand(0);
12600 if (Op1.getOpcode() == ISD::TRUNCATE)
12601 Op1 = Op1.getOperand(0);
12604 if (Op1.getOpcode() == ISD::SHL)
12605 std::swap(Op0, Op1);
12606 if (Op0.getOpcode() == ISD::SHL) {
12607 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12608 if (And00C->getZExtValue() == 1) {
12609 // If we looked past a truncate, check that it's only truncating away
12611 unsigned BitWidth = Op0.getValueSizeInBits();
12612 unsigned AndBitWidth = And.getValueSizeInBits();
12613 if (BitWidth > AndBitWidth) {
12615 DAG.computeKnownBits(Op0, Zeros, Ones);
12616 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12620 RHS = Op0.getOperand(1);
12622 } else if (Op1.getOpcode() == ISD::Constant) {
12623 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12624 uint64_t AndRHSVal = AndRHS->getZExtValue();
12625 SDValue AndLHS = Op0;
12627 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12628 LHS = AndLHS.getOperand(0);
12629 RHS = AndLHS.getOperand(1);
12632 // Use BT if the immediate can't be encoded in a TEST instruction.
12633 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12635 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12639 if (LHS.getNode()) {
12640 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12641 // instruction. Since the shift amount is in-range-or-undefined, we know
12642 // that doing a bittest on the i32 value is ok. We extend to i32 because
12643 // the encoding for the i16 version is larger than the i32 version.
12644 // Also promote i16 to i32 for performance / code size reason.
12645 if (LHS.getValueType() == MVT::i8 ||
12646 LHS.getValueType() == MVT::i16)
12647 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12649 // If the operand types disagree, extend the shift amount to match. Since
12650 // BT ignores high bits (like shifts) we can use anyextend.
12651 if (LHS.getValueType() != RHS.getValueType())
12652 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12654 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12655 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12656 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12657 DAG.getConstant(Cond, MVT::i8), BT);
12663 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12665 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12670 // SSE Condition code mapping:
12679 switch (SetCCOpcode) {
12680 default: llvm_unreachable("Unexpected SETCC condition");
12682 case ISD::SETEQ: SSECC = 0; break;
12684 case ISD::SETGT: Swap = true; // Fallthrough
12686 case ISD::SETOLT: SSECC = 1; break;
12688 case ISD::SETGE: Swap = true; // Fallthrough
12690 case ISD::SETOLE: SSECC = 2; break;
12691 case ISD::SETUO: SSECC = 3; break;
12693 case ISD::SETNE: SSECC = 4; break;
12694 case ISD::SETULE: Swap = true; // Fallthrough
12695 case ISD::SETUGE: SSECC = 5; break;
12696 case ISD::SETULT: Swap = true; // Fallthrough
12697 case ISD::SETUGT: SSECC = 6; break;
12698 case ISD::SETO: SSECC = 7; break;
12700 case ISD::SETONE: SSECC = 8; break;
12703 std::swap(Op0, Op1);
12708 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12709 // ones, and then concatenate the result back.
12710 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12711 MVT VT = Op.getSimpleValueType();
12713 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12714 "Unsupported value type for operation");
12716 unsigned NumElems = VT.getVectorNumElements();
12718 SDValue CC = Op.getOperand(2);
12720 // Extract the LHS vectors
12721 SDValue LHS = Op.getOperand(0);
12722 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12723 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12725 // Extract the RHS vectors
12726 SDValue RHS = Op.getOperand(1);
12727 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12728 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12730 // Issue the operation on the smaller types and concatenate the result back
12731 MVT EltVT = VT.getVectorElementType();
12732 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12733 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12734 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12735 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12738 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12739 const X86Subtarget *Subtarget) {
12740 SDValue Op0 = Op.getOperand(0);
12741 SDValue Op1 = Op.getOperand(1);
12742 SDValue CC = Op.getOperand(2);
12743 MVT VT = Op.getSimpleValueType();
12746 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12747 Op.getValueType().getScalarType() == MVT::i1 &&
12748 "Cannot set masked compare for this operation");
12750 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12752 bool Unsigned = false;
12755 switch (SetCCOpcode) {
12756 default: llvm_unreachable("Unexpected SETCC condition");
12757 case ISD::SETNE: SSECC = 4; break;
12758 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12759 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12760 case ISD::SETLT: Swap = true; //fall-through
12761 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12762 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12763 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12764 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12765 case ISD::SETULE: Unsigned = true; //fall-through
12766 case ISD::SETLE: SSECC = 2; break;
12770 std::swap(Op0, Op1);
12772 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12773 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12774 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12775 DAG.getConstant(SSECC, MVT::i8));
12778 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12779 /// operand \p Op1. If non-trivial (for example because it's not constant)
12780 /// return an empty value.
12781 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12783 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12787 MVT VT = Op1.getSimpleValueType();
12788 MVT EVT = VT.getVectorElementType();
12789 unsigned n = VT.getVectorNumElements();
12790 SmallVector<SDValue, 8> ULTOp1;
12792 for (unsigned i = 0; i < n; ++i) {
12793 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12794 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12797 // Avoid underflow.
12798 APInt Val = Elt->getAPIntValue();
12802 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12805 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12808 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12809 SelectionDAG &DAG) {
12810 SDValue Op0 = Op.getOperand(0);
12811 SDValue Op1 = Op.getOperand(1);
12812 SDValue CC = Op.getOperand(2);
12813 MVT VT = Op.getSimpleValueType();
12814 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12815 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12820 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12821 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12824 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12825 unsigned Opc = X86ISD::CMPP;
12826 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12827 assert(VT.getVectorNumElements() <= 16);
12828 Opc = X86ISD::CMPM;
12830 // In the two special cases we can't handle, emit two comparisons.
12833 unsigned CombineOpc;
12834 if (SetCCOpcode == ISD::SETUEQ) {
12835 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12837 assert(SetCCOpcode == ISD::SETONE);
12838 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12841 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12842 DAG.getConstant(CC0, MVT::i8));
12843 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12844 DAG.getConstant(CC1, MVT::i8));
12845 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12847 // Handle all other FP comparisons here.
12848 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12849 DAG.getConstant(SSECC, MVT::i8));
12852 // Break 256-bit integer vector compare into smaller ones.
12853 if (VT.is256BitVector() && !Subtarget->hasInt256())
12854 return Lower256IntVSETCC(Op, DAG);
12856 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12857 EVT OpVT = Op1.getValueType();
12858 if (Subtarget->hasAVX512()) {
12859 if (Op1.getValueType().is512BitVector() ||
12860 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12861 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12862 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12864 // In AVX-512 architecture setcc returns mask with i1 elements,
12865 // But there is no compare instruction for i8 and i16 elements in KNL.
12866 // We are not talking about 512-bit operands in this case, these
12867 // types are illegal.
12869 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12870 OpVT.getVectorElementType().getSizeInBits() >= 8))
12871 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12872 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12875 // We are handling one of the integer comparisons here. Since SSE only has
12876 // GT and EQ comparisons for integer, swapping operands and multiple
12877 // operations may be required for some comparisons.
12879 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12880 bool Subus = false;
12882 switch (SetCCOpcode) {
12883 default: llvm_unreachable("Unexpected SETCC condition");
12884 case ISD::SETNE: Invert = true;
12885 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12886 case ISD::SETLT: Swap = true;
12887 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12888 case ISD::SETGE: Swap = true;
12889 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12890 Invert = true; break;
12891 case ISD::SETULT: Swap = true;
12892 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12893 FlipSigns = true; break;
12894 case ISD::SETUGE: Swap = true;
12895 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12896 FlipSigns = true; Invert = true; break;
12899 // Special case: Use min/max operations for SETULE/SETUGE
12900 MVT VET = VT.getVectorElementType();
12902 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12903 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12906 switch (SetCCOpcode) {
12908 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12909 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12912 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12915 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12916 if (!MinMax && hasSubus) {
12917 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12919 // t = psubus Op0, Op1
12920 // pcmpeq t, <0..0>
12921 switch (SetCCOpcode) {
12923 case ISD::SETULT: {
12924 // If the comparison is against a constant we can turn this into a
12925 // setule. With psubus, setule does not require a swap. This is
12926 // beneficial because the constant in the register is no longer
12927 // destructed as the destination so it can be hoisted out of a loop.
12928 // Only do this pre-AVX since vpcmp* is no longer destructive.
12929 if (Subtarget->hasAVX())
12931 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12932 if (ULEOp1.getNode()) {
12934 Subus = true; Invert = false; Swap = false;
12938 // Psubus is better than flip-sign because it requires no inversion.
12939 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12940 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12944 Opc = X86ISD::SUBUS;
12950 std::swap(Op0, Op1);
12952 // Check that the operation in question is available (most are plain SSE2,
12953 // but PCMPGTQ and PCMPEQQ have different requirements).
12954 if (VT == MVT::v2i64) {
12955 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12956 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12958 // First cast everything to the right type.
12959 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12960 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12962 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12963 // bits of the inputs before performing those operations. The lower
12964 // compare is always unsigned.
12967 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12969 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12970 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12971 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12972 Sign, Zero, Sign, Zero);
12974 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12975 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12977 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12978 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12979 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12981 // Create masks for only the low parts/high parts of the 64 bit integers.
12982 static const int MaskHi[] = { 1, 1, 3, 3 };
12983 static const int MaskLo[] = { 0, 0, 2, 2 };
12984 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12985 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12986 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12988 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12989 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12992 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12994 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12997 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12998 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12999 // pcmpeqd + pshufd + pand.
13000 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13002 // First cast everything to the right type.
13003 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13004 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13007 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13009 // Make sure the lower and upper halves are both all-ones.
13010 static const int Mask[] = { 1, 0, 3, 2 };
13011 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13012 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13015 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13017 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13021 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13022 // bits of the inputs before performing those operations.
13024 EVT EltVT = VT.getVectorElementType();
13025 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13026 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13027 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13030 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13032 // If the logical-not of the result is required, perform that now.
13034 Result = DAG.getNOT(dl, Result, VT);
13037 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13040 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13041 getZeroVector(VT, Subtarget, DAG, dl));
13046 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13048 MVT VT = Op.getSimpleValueType();
13050 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13052 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13053 && "SetCC type must be 8-bit or 1-bit integer");
13054 SDValue Op0 = Op.getOperand(0);
13055 SDValue Op1 = Op.getOperand(1);
13057 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13059 // Optimize to BT if possible.
13060 // Lower (X & (1 << N)) == 0 to BT(X, N).
13061 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13062 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13063 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13064 Op1.getOpcode() == ISD::Constant &&
13065 cast<ConstantSDNode>(Op1)->isNullValue() &&
13066 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13067 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13068 if (NewSetCC.getNode()) {
13070 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13075 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13077 if (Op1.getOpcode() == ISD::Constant &&
13078 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13079 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13080 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13082 // If the input is a setcc, then reuse the input setcc or use a new one with
13083 // the inverted condition.
13084 if (Op0.getOpcode() == X86ISD::SETCC) {
13085 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13086 bool Invert = (CC == ISD::SETNE) ^
13087 cast<ConstantSDNode>(Op1)->isNullValue();
13091 CCode = X86::GetOppositeBranchCondition(CCode);
13092 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13093 DAG.getConstant(CCode, MVT::i8),
13094 Op0.getOperand(1));
13096 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13100 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13101 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13102 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13104 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13105 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13108 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13109 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13110 if (X86CC == X86::COND_INVALID)
13113 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13114 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13115 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13116 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13118 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13122 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13123 static bool isX86LogicalCmp(SDValue Op) {
13124 unsigned Opc = Op.getNode()->getOpcode();
13125 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13126 Opc == X86ISD::SAHF)
13128 if (Op.getResNo() == 1 &&
13129 (Opc == X86ISD::ADD ||
13130 Opc == X86ISD::SUB ||
13131 Opc == X86ISD::ADC ||
13132 Opc == X86ISD::SBB ||
13133 Opc == X86ISD::SMUL ||
13134 Opc == X86ISD::UMUL ||
13135 Opc == X86ISD::INC ||
13136 Opc == X86ISD::DEC ||
13137 Opc == X86ISD::OR ||
13138 Opc == X86ISD::XOR ||
13139 Opc == X86ISD::AND))
13142 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13148 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13149 if (V.getOpcode() != ISD::TRUNCATE)
13152 SDValue VOp0 = V.getOperand(0);
13153 unsigned InBits = VOp0.getValueSizeInBits();
13154 unsigned Bits = V.getValueSizeInBits();
13155 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13158 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13159 bool addTest = true;
13160 SDValue Cond = Op.getOperand(0);
13161 SDValue Op1 = Op.getOperand(1);
13162 SDValue Op2 = Op.getOperand(2);
13164 EVT VT = Op1.getValueType();
13167 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13168 // are available. Otherwise fp cmovs get lowered into a less efficient branch
13169 // sequence later on.
13170 if (Cond.getOpcode() == ISD::SETCC &&
13171 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13172 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13173 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13174 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13175 int SSECC = translateX86FSETCC(
13176 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13179 if (Subtarget->hasAVX512()) {
13180 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13181 DAG.getConstant(SSECC, MVT::i8));
13182 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13184 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13185 DAG.getConstant(SSECC, MVT::i8));
13186 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13187 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13188 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13192 if (Cond.getOpcode() == ISD::SETCC) {
13193 SDValue NewCond = LowerSETCC(Cond, DAG);
13194 if (NewCond.getNode())
13198 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13199 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13200 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13201 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13202 if (Cond.getOpcode() == X86ISD::SETCC &&
13203 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13204 isZero(Cond.getOperand(1).getOperand(1))) {
13205 SDValue Cmp = Cond.getOperand(1);
13207 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13209 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13210 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13211 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13213 SDValue CmpOp0 = Cmp.getOperand(0);
13214 // Apply further optimizations for special cases
13215 // (select (x != 0), -1, 0) -> neg & sbb
13216 // (select (x == 0), 0, -1) -> neg & sbb
13217 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13218 if (YC->isNullValue() &&
13219 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13220 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13221 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13222 DAG.getConstant(0, CmpOp0.getValueType()),
13224 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13225 DAG.getConstant(X86::COND_B, MVT::i8),
13226 SDValue(Neg.getNode(), 1));
13230 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13231 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13232 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13234 SDValue Res = // Res = 0 or -1.
13235 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13236 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13238 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13239 Res = DAG.getNOT(DL, Res, Res.getValueType());
13241 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13242 if (!N2C || !N2C->isNullValue())
13243 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13248 // Look past (and (setcc_carry (cmp ...)), 1).
13249 if (Cond.getOpcode() == ISD::AND &&
13250 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13251 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13252 if (C && C->getAPIntValue() == 1)
13253 Cond = Cond.getOperand(0);
13256 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13257 // setting operand in place of the X86ISD::SETCC.
13258 unsigned CondOpcode = Cond.getOpcode();
13259 if (CondOpcode == X86ISD::SETCC ||
13260 CondOpcode == X86ISD::SETCC_CARRY) {
13261 CC = Cond.getOperand(0);
13263 SDValue Cmp = Cond.getOperand(1);
13264 unsigned Opc = Cmp.getOpcode();
13265 MVT VT = Op.getSimpleValueType();
13267 bool IllegalFPCMov = false;
13268 if (VT.isFloatingPoint() && !VT.isVector() &&
13269 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13270 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13272 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13273 Opc == X86ISD::BT) { // FIXME
13277 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13278 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13279 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13280 Cond.getOperand(0).getValueType() != MVT::i8)) {
13281 SDValue LHS = Cond.getOperand(0);
13282 SDValue RHS = Cond.getOperand(1);
13283 unsigned X86Opcode;
13286 switch (CondOpcode) {
13287 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13288 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13289 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13290 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13291 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13292 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13293 default: llvm_unreachable("unexpected overflowing operator");
13295 if (CondOpcode == ISD::UMULO)
13296 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13299 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13301 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13303 if (CondOpcode == ISD::UMULO)
13304 Cond = X86Op.getValue(2);
13306 Cond = X86Op.getValue(1);
13308 CC = DAG.getConstant(X86Cond, MVT::i8);
13313 // Look pass the truncate if the high bits are known zero.
13314 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13315 Cond = Cond.getOperand(0);
13317 // We know the result of AND is compared against zero. Try to match
13319 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13320 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13321 if (NewSetCC.getNode()) {
13322 CC = NewSetCC.getOperand(0);
13323 Cond = NewSetCC.getOperand(1);
13330 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13331 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13334 // a < b ? -1 : 0 -> RES = ~setcc_carry
13335 // a < b ? 0 : -1 -> RES = setcc_carry
13336 // a >= b ? -1 : 0 -> RES = setcc_carry
13337 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13338 if (Cond.getOpcode() == X86ISD::SUB) {
13339 Cond = ConvertCmpIfNecessary(Cond, DAG);
13340 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13342 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13343 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13344 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13345 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13346 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13347 return DAG.getNOT(DL, Res, Res.getValueType());
13352 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13353 // widen the cmov and push the truncate through. This avoids introducing a new
13354 // branch during isel and doesn't add any extensions.
13355 if (Op.getValueType() == MVT::i8 &&
13356 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13357 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13358 if (T1.getValueType() == T2.getValueType() &&
13359 // Blacklist CopyFromReg to avoid partial register stalls.
13360 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13361 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13362 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13363 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13367 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13368 // condition is true.
13369 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13370 SDValue Ops[] = { Op2, Op1, CC, Cond };
13371 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13374 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13375 SelectionDAG &DAG) {
13376 MVT VT = Op->getSimpleValueType(0);
13377 SDValue In = Op->getOperand(0);
13378 MVT InVT = In.getSimpleValueType();
13379 MVT VTElt = VT.getVectorElementType();
13380 MVT InVTElt = InVT.getVectorElementType();
13384 if ((InVTElt == MVT::i1) &&
13385 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13386 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13388 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13389 VTElt.getSizeInBits() <= 16)) ||
13391 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13392 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13394 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13395 VTElt.getSizeInBits() >= 32))))
13396 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13398 unsigned int NumElts = VT.getVectorNumElements();
13400 if (NumElts != 8 && NumElts != 16)
13403 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13404 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13405 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13406 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13409 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13410 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13412 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13413 Constant *C = ConstantInt::get(*DAG.getContext(),
13414 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13416 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13417 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13418 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13419 MachinePointerInfo::getConstantPool(),
13420 false, false, false, Alignment);
13421 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13422 if (VT.is512BitVector())
13424 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13427 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13428 SelectionDAG &DAG) {
13429 MVT VT = Op->getSimpleValueType(0);
13430 SDValue In = Op->getOperand(0);
13431 MVT InVT = In.getSimpleValueType();
13434 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13435 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13437 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13438 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13439 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13442 if (Subtarget->hasInt256())
13443 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13445 // Optimize vectors in AVX mode
13446 // Sign extend v8i16 to v8i32 and
13449 // Divide input vector into two parts
13450 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13451 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13452 // concat the vectors to original VT
13454 unsigned NumElems = InVT.getVectorNumElements();
13455 SDValue Undef = DAG.getUNDEF(InVT);
13457 SmallVector<int,8> ShufMask1(NumElems, -1);
13458 for (unsigned i = 0; i != NumElems/2; ++i)
13461 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13463 SmallVector<int,8> ShufMask2(NumElems, -1);
13464 for (unsigned i = 0; i != NumElems/2; ++i)
13465 ShufMask2[i] = i + NumElems/2;
13467 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13469 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13470 VT.getVectorNumElements()/2);
13472 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13473 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13475 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13478 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13479 // may emit an illegal shuffle but the expansion is still better than scalar
13480 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13481 // we'll emit a shuffle and a arithmetic shift.
13482 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13483 // TODO: It is possible to support ZExt by zeroing the undef values during
13484 // the shuffle phase or after the shuffle.
13485 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13486 SelectionDAG &DAG) {
13487 MVT RegVT = Op.getSimpleValueType();
13488 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13489 assert(RegVT.isInteger() &&
13490 "We only custom lower integer vector sext loads.");
13492 // Nothing useful we can do without SSE2 shuffles.
13493 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13495 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13497 EVT MemVT = Ld->getMemoryVT();
13498 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13499 unsigned RegSz = RegVT.getSizeInBits();
13501 ISD::LoadExtType Ext = Ld->getExtensionType();
13503 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13504 && "Only anyext and sext are currently implemented.");
13505 assert(MemVT != RegVT && "Cannot extend to the same type");
13506 assert(MemVT.isVector() && "Must load a vector from memory");
13508 unsigned NumElems = RegVT.getVectorNumElements();
13509 unsigned MemSz = MemVT.getSizeInBits();
13510 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13512 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13513 // The only way in which we have a legal 256-bit vector result but not the
13514 // integer 256-bit operations needed to directly lower a sextload is if we
13515 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13516 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13517 // correctly legalized. We do this late to allow the canonical form of
13518 // sextload to persist throughout the rest of the DAG combiner -- it wants
13519 // to fold together any extensions it can, and so will fuse a sign_extend
13520 // of an sextload into a sextload targeting a wider value.
13522 if (MemSz == 128) {
13523 // Just switch this to a normal load.
13524 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13525 "it must be a legal 128-bit vector "
13527 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13528 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13529 Ld->isInvariant(), Ld->getAlignment());
13531 assert(MemSz < 128 &&
13532 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13533 // Do an sext load to a 128-bit vector type. We want to use the same
13534 // number of elements, but elements half as wide. This will end up being
13535 // recursively lowered by this routine, but will succeed as we definitely
13536 // have all the necessary features if we're using AVX1.
13538 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13539 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13541 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13542 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13543 Ld->isNonTemporal(), Ld->isInvariant(),
13544 Ld->getAlignment());
13547 // Replace chain users with the new chain.
13548 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13549 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13551 // Finally, do a normal sign-extend to the desired register.
13552 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13555 // All sizes must be a power of two.
13556 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13557 "Non-power-of-two elements are not custom lowered!");
13559 // Attempt to load the original value using scalar loads.
13560 // Find the largest scalar type that divides the total loaded size.
13561 MVT SclrLoadTy = MVT::i8;
13562 for (MVT Tp : MVT::integer_valuetypes()) {
13563 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13568 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13569 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13571 SclrLoadTy = MVT::f64;
13573 // Calculate the number of scalar loads that we need to perform
13574 // in order to load our vector from memory.
13575 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13577 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13578 "Can only lower sext loads with a single scalar load!");
13580 unsigned loadRegZize = RegSz;
13581 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13584 // Represent our vector as a sequence of elements which are the
13585 // largest scalar that we can load.
13586 EVT LoadUnitVecVT = EVT::getVectorVT(
13587 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13589 // Represent the data using the same element type that is stored in
13590 // memory. In practice, we ''widen'' MemVT.
13592 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13593 loadRegZize / MemVT.getScalarType().getSizeInBits());
13595 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13596 "Invalid vector type");
13598 // We can't shuffle using an illegal type.
13599 assert(TLI.isTypeLegal(WideVecVT) &&
13600 "We only lower types that form legal widened vector types");
13602 SmallVector<SDValue, 8> Chains;
13603 SDValue Ptr = Ld->getBasePtr();
13604 SDValue Increment =
13605 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13606 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13608 for (unsigned i = 0; i < NumLoads; ++i) {
13609 // Perform a single load.
13610 SDValue ScalarLoad =
13611 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13612 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13613 Ld->getAlignment());
13614 Chains.push_back(ScalarLoad.getValue(1));
13615 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13616 // another round of DAGCombining.
13618 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13620 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13621 ScalarLoad, DAG.getIntPtrConstant(i));
13623 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13626 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13628 // Bitcast the loaded value to a vector of the original element type, in
13629 // the size of the target vector type.
13630 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13631 unsigned SizeRatio = RegSz / MemSz;
13633 if (Ext == ISD::SEXTLOAD) {
13634 // If we have SSE4.1, we can directly emit a VSEXT node.
13635 if (Subtarget->hasSSE41()) {
13636 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13637 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13641 // Otherwise we'll shuffle the small elements in the high bits of the
13642 // larger type and perform an arithmetic shift. If the shift is not legal
13643 // it's better to scalarize.
13644 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13645 "We can't implement a sext load without an arithmetic right shift!");
13647 // Redistribute the loaded elements into the different locations.
13648 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13649 for (unsigned i = 0; i != NumElems; ++i)
13650 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13652 SDValue Shuff = DAG.getVectorShuffle(
13653 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13655 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13657 // Build the arithmetic shift.
13658 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13659 MemVT.getVectorElementType().getSizeInBits();
13661 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13663 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13667 // Redistribute the loaded elements into the different locations.
13668 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13669 for (unsigned i = 0; i != NumElems; ++i)
13670 ShuffleVec[i * SizeRatio] = i;
13672 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13673 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13675 // Bitcast to the requested type.
13676 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13677 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13681 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13682 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13683 // from the AND / OR.
13684 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13685 Opc = Op.getOpcode();
13686 if (Opc != ISD::OR && Opc != ISD::AND)
13688 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13689 Op.getOperand(0).hasOneUse() &&
13690 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13691 Op.getOperand(1).hasOneUse());
13694 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13695 // 1 and that the SETCC node has a single use.
13696 static bool isXor1OfSetCC(SDValue Op) {
13697 if (Op.getOpcode() != ISD::XOR)
13699 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13700 if (N1C && N1C->getAPIntValue() == 1) {
13701 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13702 Op.getOperand(0).hasOneUse();
13707 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13708 bool addTest = true;
13709 SDValue Chain = Op.getOperand(0);
13710 SDValue Cond = Op.getOperand(1);
13711 SDValue Dest = Op.getOperand(2);
13714 bool Inverted = false;
13716 if (Cond.getOpcode() == ISD::SETCC) {
13717 // Check for setcc([su]{add,sub,mul}o == 0).
13718 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13719 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13720 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13721 Cond.getOperand(0).getResNo() == 1 &&
13722 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13723 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13724 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13725 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13726 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13727 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13729 Cond = Cond.getOperand(0);
13731 SDValue NewCond = LowerSETCC(Cond, DAG);
13732 if (NewCond.getNode())
13737 // FIXME: LowerXALUO doesn't handle these!!
13738 else if (Cond.getOpcode() == X86ISD::ADD ||
13739 Cond.getOpcode() == X86ISD::SUB ||
13740 Cond.getOpcode() == X86ISD::SMUL ||
13741 Cond.getOpcode() == X86ISD::UMUL)
13742 Cond = LowerXALUO(Cond, DAG);
13745 // Look pass (and (setcc_carry (cmp ...)), 1).
13746 if (Cond.getOpcode() == ISD::AND &&
13747 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13748 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13749 if (C && C->getAPIntValue() == 1)
13750 Cond = Cond.getOperand(0);
13753 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13754 // setting operand in place of the X86ISD::SETCC.
13755 unsigned CondOpcode = Cond.getOpcode();
13756 if (CondOpcode == X86ISD::SETCC ||
13757 CondOpcode == X86ISD::SETCC_CARRY) {
13758 CC = Cond.getOperand(0);
13760 SDValue Cmp = Cond.getOperand(1);
13761 unsigned Opc = Cmp.getOpcode();
13762 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13763 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13767 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13771 // These can only come from an arithmetic instruction with overflow,
13772 // e.g. SADDO, UADDO.
13773 Cond = Cond.getNode()->getOperand(1);
13779 CondOpcode = Cond.getOpcode();
13780 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13781 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13782 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13783 Cond.getOperand(0).getValueType() != MVT::i8)) {
13784 SDValue LHS = Cond.getOperand(0);
13785 SDValue RHS = Cond.getOperand(1);
13786 unsigned X86Opcode;
13789 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13790 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13792 switch (CondOpcode) {
13793 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13795 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13797 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13800 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13801 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13803 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13805 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13808 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13809 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13810 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13811 default: llvm_unreachable("unexpected overflowing operator");
13814 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13815 if (CondOpcode == ISD::UMULO)
13816 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13819 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13821 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13823 if (CondOpcode == ISD::UMULO)
13824 Cond = X86Op.getValue(2);
13826 Cond = X86Op.getValue(1);
13828 CC = DAG.getConstant(X86Cond, MVT::i8);
13832 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13833 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13834 if (CondOpc == ISD::OR) {
13835 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13836 // two branches instead of an explicit OR instruction with a
13838 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13839 isX86LogicalCmp(Cmp)) {
13840 CC = Cond.getOperand(0).getOperand(0);
13841 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13842 Chain, Dest, CC, Cmp);
13843 CC = Cond.getOperand(1).getOperand(0);
13847 } else { // ISD::AND
13848 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13849 // two branches instead of an explicit AND instruction with a
13850 // separate test. However, we only do this if this block doesn't
13851 // have a fall-through edge, because this requires an explicit
13852 // jmp when the condition is false.
13853 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13854 isX86LogicalCmp(Cmp) &&
13855 Op.getNode()->hasOneUse()) {
13856 X86::CondCode CCode =
13857 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13858 CCode = X86::GetOppositeBranchCondition(CCode);
13859 CC = DAG.getConstant(CCode, MVT::i8);
13860 SDNode *User = *Op.getNode()->use_begin();
13861 // Look for an unconditional branch following this conditional branch.
13862 // We need this because we need to reverse the successors in order
13863 // to implement FCMP_OEQ.
13864 if (User->getOpcode() == ISD::BR) {
13865 SDValue FalseBB = User->getOperand(1);
13867 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13868 assert(NewBR == User);
13872 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13873 Chain, Dest, CC, Cmp);
13874 X86::CondCode CCode =
13875 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13876 CCode = X86::GetOppositeBranchCondition(CCode);
13877 CC = DAG.getConstant(CCode, MVT::i8);
13883 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13884 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13885 // It should be transformed during dag combiner except when the condition
13886 // is set by a arithmetics with overflow node.
13887 X86::CondCode CCode =
13888 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13889 CCode = X86::GetOppositeBranchCondition(CCode);
13890 CC = DAG.getConstant(CCode, MVT::i8);
13891 Cond = Cond.getOperand(0).getOperand(1);
13893 } else if (Cond.getOpcode() == ISD::SETCC &&
13894 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13895 // For FCMP_OEQ, we can emit
13896 // two branches instead of an explicit AND instruction with a
13897 // separate test. However, we only do this if this block doesn't
13898 // have a fall-through edge, because this requires an explicit
13899 // jmp when the condition is false.
13900 if (Op.getNode()->hasOneUse()) {
13901 SDNode *User = *Op.getNode()->use_begin();
13902 // Look for an unconditional branch following this conditional branch.
13903 // We need this because we need to reverse the successors in order
13904 // to implement FCMP_OEQ.
13905 if (User->getOpcode() == ISD::BR) {
13906 SDValue FalseBB = User->getOperand(1);
13908 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13909 assert(NewBR == User);
13913 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13914 Cond.getOperand(0), Cond.getOperand(1));
13915 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13916 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13917 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13918 Chain, Dest, CC, Cmp);
13919 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13924 } else if (Cond.getOpcode() == ISD::SETCC &&
13925 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13926 // For FCMP_UNE, we can emit
13927 // two branches instead of an explicit AND instruction with a
13928 // separate test. However, we only do this if this block doesn't
13929 // have a fall-through edge, because this requires an explicit
13930 // jmp when the condition is false.
13931 if (Op.getNode()->hasOneUse()) {
13932 SDNode *User = *Op.getNode()->use_begin();
13933 // Look for an unconditional branch following this conditional branch.
13934 // We need this because we need to reverse the successors in order
13935 // to implement FCMP_UNE.
13936 if (User->getOpcode() == ISD::BR) {
13937 SDValue FalseBB = User->getOperand(1);
13939 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13940 assert(NewBR == User);
13943 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13944 Cond.getOperand(0), Cond.getOperand(1));
13945 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13946 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13947 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13948 Chain, Dest, CC, Cmp);
13949 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13959 // Look pass the truncate if the high bits are known zero.
13960 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13961 Cond = Cond.getOperand(0);
13963 // We know the result of AND is compared against zero. Try to match
13965 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13966 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13967 if (NewSetCC.getNode()) {
13968 CC = NewSetCC.getOperand(0);
13969 Cond = NewSetCC.getOperand(1);
13976 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13977 CC = DAG.getConstant(X86Cond, MVT::i8);
13978 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13980 Cond = ConvertCmpIfNecessary(Cond, DAG);
13981 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13982 Chain, Dest, CC, Cond);
13985 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13986 // Calls to _alloca are needed to probe the stack when allocating more than 4k
13987 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13988 // that the guard pages used by the OS virtual memory manager are allocated in
13989 // correct sequence.
13991 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13992 SelectionDAG &DAG) const {
13993 MachineFunction &MF = DAG.getMachineFunction();
13994 bool SplitStack = MF.shouldSplitStack();
13995 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14000 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14001 SDNode* Node = Op.getNode();
14003 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14004 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14005 " not tell us which reg is the stack pointer!");
14006 EVT VT = Node->getValueType(0);
14007 SDValue Tmp1 = SDValue(Node, 0);
14008 SDValue Tmp2 = SDValue(Node, 1);
14009 SDValue Tmp3 = Node->getOperand(2);
14010 SDValue Chain = Tmp1.getOperand(0);
14012 // Chain the dynamic stack allocation so that it doesn't modify the stack
14013 // pointer when other instructions are using the stack.
14014 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14017 SDValue Size = Tmp2.getOperand(1);
14018 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14019 Chain = SP.getValue(1);
14020 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14021 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14022 unsigned StackAlign = TFI.getStackAlignment();
14023 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14024 if (Align > StackAlign)
14025 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14026 DAG.getConstant(-(uint64_t)Align, VT));
14027 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14029 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14030 DAG.getIntPtrConstant(0, true), SDValue(),
14033 SDValue Ops[2] = { Tmp1, Tmp2 };
14034 return DAG.getMergeValues(Ops, dl);
14038 SDValue Chain = Op.getOperand(0);
14039 SDValue Size = Op.getOperand(1);
14040 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14041 EVT VT = Op.getNode()->getValueType(0);
14043 bool Is64Bit = Subtarget->is64Bit();
14044 EVT SPTy = getPointerTy();
14047 MachineRegisterInfo &MRI = MF.getRegInfo();
14050 // The 64 bit implementation of segmented stacks needs to clobber both r10
14051 // r11. This makes it impossible to use it along with nested parameters.
14052 const Function *F = MF.getFunction();
14054 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14056 if (I->hasNestAttr())
14057 report_fatal_error("Cannot use segmented stacks with functions that "
14058 "have nested arguments.");
14061 const TargetRegisterClass *AddrRegClass =
14062 getRegClassFor(getPointerTy());
14063 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14064 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14065 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14066 DAG.getRegister(Vreg, SPTy));
14067 SDValue Ops1[2] = { Value, Chain };
14068 return DAG.getMergeValues(Ops1, dl);
14071 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14073 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14074 Flag = Chain.getValue(1);
14075 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14077 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14079 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14080 unsigned SPReg = RegInfo->getStackRegister();
14081 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14082 Chain = SP.getValue(1);
14085 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14086 DAG.getConstant(-(uint64_t)Align, VT));
14087 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14090 SDValue Ops1[2] = { SP, Chain };
14091 return DAG.getMergeValues(Ops1, dl);
14095 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14096 MachineFunction &MF = DAG.getMachineFunction();
14097 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14099 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14102 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14103 // vastart just stores the address of the VarArgsFrameIndex slot into the
14104 // memory location argument.
14105 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14107 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14108 MachinePointerInfo(SV), false, false, 0);
14112 // gp_offset (0 - 6 * 8)
14113 // fp_offset (48 - 48 + 8 * 16)
14114 // overflow_arg_area (point to parameters coming in memory).
14116 SmallVector<SDValue, 8> MemOps;
14117 SDValue FIN = Op.getOperand(1);
14119 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14120 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14122 FIN, MachinePointerInfo(SV), false, false, 0);
14123 MemOps.push_back(Store);
14126 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14127 FIN, DAG.getIntPtrConstant(4));
14128 Store = DAG.getStore(Op.getOperand(0), DL,
14129 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14131 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14132 MemOps.push_back(Store);
14134 // Store ptr to overflow_arg_area
14135 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14136 FIN, DAG.getIntPtrConstant(4));
14137 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14139 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14140 MachinePointerInfo(SV, 8),
14142 MemOps.push_back(Store);
14144 // Store ptr to reg_save_area.
14145 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14146 FIN, DAG.getIntPtrConstant(8));
14147 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14149 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14150 MachinePointerInfo(SV, 16), false, false, 0);
14151 MemOps.push_back(Store);
14152 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14155 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14156 assert(Subtarget->is64Bit() &&
14157 "LowerVAARG only handles 64-bit va_arg!");
14158 assert((Subtarget->isTargetLinux() ||
14159 Subtarget->isTargetDarwin()) &&
14160 "Unhandled target in LowerVAARG");
14161 assert(Op.getNode()->getNumOperands() == 4);
14162 SDValue Chain = Op.getOperand(0);
14163 SDValue SrcPtr = Op.getOperand(1);
14164 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14165 unsigned Align = Op.getConstantOperandVal(3);
14168 EVT ArgVT = Op.getNode()->getValueType(0);
14169 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14170 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14173 // Decide which area this value should be read from.
14174 // TODO: Implement the AMD64 ABI in its entirety. This simple
14175 // selection mechanism works only for the basic types.
14176 if (ArgVT == MVT::f80) {
14177 llvm_unreachable("va_arg for f80 not yet implemented");
14178 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14179 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14180 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14181 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14183 llvm_unreachable("Unhandled argument type in LowerVAARG");
14186 if (ArgMode == 2) {
14187 // Sanity Check: Make sure using fp_offset makes sense.
14188 assert(!DAG.getTarget().Options.UseSoftFloat &&
14189 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14190 Attribute::NoImplicitFloat)) &&
14191 Subtarget->hasSSE1());
14194 // Insert VAARG_64 node into the DAG
14195 // VAARG_64 returns two values: Variable Argument Address, Chain
14196 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14197 DAG.getConstant(ArgMode, MVT::i8),
14198 DAG.getConstant(Align, MVT::i32)};
14199 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14200 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14201 VTs, InstOps, MVT::i64,
14202 MachinePointerInfo(SV),
14204 /*Volatile=*/false,
14206 /*WriteMem=*/true);
14207 Chain = VAARG.getValue(1);
14209 // Load the next argument and return it
14210 return DAG.getLoad(ArgVT, dl,
14213 MachinePointerInfo(),
14214 false, false, false, 0);
14217 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14218 SelectionDAG &DAG) {
14219 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14220 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14221 SDValue Chain = Op.getOperand(0);
14222 SDValue DstPtr = Op.getOperand(1);
14223 SDValue SrcPtr = Op.getOperand(2);
14224 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14225 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14228 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14229 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14231 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14234 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14235 // amount is a constant. Takes immediate version of shift as input.
14236 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14237 SDValue SrcOp, uint64_t ShiftAmt,
14238 SelectionDAG &DAG) {
14239 MVT ElementType = VT.getVectorElementType();
14241 // Fold this packed shift into its first operand if ShiftAmt is 0.
14245 // Check for ShiftAmt >= element width
14246 if (ShiftAmt >= ElementType.getSizeInBits()) {
14247 if (Opc == X86ISD::VSRAI)
14248 ShiftAmt = ElementType.getSizeInBits() - 1;
14250 return DAG.getConstant(0, VT);
14253 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14254 && "Unknown target vector shift-by-constant node");
14256 // Fold this packed vector shift into a build vector if SrcOp is a
14257 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14258 if (VT == SrcOp.getSimpleValueType() &&
14259 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14260 SmallVector<SDValue, 8> Elts;
14261 unsigned NumElts = SrcOp->getNumOperands();
14262 ConstantSDNode *ND;
14265 default: llvm_unreachable(nullptr);
14266 case X86ISD::VSHLI:
14267 for (unsigned i=0; i!=NumElts; ++i) {
14268 SDValue CurrentOp = SrcOp->getOperand(i);
14269 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14270 Elts.push_back(CurrentOp);
14273 ND = cast<ConstantSDNode>(CurrentOp);
14274 const APInt &C = ND->getAPIntValue();
14275 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14278 case X86ISD::VSRLI:
14279 for (unsigned i=0; i!=NumElts; ++i) {
14280 SDValue CurrentOp = SrcOp->getOperand(i);
14281 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14282 Elts.push_back(CurrentOp);
14285 ND = cast<ConstantSDNode>(CurrentOp);
14286 const APInt &C = ND->getAPIntValue();
14287 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14290 case X86ISD::VSRAI:
14291 for (unsigned i=0; i!=NumElts; ++i) {
14292 SDValue CurrentOp = SrcOp->getOperand(i);
14293 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14294 Elts.push_back(CurrentOp);
14297 ND = cast<ConstantSDNode>(CurrentOp);
14298 const APInt &C = ND->getAPIntValue();
14299 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14304 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14307 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14310 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14311 // may or may not be a constant. Takes immediate version of shift as input.
14312 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14313 SDValue SrcOp, SDValue ShAmt,
14314 SelectionDAG &DAG) {
14315 MVT SVT = ShAmt.getSimpleValueType();
14316 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14318 // Catch shift-by-constant.
14319 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14320 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14321 CShAmt->getZExtValue(), DAG);
14323 // Change opcode to non-immediate version
14325 default: llvm_unreachable("Unknown target vector shift node");
14326 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14327 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14328 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14331 const X86Subtarget &Subtarget =
14332 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14333 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14334 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14335 // Let the shuffle legalizer expand this shift amount node.
14336 SDValue Op0 = ShAmt.getOperand(0);
14337 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14338 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14340 // Need to build a vector containing shift amount.
14341 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14342 SmallVector<SDValue, 4> ShOps;
14343 ShOps.push_back(ShAmt);
14344 if (SVT == MVT::i32) {
14345 ShOps.push_back(DAG.getConstant(0, SVT));
14346 ShOps.push_back(DAG.getUNDEF(SVT));
14348 ShOps.push_back(DAG.getUNDEF(SVT));
14350 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14351 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14354 // The return type has to be a 128-bit type with the same element
14355 // type as the input type.
14356 MVT EltVT = VT.getVectorElementType();
14357 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14359 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14360 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14363 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14364 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14365 /// necessary casting for \p Mask when lowering masking intrinsics.
14366 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14367 SDValue PreservedSrc,
14368 const X86Subtarget *Subtarget,
14369 SelectionDAG &DAG) {
14370 EVT VT = Op.getValueType();
14371 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14372 MVT::i1, VT.getVectorNumElements());
14373 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14374 Mask.getValueType().getSizeInBits());
14377 assert(MaskVT.isSimple() && "invalid mask type");
14379 if (isAllOnes(Mask))
14382 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14383 // are extracted by EXTRACT_SUBVECTOR.
14384 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14385 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14386 DAG.getIntPtrConstant(0));
14388 switch (Op.getOpcode()) {
14390 case X86ISD::PCMPEQM:
14391 case X86ISD::PCMPGTM:
14393 case X86ISD::CMPMU:
14394 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14396 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14397 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14398 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14401 /// \brief Creates an SDNode for a predicated scalar operation.
14402 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14403 /// The mask is comming as MVT::i8 and it should be truncated
14404 /// to MVT::i1 while lowering masking intrinsics.
14405 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14406 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14407 /// a scalar instruction.
14408 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14409 SDValue PreservedSrc,
14410 const X86Subtarget *Subtarget,
14411 SelectionDAG &DAG) {
14412 if (isAllOnes(Mask))
14415 EVT VT = Op.getValueType();
14417 // The mask should be of type MVT::i1
14418 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14420 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14421 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14422 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14425 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14426 SelectionDAG &DAG) {
14428 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14429 EVT VT = Op.getValueType();
14430 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14432 switch(IntrData->Type) {
14433 case INTR_TYPE_1OP:
14434 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14435 case INTR_TYPE_2OP:
14436 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14438 case INTR_TYPE_3OP:
14439 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14440 Op.getOperand(2), Op.getOperand(3));
14441 case INTR_TYPE_1OP_MASK_RM: {
14442 SDValue Src = Op.getOperand(1);
14443 SDValue Src0 = Op.getOperand(2);
14444 SDValue Mask = Op.getOperand(3);
14445 SDValue RoundingMode = Op.getOperand(4);
14446 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14448 Mask, Src0, Subtarget, DAG);
14450 case INTR_TYPE_SCALAR_MASK_RM: {
14451 SDValue Src1 = Op.getOperand(1);
14452 SDValue Src2 = Op.getOperand(2);
14453 SDValue Src0 = Op.getOperand(3);
14454 SDValue Mask = Op.getOperand(4);
14455 // There are 2 kinds of intrinsics in this group:
14456 // (1) With supress-all-exceptions (sae) - 6 operands
14457 // (2) With rounding mode and sae - 7 operands.
14458 if (Op.getNumOperands() == 6) {
14459 SDValue Sae = Op.getOperand(5);
14460 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14462 Mask, Src0, Subtarget, DAG);
14464 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14465 SDValue RoundingMode = Op.getOperand(5);
14466 SDValue Sae = Op.getOperand(6);
14467 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14468 RoundingMode, Sae),
14469 Mask, Src0, Subtarget, DAG);
14471 case INTR_TYPE_2OP_MASK: {
14472 SDValue Src1 = Op.getOperand(1);
14473 SDValue Src2 = Op.getOperand(2);
14474 SDValue PassThru = Op.getOperand(3);
14475 SDValue Mask = Op.getOperand(4);
14476 // We specify 2 possible opcodes for intrinsics with rounding modes.
14477 // First, we check if the intrinsic may have non-default rounding mode,
14478 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14479 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14480 if (IntrWithRoundingModeOpcode != 0) {
14481 SDValue Rnd = Op.getOperand(5);
14482 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14483 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14484 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14485 dl, Op.getValueType(),
14487 Mask, PassThru, Subtarget, DAG);
14490 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14492 Mask, PassThru, Subtarget, DAG);
14494 case FMA_OP_MASK: {
14495 SDValue Src1 = Op.getOperand(1);
14496 SDValue Src2 = Op.getOperand(2);
14497 SDValue Src3 = Op.getOperand(3);
14498 SDValue Mask = Op.getOperand(4);
14499 // We specify 2 possible opcodes for intrinsics with rounding modes.
14500 // First, we check if the intrinsic may have non-default rounding mode,
14501 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14502 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14503 if (IntrWithRoundingModeOpcode != 0) {
14504 SDValue Rnd = Op.getOperand(5);
14505 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14506 X86::STATIC_ROUNDING::CUR_DIRECTION)
14507 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14508 dl, Op.getValueType(),
14509 Src1, Src2, Src3, Rnd),
14510 Mask, Src1, Subtarget, DAG);
14512 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14513 dl, Op.getValueType(),
14515 Mask, Src1, Subtarget, DAG);
14518 case CMP_MASK_CC: {
14519 // Comparison intrinsics with masks.
14520 // Example of transformation:
14521 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14522 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14524 // (v8i1 (insert_subvector undef,
14525 // (v2i1 (and (PCMPEQM %a, %b),
14526 // (extract_subvector
14527 // (v8i1 (bitcast %mask)), 0))), 0))))
14528 EVT VT = Op.getOperand(1).getValueType();
14529 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14530 VT.getVectorNumElements());
14531 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14532 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14533 Mask.getValueType().getSizeInBits());
14535 if (IntrData->Type == CMP_MASK_CC) {
14536 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14537 Op.getOperand(2), Op.getOperand(3));
14539 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14540 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14543 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14544 DAG.getTargetConstant(0, MaskVT),
14546 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14547 DAG.getUNDEF(BitcastVT), CmpMask,
14548 DAG.getIntPtrConstant(0));
14549 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14551 case COMI: { // Comparison intrinsics
14552 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14553 SDValue LHS = Op.getOperand(1);
14554 SDValue RHS = Op.getOperand(2);
14555 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14556 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14557 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14558 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14559 DAG.getConstant(X86CC, MVT::i8), Cond);
14560 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14563 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14564 Op.getOperand(1), Op.getOperand(2), DAG);
14566 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14567 Op.getSimpleValueType(),
14569 Op.getOperand(2), DAG),
14570 Op.getOperand(4), Op.getOperand(3), Subtarget,
14572 case COMPRESS_EXPAND_IN_REG: {
14573 SDValue Mask = Op.getOperand(3);
14574 SDValue DataToCompress = Op.getOperand(1);
14575 SDValue PassThru = Op.getOperand(2);
14576 if (isAllOnes(Mask)) // return data as is
14577 return Op.getOperand(1);
14578 EVT VT = Op.getValueType();
14579 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14580 VT.getVectorNumElements());
14581 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14582 Mask.getValueType().getSizeInBits());
14584 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14585 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14586 DAG.getIntPtrConstant(0));
14588 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14592 SDValue Mask = Op.getOperand(3);
14593 EVT VT = Op.getValueType();
14594 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14595 VT.getVectorNumElements());
14596 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14597 Mask.getValueType().getSizeInBits());
14599 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14600 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14601 DAG.getIntPtrConstant(0));
14602 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14611 default: return SDValue(); // Don't custom lower most intrinsics.
14613 case Intrinsic::x86_avx512_mask_valign_q_512:
14614 case Intrinsic::x86_avx512_mask_valign_d_512:
14615 // Vector source operands are swapped.
14616 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14617 Op.getValueType(), Op.getOperand(2),
14620 Op.getOperand(5), Op.getOperand(4),
14623 // ptest and testp intrinsics. The intrinsic these come from are designed to
14624 // return an integer value, not just an instruction so lower it to the ptest
14625 // or testp pattern and a setcc for the result.
14626 case Intrinsic::x86_sse41_ptestz:
14627 case Intrinsic::x86_sse41_ptestc:
14628 case Intrinsic::x86_sse41_ptestnzc:
14629 case Intrinsic::x86_avx_ptestz_256:
14630 case Intrinsic::x86_avx_ptestc_256:
14631 case Intrinsic::x86_avx_ptestnzc_256:
14632 case Intrinsic::x86_avx_vtestz_ps:
14633 case Intrinsic::x86_avx_vtestc_ps:
14634 case Intrinsic::x86_avx_vtestnzc_ps:
14635 case Intrinsic::x86_avx_vtestz_pd:
14636 case Intrinsic::x86_avx_vtestc_pd:
14637 case Intrinsic::x86_avx_vtestnzc_pd:
14638 case Intrinsic::x86_avx_vtestz_ps_256:
14639 case Intrinsic::x86_avx_vtestc_ps_256:
14640 case Intrinsic::x86_avx_vtestnzc_ps_256:
14641 case Intrinsic::x86_avx_vtestz_pd_256:
14642 case Intrinsic::x86_avx_vtestc_pd_256:
14643 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14644 bool IsTestPacked = false;
14647 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14648 case Intrinsic::x86_avx_vtestz_ps:
14649 case Intrinsic::x86_avx_vtestz_pd:
14650 case Intrinsic::x86_avx_vtestz_ps_256:
14651 case Intrinsic::x86_avx_vtestz_pd_256:
14652 IsTestPacked = true; // Fallthrough
14653 case Intrinsic::x86_sse41_ptestz:
14654 case Intrinsic::x86_avx_ptestz_256:
14656 X86CC = X86::COND_E;
14658 case Intrinsic::x86_avx_vtestc_ps:
14659 case Intrinsic::x86_avx_vtestc_pd:
14660 case Intrinsic::x86_avx_vtestc_ps_256:
14661 case Intrinsic::x86_avx_vtestc_pd_256:
14662 IsTestPacked = true; // Fallthrough
14663 case Intrinsic::x86_sse41_ptestc:
14664 case Intrinsic::x86_avx_ptestc_256:
14666 X86CC = X86::COND_B;
14668 case Intrinsic::x86_avx_vtestnzc_ps:
14669 case Intrinsic::x86_avx_vtestnzc_pd:
14670 case Intrinsic::x86_avx_vtestnzc_ps_256:
14671 case Intrinsic::x86_avx_vtestnzc_pd_256:
14672 IsTestPacked = true; // Fallthrough
14673 case Intrinsic::x86_sse41_ptestnzc:
14674 case Intrinsic::x86_avx_ptestnzc_256:
14676 X86CC = X86::COND_A;
14680 SDValue LHS = Op.getOperand(1);
14681 SDValue RHS = Op.getOperand(2);
14682 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14683 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14684 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14685 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14686 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14688 case Intrinsic::x86_avx512_kortestz_w:
14689 case Intrinsic::x86_avx512_kortestc_w: {
14690 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14691 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14692 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14693 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14694 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14695 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14696 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14699 case Intrinsic::x86_sse42_pcmpistria128:
14700 case Intrinsic::x86_sse42_pcmpestria128:
14701 case Intrinsic::x86_sse42_pcmpistric128:
14702 case Intrinsic::x86_sse42_pcmpestric128:
14703 case Intrinsic::x86_sse42_pcmpistrio128:
14704 case Intrinsic::x86_sse42_pcmpestrio128:
14705 case Intrinsic::x86_sse42_pcmpistris128:
14706 case Intrinsic::x86_sse42_pcmpestris128:
14707 case Intrinsic::x86_sse42_pcmpistriz128:
14708 case Intrinsic::x86_sse42_pcmpestriz128: {
14712 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14713 case Intrinsic::x86_sse42_pcmpistria128:
14714 Opcode = X86ISD::PCMPISTRI;
14715 X86CC = X86::COND_A;
14717 case Intrinsic::x86_sse42_pcmpestria128:
14718 Opcode = X86ISD::PCMPESTRI;
14719 X86CC = X86::COND_A;
14721 case Intrinsic::x86_sse42_pcmpistric128:
14722 Opcode = X86ISD::PCMPISTRI;
14723 X86CC = X86::COND_B;
14725 case Intrinsic::x86_sse42_pcmpestric128:
14726 Opcode = X86ISD::PCMPESTRI;
14727 X86CC = X86::COND_B;
14729 case Intrinsic::x86_sse42_pcmpistrio128:
14730 Opcode = X86ISD::PCMPISTRI;
14731 X86CC = X86::COND_O;
14733 case Intrinsic::x86_sse42_pcmpestrio128:
14734 Opcode = X86ISD::PCMPESTRI;
14735 X86CC = X86::COND_O;
14737 case Intrinsic::x86_sse42_pcmpistris128:
14738 Opcode = X86ISD::PCMPISTRI;
14739 X86CC = X86::COND_S;
14741 case Intrinsic::x86_sse42_pcmpestris128:
14742 Opcode = X86ISD::PCMPESTRI;
14743 X86CC = X86::COND_S;
14745 case Intrinsic::x86_sse42_pcmpistriz128:
14746 Opcode = X86ISD::PCMPISTRI;
14747 X86CC = X86::COND_E;
14749 case Intrinsic::x86_sse42_pcmpestriz128:
14750 Opcode = X86ISD::PCMPESTRI;
14751 X86CC = X86::COND_E;
14754 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14755 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14756 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14757 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14758 DAG.getConstant(X86CC, MVT::i8),
14759 SDValue(PCMP.getNode(), 1));
14760 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14763 case Intrinsic::x86_sse42_pcmpistri128:
14764 case Intrinsic::x86_sse42_pcmpestri128: {
14766 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14767 Opcode = X86ISD::PCMPISTRI;
14769 Opcode = X86ISD::PCMPESTRI;
14771 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14772 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14773 return DAG.getNode(Opcode, dl, VTs, NewOps);
14778 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14779 SDValue Src, SDValue Mask, SDValue Base,
14780 SDValue Index, SDValue ScaleOp, SDValue Chain,
14781 const X86Subtarget * Subtarget) {
14783 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14784 assert(C && "Invalid scale type");
14785 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14786 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14787 Index.getSimpleValueType().getVectorNumElements());
14789 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14791 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14793 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14794 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14795 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14796 SDValue Segment = DAG.getRegister(0, MVT::i32);
14797 if (Src.getOpcode() == ISD::UNDEF)
14798 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14799 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14800 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14801 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14802 return DAG.getMergeValues(RetOps, dl);
14805 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14806 SDValue Src, SDValue Mask, SDValue Base,
14807 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14809 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14810 assert(C && "Invalid scale type");
14811 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14812 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14813 SDValue Segment = DAG.getRegister(0, MVT::i32);
14814 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14815 Index.getSimpleValueType().getVectorNumElements());
14817 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14819 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14821 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14822 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14823 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14824 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14825 return SDValue(Res, 1);
14828 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14829 SDValue Mask, SDValue Base, SDValue Index,
14830 SDValue ScaleOp, SDValue Chain) {
14832 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14833 assert(C && "Invalid scale type");
14834 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14835 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14836 SDValue Segment = DAG.getRegister(0, MVT::i32);
14838 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14840 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14842 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14844 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14845 //SDVTList VTs = DAG.getVTList(MVT::Other);
14846 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14847 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14848 return SDValue(Res, 0);
14851 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14852 // read performance monitor counters (x86_rdpmc).
14853 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14854 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14855 SmallVectorImpl<SDValue> &Results) {
14856 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14857 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14860 // The ECX register is used to select the index of the performance counter
14862 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14864 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14866 // Reads the content of a 64-bit performance counter and returns it in the
14867 // registers EDX:EAX.
14868 if (Subtarget->is64Bit()) {
14869 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14870 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14873 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14874 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14877 Chain = HI.getValue(1);
14879 if (Subtarget->is64Bit()) {
14880 // The EAX register is loaded with the low-order 32 bits. The EDX register
14881 // is loaded with the supported high-order bits of the counter.
14882 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14883 DAG.getConstant(32, MVT::i8));
14884 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14885 Results.push_back(Chain);
14889 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14890 SDValue Ops[] = { LO, HI };
14891 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14892 Results.push_back(Pair);
14893 Results.push_back(Chain);
14896 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14897 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14898 // also used to custom lower READCYCLECOUNTER nodes.
14899 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14900 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14901 SmallVectorImpl<SDValue> &Results) {
14902 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14903 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14906 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14907 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14908 // and the EAX register is loaded with the low-order 32 bits.
14909 if (Subtarget->is64Bit()) {
14910 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14911 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14914 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14915 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14918 SDValue Chain = HI.getValue(1);
14920 if (Opcode == X86ISD::RDTSCP_DAG) {
14921 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14923 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14924 // the ECX register. Add 'ecx' explicitly to the chain.
14925 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14927 // Explicitly store the content of ECX at the location passed in input
14928 // to the 'rdtscp' intrinsic.
14929 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14930 MachinePointerInfo(), false, false, 0);
14933 if (Subtarget->is64Bit()) {
14934 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14935 // the EAX register is loaded with the low-order 32 bits.
14936 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14937 DAG.getConstant(32, MVT::i8));
14938 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14939 Results.push_back(Chain);
14943 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14944 SDValue Ops[] = { LO, HI };
14945 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14946 Results.push_back(Pair);
14947 Results.push_back(Chain);
14950 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14951 SelectionDAG &DAG) {
14952 SmallVector<SDValue, 2> Results;
14954 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14956 return DAG.getMergeValues(Results, DL);
14960 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14961 SelectionDAG &DAG) {
14962 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14964 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
14969 switch(IntrData->Type) {
14971 llvm_unreachable("Unknown Intrinsic Type");
14975 // Emit the node with the right value type.
14976 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14977 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
14979 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14980 // Otherwise return the value from Rand, which is always 0, casted to i32.
14981 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14982 DAG.getConstant(1, Op->getValueType(1)),
14983 DAG.getConstant(X86::COND_B, MVT::i32),
14984 SDValue(Result.getNode(), 1) };
14985 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14986 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14989 // Return { result, isValid, chain }.
14990 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14991 SDValue(Result.getNode(), 2));
14994 //gather(v1, mask, index, base, scale);
14995 SDValue Chain = Op.getOperand(0);
14996 SDValue Src = Op.getOperand(2);
14997 SDValue Base = Op.getOperand(3);
14998 SDValue Index = Op.getOperand(4);
14999 SDValue Mask = Op.getOperand(5);
15000 SDValue Scale = Op.getOperand(6);
15001 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15005 //scatter(base, mask, index, v1, scale);
15006 SDValue Chain = Op.getOperand(0);
15007 SDValue Base = Op.getOperand(2);
15008 SDValue Mask = Op.getOperand(3);
15009 SDValue Index = Op.getOperand(4);
15010 SDValue Src = Op.getOperand(5);
15011 SDValue Scale = Op.getOperand(6);
15012 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15015 SDValue Hint = Op.getOperand(6);
15017 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15018 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15019 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15020 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15021 SDValue Chain = Op.getOperand(0);
15022 SDValue Mask = Op.getOperand(2);
15023 SDValue Index = Op.getOperand(3);
15024 SDValue Base = Op.getOperand(4);
15025 SDValue Scale = Op.getOperand(5);
15026 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15028 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15030 SmallVector<SDValue, 2> Results;
15031 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15032 return DAG.getMergeValues(Results, dl);
15034 // Read Performance Monitoring Counters.
15036 SmallVector<SDValue, 2> Results;
15037 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15038 return DAG.getMergeValues(Results, dl);
15040 // XTEST intrinsics.
15042 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15043 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15044 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15045 DAG.getConstant(X86::COND_NE, MVT::i8),
15047 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15048 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15049 Ret, SDValue(InTrans.getNode(), 1));
15053 SmallVector<SDValue, 2> Results;
15054 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15055 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15056 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15057 DAG.getConstant(-1, MVT::i8));
15058 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15059 Op.getOperand(4), GenCF.getValue(1));
15060 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15061 Op.getOperand(5), MachinePointerInfo(),
15063 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15064 DAG.getConstant(X86::COND_B, MVT::i8),
15066 Results.push_back(SetCC);
15067 Results.push_back(Store);
15068 return DAG.getMergeValues(Results, dl);
15070 case COMPRESS_TO_MEM: {
15072 SDValue Mask = Op.getOperand(4);
15073 SDValue DataToCompress = Op.getOperand(3);
15074 SDValue Addr = Op.getOperand(2);
15075 SDValue Chain = Op.getOperand(0);
15077 if (isAllOnes(Mask)) // return just a store
15078 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15079 MachinePointerInfo(), false, false, 0);
15081 EVT VT = DataToCompress.getValueType();
15082 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15083 VT.getVectorNumElements());
15084 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15085 Mask.getValueType().getSizeInBits());
15086 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15087 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15088 DAG.getIntPtrConstant(0));
15090 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15091 DataToCompress, DAG.getUNDEF(VT));
15092 return DAG.getStore(Chain, dl, Compressed, Addr,
15093 MachinePointerInfo(), false, false, 0);
15095 case EXPAND_FROM_MEM: {
15097 SDValue Mask = Op.getOperand(4);
15098 SDValue PathThru = Op.getOperand(3);
15099 SDValue Addr = Op.getOperand(2);
15100 SDValue Chain = Op.getOperand(0);
15101 EVT VT = Op.getValueType();
15103 if (isAllOnes(Mask)) // return just a load
15104 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15106 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15107 VT.getVectorNumElements());
15108 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15109 Mask.getValueType().getSizeInBits());
15110 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15111 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15112 DAG.getIntPtrConstant(0));
15114 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15115 false, false, false, 0);
15117 SDValue Results[] = {
15118 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15120 return DAG.getMergeValues(Results, dl);
15125 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15126 SelectionDAG &DAG) const {
15127 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15128 MFI->setReturnAddressIsTaken(true);
15130 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15133 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15135 EVT PtrVT = getPointerTy();
15138 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15139 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15140 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15141 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15142 DAG.getNode(ISD::ADD, dl, PtrVT,
15143 FrameAddr, Offset),
15144 MachinePointerInfo(), false, false, false, 0);
15147 // Just load the return address.
15148 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15149 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15150 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15153 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15154 MachineFunction &MF = DAG.getMachineFunction();
15155 MachineFrameInfo *MFI = MF.getFrameInfo();
15156 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15157 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15158 EVT VT = Op.getValueType();
15160 MFI->setFrameAddressIsTaken(true);
15162 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15163 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15164 // is not possible to crawl up the stack without looking at the unwind codes
15166 int FrameAddrIndex = FuncInfo->getFAIndex();
15167 if (!FrameAddrIndex) {
15168 // Set up a frame object for the return address.
15169 unsigned SlotSize = RegInfo->getSlotSize();
15170 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15171 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15172 FuncInfo->setFAIndex(FrameAddrIndex);
15174 return DAG.getFrameIndex(FrameAddrIndex, VT);
15177 unsigned FrameReg =
15178 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15179 SDLoc dl(Op); // FIXME probably not meaningful
15180 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15181 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15182 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15183 "Invalid Frame Register!");
15184 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15186 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15187 MachinePointerInfo(),
15188 false, false, false, 0);
15192 // FIXME? Maybe this could be a TableGen attribute on some registers and
15193 // this table could be generated automatically from RegInfo.
15194 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15196 unsigned Reg = StringSwitch<unsigned>(RegName)
15197 .Case("esp", X86::ESP)
15198 .Case("rsp", X86::RSP)
15202 report_fatal_error("Invalid register name global variable");
15205 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15206 SelectionDAG &DAG) const {
15207 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15208 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15211 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15212 SDValue Chain = Op.getOperand(0);
15213 SDValue Offset = Op.getOperand(1);
15214 SDValue Handler = Op.getOperand(2);
15217 EVT PtrVT = getPointerTy();
15218 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15219 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15220 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15221 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15222 "Invalid Frame Register!");
15223 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15224 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15226 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15227 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15228 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15229 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15231 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15233 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15234 DAG.getRegister(StoreAddrReg, PtrVT));
15237 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15238 SelectionDAG &DAG) const {
15240 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15241 DAG.getVTList(MVT::i32, MVT::Other),
15242 Op.getOperand(0), Op.getOperand(1));
15245 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15246 SelectionDAG &DAG) const {
15248 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15249 Op.getOperand(0), Op.getOperand(1));
15252 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15253 return Op.getOperand(0);
15256 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15257 SelectionDAG &DAG) const {
15258 SDValue Root = Op.getOperand(0);
15259 SDValue Trmp = Op.getOperand(1); // trampoline
15260 SDValue FPtr = Op.getOperand(2); // nested function
15261 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15264 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15265 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15267 if (Subtarget->is64Bit()) {
15268 SDValue OutChains[6];
15270 // Large code-model.
15271 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15272 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15274 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15275 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15277 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15279 // Load the pointer to the nested function into R11.
15280 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15281 SDValue Addr = Trmp;
15282 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15283 Addr, MachinePointerInfo(TrmpAddr),
15286 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15287 DAG.getConstant(2, MVT::i64));
15288 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15289 MachinePointerInfo(TrmpAddr, 2),
15292 // Load the 'nest' parameter value into R10.
15293 // R10 is specified in X86CallingConv.td
15294 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15295 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15296 DAG.getConstant(10, MVT::i64));
15297 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15298 Addr, MachinePointerInfo(TrmpAddr, 10),
15301 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15302 DAG.getConstant(12, MVT::i64));
15303 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15304 MachinePointerInfo(TrmpAddr, 12),
15307 // Jump to the nested function.
15308 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15309 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15310 DAG.getConstant(20, MVT::i64));
15311 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15312 Addr, MachinePointerInfo(TrmpAddr, 20),
15315 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15316 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15317 DAG.getConstant(22, MVT::i64));
15318 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15319 MachinePointerInfo(TrmpAddr, 22),
15322 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15324 const Function *Func =
15325 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15326 CallingConv::ID CC = Func->getCallingConv();
15331 llvm_unreachable("Unsupported calling convention");
15332 case CallingConv::C:
15333 case CallingConv::X86_StdCall: {
15334 // Pass 'nest' parameter in ECX.
15335 // Must be kept in sync with X86CallingConv.td
15336 NestReg = X86::ECX;
15338 // Check that ECX wasn't needed by an 'inreg' parameter.
15339 FunctionType *FTy = Func->getFunctionType();
15340 const AttributeSet &Attrs = Func->getAttributes();
15342 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15343 unsigned InRegCount = 0;
15346 for (FunctionType::param_iterator I = FTy->param_begin(),
15347 E = FTy->param_end(); I != E; ++I, ++Idx)
15348 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15349 // FIXME: should only count parameters that are lowered to integers.
15350 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15352 if (InRegCount > 2) {
15353 report_fatal_error("Nest register in use - reduce number of inreg"
15359 case CallingConv::X86_FastCall:
15360 case CallingConv::X86_ThisCall:
15361 case CallingConv::Fast:
15362 // Pass 'nest' parameter in EAX.
15363 // Must be kept in sync with X86CallingConv.td
15364 NestReg = X86::EAX;
15368 SDValue OutChains[4];
15369 SDValue Addr, Disp;
15371 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15372 DAG.getConstant(10, MVT::i32));
15373 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15375 // This is storing the opcode for MOV32ri.
15376 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15377 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15378 OutChains[0] = DAG.getStore(Root, dl,
15379 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15380 Trmp, MachinePointerInfo(TrmpAddr),
15383 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15384 DAG.getConstant(1, MVT::i32));
15385 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15386 MachinePointerInfo(TrmpAddr, 1),
15389 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15390 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15391 DAG.getConstant(5, MVT::i32));
15392 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15393 MachinePointerInfo(TrmpAddr, 5),
15396 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15397 DAG.getConstant(6, MVT::i32));
15398 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15399 MachinePointerInfo(TrmpAddr, 6),
15402 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15406 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15407 SelectionDAG &DAG) const {
15409 The rounding mode is in bits 11:10 of FPSR, and has the following
15411 00 Round to nearest
15416 FLT_ROUNDS, on the other hand, expects the following:
15423 To perform the conversion, we do:
15424 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15427 MachineFunction &MF = DAG.getMachineFunction();
15428 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15429 unsigned StackAlignment = TFI.getStackAlignment();
15430 MVT VT = Op.getSimpleValueType();
15433 // Save FP Control Word to stack slot
15434 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15435 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15437 MachineMemOperand *MMO =
15438 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15439 MachineMemOperand::MOStore, 2, 2);
15441 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15442 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15443 DAG.getVTList(MVT::Other),
15444 Ops, MVT::i16, MMO);
15446 // Load FP Control Word from stack slot
15447 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15448 MachinePointerInfo(), false, false, false, 0);
15450 // Transform as necessary
15452 DAG.getNode(ISD::SRL, DL, MVT::i16,
15453 DAG.getNode(ISD::AND, DL, MVT::i16,
15454 CWD, DAG.getConstant(0x800, MVT::i16)),
15455 DAG.getConstant(11, MVT::i8));
15457 DAG.getNode(ISD::SRL, DL, MVT::i16,
15458 DAG.getNode(ISD::AND, DL, MVT::i16,
15459 CWD, DAG.getConstant(0x400, MVT::i16)),
15460 DAG.getConstant(9, MVT::i8));
15463 DAG.getNode(ISD::AND, DL, MVT::i16,
15464 DAG.getNode(ISD::ADD, DL, MVT::i16,
15465 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15466 DAG.getConstant(1, MVT::i16)),
15467 DAG.getConstant(3, MVT::i16));
15469 return DAG.getNode((VT.getSizeInBits() < 16 ?
15470 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15473 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15474 MVT VT = Op.getSimpleValueType();
15476 unsigned NumBits = VT.getSizeInBits();
15479 Op = Op.getOperand(0);
15480 if (VT == MVT::i8) {
15481 // Zero extend to i32 since there is not an i8 bsr.
15483 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15486 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15487 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15488 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15490 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15493 DAG.getConstant(NumBits+NumBits-1, OpVT),
15494 DAG.getConstant(X86::COND_E, MVT::i8),
15497 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15499 // Finally xor with NumBits-1.
15500 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15503 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15507 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15508 MVT VT = Op.getSimpleValueType();
15510 unsigned NumBits = VT.getSizeInBits();
15513 Op = Op.getOperand(0);
15514 if (VT == MVT::i8) {
15515 // Zero extend to i32 since there is not an i8 bsr.
15517 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15520 // Issue a bsr (scan bits in reverse).
15521 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15522 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15524 // And xor with NumBits-1.
15525 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15528 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15532 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15533 MVT VT = Op.getSimpleValueType();
15534 unsigned NumBits = VT.getSizeInBits();
15536 Op = Op.getOperand(0);
15538 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15539 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15540 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15542 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15545 DAG.getConstant(NumBits, VT),
15546 DAG.getConstant(X86::COND_E, MVT::i8),
15549 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15552 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15553 // ones, and then concatenate the result back.
15554 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15555 MVT VT = Op.getSimpleValueType();
15557 assert(VT.is256BitVector() && VT.isInteger() &&
15558 "Unsupported value type for operation");
15560 unsigned NumElems = VT.getVectorNumElements();
15563 // Extract the LHS vectors
15564 SDValue LHS = Op.getOperand(0);
15565 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15566 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15568 // Extract the RHS vectors
15569 SDValue RHS = Op.getOperand(1);
15570 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15571 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15573 MVT EltVT = VT.getVectorElementType();
15574 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15576 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15577 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15578 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15581 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15582 assert(Op.getSimpleValueType().is256BitVector() &&
15583 Op.getSimpleValueType().isInteger() &&
15584 "Only handle AVX 256-bit vector integer operation");
15585 return Lower256IntArith(Op, DAG);
15588 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15589 assert(Op.getSimpleValueType().is256BitVector() &&
15590 Op.getSimpleValueType().isInteger() &&
15591 "Only handle AVX 256-bit vector integer operation");
15592 return Lower256IntArith(Op, DAG);
15595 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15596 SelectionDAG &DAG) {
15598 MVT VT = Op.getSimpleValueType();
15600 // Decompose 256-bit ops into smaller 128-bit ops.
15601 if (VT.is256BitVector() && !Subtarget->hasInt256())
15602 return Lower256IntArith(Op, DAG);
15604 SDValue A = Op.getOperand(0);
15605 SDValue B = Op.getOperand(1);
15607 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15608 if (VT == MVT::v4i32) {
15609 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15610 "Should not custom lower when pmuldq is available!");
15612 // Extract the odd parts.
15613 static const int UnpackMask[] = { 1, -1, 3, -1 };
15614 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15615 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15617 // Multiply the even parts.
15618 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15619 // Now multiply odd parts.
15620 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15622 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15623 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15625 // Merge the two vectors back together with a shuffle. This expands into 2
15627 static const int ShufMask[] = { 0, 4, 2, 6 };
15628 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15631 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15632 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15634 // Ahi = psrlqi(a, 32);
15635 // Bhi = psrlqi(b, 32);
15637 // AloBlo = pmuludq(a, b);
15638 // AloBhi = pmuludq(a, Bhi);
15639 // AhiBlo = pmuludq(Ahi, b);
15641 // AloBhi = psllqi(AloBhi, 32);
15642 // AhiBlo = psllqi(AhiBlo, 32);
15643 // return AloBlo + AloBhi + AhiBlo;
15645 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15646 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15648 // Bit cast to 32-bit vectors for MULUDQ
15649 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15650 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15651 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15652 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15653 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15654 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15656 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15657 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15658 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15660 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15661 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15663 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15664 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15667 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15668 assert(Subtarget->isTargetWin64() && "Unexpected target");
15669 EVT VT = Op.getValueType();
15670 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15671 "Unexpected return type for lowering");
15675 switch (Op->getOpcode()) {
15676 default: llvm_unreachable("Unexpected request for libcall!");
15677 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15678 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15679 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15680 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15681 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15682 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15686 SDValue InChain = DAG.getEntryNode();
15688 TargetLowering::ArgListTy Args;
15689 TargetLowering::ArgListEntry Entry;
15690 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15691 EVT ArgVT = Op->getOperand(i).getValueType();
15692 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15693 "Unexpected argument type for lowering");
15694 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15695 Entry.Node = StackPtr;
15696 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15698 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15699 Entry.Ty = PointerType::get(ArgTy,0);
15700 Entry.isSExt = false;
15701 Entry.isZExt = false;
15702 Args.push_back(Entry);
15705 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15708 TargetLowering::CallLoweringInfo CLI(DAG);
15709 CLI.setDebugLoc(dl).setChain(InChain)
15710 .setCallee(getLibcallCallingConv(LC),
15711 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15712 Callee, std::move(Args), 0)
15713 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15715 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15716 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15719 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15720 SelectionDAG &DAG) {
15721 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15722 EVT VT = Op0.getValueType();
15725 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15726 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15728 // PMULxD operations multiply each even value (starting at 0) of LHS with
15729 // the related value of RHS and produce a widen result.
15730 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15731 // => <2 x i64> <ae|cg>
15733 // In other word, to have all the results, we need to perform two PMULxD:
15734 // 1. one with the even values.
15735 // 2. one with the odd values.
15736 // To achieve #2, with need to place the odd values at an even position.
15738 // Place the odd value at an even position (basically, shift all values 1
15739 // step to the left):
15740 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15741 // <a|b|c|d> => <b|undef|d|undef>
15742 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15743 // <e|f|g|h> => <f|undef|h|undef>
15744 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15746 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15748 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15749 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15751 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15752 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15753 // => <2 x i64> <ae|cg>
15754 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15755 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15756 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15757 // => <2 x i64> <bf|dh>
15758 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15759 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15761 // Shuffle it back into the right order.
15762 SDValue Highs, Lows;
15763 if (VT == MVT::v8i32) {
15764 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15765 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15766 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15767 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15769 const int HighMask[] = {1, 5, 3, 7};
15770 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15771 const int LowMask[] = {0, 4, 2, 6};
15772 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15775 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15776 // unsigned multiply.
15777 if (IsSigned && !Subtarget->hasSSE41()) {
15779 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15780 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15781 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15782 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15783 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15785 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15786 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15789 // The first result of MUL_LOHI is actually the low value, followed by the
15791 SDValue Ops[] = {Lows, Highs};
15792 return DAG.getMergeValues(Ops, dl);
15795 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15796 const X86Subtarget *Subtarget) {
15797 MVT VT = Op.getSimpleValueType();
15799 SDValue R = Op.getOperand(0);
15800 SDValue Amt = Op.getOperand(1);
15802 // Optimize shl/srl/sra with constant shift amount.
15803 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15804 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15805 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15807 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15808 (Subtarget->hasInt256() &&
15809 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15810 (Subtarget->hasAVX512() &&
15811 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15812 if (Op.getOpcode() == ISD::SHL)
15813 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15815 if (Op.getOpcode() == ISD::SRL)
15816 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15818 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15819 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15823 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15824 unsigned NumElts = VT.getVectorNumElements();
15825 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15827 if (Op.getOpcode() == ISD::SHL) {
15828 // Make a large shift.
15829 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15831 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15832 // Zero out the rightmost bits.
15833 SmallVector<SDValue, 32> V(
15834 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15835 return DAG.getNode(ISD::AND, dl, VT, SHL,
15836 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15838 if (Op.getOpcode() == ISD::SRL) {
15839 // Make a large shift.
15840 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15842 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15843 // Zero out the leftmost bits.
15844 SmallVector<SDValue, 32> V(
15845 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15846 return DAG.getNode(ISD::AND, dl, VT, SRL,
15847 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15849 if (Op.getOpcode() == ISD::SRA) {
15850 if (ShiftAmt == 7) {
15851 // R s>> 7 === R s< 0
15852 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15853 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15856 // R s>> a === ((R u>> a) ^ m) - m
15857 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15858 SmallVector<SDValue, 32> V(NumElts,
15859 DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15860 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15861 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15862 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15865 llvm_unreachable("Unknown shift opcode.");
15870 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15871 if (!Subtarget->is64Bit() &&
15872 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15873 Amt.getOpcode() == ISD::BITCAST &&
15874 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15875 Amt = Amt.getOperand(0);
15876 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15877 VT.getVectorNumElements();
15878 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15879 uint64_t ShiftAmt = 0;
15880 for (unsigned i = 0; i != Ratio; ++i) {
15881 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15885 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15887 // Check remaining shift amounts.
15888 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15889 uint64_t ShAmt = 0;
15890 for (unsigned j = 0; j != Ratio; ++j) {
15891 ConstantSDNode *C =
15892 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15896 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15898 if (ShAmt != ShiftAmt)
15901 switch (Op.getOpcode()) {
15903 llvm_unreachable("Unknown shift opcode!");
15905 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15908 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15911 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15919 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15920 const X86Subtarget* Subtarget) {
15921 MVT VT = Op.getSimpleValueType();
15923 SDValue R = Op.getOperand(0);
15924 SDValue Amt = Op.getOperand(1);
15926 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15927 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15928 (Subtarget->hasInt256() &&
15929 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15930 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15931 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15933 EVT EltVT = VT.getVectorElementType();
15935 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
15936 // Check if this build_vector node is doing a splat.
15937 // If so, then set BaseShAmt equal to the splat value.
15938 BaseShAmt = BV->getSplatValue();
15939 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
15940 BaseShAmt = SDValue();
15942 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15943 Amt = Amt.getOperand(0);
15945 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
15946 if (SVN && SVN->isSplat()) {
15947 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
15948 SDValue InVec = Amt.getOperand(0);
15949 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15950 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
15951 "Unexpected shuffle index found!");
15952 BaseShAmt = InVec.getOperand(SplatIdx);
15953 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15954 if (ConstantSDNode *C =
15955 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15956 if (C->getZExtValue() == SplatIdx)
15957 BaseShAmt = InVec.getOperand(1);
15962 // Avoid introducing an extract element from a shuffle.
15963 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
15964 DAG.getIntPtrConstant(SplatIdx));
15968 if (BaseShAmt.getNode()) {
15969 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
15970 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
15971 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
15972 else if (EltVT.bitsLT(MVT::i32))
15973 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15975 switch (Op.getOpcode()) {
15977 llvm_unreachable("Unknown shift opcode!");
15979 switch (VT.SimpleTy) {
15980 default: return SDValue();
15989 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15992 switch (VT.SimpleTy) {
15993 default: return SDValue();
16000 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16003 switch (VT.SimpleTy) {
16004 default: return SDValue();
16013 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16019 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16020 if (!Subtarget->is64Bit() &&
16021 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16022 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16023 Amt.getOpcode() == ISD::BITCAST &&
16024 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16025 Amt = Amt.getOperand(0);
16026 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16027 VT.getVectorNumElements();
16028 std::vector<SDValue> Vals(Ratio);
16029 for (unsigned i = 0; i != Ratio; ++i)
16030 Vals[i] = Amt.getOperand(i);
16031 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16032 for (unsigned j = 0; j != Ratio; ++j)
16033 if (Vals[j] != Amt.getOperand(i + j))
16036 switch (Op.getOpcode()) {
16038 llvm_unreachable("Unknown shift opcode!");
16040 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16042 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16044 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16051 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16052 SelectionDAG &DAG) {
16053 MVT VT = Op.getSimpleValueType();
16055 SDValue R = Op.getOperand(0);
16056 SDValue Amt = Op.getOperand(1);
16059 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16060 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16062 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16066 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16070 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16072 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16073 if (Subtarget->hasInt256()) {
16074 if (Op.getOpcode() == ISD::SRL &&
16075 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16076 VT == MVT::v4i64 || VT == MVT::v8i32))
16078 if (Op.getOpcode() == ISD::SHL &&
16079 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16080 VT == MVT::v4i64 || VT == MVT::v8i32))
16082 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16086 // If possible, lower this packed shift into a vector multiply instead of
16087 // expanding it into a sequence of scalar shifts.
16088 // Do this only if the vector shift count is a constant build_vector.
16089 if (Op.getOpcode() == ISD::SHL &&
16090 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16091 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16092 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16093 SmallVector<SDValue, 8> Elts;
16094 EVT SVT = VT.getScalarType();
16095 unsigned SVTBits = SVT.getSizeInBits();
16096 const APInt &One = APInt(SVTBits, 1);
16097 unsigned NumElems = VT.getVectorNumElements();
16099 for (unsigned i=0; i !=NumElems; ++i) {
16100 SDValue Op = Amt->getOperand(i);
16101 if (Op->getOpcode() == ISD::UNDEF) {
16102 Elts.push_back(Op);
16106 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16107 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16108 uint64_t ShAmt = C.getZExtValue();
16109 if (ShAmt >= SVTBits) {
16110 Elts.push_back(DAG.getUNDEF(SVT));
16113 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16115 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16116 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16119 // Lower SHL with variable shift amount.
16120 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16121 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16123 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16124 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16125 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16126 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16129 // If possible, lower this shift as a sequence of two shifts by
16130 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16132 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16134 // Could be rewritten as:
16135 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16137 // The advantage is that the two shifts from the example would be
16138 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16139 // the vector shift into four scalar shifts plus four pairs of vector
16141 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16142 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16143 unsigned TargetOpcode = X86ISD::MOVSS;
16144 bool CanBeSimplified;
16145 // The splat value for the first packed shift (the 'X' from the example).
16146 SDValue Amt1 = Amt->getOperand(0);
16147 // The splat value for the second packed shift (the 'Y' from the example).
16148 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16149 Amt->getOperand(2);
16151 // See if it is possible to replace this node with a sequence of
16152 // two shifts followed by a MOVSS/MOVSD
16153 if (VT == MVT::v4i32) {
16154 // Check if it is legal to use a MOVSS.
16155 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16156 Amt2 == Amt->getOperand(3);
16157 if (!CanBeSimplified) {
16158 // Otherwise, check if we can still simplify this node using a MOVSD.
16159 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16160 Amt->getOperand(2) == Amt->getOperand(3);
16161 TargetOpcode = X86ISD::MOVSD;
16162 Amt2 = Amt->getOperand(2);
16165 // Do similar checks for the case where the machine value type
16167 CanBeSimplified = Amt1 == Amt->getOperand(1);
16168 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16169 CanBeSimplified = Amt2 == Amt->getOperand(i);
16171 if (!CanBeSimplified) {
16172 TargetOpcode = X86ISD::MOVSD;
16173 CanBeSimplified = true;
16174 Amt2 = Amt->getOperand(4);
16175 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16176 CanBeSimplified = Amt1 == Amt->getOperand(i);
16177 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16178 CanBeSimplified = Amt2 == Amt->getOperand(j);
16182 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16183 isa<ConstantSDNode>(Amt2)) {
16184 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16185 EVT CastVT = MVT::v4i32;
16187 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16188 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16190 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16191 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16192 if (TargetOpcode == X86ISD::MOVSD)
16193 CastVT = MVT::v2i64;
16194 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16195 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16196 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16198 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16202 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16203 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16206 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16207 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16209 // Turn 'a' into a mask suitable for VSELECT
16210 SDValue VSelM = DAG.getConstant(0x80, VT);
16211 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16212 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16214 SDValue CM1 = DAG.getConstant(0x0f, VT);
16215 SDValue CM2 = DAG.getConstant(0x3f, VT);
16217 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16218 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16219 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16220 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16221 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16224 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16225 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16226 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16228 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16229 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16230 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16231 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16232 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16235 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16236 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16237 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16239 // return VSELECT(r, r+r, a);
16240 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16241 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16245 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16246 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16247 // solution better.
16248 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16249 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16251 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16252 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16253 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16254 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16255 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16258 // Decompose 256-bit shifts into smaller 128-bit shifts.
16259 if (VT.is256BitVector()) {
16260 unsigned NumElems = VT.getVectorNumElements();
16261 MVT EltVT = VT.getVectorElementType();
16262 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16264 // Extract the two vectors
16265 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16266 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16268 // Recreate the shift amount vectors
16269 SDValue Amt1, Amt2;
16270 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16271 // Constant shift amount
16272 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16273 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16274 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16276 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16277 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16279 // Variable shift amount
16280 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16281 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16284 // Issue new vector shifts for the smaller types
16285 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16286 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16288 // Concatenate the result back
16289 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16295 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16296 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16297 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16298 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16299 // has only one use.
16300 SDNode *N = Op.getNode();
16301 SDValue LHS = N->getOperand(0);
16302 SDValue RHS = N->getOperand(1);
16303 unsigned BaseOp = 0;
16306 switch (Op.getOpcode()) {
16307 default: llvm_unreachable("Unknown ovf instruction!");
16309 // A subtract of one will be selected as a INC. Note that INC doesn't
16310 // set CF, so we can't do this for UADDO.
16311 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16313 BaseOp = X86ISD::INC;
16314 Cond = X86::COND_O;
16317 BaseOp = X86ISD::ADD;
16318 Cond = X86::COND_O;
16321 BaseOp = X86ISD::ADD;
16322 Cond = X86::COND_B;
16325 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16326 // set CF, so we can't do this for USUBO.
16327 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16329 BaseOp = X86ISD::DEC;
16330 Cond = X86::COND_O;
16333 BaseOp = X86ISD::SUB;
16334 Cond = X86::COND_O;
16337 BaseOp = X86ISD::SUB;
16338 Cond = X86::COND_B;
16341 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16342 Cond = X86::COND_O;
16344 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16345 if (N->getValueType(0) == MVT::i8) {
16346 BaseOp = X86ISD::UMUL8;
16347 Cond = X86::COND_O;
16350 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16352 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16355 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16356 DAG.getConstant(X86::COND_O, MVT::i32),
16357 SDValue(Sum.getNode(), 2));
16359 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16363 // Also sets EFLAGS.
16364 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16365 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16368 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16369 DAG.getConstant(Cond, MVT::i32),
16370 SDValue(Sum.getNode(), 1));
16372 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16375 /// Returns true if the operand type is exactly twice the native width, and
16376 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16377 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16378 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16379 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16380 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16383 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16384 else if (OpWidth == 128)
16385 return Subtarget->hasCmpxchg16b();
16390 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16391 return needsCmpXchgNb(SI->getValueOperand()->getType());
16394 // Note: this turns large loads into lock cmpxchg8b/16b.
16395 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16396 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16397 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16398 return needsCmpXchgNb(PTy->getElementType());
16401 TargetLoweringBase::AtomicRMWExpansionKind
16402 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16403 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16404 const Type *MemType = AI->getType();
16406 // If the operand is too big, we must see if cmpxchg8/16b is available
16407 // and default to library calls otherwise.
16408 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16409 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16410 : AtomicRMWExpansionKind::None;
16413 AtomicRMWInst::BinOp Op = AI->getOperation();
16416 llvm_unreachable("Unknown atomic operation");
16417 case AtomicRMWInst::Xchg:
16418 case AtomicRMWInst::Add:
16419 case AtomicRMWInst::Sub:
16420 // It's better to use xadd, xsub or xchg for these in all cases.
16421 return AtomicRMWExpansionKind::None;
16422 case AtomicRMWInst::Or:
16423 case AtomicRMWInst::And:
16424 case AtomicRMWInst::Xor:
16425 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16426 // prefix to a normal instruction for these operations.
16427 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16428 : AtomicRMWExpansionKind::None;
16429 case AtomicRMWInst::Nand:
16430 case AtomicRMWInst::Max:
16431 case AtomicRMWInst::Min:
16432 case AtomicRMWInst::UMax:
16433 case AtomicRMWInst::UMin:
16434 // These always require a non-trivial set of data operations on x86. We must
16435 // use a cmpxchg loop.
16436 return AtomicRMWExpansionKind::CmpXChg;
16440 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16441 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16442 // no-sse2). There isn't any reason to disable it if the target processor
16444 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16448 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16449 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16450 const Type *MemType = AI->getType();
16451 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16452 // there is no benefit in turning such RMWs into loads, and it is actually
16453 // harmful as it introduces a mfence.
16454 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16457 auto Builder = IRBuilder<>(AI);
16458 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16459 auto SynchScope = AI->getSynchScope();
16460 // We must restrict the ordering to avoid generating loads with Release or
16461 // ReleaseAcquire orderings.
16462 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16463 auto Ptr = AI->getPointerOperand();
16465 // Before the load we need a fence. Here is an example lifted from
16466 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16469 // x.store(1, relaxed);
16470 // r1 = y.fetch_add(0, release);
16472 // y.fetch_add(42, acquire);
16473 // r2 = x.load(relaxed);
16474 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16475 // lowered to just a load without a fence. A mfence flushes the store buffer,
16476 // making the optimization clearly correct.
16477 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16478 // otherwise, we might be able to be more agressive on relaxed idempotent
16479 // rmw. In practice, they do not look useful, so we don't try to be
16480 // especially clever.
16481 if (SynchScope == SingleThread) {
16482 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16483 // the IR level, so we must wrap it in an intrinsic.
16485 } else if (hasMFENCE(*Subtarget)) {
16486 Function *MFence = llvm::Intrinsic::getDeclaration(M,
16487 Intrinsic::x86_sse2_mfence);
16488 Builder.CreateCall(MFence);
16490 // FIXME: it might make sense to use a locked operation here but on a
16491 // different cache-line to prevent cache-line bouncing. In practice it
16492 // is probably a small win, and x86 processors without mfence are rare
16493 // enough that we do not bother.
16497 // Finally we can emit the atomic load.
16498 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16499 AI->getType()->getPrimitiveSizeInBits());
16500 Loaded->setAtomic(Order, SynchScope);
16501 AI->replaceAllUsesWith(Loaded);
16502 AI->eraseFromParent();
16506 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16507 SelectionDAG &DAG) {
16509 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16510 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16511 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16512 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16514 // The only fence that needs an instruction is a sequentially-consistent
16515 // cross-thread fence.
16516 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16517 if (hasMFENCE(*Subtarget))
16518 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16520 SDValue Chain = Op.getOperand(0);
16521 SDValue Zero = DAG.getConstant(0, MVT::i32);
16523 DAG.getRegister(X86::ESP, MVT::i32), // Base
16524 DAG.getTargetConstant(1, MVT::i8), // Scale
16525 DAG.getRegister(0, MVT::i32), // Index
16526 DAG.getTargetConstant(0, MVT::i32), // Disp
16527 DAG.getRegister(0, MVT::i32), // Segment.
16531 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16532 return SDValue(Res, 0);
16535 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16536 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16539 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16540 SelectionDAG &DAG) {
16541 MVT T = Op.getSimpleValueType();
16545 switch(T.SimpleTy) {
16546 default: llvm_unreachable("Invalid value type!");
16547 case MVT::i8: Reg = X86::AL; size = 1; break;
16548 case MVT::i16: Reg = X86::AX; size = 2; break;
16549 case MVT::i32: Reg = X86::EAX; size = 4; break;
16551 assert(Subtarget->is64Bit() && "Node not type legal!");
16552 Reg = X86::RAX; size = 8;
16555 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16556 Op.getOperand(2), SDValue());
16557 SDValue Ops[] = { cpIn.getValue(0),
16560 DAG.getTargetConstant(size, MVT::i8),
16561 cpIn.getValue(1) };
16562 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16563 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16564 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16568 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16569 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16570 MVT::i32, cpOut.getValue(2));
16571 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16572 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16574 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16575 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16576 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16580 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16581 SelectionDAG &DAG) {
16582 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16583 MVT DstVT = Op.getSimpleValueType();
16585 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16586 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16587 if (DstVT != MVT::f64)
16588 // This conversion needs to be expanded.
16591 SDValue InVec = Op->getOperand(0);
16593 unsigned NumElts = SrcVT.getVectorNumElements();
16594 EVT SVT = SrcVT.getVectorElementType();
16596 // Widen the vector in input in the case of MVT::v2i32.
16597 // Example: from MVT::v2i32 to MVT::v4i32.
16598 SmallVector<SDValue, 16> Elts;
16599 for (unsigned i = 0, e = NumElts; i != e; ++i)
16600 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16601 DAG.getIntPtrConstant(i)));
16603 // Explicitly mark the extra elements as Undef.
16604 Elts.append(NumElts, DAG.getUNDEF(SVT));
16606 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16607 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16608 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16609 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16610 DAG.getIntPtrConstant(0));
16613 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16614 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16615 assert((DstVT == MVT::i64 ||
16616 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16617 "Unexpected custom BITCAST");
16618 // i64 <=> MMX conversions are Legal.
16619 if (SrcVT==MVT::i64 && DstVT.isVector())
16621 if (DstVT==MVT::i64 && SrcVT.isVector())
16623 // MMX <=> MMX conversions are Legal.
16624 if (SrcVT.isVector() && DstVT.isVector())
16626 // All other conversions need to be expanded.
16630 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16631 SelectionDAG &DAG) {
16632 SDNode *Node = Op.getNode();
16635 Op = Op.getOperand(0);
16636 EVT VT = Op.getValueType();
16637 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16638 "CTPOP lowering only implemented for 128/256-bit wide vector types");
16640 unsigned NumElts = VT.getVectorNumElements();
16641 EVT EltVT = VT.getVectorElementType();
16642 unsigned Len = EltVT.getSizeInBits();
16644 // This is the vectorized version of the "best" algorithm from
16645 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16646 // with a minor tweak to use a series of adds + shifts instead of vector
16647 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16649 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16650 // v8i32 => Always profitable
16652 // FIXME: There a couple of possible improvements:
16654 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16655 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16657 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16658 "CTPOP not implemented for this vector element type.");
16660 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16661 // extra legalization.
16662 bool NeedsBitcast = EltVT == MVT::i32;
16663 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16665 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16666 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16667 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16669 // v = v - ((v >> 1) & 0x55555555...)
16670 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16671 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16672 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16674 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16676 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16677 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16679 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16681 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16682 if (VT != And.getValueType())
16683 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16684 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16686 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16687 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16688 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16689 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16690 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16692 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16693 if (NeedsBitcast) {
16694 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16695 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16696 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16699 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16700 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16701 if (VT != AndRHS.getValueType()) {
16702 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16703 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16705 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16707 // v = (v + (v >> 4)) & 0x0F0F0F0F...
16708 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16709 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16710 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16711 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16713 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16714 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16715 if (NeedsBitcast) {
16716 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16717 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16719 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16720 if (VT != And.getValueType())
16721 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16723 // The algorithm mentioned above uses:
16724 // v = (v * 0x01010101...) >> (Len - 8)
16726 // Change it to use vector adds + vector shifts which yield faster results on
16727 // Haswell than using vector integer multiplication.
16729 // For i32 elements:
16730 // v = v + (v >> 8)
16731 // v = v + (v >> 16)
16733 // For i64 elements:
16734 // v = v + (v >> 8)
16735 // v = v + (v >> 16)
16736 // v = v + (v >> 32)
16739 SmallVector<SDValue, 8> Csts;
16740 for (unsigned i = 8; i <= Len/2; i *= 2) {
16741 Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16742 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16743 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16744 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16748 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16749 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16750 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16751 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16752 if (NeedsBitcast) {
16753 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16754 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16756 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16757 if (VT != And.getValueType())
16758 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16763 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16764 SDNode *Node = Op.getNode();
16766 EVT T = Node->getValueType(0);
16767 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16768 DAG.getConstant(0, T), Node->getOperand(2));
16769 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16770 cast<AtomicSDNode>(Node)->getMemoryVT(),
16771 Node->getOperand(0),
16772 Node->getOperand(1), negOp,
16773 cast<AtomicSDNode>(Node)->getMemOperand(),
16774 cast<AtomicSDNode>(Node)->getOrdering(),
16775 cast<AtomicSDNode>(Node)->getSynchScope());
16778 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16779 SDNode *Node = Op.getNode();
16781 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16783 // Convert seq_cst store -> xchg
16784 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16785 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16786 // (The only way to get a 16-byte store is cmpxchg16b)
16787 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16788 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16789 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16790 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16791 cast<AtomicSDNode>(Node)->getMemoryVT(),
16792 Node->getOperand(0),
16793 Node->getOperand(1), Node->getOperand(2),
16794 cast<AtomicSDNode>(Node)->getMemOperand(),
16795 cast<AtomicSDNode>(Node)->getOrdering(),
16796 cast<AtomicSDNode>(Node)->getSynchScope());
16797 return Swap.getValue(1);
16799 // Other atomic stores have a simple pattern.
16803 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16804 EVT VT = Op.getNode()->getSimpleValueType(0);
16806 // Let legalize expand this if it isn't a legal type yet.
16807 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16810 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16813 bool ExtraOp = false;
16814 switch (Op.getOpcode()) {
16815 default: llvm_unreachable("Invalid code");
16816 case ISD::ADDC: Opc = X86ISD::ADD; break;
16817 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16818 case ISD::SUBC: Opc = X86ISD::SUB; break;
16819 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16823 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16825 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16826 Op.getOperand(1), Op.getOperand(2));
16829 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16830 SelectionDAG &DAG) {
16831 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16833 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16834 // which returns the values as { float, float } (in XMM0) or
16835 // { double, double } (which is returned in XMM0, XMM1).
16837 SDValue Arg = Op.getOperand(0);
16838 EVT ArgVT = Arg.getValueType();
16839 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16841 TargetLowering::ArgListTy Args;
16842 TargetLowering::ArgListEntry Entry;
16846 Entry.isSExt = false;
16847 Entry.isZExt = false;
16848 Args.push_back(Entry);
16850 bool isF64 = ArgVT == MVT::f64;
16851 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16852 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16853 // the results are returned via SRet in memory.
16854 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16855 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16856 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16858 Type *RetTy = isF64
16859 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16860 : (Type*)VectorType::get(ArgTy, 4);
16862 TargetLowering::CallLoweringInfo CLI(DAG);
16863 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16864 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16866 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16869 // Returned in xmm0 and xmm1.
16870 return CallResult.first;
16872 // Returned in bits 0:31 and 32:64 xmm0.
16873 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16874 CallResult.first, DAG.getIntPtrConstant(0));
16875 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16876 CallResult.first, DAG.getIntPtrConstant(1));
16877 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16878 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16881 /// LowerOperation - Provide custom lowering hooks for some operations.
16883 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16884 switch (Op.getOpcode()) {
16885 default: llvm_unreachable("Should not custom lower this!");
16886 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16887 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16888 return LowerCMP_SWAP(Op, Subtarget, DAG);
16889 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
16890 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16891 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16892 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16893 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16894 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
16895 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16896 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16897 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16898 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16899 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16900 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16901 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16902 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16903 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16904 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16905 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16906 case ISD::SHL_PARTS:
16907 case ISD::SRA_PARTS:
16908 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16909 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16910 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16911 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16912 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16913 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16914 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16915 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16916 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16917 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16918 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16920 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
16921 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16922 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16923 case ISD::SETCC: return LowerSETCC(Op, DAG);
16924 case ISD::SELECT: return LowerSELECT(Op, DAG);
16925 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16926 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16927 case ISD::VASTART: return LowerVASTART(Op, DAG);
16928 case ISD::VAARG: return LowerVAARG(Op, DAG);
16929 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16930 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
16931 case ISD::INTRINSIC_VOID:
16932 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16933 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16934 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16935 case ISD::FRAME_TO_ARGS_OFFSET:
16936 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16937 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16938 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16939 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16940 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16941 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16942 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16943 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16944 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16945 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16946 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16947 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16948 case ISD::UMUL_LOHI:
16949 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16952 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16958 case ISD::UMULO: return LowerXALUO(Op, DAG);
16959 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16960 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16964 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16965 case ISD::ADD: return LowerADD(Op, DAG);
16966 case ISD::SUB: return LowerSUB(Op, DAG);
16967 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16971 /// ReplaceNodeResults - Replace a node with an illegal result type
16972 /// with a new node built out of custom code.
16973 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16974 SmallVectorImpl<SDValue>&Results,
16975 SelectionDAG &DAG) const {
16977 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16978 switch (N->getOpcode()) {
16980 llvm_unreachable("Do not know how to custom type legalize this operation!");
16981 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
16982 case X86ISD::FMINC:
16984 case X86ISD::FMAXC:
16985 case X86ISD::FMAX: {
16986 EVT VT = N->getValueType(0);
16987 if (VT != MVT::v2f32)
16988 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
16989 SDValue UNDEF = DAG.getUNDEF(VT);
16990 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
16991 N->getOperand(0), UNDEF);
16992 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
16993 N->getOperand(1), UNDEF);
16994 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
16997 case ISD::SIGN_EXTEND_INREG:
17002 // We don't want to expand or promote these.
17009 case ISD::UDIVREM: {
17010 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17011 Results.push_back(V);
17014 case ISD::FP_TO_SINT:
17015 case ISD::FP_TO_UINT: {
17016 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17018 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17021 std::pair<SDValue,SDValue> Vals =
17022 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17023 SDValue FIST = Vals.first, StackSlot = Vals.second;
17024 if (FIST.getNode()) {
17025 EVT VT = N->getValueType(0);
17026 // Return a load from the stack slot.
17027 if (StackSlot.getNode())
17028 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17029 MachinePointerInfo(),
17030 false, false, false, 0));
17032 Results.push_back(FIST);
17036 case ISD::UINT_TO_FP: {
17037 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17038 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17039 N->getValueType(0) != MVT::v2f32)
17041 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17043 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17045 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17046 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17047 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17048 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17049 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17050 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17053 case ISD::FP_ROUND: {
17054 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17056 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17057 Results.push_back(V);
17060 case ISD::INTRINSIC_W_CHAIN: {
17061 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17063 default : llvm_unreachable("Do not know how to custom type "
17064 "legalize this intrinsic operation!");
17065 case Intrinsic::x86_rdtsc:
17066 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17068 case Intrinsic::x86_rdtscp:
17069 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17071 case Intrinsic::x86_rdpmc:
17072 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17075 case ISD::READCYCLECOUNTER: {
17076 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17079 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17080 EVT T = N->getValueType(0);
17081 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17082 bool Regs64bit = T == MVT::i128;
17083 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17084 SDValue cpInL, cpInH;
17085 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17086 DAG.getConstant(0, HalfT));
17087 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17088 DAG.getConstant(1, HalfT));
17089 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17090 Regs64bit ? X86::RAX : X86::EAX,
17092 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17093 Regs64bit ? X86::RDX : X86::EDX,
17094 cpInH, cpInL.getValue(1));
17095 SDValue swapInL, swapInH;
17096 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17097 DAG.getConstant(0, HalfT));
17098 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17099 DAG.getConstant(1, HalfT));
17100 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17101 Regs64bit ? X86::RBX : X86::EBX,
17102 swapInL, cpInH.getValue(1));
17103 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17104 Regs64bit ? X86::RCX : X86::ECX,
17105 swapInH, swapInL.getValue(1));
17106 SDValue Ops[] = { swapInH.getValue(0),
17108 swapInH.getValue(1) };
17109 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17110 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17111 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17112 X86ISD::LCMPXCHG8_DAG;
17113 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17114 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17115 Regs64bit ? X86::RAX : X86::EAX,
17116 HalfT, Result.getValue(1));
17117 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17118 Regs64bit ? X86::RDX : X86::EDX,
17119 HalfT, cpOutL.getValue(2));
17120 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17122 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17123 MVT::i32, cpOutH.getValue(2));
17125 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17126 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17127 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17129 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17130 Results.push_back(Success);
17131 Results.push_back(EFLAGS.getValue(1));
17134 case ISD::ATOMIC_SWAP:
17135 case ISD::ATOMIC_LOAD_ADD:
17136 case ISD::ATOMIC_LOAD_SUB:
17137 case ISD::ATOMIC_LOAD_AND:
17138 case ISD::ATOMIC_LOAD_OR:
17139 case ISD::ATOMIC_LOAD_XOR:
17140 case ISD::ATOMIC_LOAD_NAND:
17141 case ISD::ATOMIC_LOAD_MIN:
17142 case ISD::ATOMIC_LOAD_MAX:
17143 case ISD::ATOMIC_LOAD_UMIN:
17144 case ISD::ATOMIC_LOAD_UMAX:
17145 case ISD::ATOMIC_LOAD: {
17146 // Delegate to generic TypeLegalization. Situations we can really handle
17147 // should have already been dealt with by AtomicExpandPass.cpp.
17150 case ISD::BITCAST: {
17151 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17152 EVT DstVT = N->getValueType(0);
17153 EVT SrcVT = N->getOperand(0)->getValueType(0);
17155 if (SrcVT != MVT::f64 ||
17156 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17159 unsigned NumElts = DstVT.getVectorNumElements();
17160 EVT SVT = DstVT.getVectorElementType();
17161 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17162 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17163 MVT::v2f64, N->getOperand(0));
17164 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17166 if (ExperimentalVectorWideningLegalization) {
17167 // If we are legalizing vectors by widening, we already have the desired
17168 // legal vector type, just return it.
17169 Results.push_back(ToVecInt);
17173 SmallVector<SDValue, 8> Elts;
17174 for (unsigned i = 0, e = NumElts; i != e; ++i)
17175 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17176 ToVecInt, DAG.getIntPtrConstant(i)));
17178 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17183 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17185 default: return nullptr;
17186 case X86ISD::BSF: return "X86ISD::BSF";
17187 case X86ISD::BSR: return "X86ISD::BSR";
17188 case X86ISD::SHLD: return "X86ISD::SHLD";
17189 case X86ISD::SHRD: return "X86ISD::SHRD";
17190 case X86ISD::FAND: return "X86ISD::FAND";
17191 case X86ISD::FANDN: return "X86ISD::FANDN";
17192 case X86ISD::FOR: return "X86ISD::FOR";
17193 case X86ISD::FXOR: return "X86ISD::FXOR";
17194 case X86ISD::FSRL: return "X86ISD::FSRL";
17195 case X86ISD::FILD: return "X86ISD::FILD";
17196 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17197 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17198 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17199 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17200 case X86ISD::FLD: return "X86ISD::FLD";
17201 case X86ISD::FST: return "X86ISD::FST";
17202 case X86ISD::CALL: return "X86ISD::CALL";
17203 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17204 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17205 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17206 case X86ISD::BT: return "X86ISD::BT";
17207 case X86ISD::CMP: return "X86ISD::CMP";
17208 case X86ISD::COMI: return "X86ISD::COMI";
17209 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17210 case X86ISD::CMPM: return "X86ISD::CMPM";
17211 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17212 case X86ISD::SETCC: return "X86ISD::SETCC";
17213 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17214 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17215 case X86ISD::CMOV: return "X86ISD::CMOV";
17216 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17217 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17218 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17219 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17220 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17221 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17222 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17223 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17224 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17225 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17226 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17227 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17228 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17229 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17230 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17231 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17232 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17233 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17234 case X86ISD::HADD: return "X86ISD::HADD";
17235 case X86ISD::HSUB: return "X86ISD::HSUB";
17236 case X86ISD::FHADD: return "X86ISD::FHADD";
17237 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17238 case X86ISD::UMAX: return "X86ISD::UMAX";
17239 case X86ISD::UMIN: return "X86ISD::UMIN";
17240 case X86ISD::SMAX: return "X86ISD::SMAX";
17241 case X86ISD::SMIN: return "X86ISD::SMIN";
17242 case X86ISD::FMAX: return "X86ISD::FMAX";
17243 case X86ISD::FMIN: return "X86ISD::FMIN";
17244 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17245 case X86ISD::FMINC: return "X86ISD::FMINC";
17246 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17247 case X86ISD::FRCP: return "X86ISD::FRCP";
17248 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17249 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17250 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17251 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17252 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17253 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17254 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17255 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17256 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17257 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17258 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17259 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17260 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17261 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17262 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17263 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17264 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17265 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17266 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17267 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17268 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17269 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17270 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17271 case X86ISD::VSHL: return "X86ISD::VSHL";
17272 case X86ISD::VSRL: return "X86ISD::VSRL";
17273 case X86ISD::VSRA: return "X86ISD::VSRA";
17274 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17275 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17276 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17277 case X86ISD::CMPP: return "X86ISD::CMPP";
17278 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17279 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17280 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17281 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17282 case X86ISD::ADD: return "X86ISD::ADD";
17283 case X86ISD::SUB: return "X86ISD::SUB";
17284 case X86ISD::ADC: return "X86ISD::ADC";
17285 case X86ISD::SBB: return "X86ISD::SBB";
17286 case X86ISD::SMUL: return "X86ISD::SMUL";
17287 case X86ISD::UMUL: return "X86ISD::UMUL";
17288 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17289 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17290 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17291 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17292 case X86ISD::INC: return "X86ISD::INC";
17293 case X86ISD::DEC: return "X86ISD::DEC";
17294 case X86ISD::OR: return "X86ISD::OR";
17295 case X86ISD::XOR: return "X86ISD::XOR";
17296 case X86ISD::AND: return "X86ISD::AND";
17297 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17298 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17299 case X86ISD::PTEST: return "X86ISD::PTEST";
17300 case X86ISD::TESTP: return "X86ISD::TESTP";
17301 case X86ISD::TESTM: return "X86ISD::TESTM";
17302 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17303 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17304 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17305 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17306 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17307 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17308 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17309 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17310 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17311 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17312 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17313 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17314 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17315 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17316 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17317 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17318 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17319 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17320 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17321 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17322 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17323 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17324 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17325 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17326 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17327 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17328 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17329 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17330 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17331 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17332 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17333 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17334 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17335 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17336 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17337 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17338 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17339 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17340 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17341 case X86ISD::SAHF: return "X86ISD::SAHF";
17342 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17343 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17344 case X86ISD::FMADD: return "X86ISD::FMADD";
17345 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17346 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17347 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17348 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17349 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17350 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17351 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17352 case X86ISD::XTEST: return "X86ISD::XTEST";
17353 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
17354 case X86ISD::EXPAND: return "X86ISD::EXPAND";
17355 case X86ISD::SELECT: return "X86ISD::SELECT";
17356 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
17357 case X86ISD::RCP28: return "X86ISD::RCP28";
17358 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
17359 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
17360 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
17361 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
17362 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
17366 // isLegalAddressingMode - Return true if the addressing mode represented
17367 // by AM is legal for this target, for a load/store of the specified type.
17368 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17370 // X86 supports extremely general addressing modes.
17371 CodeModel::Model M = getTargetMachine().getCodeModel();
17372 Reloc::Model R = getTargetMachine().getRelocationModel();
17374 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17375 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17380 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17382 // If a reference to this global requires an extra load, we can't fold it.
17383 if (isGlobalStubReference(GVFlags))
17386 // If BaseGV requires a register for the PIC base, we cannot also have a
17387 // BaseReg specified.
17388 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17391 // If lower 4G is not available, then we must use rip-relative addressing.
17392 if ((M != CodeModel::Small || R != Reloc::Static) &&
17393 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17397 switch (AM.Scale) {
17403 // These scales always work.
17408 // These scales are formed with basereg+scalereg. Only accept if there is
17413 default: // Other stuff never works.
17420 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17421 unsigned Bits = Ty->getScalarSizeInBits();
17423 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17424 // particularly cheaper than those without.
17428 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17429 // variable shifts just as cheap as scalar ones.
17430 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17433 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17434 // fully general vector.
17438 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17439 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17441 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17442 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17443 return NumBits1 > NumBits2;
17446 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17447 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17450 if (!isTypeLegal(EVT::getEVT(Ty1)))
17453 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17455 // Assuming the caller doesn't have a zeroext or signext return parameter,
17456 // truncation all the way down to i1 is valid.
17460 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17461 return isInt<32>(Imm);
17464 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17465 // Can also use sub to handle negated immediates.
17466 return isInt<32>(Imm);
17469 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17470 if (!VT1.isInteger() || !VT2.isInteger())
17472 unsigned NumBits1 = VT1.getSizeInBits();
17473 unsigned NumBits2 = VT2.getSizeInBits();
17474 return NumBits1 > NumBits2;
17477 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17478 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17479 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17482 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17483 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17484 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17487 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17488 EVT VT1 = Val.getValueType();
17489 if (isZExtFree(VT1, VT2))
17492 if (Val.getOpcode() != ISD::LOAD)
17495 if (!VT1.isSimple() || !VT1.isInteger() ||
17496 !VT2.isSimple() || !VT2.isInteger())
17499 switch (VT1.getSimpleVT().SimpleTy) {
17504 // X86 has 8, 16, and 32-bit zero-extending loads.
17511 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17514 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17515 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17518 VT = VT.getScalarType();
17520 if (!VT.isSimple())
17523 switch (VT.getSimpleVT().SimpleTy) {
17534 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17535 // i16 instructions are longer (0x66 prefix) and potentially slower.
17536 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17539 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17540 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17541 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17542 /// are assumed to be legal.
17544 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17546 if (!VT.isSimple())
17549 // Very little shuffling can be done for 64-bit vectors right now.
17550 if (VT.getSizeInBits() == 64)
17553 // We only care that the types being shuffled are legal. The lowering can
17554 // handle any possible shuffle mask that results.
17555 return isTypeLegal(VT.getSimpleVT());
17559 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17561 // Just delegate to the generic legality, clear masks aren't special.
17562 return isShuffleMaskLegal(Mask, VT);
17565 //===----------------------------------------------------------------------===//
17566 // X86 Scheduler Hooks
17567 //===----------------------------------------------------------------------===//
17569 /// Utility function to emit xbegin specifying the start of an RTM region.
17570 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17571 const TargetInstrInfo *TII) {
17572 DebugLoc DL = MI->getDebugLoc();
17574 const BasicBlock *BB = MBB->getBasicBlock();
17575 MachineFunction::iterator I = MBB;
17578 // For the v = xbegin(), we generate
17589 MachineBasicBlock *thisMBB = MBB;
17590 MachineFunction *MF = MBB->getParent();
17591 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17592 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17593 MF->insert(I, mainMBB);
17594 MF->insert(I, sinkMBB);
17596 // Transfer the remainder of BB and its successor edges to sinkMBB.
17597 sinkMBB->splice(sinkMBB->begin(), MBB,
17598 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17599 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17603 // # fallthrough to mainMBB
17604 // # abortion to sinkMBB
17605 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17606 thisMBB->addSuccessor(mainMBB);
17607 thisMBB->addSuccessor(sinkMBB);
17611 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17612 mainMBB->addSuccessor(sinkMBB);
17615 // EAX is live into the sinkMBB
17616 sinkMBB->addLiveIn(X86::EAX);
17617 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17618 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17621 MI->eraseFromParent();
17625 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17626 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17627 // in the .td file.
17628 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17629 const TargetInstrInfo *TII) {
17631 switch (MI->getOpcode()) {
17632 default: llvm_unreachable("illegal opcode!");
17633 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17634 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17635 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17636 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17637 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17638 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17639 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17640 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17643 DebugLoc dl = MI->getDebugLoc();
17644 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17646 unsigned NumArgs = MI->getNumOperands();
17647 for (unsigned i = 1; i < NumArgs; ++i) {
17648 MachineOperand &Op = MI->getOperand(i);
17649 if (!(Op.isReg() && Op.isImplicit()))
17650 MIB.addOperand(Op);
17652 if (MI->hasOneMemOperand())
17653 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17655 BuildMI(*BB, MI, dl,
17656 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17657 .addReg(X86::XMM0);
17659 MI->eraseFromParent();
17663 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17664 // defs in an instruction pattern
17665 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17666 const TargetInstrInfo *TII) {
17668 switch (MI->getOpcode()) {
17669 default: llvm_unreachable("illegal opcode!");
17670 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17671 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17672 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17673 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17674 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17675 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17676 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17677 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17680 DebugLoc dl = MI->getDebugLoc();
17681 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17683 unsigned NumArgs = MI->getNumOperands(); // remove the results
17684 for (unsigned i = 1; i < NumArgs; ++i) {
17685 MachineOperand &Op = MI->getOperand(i);
17686 if (!(Op.isReg() && Op.isImplicit()))
17687 MIB.addOperand(Op);
17689 if (MI->hasOneMemOperand())
17690 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17692 BuildMI(*BB, MI, dl,
17693 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17696 MI->eraseFromParent();
17700 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17701 const X86Subtarget *Subtarget) {
17702 DebugLoc dl = MI->getDebugLoc();
17703 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17704 // Address into RAX/EAX, other two args into ECX, EDX.
17705 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17706 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17707 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17708 for (int i = 0; i < X86::AddrNumOperands; ++i)
17709 MIB.addOperand(MI->getOperand(i));
17711 unsigned ValOps = X86::AddrNumOperands;
17712 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17713 .addReg(MI->getOperand(ValOps).getReg());
17714 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17715 .addReg(MI->getOperand(ValOps+1).getReg());
17717 // The instruction doesn't actually take any operands though.
17718 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17720 MI->eraseFromParent(); // The pseudo is gone now.
17724 MachineBasicBlock *
17725 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17726 MachineBasicBlock *MBB) const {
17727 // Emit va_arg instruction on X86-64.
17729 // Operands to this pseudo-instruction:
17730 // 0 ) Output : destination address (reg)
17731 // 1-5) Input : va_list address (addr, i64mem)
17732 // 6 ) ArgSize : Size (in bytes) of vararg type
17733 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17734 // 8 ) Align : Alignment of type
17735 // 9 ) EFLAGS (implicit-def)
17737 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17738 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17740 unsigned DestReg = MI->getOperand(0).getReg();
17741 MachineOperand &Base = MI->getOperand(1);
17742 MachineOperand &Scale = MI->getOperand(2);
17743 MachineOperand &Index = MI->getOperand(3);
17744 MachineOperand &Disp = MI->getOperand(4);
17745 MachineOperand &Segment = MI->getOperand(5);
17746 unsigned ArgSize = MI->getOperand(6).getImm();
17747 unsigned ArgMode = MI->getOperand(7).getImm();
17748 unsigned Align = MI->getOperand(8).getImm();
17750 // Memory Reference
17751 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17752 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17753 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17755 // Machine Information
17756 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17757 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17758 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17759 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17760 DebugLoc DL = MI->getDebugLoc();
17762 // struct va_list {
17765 // i64 overflow_area (address)
17766 // i64 reg_save_area (address)
17768 // sizeof(va_list) = 24
17769 // alignment(va_list) = 8
17771 unsigned TotalNumIntRegs = 6;
17772 unsigned TotalNumXMMRegs = 8;
17773 bool UseGPOffset = (ArgMode == 1);
17774 bool UseFPOffset = (ArgMode == 2);
17775 unsigned MaxOffset = TotalNumIntRegs * 8 +
17776 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17778 /* Align ArgSize to a multiple of 8 */
17779 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17780 bool NeedsAlign = (Align > 8);
17782 MachineBasicBlock *thisMBB = MBB;
17783 MachineBasicBlock *overflowMBB;
17784 MachineBasicBlock *offsetMBB;
17785 MachineBasicBlock *endMBB;
17787 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17788 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17789 unsigned OffsetReg = 0;
17791 if (!UseGPOffset && !UseFPOffset) {
17792 // If we only pull from the overflow region, we don't create a branch.
17793 // We don't need to alter control flow.
17794 OffsetDestReg = 0; // unused
17795 OverflowDestReg = DestReg;
17797 offsetMBB = nullptr;
17798 overflowMBB = thisMBB;
17801 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17802 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17803 // If not, pull from overflow_area. (branch to overflowMBB)
17808 // offsetMBB overflowMBB
17813 // Registers for the PHI in endMBB
17814 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17815 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17817 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17818 MachineFunction *MF = MBB->getParent();
17819 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17820 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17821 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17823 MachineFunction::iterator MBBIter = MBB;
17826 // Insert the new basic blocks
17827 MF->insert(MBBIter, offsetMBB);
17828 MF->insert(MBBIter, overflowMBB);
17829 MF->insert(MBBIter, endMBB);
17831 // Transfer the remainder of MBB and its successor edges to endMBB.
17832 endMBB->splice(endMBB->begin(), thisMBB,
17833 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17834 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17836 // Make offsetMBB and overflowMBB successors of thisMBB
17837 thisMBB->addSuccessor(offsetMBB);
17838 thisMBB->addSuccessor(overflowMBB);
17840 // endMBB is a successor of both offsetMBB and overflowMBB
17841 offsetMBB->addSuccessor(endMBB);
17842 overflowMBB->addSuccessor(endMBB);
17844 // Load the offset value into a register
17845 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17846 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17850 .addDisp(Disp, UseFPOffset ? 4 : 0)
17851 .addOperand(Segment)
17852 .setMemRefs(MMOBegin, MMOEnd);
17854 // Check if there is enough room left to pull this argument.
17855 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17857 .addImm(MaxOffset + 8 - ArgSizeA8);
17859 // Branch to "overflowMBB" if offset >= max
17860 // Fall through to "offsetMBB" otherwise
17861 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17862 .addMBB(overflowMBB);
17865 // In offsetMBB, emit code to use the reg_save_area.
17867 assert(OffsetReg != 0);
17869 // Read the reg_save_area address.
17870 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17871 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17876 .addOperand(Segment)
17877 .setMemRefs(MMOBegin, MMOEnd);
17879 // Zero-extend the offset
17880 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17881 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17884 .addImm(X86::sub_32bit);
17886 // Add the offset to the reg_save_area to get the final address.
17887 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17888 .addReg(OffsetReg64)
17889 .addReg(RegSaveReg);
17891 // Compute the offset for the next argument
17892 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17893 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17895 .addImm(UseFPOffset ? 16 : 8);
17897 // Store it back into the va_list.
17898 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17902 .addDisp(Disp, UseFPOffset ? 4 : 0)
17903 .addOperand(Segment)
17904 .addReg(NextOffsetReg)
17905 .setMemRefs(MMOBegin, MMOEnd);
17908 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
17913 // Emit code to use overflow area
17916 // Load the overflow_area address into a register.
17917 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17918 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17923 .addOperand(Segment)
17924 .setMemRefs(MMOBegin, MMOEnd);
17926 // If we need to align it, do so. Otherwise, just copy the address
17927 // to OverflowDestReg.
17929 // Align the overflow address
17930 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17931 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17933 // aligned_addr = (addr + (align-1)) & ~(align-1)
17934 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17935 .addReg(OverflowAddrReg)
17938 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17940 .addImm(~(uint64_t)(Align-1));
17942 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17943 .addReg(OverflowAddrReg);
17946 // Compute the next overflow address after this argument.
17947 // (the overflow address should be kept 8-byte aligned)
17948 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17949 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17950 .addReg(OverflowDestReg)
17951 .addImm(ArgSizeA8);
17953 // Store the new overflow address.
17954 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17959 .addOperand(Segment)
17960 .addReg(NextAddrReg)
17961 .setMemRefs(MMOBegin, MMOEnd);
17963 // If we branched, emit the PHI to the front of endMBB.
17965 BuildMI(*endMBB, endMBB->begin(), DL,
17966 TII->get(X86::PHI), DestReg)
17967 .addReg(OffsetDestReg).addMBB(offsetMBB)
17968 .addReg(OverflowDestReg).addMBB(overflowMBB);
17971 // Erase the pseudo instruction
17972 MI->eraseFromParent();
17977 MachineBasicBlock *
17978 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17980 MachineBasicBlock *MBB) const {
17981 // Emit code to save XMM registers to the stack. The ABI says that the
17982 // number of registers to save is given in %al, so it's theoretically
17983 // possible to do an indirect jump trick to avoid saving all of them,
17984 // however this code takes a simpler approach and just executes all
17985 // of the stores if %al is non-zero. It's less code, and it's probably
17986 // easier on the hardware branch predictor, and stores aren't all that
17987 // expensive anyway.
17989 // Create the new basic blocks. One block contains all the XMM stores,
17990 // and one block is the final destination regardless of whether any
17991 // stores were performed.
17992 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17993 MachineFunction *F = MBB->getParent();
17994 MachineFunction::iterator MBBIter = MBB;
17996 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17997 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17998 F->insert(MBBIter, XMMSaveMBB);
17999 F->insert(MBBIter, EndMBB);
18001 // Transfer the remainder of MBB and its successor edges to EndMBB.
18002 EndMBB->splice(EndMBB->begin(), MBB,
18003 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18004 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18006 // The original block will now fall through to the XMM save block.
18007 MBB->addSuccessor(XMMSaveMBB);
18008 // The XMMSaveMBB will fall through to the end block.
18009 XMMSaveMBB->addSuccessor(EndMBB);
18011 // Now add the instructions.
18012 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18013 DebugLoc DL = MI->getDebugLoc();
18015 unsigned CountReg = MI->getOperand(0).getReg();
18016 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18017 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18019 if (!Subtarget->isTargetWin64()) {
18020 // If %al is 0, branch around the XMM save block.
18021 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18022 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18023 MBB->addSuccessor(EndMBB);
18026 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18027 // that was just emitted, but clearly shouldn't be "saved".
18028 assert((MI->getNumOperands() <= 3 ||
18029 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18030 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18031 && "Expected last argument to be EFLAGS");
18032 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18033 // In the XMM save block, save all the XMM argument registers.
18034 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18035 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18036 MachineMemOperand *MMO =
18037 F->getMachineMemOperand(
18038 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18039 MachineMemOperand::MOStore,
18040 /*Size=*/16, /*Align=*/16);
18041 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18042 .addFrameIndex(RegSaveFrameIndex)
18043 .addImm(/*Scale=*/1)
18044 .addReg(/*IndexReg=*/0)
18045 .addImm(/*Disp=*/Offset)
18046 .addReg(/*Segment=*/0)
18047 .addReg(MI->getOperand(i).getReg())
18048 .addMemOperand(MMO);
18051 MI->eraseFromParent(); // The pseudo instruction is gone now.
18056 // The EFLAGS operand of SelectItr might be missing a kill marker
18057 // because there were multiple uses of EFLAGS, and ISel didn't know
18058 // which to mark. Figure out whether SelectItr should have had a
18059 // kill marker, and set it if it should. Returns the correct kill
18061 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18062 MachineBasicBlock* BB,
18063 const TargetRegisterInfo* TRI) {
18064 // Scan forward through BB for a use/def of EFLAGS.
18065 MachineBasicBlock::iterator miI(std::next(SelectItr));
18066 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18067 const MachineInstr& mi = *miI;
18068 if (mi.readsRegister(X86::EFLAGS))
18070 if (mi.definesRegister(X86::EFLAGS))
18071 break; // Should have kill-flag - update below.
18074 // If we hit the end of the block, check whether EFLAGS is live into a
18076 if (miI == BB->end()) {
18077 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18078 sEnd = BB->succ_end();
18079 sItr != sEnd; ++sItr) {
18080 MachineBasicBlock* succ = *sItr;
18081 if (succ->isLiveIn(X86::EFLAGS))
18086 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18087 // out. SelectMI should have a kill flag on EFLAGS.
18088 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18092 MachineBasicBlock *
18093 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18094 MachineBasicBlock *BB) const {
18095 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18096 DebugLoc DL = MI->getDebugLoc();
18098 // To "insert" a SELECT_CC instruction, we actually have to insert the
18099 // diamond control-flow pattern. The incoming instruction knows the
18100 // destination vreg to set, the condition code register to branch on, the
18101 // true/false values to select between, and a branch opcode to use.
18102 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18103 MachineFunction::iterator It = BB;
18109 // cmpTY ccX, r1, r2
18111 // fallthrough --> copy0MBB
18112 MachineBasicBlock *thisMBB = BB;
18113 MachineFunction *F = BB->getParent();
18115 // We also lower double CMOVs:
18116 // (CMOV (CMOV F, T, cc1), T, cc2)
18117 // to two successives branches. For that, we look for another CMOV as the
18118 // following instruction.
18120 // Without this, we would add a PHI between the two jumps, which ends up
18121 // creating a few copies all around. For instance, for
18123 // (sitofp (zext (fcmp une)))
18125 // we would generate:
18127 // ucomiss %xmm1, %xmm0
18128 // movss <1.0f>, %xmm0
18129 // movaps %xmm0, %xmm1
18131 // xorps %xmm1, %xmm1
18134 // movaps %xmm1, %xmm0
18138 // because this custom-inserter would have generated:
18150 // A: X = ...; Y = ...
18152 // C: Z = PHI [X, A], [Y, B]
18154 // E: PHI [X, C], [Z, D]
18156 // If we lower both CMOVs in a single step, we can instead generate:
18168 // A: X = ...; Y = ...
18170 // E: PHI [X, A], [X, C], [Y, D]
18172 // Which, in our sitofp/fcmp example, gives us something like:
18174 // ucomiss %xmm1, %xmm0
18175 // movss <1.0f>, %xmm0
18178 // xorps %xmm0, %xmm0
18182 MachineInstr *NextCMOV = nullptr;
18183 MachineBasicBlock::iterator NextMIIt =
18184 std::next(MachineBasicBlock::iterator(MI));
18185 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18186 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18187 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18188 NextCMOV = &*NextMIIt;
18190 MachineBasicBlock *jcc1MBB = nullptr;
18192 // If we have a double CMOV, we lower it to two successive branches to
18193 // the same block. EFLAGS is used by both, so mark it as live in the second.
18195 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18196 F->insert(It, jcc1MBB);
18197 jcc1MBB->addLiveIn(X86::EFLAGS);
18200 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18201 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18202 F->insert(It, copy0MBB);
18203 F->insert(It, sinkMBB);
18205 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18206 // live into the sink and copy blocks.
18207 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18209 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18210 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18211 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18212 copy0MBB->addLiveIn(X86::EFLAGS);
18213 sinkMBB->addLiveIn(X86::EFLAGS);
18216 // Transfer the remainder of BB and its successor edges to sinkMBB.
18217 sinkMBB->splice(sinkMBB->begin(), BB,
18218 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18219 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18221 // Add the true and fallthrough blocks as its successors.
18223 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18224 BB->addSuccessor(jcc1MBB);
18226 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18227 // jump to the sinkMBB.
18228 jcc1MBB->addSuccessor(copy0MBB);
18229 jcc1MBB->addSuccessor(sinkMBB);
18231 BB->addSuccessor(copy0MBB);
18234 // The true block target of the first (or only) branch is always sinkMBB.
18235 BB->addSuccessor(sinkMBB);
18237 // Create the conditional branch instruction.
18239 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18240 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18243 unsigned Opc2 = X86::GetCondBranchFromCond(
18244 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18245 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18249 // %FalseValue = ...
18250 // # fallthrough to sinkMBB
18251 copy0MBB->addSuccessor(sinkMBB);
18254 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18256 MachineInstrBuilder MIB =
18257 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18258 MI->getOperand(0).getReg())
18259 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18260 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18262 // If we have a double CMOV, the second Jcc provides the same incoming
18263 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18265 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18266 // Copy the PHI result to the register defined by the second CMOV.
18267 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18268 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18269 .addReg(MI->getOperand(0).getReg());
18270 NextCMOV->eraseFromParent();
18273 MI->eraseFromParent(); // The pseudo instruction is gone now.
18277 MachineBasicBlock *
18278 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18279 MachineBasicBlock *BB) const {
18280 MachineFunction *MF = BB->getParent();
18281 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18282 DebugLoc DL = MI->getDebugLoc();
18283 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18285 assert(MF->shouldSplitStack());
18287 const bool Is64Bit = Subtarget->is64Bit();
18288 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18290 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18291 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18294 // ... [Till the alloca]
18295 // If stacklet is not large enough, jump to mallocMBB
18298 // Allocate by subtracting from RSP
18299 // Jump to continueMBB
18302 // Allocate by call to runtime
18306 // [rest of original BB]
18309 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18310 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18311 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18313 MachineRegisterInfo &MRI = MF->getRegInfo();
18314 const TargetRegisterClass *AddrRegClass =
18315 getRegClassFor(getPointerTy());
18317 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18318 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18319 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18320 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18321 sizeVReg = MI->getOperand(1).getReg(),
18322 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18324 MachineFunction::iterator MBBIter = BB;
18327 MF->insert(MBBIter, bumpMBB);
18328 MF->insert(MBBIter, mallocMBB);
18329 MF->insert(MBBIter, continueMBB);
18331 continueMBB->splice(continueMBB->begin(), BB,
18332 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18333 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18335 // Add code to the main basic block to check if the stack limit has been hit,
18336 // and if so, jump to mallocMBB otherwise to bumpMBB.
18337 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18338 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18339 .addReg(tmpSPVReg).addReg(sizeVReg);
18340 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18341 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18342 .addReg(SPLimitVReg);
18343 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18345 // bumpMBB simply decreases the stack pointer, since we know the current
18346 // stacklet has enough space.
18347 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18348 .addReg(SPLimitVReg);
18349 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18350 .addReg(SPLimitVReg);
18351 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18353 // Calls into a routine in libgcc to allocate more space from the heap.
18354 const uint32_t *RegMask =
18355 Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18357 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18359 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18360 .addExternalSymbol("__morestack_allocate_stack_space")
18361 .addRegMask(RegMask)
18362 .addReg(X86::RDI, RegState::Implicit)
18363 .addReg(X86::RAX, RegState::ImplicitDefine);
18364 } else if (Is64Bit) {
18365 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18367 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18368 .addExternalSymbol("__morestack_allocate_stack_space")
18369 .addRegMask(RegMask)
18370 .addReg(X86::EDI, RegState::Implicit)
18371 .addReg(X86::EAX, RegState::ImplicitDefine);
18373 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18375 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18376 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18377 .addExternalSymbol("__morestack_allocate_stack_space")
18378 .addRegMask(RegMask)
18379 .addReg(X86::EAX, RegState::ImplicitDefine);
18383 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18386 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18387 .addReg(IsLP64 ? X86::RAX : X86::EAX);
18388 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18390 // Set up the CFG correctly.
18391 BB->addSuccessor(bumpMBB);
18392 BB->addSuccessor(mallocMBB);
18393 mallocMBB->addSuccessor(continueMBB);
18394 bumpMBB->addSuccessor(continueMBB);
18396 // Take care of the PHI nodes.
18397 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18398 MI->getOperand(0).getReg())
18399 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18400 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18402 // Delete the original pseudo instruction.
18403 MI->eraseFromParent();
18406 return continueMBB;
18409 MachineBasicBlock *
18410 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18411 MachineBasicBlock *BB) const {
18412 DebugLoc DL = MI->getDebugLoc();
18414 assert(!Subtarget->isTargetMachO());
18416 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18418 MI->eraseFromParent(); // The pseudo instruction is gone now.
18422 MachineBasicBlock *
18423 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18424 MachineBasicBlock *BB) const {
18425 // This is pretty easy. We're taking the value that we received from
18426 // our load from the relocation, sticking it in either RDI (x86-64)
18427 // or EAX and doing an indirect call. The return value will then
18428 // be in the normal return register.
18429 MachineFunction *F = BB->getParent();
18430 const X86InstrInfo *TII = Subtarget->getInstrInfo();
18431 DebugLoc DL = MI->getDebugLoc();
18433 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18434 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18436 // Get a register mask for the lowered call.
18437 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18438 // proper register mask.
18439 const uint32_t *RegMask =
18440 Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18441 if (Subtarget->is64Bit()) {
18442 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18443 TII->get(X86::MOV64rm), X86::RDI)
18445 .addImm(0).addReg(0)
18446 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18447 MI->getOperand(3).getTargetFlags())
18449 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18450 addDirectMem(MIB, X86::RDI);
18451 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18452 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18453 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18454 TII->get(X86::MOV32rm), X86::EAX)
18456 .addImm(0).addReg(0)
18457 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18458 MI->getOperand(3).getTargetFlags())
18460 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18461 addDirectMem(MIB, X86::EAX);
18462 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18464 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18465 TII->get(X86::MOV32rm), X86::EAX)
18466 .addReg(TII->getGlobalBaseReg(F))
18467 .addImm(0).addReg(0)
18468 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18469 MI->getOperand(3).getTargetFlags())
18471 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18472 addDirectMem(MIB, X86::EAX);
18473 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18476 MI->eraseFromParent(); // The pseudo instruction is gone now.
18480 MachineBasicBlock *
18481 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18482 MachineBasicBlock *MBB) const {
18483 DebugLoc DL = MI->getDebugLoc();
18484 MachineFunction *MF = MBB->getParent();
18485 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18486 MachineRegisterInfo &MRI = MF->getRegInfo();
18488 const BasicBlock *BB = MBB->getBasicBlock();
18489 MachineFunction::iterator I = MBB;
18492 // Memory Reference
18493 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18494 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18497 unsigned MemOpndSlot = 0;
18499 unsigned CurOp = 0;
18501 DstReg = MI->getOperand(CurOp++).getReg();
18502 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18503 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18504 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18505 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18507 MemOpndSlot = CurOp;
18509 MVT PVT = getPointerTy();
18510 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18511 "Invalid Pointer Size!");
18513 // For v = setjmp(buf), we generate
18516 // buf[LabelOffset] = restoreMBB
18517 // SjLjSetup restoreMBB
18523 // v = phi(main, restore)
18526 // if base pointer being used, load it from frame
18529 MachineBasicBlock *thisMBB = MBB;
18530 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18531 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18532 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18533 MF->insert(I, mainMBB);
18534 MF->insert(I, sinkMBB);
18535 MF->push_back(restoreMBB);
18537 MachineInstrBuilder MIB;
18539 // Transfer the remainder of BB and its successor edges to sinkMBB.
18540 sinkMBB->splice(sinkMBB->begin(), MBB,
18541 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18542 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18545 unsigned PtrStoreOpc = 0;
18546 unsigned LabelReg = 0;
18547 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18548 Reloc::Model RM = MF->getTarget().getRelocationModel();
18549 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18550 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18552 // Prepare IP either in reg or imm.
18553 if (!UseImmLabel) {
18554 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18555 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18556 LabelReg = MRI.createVirtualRegister(PtrRC);
18557 if (Subtarget->is64Bit()) {
18558 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18562 .addMBB(restoreMBB)
18565 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18566 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18567 .addReg(XII->getGlobalBaseReg(MF))
18570 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18574 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18576 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18577 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18578 if (i == X86::AddrDisp)
18579 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18581 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18584 MIB.addReg(LabelReg);
18586 MIB.addMBB(restoreMBB);
18587 MIB.setMemRefs(MMOBegin, MMOEnd);
18589 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18590 .addMBB(restoreMBB);
18592 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18593 MIB.addRegMask(RegInfo->getNoPreservedMask());
18594 thisMBB->addSuccessor(mainMBB);
18595 thisMBB->addSuccessor(restoreMBB);
18599 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18600 mainMBB->addSuccessor(sinkMBB);
18603 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18604 TII->get(X86::PHI), DstReg)
18605 .addReg(mainDstReg).addMBB(mainMBB)
18606 .addReg(restoreDstReg).addMBB(restoreMBB);
18609 if (RegInfo->hasBasePointer(*MF)) {
18610 const bool Uses64BitFramePtr =
18611 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18612 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18613 X86FI->setRestoreBasePointer(MF);
18614 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18615 unsigned BasePtr = RegInfo->getBaseRegister();
18616 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18617 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18618 FramePtr, true, X86FI->getRestoreBasePointerOffset())
18619 .setMIFlag(MachineInstr::FrameSetup);
18621 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18622 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18623 restoreMBB->addSuccessor(sinkMBB);
18625 MI->eraseFromParent();
18629 MachineBasicBlock *
18630 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18631 MachineBasicBlock *MBB) const {
18632 DebugLoc DL = MI->getDebugLoc();
18633 MachineFunction *MF = MBB->getParent();
18634 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18635 MachineRegisterInfo &MRI = MF->getRegInfo();
18637 // Memory Reference
18638 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18639 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18641 MVT PVT = getPointerTy();
18642 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18643 "Invalid Pointer Size!");
18645 const TargetRegisterClass *RC =
18646 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18647 unsigned Tmp = MRI.createVirtualRegister(RC);
18648 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18649 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18650 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18651 unsigned SP = RegInfo->getStackRegister();
18653 MachineInstrBuilder MIB;
18655 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18656 const int64_t SPOffset = 2 * PVT.getStoreSize();
18658 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18659 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18662 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18663 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18664 MIB.addOperand(MI->getOperand(i));
18665 MIB.setMemRefs(MMOBegin, MMOEnd);
18667 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18668 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18669 if (i == X86::AddrDisp)
18670 MIB.addDisp(MI->getOperand(i), LabelOffset);
18672 MIB.addOperand(MI->getOperand(i));
18674 MIB.setMemRefs(MMOBegin, MMOEnd);
18676 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18677 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18678 if (i == X86::AddrDisp)
18679 MIB.addDisp(MI->getOperand(i), SPOffset);
18681 MIB.addOperand(MI->getOperand(i));
18683 MIB.setMemRefs(MMOBegin, MMOEnd);
18685 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18687 MI->eraseFromParent();
18691 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18692 // accumulator loops. Writing back to the accumulator allows the coalescer
18693 // to remove extra copies in the loop.
18694 MachineBasicBlock *
18695 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18696 MachineBasicBlock *MBB) const {
18697 MachineOperand &AddendOp = MI->getOperand(3);
18699 // Bail out early if the addend isn't a register - we can't switch these.
18700 if (!AddendOp.isReg())
18703 MachineFunction &MF = *MBB->getParent();
18704 MachineRegisterInfo &MRI = MF.getRegInfo();
18706 // Check whether the addend is defined by a PHI:
18707 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18708 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18709 if (!AddendDef.isPHI())
18712 // Look for the following pattern:
18714 // %addend = phi [%entry, 0], [%loop, %result]
18716 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18720 // %addend = phi [%entry, 0], [%loop, %result]
18722 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18724 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18725 assert(AddendDef.getOperand(i).isReg());
18726 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18727 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18728 if (&PHISrcInst == MI) {
18729 // Found a matching instruction.
18730 unsigned NewFMAOpc = 0;
18731 switch (MI->getOpcode()) {
18732 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18733 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18734 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18735 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18736 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18737 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18738 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18739 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18740 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18741 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18742 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18743 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18744 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18745 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18746 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18747 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18748 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18749 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18750 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18751 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18753 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18754 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18755 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18756 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18757 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18758 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18759 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18760 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18761 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18762 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18763 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18764 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18765 default: llvm_unreachable("Unrecognized FMA variant.");
18768 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18769 MachineInstrBuilder MIB =
18770 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18771 .addOperand(MI->getOperand(0))
18772 .addOperand(MI->getOperand(3))
18773 .addOperand(MI->getOperand(2))
18774 .addOperand(MI->getOperand(1));
18775 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18776 MI->eraseFromParent();
18783 MachineBasicBlock *
18784 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18785 MachineBasicBlock *BB) const {
18786 switch (MI->getOpcode()) {
18787 default: llvm_unreachable("Unexpected instr type to insert");
18788 case X86::TAILJMPd64:
18789 case X86::TAILJMPr64:
18790 case X86::TAILJMPm64:
18791 case X86::TAILJMPd64_REX:
18792 case X86::TAILJMPr64_REX:
18793 case X86::TAILJMPm64_REX:
18794 llvm_unreachable("TAILJMP64 would not be touched here.");
18795 case X86::TCRETURNdi64:
18796 case X86::TCRETURNri64:
18797 case X86::TCRETURNmi64:
18799 case X86::WIN_ALLOCA:
18800 return EmitLoweredWinAlloca(MI, BB);
18801 case X86::SEG_ALLOCA_32:
18802 case X86::SEG_ALLOCA_64:
18803 return EmitLoweredSegAlloca(MI, BB);
18804 case X86::TLSCall_32:
18805 case X86::TLSCall_64:
18806 return EmitLoweredTLSCall(MI, BB);
18807 case X86::CMOV_GR8:
18808 case X86::CMOV_FR32:
18809 case X86::CMOV_FR64:
18810 case X86::CMOV_V4F32:
18811 case X86::CMOV_V2F64:
18812 case X86::CMOV_V2I64:
18813 case X86::CMOV_V8F32:
18814 case X86::CMOV_V4F64:
18815 case X86::CMOV_V4I64:
18816 case X86::CMOV_V16F32:
18817 case X86::CMOV_V8F64:
18818 case X86::CMOV_V8I64:
18819 case X86::CMOV_GR16:
18820 case X86::CMOV_GR32:
18821 case X86::CMOV_RFP32:
18822 case X86::CMOV_RFP64:
18823 case X86::CMOV_RFP80:
18824 return EmitLoweredSelect(MI, BB);
18826 case X86::FP32_TO_INT16_IN_MEM:
18827 case X86::FP32_TO_INT32_IN_MEM:
18828 case X86::FP32_TO_INT64_IN_MEM:
18829 case X86::FP64_TO_INT16_IN_MEM:
18830 case X86::FP64_TO_INT32_IN_MEM:
18831 case X86::FP64_TO_INT64_IN_MEM:
18832 case X86::FP80_TO_INT16_IN_MEM:
18833 case X86::FP80_TO_INT32_IN_MEM:
18834 case X86::FP80_TO_INT64_IN_MEM: {
18835 MachineFunction *F = BB->getParent();
18836 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18837 DebugLoc DL = MI->getDebugLoc();
18839 // Change the floating point control register to use "round towards zero"
18840 // mode when truncating to an integer value.
18841 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18842 addFrameReference(BuildMI(*BB, MI, DL,
18843 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18845 // Load the old value of the high byte of the control word...
18847 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18848 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18851 // Set the high part to be round to zero...
18852 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18855 // Reload the modified control word now...
18856 addFrameReference(BuildMI(*BB, MI, DL,
18857 TII->get(X86::FLDCW16m)), CWFrameIdx);
18859 // Restore the memory image of control word to original value
18860 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18863 // Get the X86 opcode to use.
18865 switch (MI->getOpcode()) {
18866 default: llvm_unreachable("illegal opcode!");
18867 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18868 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18869 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18870 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18871 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18872 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18873 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18874 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18875 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18879 MachineOperand &Op = MI->getOperand(0);
18881 AM.BaseType = X86AddressMode::RegBase;
18882 AM.Base.Reg = Op.getReg();
18884 AM.BaseType = X86AddressMode::FrameIndexBase;
18885 AM.Base.FrameIndex = Op.getIndex();
18887 Op = MI->getOperand(1);
18889 AM.Scale = Op.getImm();
18890 Op = MI->getOperand(2);
18892 AM.IndexReg = Op.getImm();
18893 Op = MI->getOperand(3);
18894 if (Op.isGlobal()) {
18895 AM.GV = Op.getGlobal();
18897 AM.Disp = Op.getImm();
18899 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18900 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18902 // Reload the original control word now.
18903 addFrameReference(BuildMI(*BB, MI, DL,
18904 TII->get(X86::FLDCW16m)), CWFrameIdx);
18906 MI->eraseFromParent(); // The pseudo instruction is gone now.
18909 // String/text processing lowering.
18910 case X86::PCMPISTRM128REG:
18911 case X86::VPCMPISTRM128REG:
18912 case X86::PCMPISTRM128MEM:
18913 case X86::VPCMPISTRM128MEM:
18914 case X86::PCMPESTRM128REG:
18915 case X86::VPCMPESTRM128REG:
18916 case X86::PCMPESTRM128MEM:
18917 case X86::VPCMPESTRM128MEM:
18918 assert(Subtarget->hasSSE42() &&
18919 "Target must have SSE4.2 or AVX features enabled");
18920 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
18922 // String/text processing lowering.
18923 case X86::PCMPISTRIREG:
18924 case X86::VPCMPISTRIREG:
18925 case X86::PCMPISTRIMEM:
18926 case X86::VPCMPISTRIMEM:
18927 case X86::PCMPESTRIREG:
18928 case X86::VPCMPESTRIREG:
18929 case X86::PCMPESTRIMEM:
18930 case X86::VPCMPESTRIMEM:
18931 assert(Subtarget->hasSSE42() &&
18932 "Target must have SSE4.2 or AVX features enabled");
18933 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
18935 // Thread synchronization.
18937 return EmitMonitor(MI, BB, Subtarget);
18941 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
18943 case X86::VASTART_SAVE_XMM_REGS:
18944 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18946 case X86::VAARG_64:
18947 return EmitVAARG64WithCustomInserter(MI, BB);
18949 case X86::EH_SjLj_SetJmp32:
18950 case X86::EH_SjLj_SetJmp64:
18951 return emitEHSjLjSetJmp(MI, BB);
18953 case X86::EH_SjLj_LongJmp32:
18954 case X86::EH_SjLj_LongJmp64:
18955 return emitEHSjLjLongJmp(MI, BB);
18957 case TargetOpcode::STATEPOINT:
18958 // As an implementation detail, STATEPOINT shares the STACKMAP format at
18959 // this point in the process. We diverge later.
18960 return emitPatchPoint(MI, BB);
18962 case TargetOpcode::STACKMAP:
18963 case TargetOpcode::PATCHPOINT:
18964 return emitPatchPoint(MI, BB);
18966 case X86::VFMADDPDr213r:
18967 case X86::VFMADDPSr213r:
18968 case X86::VFMADDSDr213r:
18969 case X86::VFMADDSSr213r:
18970 case X86::VFMSUBPDr213r:
18971 case X86::VFMSUBPSr213r:
18972 case X86::VFMSUBSDr213r:
18973 case X86::VFMSUBSSr213r:
18974 case X86::VFNMADDPDr213r:
18975 case X86::VFNMADDPSr213r:
18976 case X86::VFNMADDSDr213r:
18977 case X86::VFNMADDSSr213r:
18978 case X86::VFNMSUBPDr213r:
18979 case X86::VFNMSUBPSr213r:
18980 case X86::VFNMSUBSDr213r:
18981 case X86::VFNMSUBSSr213r:
18982 case X86::VFMADDSUBPDr213r:
18983 case X86::VFMADDSUBPSr213r:
18984 case X86::VFMSUBADDPDr213r:
18985 case X86::VFMSUBADDPSr213r:
18986 case X86::VFMADDPDr213rY:
18987 case X86::VFMADDPSr213rY:
18988 case X86::VFMSUBPDr213rY:
18989 case X86::VFMSUBPSr213rY:
18990 case X86::VFNMADDPDr213rY:
18991 case X86::VFNMADDPSr213rY:
18992 case X86::VFNMSUBPDr213rY:
18993 case X86::VFNMSUBPSr213rY:
18994 case X86::VFMADDSUBPDr213rY:
18995 case X86::VFMADDSUBPSr213rY:
18996 case X86::VFMSUBADDPDr213rY:
18997 case X86::VFMSUBADDPSr213rY:
18998 return emitFMA3Instr(MI, BB);
19002 //===----------------------------------------------------------------------===//
19003 // X86 Optimization Hooks
19004 //===----------------------------------------------------------------------===//
19006 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19009 const SelectionDAG &DAG,
19010 unsigned Depth) const {
19011 unsigned BitWidth = KnownZero.getBitWidth();
19012 unsigned Opc = Op.getOpcode();
19013 assert((Opc >= ISD::BUILTIN_OP_END ||
19014 Opc == ISD::INTRINSIC_WO_CHAIN ||
19015 Opc == ISD::INTRINSIC_W_CHAIN ||
19016 Opc == ISD::INTRINSIC_VOID) &&
19017 "Should use MaskedValueIsZero if you don't know whether Op"
19018 " is a target node!");
19020 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19034 // These nodes' second result is a boolean.
19035 if (Op.getResNo() == 0)
19038 case X86ISD::SETCC:
19039 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19041 case ISD::INTRINSIC_WO_CHAIN: {
19042 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19043 unsigned NumLoBits = 0;
19046 case Intrinsic::x86_sse_movmsk_ps:
19047 case Intrinsic::x86_avx_movmsk_ps_256:
19048 case Intrinsic::x86_sse2_movmsk_pd:
19049 case Intrinsic::x86_avx_movmsk_pd_256:
19050 case Intrinsic::x86_mmx_pmovmskb:
19051 case Intrinsic::x86_sse2_pmovmskb_128:
19052 case Intrinsic::x86_avx2_pmovmskb: {
19053 // High bits of movmskp{s|d}, pmovmskb are known zero.
19055 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19056 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19057 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19058 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19059 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19060 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19061 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19062 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19064 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19073 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19075 const SelectionDAG &,
19076 unsigned Depth) const {
19077 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19078 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19079 return Op.getValueType().getScalarType().getSizeInBits();
19085 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19086 /// node is a GlobalAddress + offset.
19087 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19088 const GlobalValue* &GA,
19089 int64_t &Offset) const {
19090 if (N->getOpcode() == X86ISD::Wrapper) {
19091 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19092 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19093 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19097 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19100 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19101 /// same as extracting the high 128-bit part of 256-bit vector and then
19102 /// inserting the result into the low part of a new 256-bit vector
19103 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19104 EVT VT = SVOp->getValueType(0);
19105 unsigned NumElems = VT.getVectorNumElements();
19107 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19108 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19109 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19110 SVOp->getMaskElt(j) >= 0)
19116 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19117 /// same as extracting the low 128-bit part of 256-bit vector and then
19118 /// inserting the result into the high part of a new 256-bit vector
19119 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19120 EVT VT = SVOp->getValueType(0);
19121 unsigned NumElems = VT.getVectorNumElements();
19123 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19124 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19125 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19126 SVOp->getMaskElt(j) >= 0)
19132 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19133 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19134 TargetLowering::DAGCombinerInfo &DCI,
19135 const X86Subtarget* Subtarget) {
19137 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19138 SDValue V1 = SVOp->getOperand(0);
19139 SDValue V2 = SVOp->getOperand(1);
19140 EVT VT = SVOp->getValueType(0);
19141 unsigned NumElems = VT.getVectorNumElements();
19143 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19144 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19148 // V UNDEF BUILD_VECTOR UNDEF
19150 // CONCAT_VECTOR CONCAT_VECTOR
19153 // RESULT: V + zero extended
19155 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19156 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19157 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19160 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19163 // To match the shuffle mask, the first half of the mask should
19164 // be exactly the first vector, and all the rest a splat with the
19165 // first element of the second one.
19166 for (unsigned i = 0; i != NumElems/2; ++i)
19167 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19168 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19171 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19172 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19173 if (Ld->hasNUsesOfValue(1, 0)) {
19174 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19175 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19177 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19179 Ld->getPointerInfo(),
19180 Ld->getAlignment(),
19181 false/*isVolatile*/, true/*ReadMem*/,
19182 false/*WriteMem*/);
19184 // Make sure the newly-created LOAD is in the same position as Ld in
19185 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19186 // and update uses of Ld's output chain to use the TokenFactor.
19187 if (Ld->hasAnyUseOfValue(1)) {
19188 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19189 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19190 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19191 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19192 SDValue(ResNode.getNode(), 1));
19195 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19199 // Emit a zeroed vector and insert the desired subvector on its
19201 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19202 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19203 return DCI.CombineTo(N, InsV);
19206 //===--------------------------------------------------------------------===//
19207 // Combine some shuffles into subvector extracts and inserts:
19210 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19211 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19212 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19213 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19214 return DCI.CombineTo(N, InsV);
19217 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19218 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19219 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19220 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19221 return DCI.CombineTo(N, InsV);
19227 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19230 /// This is the leaf of the recursive combinine below. When we have found some
19231 /// chain of single-use x86 shuffle instructions and accumulated the combined
19232 /// shuffle mask represented by them, this will try to pattern match that mask
19233 /// into either a single instruction if there is a special purpose instruction
19234 /// for this operation, or into a PSHUFB instruction which is a fully general
19235 /// instruction but should only be used to replace chains over a certain depth.
19236 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19237 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19238 TargetLowering::DAGCombinerInfo &DCI,
19239 const X86Subtarget *Subtarget) {
19240 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19242 // Find the operand that enters the chain. Note that multiple uses are OK
19243 // here, we're not going to remove the operand we find.
19244 SDValue Input = Op.getOperand(0);
19245 while (Input.getOpcode() == ISD::BITCAST)
19246 Input = Input.getOperand(0);
19248 MVT VT = Input.getSimpleValueType();
19249 MVT RootVT = Root.getSimpleValueType();
19252 // Just remove no-op shuffle masks.
19253 if (Mask.size() == 1) {
19254 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19259 // Use the float domain if the operand type is a floating point type.
19260 bool FloatDomain = VT.isFloatingPoint();
19262 // For floating point shuffles, we don't have free copies in the shuffle
19263 // instructions or the ability to load as part of the instruction, so
19264 // canonicalize their shuffles to UNPCK or MOV variants.
19266 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19267 // vectors because it can have a load folded into it that UNPCK cannot. This
19268 // doesn't preclude something switching to the shorter encoding post-RA.
19270 // FIXME: Should teach these routines about AVX vector widths.
19271 if (FloatDomain && VT.getSizeInBits() == 128) {
19272 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19273 bool Lo = Mask.equals({0, 0});
19276 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19277 // is no slower than UNPCKLPD but has the option to fold the input operand
19278 // into even an unaligned memory load.
19279 if (Lo && Subtarget->hasSSE3()) {
19280 Shuffle = X86ISD::MOVDDUP;
19281 ShuffleVT = MVT::v2f64;
19283 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19284 // than the UNPCK variants.
19285 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19286 ShuffleVT = MVT::v4f32;
19288 if (Depth == 1 && Root->getOpcode() == Shuffle)
19289 return false; // Nothing to do!
19290 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19291 DCI.AddToWorklist(Op.getNode());
19292 if (Shuffle == X86ISD::MOVDDUP)
19293 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19295 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19296 DCI.AddToWorklist(Op.getNode());
19297 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19301 if (Subtarget->hasSSE3() &&
19302 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19303 bool Lo = Mask.equals({0, 0, 2, 2});
19304 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19305 MVT ShuffleVT = MVT::v4f32;
19306 if (Depth == 1 && Root->getOpcode() == Shuffle)
19307 return false; // Nothing to do!
19308 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19309 DCI.AddToWorklist(Op.getNode());
19310 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19311 DCI.AddToWorklist(Op.getNode());
19312 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19316 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19317 bool Lo = Mask.equals({0, 0, 1, 1});
19318 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19319 MVT ShuffleVT = MVT::v4f32;
19320 if (Depth == 1 && Root->getOpcode() == Shuffle)
19321 return false; // Nothing to do!
19322 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19323 DCI.AddToWorklist(Op.getNode());
19324 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19325 DCI.AddToWorklist(Op.getNode());
19326 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19332 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19333 // variants as none of these have single-instruction variants that are
19334 // superior to the UNPCK formulation.
19335 if (!FloatDomain && VT.getSizeInBits() == 128 &&
19336 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19337 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19338 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19340 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19341 bool Lo = Mask[0] == 0;
19342 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19343 if (Depth == 1 && Root->getOpcode() == Shuffle)
19344 return false; // Nothing to do!
19346 switch (Mask.size()) {
19348 ShuffleVT = MVT::v8i16;
19351 ShuffleVT = MVT::v16i8;
19354 llvm_unreachable("Impossible mask size!");
19356 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19357 DCI.AddToWorklist(Op.getNode());
19358 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19359 DCI.AddToWorklist(Op.getNode());
19360 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19365 // Don't try to re-form single instruction chains under any circumstances now
19366 // that we've done encoding canonicalization for them.
19370 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19371 // can replace them with a single PSHUFB instruction profitably. Intel's
19372 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19373 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19374 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19375 SmallVector<SDValue, 16> PSHUFBMask;
19376 int NumBytes = VT.getSizeInBits() / 8;
19377 int Ratio = NumBytes / Mask.size();
19378 for (int i = 0; i < NumBytes; ++i) {
19379 if (Mask[i / Ratio] == SM_SentinelUndef) {
19380 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19383 int M = Mask[i / Ratio] != SM_SentinelZero
19384 ? Ratio * Mask[i / Ratio] + i % Ratio
19386 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19388 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19389 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19390 DCI.AddToWorklist(Op.getNode());
19391 SDValue PSHUFBMaskOp =
19392 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19393 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19394 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19395 DCI.AddToWorklist(Op.getNode());
19396 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19401 // Failed to find any combines.
19405 /// \brief Fully generic combining of x86 shuffle instructions.
19407 /// This should be the last combine run over the x86 shuffle instructions. Once
19408 /// they have been fully optimized, this will recursively consider all chains
19409 /// of single-use shuffle instructions, build a generic model of the cumulative
19410 /// shuffle operation, and check for simpler instructions which implement this
19411 /// operation. We use this primarily for two purposes:
19413 /// 1) Collapse generic shuffles to specialized single instructions when
19414 /// equivalent. In most cases, this is just an encoding size win, but
19415 /// sometimes we will collapse multiple generic shuffles into a single
19416 /// special-purpose shuffle.
19417 /// 2) Look for sequences of shuffle instructions with 3 or more total
19418 /// instructions, and replace them with the slightly more expensive SSSE3
19419 /// PSHUFB instruction if available. We do this as the last combining step
19420 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19421 /// a suitable short sequence of other instructions. The PHUFB will either
19422 /// use a register or have to read from memory and so is slightly (but only
19423 /// slightly) more expensive than the other shuffle instructions.
19425 /// Because this is inherently a quadratic operation (for each shuffle in
19426 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19427 /// This should never be an issue in practice as the shuffle lowering doesn't
19428 /// produce sequences of more than 8 instructions.
19430 /// FIXME: We will currently miss some cases where the redundant shuffling
19431 /// would simplify under the threshold for PSHUFB formation because of
19432 /// combine-ordering. To fix this, we should do the redundant instruction
19433 /// combining in this recursive walk.
19434 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19435 ArrayRef<int> RootMask,
19436 int Depth, bool HasPSHUFB,
19438 TargetLowering::DAGCombinerInfo &DCI,
19439 const X86Subtarget *Subtarget) {
19440 // Bound the depth of our recursive combine because this is ultimately
19441 // quadratic in nature.
19445 // Directly rip through bitcasts to find the underlying operand.
19446 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19447 Op = Op.getOperand(0);
19449 MVT VT = Op.getSimpleValueType();
19450 if (!VT.isVector())
19451 return false; // Bail if we hit a non-vector.
19453 assert(Root.getSimpleValueType().isVector() &&
19454 "Shuffles operate on vector types!");
19455 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19456 "Can only combine shuffles of the same vector register size.");
19458 if (!isTargetShuffle(Op.getOpcode()))
19460 SmallVector<int, 16> OpMask;
19462 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19463 // We only can combine unary shuffles which we can decode the mask for.
19464 if (!HaveMask || !IsUnary)
19467 assert(VT.getVectorNumElements() == OpMask.size() &&
19468 "Different mask size from vector size!");
19469 assert(((RootMask.size() > OpMask.size() &&
19470 RootMask.size() % OpMask.size() == 0) ||
19471 (OpMask.size() > RootMask.size() &&
19472 OpMask.size() % RootMask.size() == 0) ||
19473 OpMask.size() == RootMask.size()) &&
19474 "The smaller number of elements must divide the larger.");
19475 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19476 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19477 assert(((RootRatio == 1 && OpRatio == 1) ||
19478 (RootRatio == 1) != (OpRatio == 1)) &&
19479 "Must not have a ratio for both incoming and op masks!");
19481 SmallVector<int, 16> Mask;
19482 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19484 // Merge this shuffle operation's mask into our accumulated mask. Note that
19485 // this shuffle's mask will be the first applied to the input, followed by the
19486 // root mask to get us all the way to the root value arrangement. The reason
19487 // for this order is that we are recursing up the operation chain.
19488 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19489 int RootIdx = i / RootRatio;
19490 if (RootMask[RootIdx] < 0) {
19491 // This is a zero or undef lane, we're done.
19492 Mask.push_back(RootMask[RootIdx]);
19496 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19497 int OpIdx = RootMaskedIdx / OpRatio;
19498 if (OpMask[OpIdx] < 0) {
19499 // The incoming lanes are zero or undef, it doesn't matter which ones we
19501 Mask.push_back(OpMask[OpIdx]);
19505 // Ok, we have non-zero lanes, map them through.
19506 Mask.push_back(OpMask[OpIdx] * OpRatio +
19507 RootMaskedIdx % OpRatio);
19510 // See if we can recurse into the operand to combine more things.
19511 switch (Op.getOpcode()) {
19512 case X86ISD::PSHUFB:
19514 case X86ISD::PSHUFD:
19515 case X86ISD::PSHUFHW:
19516 case X86ISD::PSHUFLW:
19517 if (Op.getOperand(0).hasOneUse() &&
19518 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19519 HasPSHUFB, DAG, DCI, Subtarget))
19523 case X86ISD::UNPCKL:
19524 case X86ISD::UNPCKH:
19525 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19526 // We can't check for single use, we have to check that this shuffle is the only user.
19527 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19528 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19529 HasPSHUFB, DAG, DCI, Subtarget))
19534 // Minor canonicalization of the accumulated shuffle mask to make it easier
19535 // to match below. All this does is detect masks with squential pairs of
19536 // elements, and shrink them to the half-width mask. It does this in a loop
19537 // so it will reduce the size of the mask to the minimal width mask which
19538 // performs an equivalent shuffle.
19539 SmallVector<int, 16> WidenedMask;
19540 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19541 Mask = std::move(WidenedMask);
19542 WidenedMask.clear();
19545 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19549 /// \brief Get the PSHUF-style mask from PSHUF node.
19551 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19552 /// PSHUF-style masks that can be reused with such instructions.
19553 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19554 MVT VT = N.getSimpleValueType();
19555 SmallVector<int, 4> Mask;
19557 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19561 // If we have more than 128-bits, only the low 128-bits of shuffle mask
19562 // matter. Check that the upper masks are repeats and remove them.
19563 if (VT.getSizeInBits() > 128) {
19564 int LaneElts = 128 / VT.getScalarSizeInBits();
19566 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19567 for (int j = 0; j < LaneElts; ++j)
19568 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19569 "Mask doesn't repeat in high 128-bit lanes!");
19571 Mask.resize(LaneElts);
19574 switch (N.getOpcode()) {
19575 case X86ISD::PSHUFD:
19577 case X86ISD::PSHUFLW:
19580 case X86ISD::PSHUFHW:
19581 Mask.erase(Mask.begin(), Mask.begin() + 4);
19582 for (int &M : Mask)
19586 llvm_unreachable("No valid shuffle instruction found!");
19590 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19592 /// We walk up the chain and look for a combinable shuffle, skipping over
19593 /// shuffles that we could hoist this shuffle's transformation past without
19594 /// altering anything.
19596 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19598 TargetLowering::DAGCombinerInfo &DCI) {
19599 assert(N.getOpcode() == X86ISD::PSHUFD &&
19600 "Called with something other than an x86 128-bit half shuffle!");
19603 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19604 // of the shuffles in the chain so that we can form a fresh chain to replace
19606 SmallVector<SDValue, 8> Chain;
19607 SDValue V = N.getOperand(0);
19608 for (; V.hasOneUse(); V = V.getOperand(0)) {
19609 switch (V.getOpcode()) {
19611 return SDValue(); // Nothing combined!
19614 // Skip bitcasts as we always know the type for the target specific
19618 case X86ISD::PSHUFD:
19619 // Found another dword shuffle.
19622 case X86ISD::PSHUFLW:
19623 // Check that the low words (being shuffled) are the identity in the
19624 // dword shuffle, and the high words are self-contained.
19625 if (Mask[0] != 0 || Mask[1] != 1 ||
19626 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19629 Chain.push_back(V);
19632 case X86ISD::PSHUFHW:
19633 // Check that the high words (being shuffled) are the identity in the
19634 // dword shuffle, and the low words are self-contained.
19635 if (Mask[2] != 2 || Mask[3] != 3 ||
19636 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19639 Chain.push_back(V);
19642 case X86ISD::UNPCKL:
19643 case X86ISD::UNPCKH:
19644 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19645 // shuffle into a preceding word shuffle.
19646 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19647 V.getSimpleValueType().getScalarType() != MVT::i16)
19650 // Search for a half-shuffle which we can combine with.
19651 unsigned CombineOp =
19652 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19653 if (V.getOperand(0) != V.getOperand(1) ||
19654 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19656 Chain.push_back(V);
19657 V = V.getOperand(0);
19659 switch (V.getOpcode()) {
19661 return SDValue(); // Nothing to combine.
19663 case X86ISD::PSHUFLW:
19664 case X86ISD::PSHUFHW:
19665 if (V.getOpcode() == CombineOp)
19668 Chain.push_back(V);
19672 V = V.getOperand(0);
19676 } while (V.hasOneUse());
19679 // Break out of the loop if we break out of the switch.
19683 if (!V.hasOneUse())
19684 // We fell out of the loop without finding a viable combining instruction.
19687 // Merge this node's mask and our incoming mask.
19688 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19689 for (int &M : Mask)
19691 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19692 getV4X86ShuffleImm8ForMask(Mask, DAG));
19694 // Rebuild the chain around this new shuffle.
19695 while (!Chain.empty()) {
19696 SDValue W = Chain.pop_back_val();
19698 if (V.getValueType() != W.getOperand(0).getValueType())
19699 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19701 switch (W.getOpcode()) {
19703 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19705 case X86ISD::UNPCKL:
19706 case X86ISD::UNPCKH:
19707 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19710 case X86ISD::PSHUFD:
19711 case X86ISD::PSHUFLW:
19712 case X86ISD::PSHUFHW:
19713 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19717 if (V.getValueType() != N.getValueType())
19718 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19720 // Return the new chain to replace N.
19724 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19726 /// We walk up the chain, skipping shuffles of the other half and looking
19727 /// through shuffles which switch halves trying to find a shuffle of the same
19728 /// pair of dwords.
19729 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19731 TargetLowering::DAGCombinerInfo &DCI) {
19733 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19734 "Called with something other than an x86 128-bit half shuffle!");
19736 unsigned CombineOpcode = N.getOpcode();
19738 // Walk up a single-use chain looking for a combinable shuffle.
19739 SDValue V = N.getOperand(0);
19740 for (; V.hasOneUse(); V = V.getOperand(0)) {
19741 switch (V.getOpcode()) {
19743 return false; // Nothing combined!
19746 // Skip bitcasts as we always know the type for the target specific
19750 case X86ISD::PSHUFLW:
19751 case X86ISD::PSHUFHW:
19752 if (V.getOpcode() == CombineOpcode)
19755 // Other-half shuffles are no-ops.
19758 // Break out of the loop if we break out of the switch.
19762 if (!V.hasOneUse())
19763 // We fell out of the loop without finding a viable combining instruction.
19766 // Combine away the bottom node as its shuffle will be accumulated into
19767 // a preceding shuffle.
19768 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19770 // Record the old value.
19773 // Merge this node's mask and our incoming mask (adjusted to account for all
19774 // the pshufd instructions encountered).
19775 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19776 for (int &M : Mask)
19778 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19779 getV4X86ShuffleImm8ForMask(Mask, DAG));
19781 // Check that the shuffles didn't cancel each other out. If not, we need to
19782 // combine to the new one.
19784 // Replace the combinable shuffle with the combined one, updating all users
19785 // so that we re-evaluate the chain here.
19786 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19791 /// \brief Try to combine x86 target specific shuffles.
19792 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19793 TargetLowering::DAGCombinerInfo &DCI,
19794 const X86Subtarget *Subtarget) {
19796 MVT VT = N.getSimpleValueType();
19797 SmallVector<int, 4> Mask;
19799 switch (N.getOpcode()) {
19800 case X86ISD::PSHUFD:
19801 case X86ISD::PSHUFLW:
19802 case X86ISD::PSHUFHW:
19803 Mask = getPSHUFShuffleMask(N);
19804 assert(Mask.size() == 4);
19810 // Nuke no-op shuffles that show up after combining.
19811 if (isNoopShuffleMask(Mask))
19812 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19814 // Look for simplifications involving one or two shuffle instructions.
19815 SDValue V = N.getOperand(0);
19816 switch (N.getOpcode()) {
19819 case X86ISD::PSHUFLW:
19820 case X86ISD::PSHUFHW:
19821 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
19823 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19824 return SDValue(); // We combined away this shuffle, so we're done.
19826 // See if this reduces to a PSHUFD which is no more expensive and can
19827 // combine with more operations. Note that it has to at least flip the
19828 // dwords as otherwise it would have been removed as a no-op.
19829 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
19830 int DMask[] = {0, 1, 2, 3};
19831 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19832 DMask[DOffset + 0] = DOffset + 1;
19833 DMask[DOffset + 1] = DOffset + 0;
19834 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
19835 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
19836 DCI.AddToWorklist(V.getNode());
19837 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
19838 getV4X86ShuffleImm8ForMask(DMask, DAG));
19839 DCI.AddToWorklist(V.getNode());
19840 return DAG.getNode(ISD::BITCAST, DL, VT, V);
19843 // Look for shuffle patterns which can be implemented as a single unpack.
19844 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19845 // only works when we have a PSHUFD followed by two half-shuffles.
19846 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19847 (V.getOpcode() == X86ISD::PSHUFLW ||
19848 V.getOpcode() == X86ISD::PSHUFHW) &&
19849 V.getOpcode() != N.getOpcode() &&
19851 SDValue D = V.getOperand(0);
19852 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19853 D = D.getOperand(0);
19854 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19855 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19856 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19857 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19858 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19860 for (int i = 0; i < 4; ++i) {
19861 WordMask[i + NOffset] = Mask[i] + NOffset;
19862 WordMask[i + VOffset] = VMask[i] + VOffset;
19864 // Map the word mask through the DWord mask.
19866 for (int i = 0; i < 8; ++i)
19867 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19868 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19869 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
19870 // We can replace all three shuffles with an unpack.
19871 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
19872 DCI.AddToWorklist(V.getNode());
19873 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19882 case X86ISD::PSHUFD:
19883 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19892 /// \brief Try to combine a shuffle into a target-specific add-sub node.
19894 /// We combine this directly on the abstract vector shuffle nodes so it is
19895 /// easier to generically match. We also insert dummy vector shuffle nodes for
19896 /// the operands which explicitly discard the lanes which are unused by this
19897 /// operation to try to flow through the rest of the combiner the fact that
19898 /// they're unused.
19899 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
19901 EVT VT = N->getValueType(0);
19903 // We only handle target-independent shuffles.
19904 // FIXME: It would be easy and harmless to use the target shuffle mask
19905 // extraction tool to support more.
19906 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
19909 auto *SVN = cast<ShuffleVectorSDNode>(N);
19910 ArrayRef<int> Mask = SVN->getMask();
19911 SDValue V1 = N->getOperand(0);
19912 SDValue V2 = N->getOperand(1);
19914 // We require the first shuffle operand to be the SUB node, and the second to
19915 // be the ADD node.
19916 // FIXME: We should support the commuted patterns.
19917 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
19920 // If there are other uses of these operations we can't fold them.
19921 if (!V1->hasOneUse() || !V2->hasOneUse())
19924 // Ensure that both operations have the same operands. Note that we can
19925 // commute the FADD operands.
19926 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
19927 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
19928 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
19931 // We're looking for blends between FADD and FSUB nodes. We insist on these
19932 // nodes being lined up in a specific expected pattern.
19933 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
19934 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
19935 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
19938 // Only specific types are legal at this point, assert so we notice if and
19939 // when these change.
19940 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
19941 VT == MVT::v4f64) &&
19942 "Unknown vector type encountered!");
19944 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
19947 /// PerformShuffleCombine - Performs several different shuffle combines.
19948 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19949 TargetLowering::DAGCombinerInfo &DCI,
19950 const X86Subtarget *Subtarget) {
19952 SDValue N0 = N->getOperand(0);
19953 SDValue N1 = N->getOperand(1);
19954 EVT VT = N->getValueType(0);
19956 // Don't create instructions with illegal types after legalize types has run.
19957 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19958 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19961 // If we have legalized the vector types, look for blends of FADD and FSUB
19962 // nodes that we can fuse into an ADDSUB node.
19963 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
19964 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
19967 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19968 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19969 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19970 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19972 // During Type Legalization, when promoting illegal vector types,
19973 // the backend might introduce new shuffle dag nodes and bitcasts.
19975 // This code performs the following transformation:
19976 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19977 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19979 // We do this only if both the bitcast and the BINOP dag nodes have
19980 // one use. Also, perform this transformation only if the new binary
19981 // operation is legal. This is to avoid introducing dag nodes that
19982 // potentially need to be further expanded (or custom lowered) into a
19983 // less optimal sequence of dag nodes.
19984 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19985 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19986 N0.getOpcode() == ISD::BITCAST) {
19987 SDValue BC0 = N0.getOperand(0);
19988 EVT SVT = BC0.getValueType();
19989 unsigned Opcode = BC0.getOpcode();
19990 unsigned NumElts = VT.getVectorNumElements();
19992 if (BC0.hasOneUse() && SVT.isVector() &&
19993 SVT.getVectorNumElements() * 2 == NumElts &&
19994 TLI.isOperationLegal(Opcode, VT)) {
19995 bool CanFold = false;
20007 unsigned SVTNumElts = SVT.getVectorNumElements();
20008 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20009 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20010 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20011 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20012 CanFold = SVOp->getMaskElt(i) < 0;
20015 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20016 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20017 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20018 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20023 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20024 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20025 // consecutive, non-overlapping, and in the right order.
20026 SmallVector<SDValue, 16> Elts;
20027 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20028 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20030 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20034 if (isTargetShuffle(N->getOpcode())) {
20036 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20037 if (Shuffle.getNode())
20040 // Try recursively combining arbitrary sequences of x86 shuffle
20041 // instructions into higher-order shuffles. We do this after combining
20042 // specific PSHUF instruction sequences into their minimal form so that we
20043 // can evaluate how many specialized shuffle instructions are involved in
20044 // a particular chain.
20045 SmallVector<int, 1> NonceMask; // Just a placeholder.
20046 NonceMask.push_back(0);
20047 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20048 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20050 return SDValue(); // This routine will use CombineTo to replace N.
20056 /// PerformTruncateCombine - Converts truncate operation to
20057 /// a sequence of vector shuffle operations.
20058 /// It is possible when we truncate 256-bit vector to 128-bit vector
20059 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20060 TargetLowering::DAGCombinerInfo &DCI,
20061 const X86Subtarget *Subtarget) {
20065 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20066 /// specific shuffle of a load can be folded into a single element load.
20067 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20068 /// shuffles have been custom lowered so we need to handle those here.
20069 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20070 TargetLowering::DAGCombinerInfo &DCI) {
20071 if (DCI.isBeforeLegalizeOps())
20074 SDValue InVec = N->getOperand(0);
20075 SDValue EltNo = N->getOperand(1);
20077 if (!isa<ConstantSDNode>(EltNo))
20080 EVT OriginalVT = InVec.getValueType();
20082 if (InVec.getOpcode() == ISD::BITCAST) {
20083 // Don't duplicate a load with other uses.
20084 if (!InVec.hasOneUse())
20086 EVT BCVT = InVec.getOperand(0).getValueType();
20087 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20089 InVec = InVec.getOperand(0);
20092 EVT CurrentVT = InVec.getValueType();
20094 if (!isTargetShuffle(InVec.getOpcode()))
20097 // Don't duplicate a load with other uses.
20098 if (!InVec.hasOneUse())
20101 SmallVector<int, 16> ShuffleMask;
20103 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20104 ShuffleMask, UnaryShuffle))
20107 // Select the input vector, guarding against out of range extract vector.
20108 unsigned NumElems = CurrentVT.getVectorNumElements();
20109 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20110 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20111 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20112 : InVec.getOperand(1);
20114 // If inputs to shuffle are the same for both ops, then allow 2 uses
20115 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20116 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20118 if (LdNode.getOpcode() == ISD::BITCAST) {
20119 // Don't duplicate a load with other uses.
20120 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20123 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20124 LdNode = LdNode.getOperand(0);
20127 if (!ISD::isNormalLoad(LdNode.getNode()))
20130 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20132 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20135 EVT EltVT = N->getValueType(0);
20136 // If there's a bitcast before the shuffle, check if the load type and
20137 // alignment is valid.
20138 unsigned Align = LN0->getAlignment();
20139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20140 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20141 EltVT.getTypeForEVT(*DAG.getContext()));
20143 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20146 // All checks match so transform back to vector_shuffle so that DAG combiner
20147 // can finish the job
20150 // Create shuffle node taking into account the case that its a unary shuffle
20151 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20152 : InVec.getOperand(1);
20153 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20154 InVec.getOperand(0), Shuffle,
20156 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20157 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20161 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20162 /// special and don't usually play with other vector types, it's better to
20163 /// handle them early to be sure we emit efficient code by avoiding
20164 /// store-load conversions.
20165 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20166 if (N->getValueType(0) != MVT::x86mmx ||
20167 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20168 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20171 SDValue V = N->getOperand(0);
20172 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20173 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20174 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20175 N->getValueType(0), V.getOperand(0));
20180 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20181 /// generation and convert it from being a bunch of shuffles and extracts
20182 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20183 /// storing the value and loading scalars back, while for x64 we should
20184 /// use 64-bit extracts and shifts.
20185 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20186 TargetLowering::DAGCombinerInfo &DCI) {
20187 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20188 if (NewOp.getNode())
20191 SDValue InputVector = N->getOperand(0);
20193 // Detect mmx to i32 conversion through a v2i32 elt extract.
20194 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20195 N->getValueType(0) == MVT::i32 &&
20196 InputVector.getValueType() == MVT::v2i32) {
20198 // The bitcast source is a direct mmx result.
20199 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20200 if (MMXSrc.getValueType() == MVT::x86mmx)
20201 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20202 N->getValueType(0),
20203 InputVector.getNode()->getOperand(0));
20205 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20206 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20207 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20208 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20209 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20210 MMXSrcOp.getValueType() == MVT::v1i64 &&
20211 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20212 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20213 N->getValueType(0),
20214 MMXSrcOp.getOperand(0));
20217 // Only operate on vectors of 4 elements, where the alternative shuffling
20218 // gets to be more expensive.
20219 if (InputVector.getValueType() != MVT::v4i32)
20222 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20223 // single use which is a sign-extend or zero-extend, and all elements are
20225 SmallVector<SDNode *, 4> Uses;
20226 unsigned ExtractedElements = 0;
20227 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20228 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20229 if (UI.getUse().getResNo() != InputVector.getResNo())
20232 SDNode *Extract = *UI;
20233 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20236 if (Extract->getValueType(0) != MVT::i32)
20238 if (!Extract->hasOneUse())
20240 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20241 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20243 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20246 // Record which element was extracted.
20247 ExtractedElements |=
20248 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20250 Uses.push_back(Extract);
20253 // If not all the elements were used, this may not be worthwhile.
20254 if (ExtractedElements != 15)
20257 // Ok, we've now decided to do the transformation.
20258 // If 64-bit shifts are legal, use the extract-shift sequence,
20259 // otherwise bounce the vector off the cache.
20260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20262 SDLoc dl(InputVector);
20264 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20265 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20266 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20267 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20268 DAG.getConstant(0, VecIdxTy));
20269 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20270 DAG.getConstant(1, VecIdxTy));
20272 SDValue ShAmt = DAG.getConstant(32,
20273 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20274 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20275 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20276 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20277 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20278 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20279 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20281 // Store the value to a temporary stack slot.
20282 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20283 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20284 MachinePointerInfo(), false, false, 0);
20286 EVT ElementType = InputVector.getValueType().getVectorElementType();
20287 unsigned EltSize = ElementType.getSizeInBits() / 8;
20289 // Replace each use (extract) with a load of the appropriate element.
20290 for (unsigned i = 0; i < 4; ++i) {
20291 uint64_t Offset = EltSize * i;
20292 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20294 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20295 StackPtr, OffsetVal);
20297 // Load the scalar.
20298 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20299 ScalarAddr, MachinePointerInfo(),
20300 false, false, false, 0);
20305 // Replace the extracts
20306 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20307 UE = Uses.end(); UI != UE; ++UI) {
20308 SDNode *Extract = *UI;
20310 SDValue Idx = Extract->getOperand(1);
20311 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20312 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20315 // The replacement was made in place; don't return anything.
20319 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20320 static std::pair<unsigned, bool>
20321 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20322 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20323 if (!VT.isVector())
20324 return std::make_pair(0, false);
20326 bool NeedSplit = false;
20327 switch (VT.getSimpleVT().SimpleTy) {
20328 default: return std::make_pair(0, false);
20331 if (!Subtarget->hasVLX())
20332 return std::make_pair(0, false);
20336 if (!Subtarget->hasBWI())
20337 return std::make_pair(0, false);
20341 if (!Subtarget->hasAVX512())
20342 return std::make_pair(0, false);
20347 if (!Subtarget->hasAVX2())
20349 if (!Subtarget->hasAVX())
20350 return std::make_pair(0, false);
20355 if (!Subtarget->hasSSE2())
20356 return std::make_pair(0, false);
20359 // SSE2 has only a small subset of the operations.
20360 bool hasUnsigned = Subtarget->hasSSE41() ||
20361 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20362 bool hasSigned = Subtarget->hasSSE41() ||
20363 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20365 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20368 // Check for x CC y ? x : y.
20369 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20370 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20375 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20378 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20381 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20384 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20386 // Check for x CC y ? y : x -- a min/max with reversed arms.
20387 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20388 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20393 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20396 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20399 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20402 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20406 return std::make_pair(Opc, NeedSplit);
20410 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20411 const X86Subtarget *Subtarget) {
20413 SDValue Cond = N->getOperand(0);
20414 SDValue LHS = N->getOperand(1);
20415 SDValue RHS = N->getOperand(2);
20417 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20418 SDValue CondSrc = Cond->getOperand(0);
20419 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20420 Cond = CondSrc->getOperand(0);
20423 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20426 // A vselect where all conditions and data are constants can be optimized into
20427 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20428 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20429 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20432 unsigned MaskValue = 0;
20433 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20436 MVT VT = N->getSimpleValueType(0);
20437 unsigned NumElems = VT.getVectorNumElements();
20438 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20439 for (unsigned i = 0; i < NumElems; ++i) {
20440 // Be sure we emit undef where we can.
20441 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20442 ShuffleMask[i] = -1;
20444 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20447 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20448 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20450 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20453 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20455 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20456 TargetLowering::DAGCombinerInfo &DCI,
20457 const X86Subtarget *Subtarget) {
20459 SDValue Cond = N->getOperand(0);
20460 // Get the LHS/RHS of the select.
20461 SDValue LHS = N->getOperand(1);
20462 SDValue RHS = N->getOperand(2);
20463 EVT VT = LHS.getValueType();
20464 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20466 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20467 // instructions match the semantics of the common C idiom x<y?x:y but not
20468 // x<=y?x:y, because of how they handle negative zero (which can be
20469 // ignored in unsafe-math mode).
20470 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20471 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20472 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20473 (Subtarget->hasSSE2() ||
20474 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20475 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20477 unsigned Opcode = 0;
20478 // Check for x CC y ? x : y.
20479 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20480 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20484 // Converting this to a min would handle NaNs incorrectly, and swapping
20485 // the operands would cause it to handle comparisons between positive
20486 // and negative zero incorrectly.
20487 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20488 if (!DAG.getTarget().Options.UnsafeFPMath &&
20489 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20491 std::swap(LHS, RHS);
20493 Opcode = X86ISD::FMIN;
20496 // Converting this to a min would handle comparisons between positive
20497 // and negative zero incorrectly.
20498 if (!DAG.getTarget().Options.UnsafeFPMath &&
20499 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20501 Opcode = X86ISD::FMIN;
20504 // Converting this to a min would handle both negative zeros and NaNs
20505 // incorrectly, but we can swap the operands to fix both.
20506 std::swap(LHS, RHS);
20510 Opcode = X86ISD::FMIN;
20514 // Converting this to a max would handle comparisons between positive
20515 // and negative zero incorrectly.
20516 if (!DAG.getTarget().Options.UnsafeFPMath &&
20517 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20519 Opcode = X86ISD::FMAX;
20522 // Converting this to a max would handle NaNs incorrectly, and swapping
20523 // the operands would cause it to handle comparisons between positive
20524 // and negative zero incorrectly.
20525 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20526 if (!DAG.getTarget().Options.UnsafeFPMath &&
20527 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20529 std::swap(LHS, RHS);
20531 Opcode = X86ISD::FMAX;
20534 // Converting this to a max would handle both negative zeros and NaNs
20535 // incorrectly, but we can swap the operands to fix both.
20536 std::swap(LHS, RHS);
20540 Opcode = X86ISD::FMAX;
20543 // Check for x CC y ? y : x -- a min/max with reversed arms.
20544 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20545 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20549 // Converting this to a min would handle comparisons between positive
20550 // and negative zero incorrectly, and swapping the operands would
20551 // cause it to handle NaNs incorrectly.
20552 if (!DAG.getTarget().Options.UnsafeFPMath &&
20553 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20554 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20556 std::swap(LHS, RHS);
20558 Opcode = X86ISD::FMIN;
20561 // Converting this to a min would handle NaNs incorrectly.
20562 if (!DAG.getTarget().Options.UnsafeFPMath &&
20563 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20565 Opcode = X86ISD::FMIN;
20568 // Converting this to a min would handle both negative zeros and NaNs
20569 // incorrectly, but we can swap the operands to fix both.
20570 std::swap(LHS, RHS);
20574 Opcode = X86ISD::FMIN;
20578 // Converting this to a max would handle NaNs incorrectly.
20579 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20581 Opcode = X86ISD::FMAX;
20584 // Converting this to a max would handle comparisons between positive
20585 // and negative zero incorrectly, and swapping the operands would
20586 // cause it to handle NaNs incorrectly.
20587 if (!DAG.getTarget().Options.UnsafeFPMath &&
20588 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20589 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20591 std::swap(LHS, RHS);
20593 Opcode = X86ISD::FMAX;
20596 // Converting this to a max would handle both negative zeros and NaNs
20597 // incorrectly, but we can swap the operands to fix both.
20598 std::swap(LHS, RHS);
20602 Opcode = X86ISD::FMAX;
20608 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20611 EVT CondVT = Cond.getValueType();
20612 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20613 CondVT.getVectorElementType() == MVT::i1) {
20614 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20615 // lowering on KNL. In this case we convert it to
20616 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20617 // The same situation for all 128 and 256-bit vectors of i8 and i16.
20618 // Since SKX these selects have a proper lowering.
20619 EVT OpVT = LHS.getValueType();
20620 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20621 (OpVT.getVectorElementType() == MVT::i8 ||
20622 OpVT.getVectorElementType() == MVT::i16) &&
20623 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20624 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20625 DCI.AddToWorklist(Cond.getNode());
20626 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20629 // If this is a select between two integer constants, try to do some
20631 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20632 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20633 // Don't do this for crazy integer types.
20634 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20635 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20636 // so that TrueC (the true value) is larger than FalseC.
20637 bool NeedsCondInvert = false;
20639 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20640 // Efficiently invertible.
20641 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20642 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20643 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20644 NeedsCondInvert = true;
20645 std::swap(TrueC, FalseC);
20648 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20649 if (FalseC->getAPIntValue() == 0 &&
20650 TrueC->getAPIntValue().isPowerOf2()) {
20651 if (NeedsCondInvert) // Invert the condition if needed.
20652 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20653 DAG.getConstant(1, Cond.getValueType()));
20655 // Zero extend the condition if needed.
20656 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20658 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20659 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20660 DAG.getConstant(ShAmt, MVT::i8));
20663 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20664 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20665 if (NeedsCondInvert) // Invert the condition if needed.
20666 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20667 DAG.getConstant(1, Cond.getValueType()));
20669 // Zero extend the condition if needed.
20670 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20671 FalseC->getValueType(0), Cond);
20672 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20673 SDValue(FalseC, 0));
20676 // Optimize cases that will turn into an LEA instruction. This requires
20677 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20678 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20679 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20680 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20682 bool isFastMultiplier = false;
20684 switch ((unsigned char)Diff) {
20686 case 1: // result = add base, cond
20687 case 2: // result = lea base( , cond*2)
20688 case 3: // result = lea base(cond, cond*2)
20689 case 4: // result = lea base( , cond*4)
20690 case 5: // result = lea base(cond, cond*4)
20691 case 8: // result = lea base( , cond*8)
20692 case 9: // result = lea base(cond, cond*8)
20693 isFastMultiplier = true;
20698 if (isFastMultiplier) {
20699 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20700 if (NeedsCondInvert) // Invert the condition if needed.
20701 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20702 DAG.getConstant(1, Cond.getValueType()));
20704 // Zero extend the condition if needed.
20705 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20707 // Scale the condition by the difference.
20709 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20710 DAG.getConstant(Diff, Cond.getValueType()));
20712 // Add the base if non-zero.
20713 if (FalseC->getAPIntValue() != 0)
20714 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20715 SDValue(FalseC, 0));
20722 // Canonicalize max and min:
20723 // (x > y) ? x : y -> (x >= y) ? x : y
20724 // (x < y) ? x : y -> (x <= y) ? x : y
20725 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20726 // the need for an extra compare
20727 // against zero. e.g.
20728 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20730 // testl %edi, %edi
20732 // cmovgl %edi, %eax
20736 // cmovsl %eax, %edi
20737 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20738 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20739 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20740 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20745 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20746 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20747 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20748 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20753 // Early exit check
20754 if (!TLI.isTypeLegal(VT))
20757 // Match VSELECTs into subs with unsigned saturation.
20758 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20759 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20760 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20761 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20762 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20764 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20765 // left side invert the predicate to simplify logic below.
20767 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20769 CC = ISD::getSetCCInverse(CC, true);
20770 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20774 if (Other.getNode() && Other->getNumOperands() == 2 &&
20775 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20776 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20777 SDValue CondRHS = Cond->getOperand(1);
20779 // Look for a general sub with unsigned saturation first.
20780 // x >= y ? x-y : 0 --> subus x, y
20781 // x > y ? x-y : 0 --> subus x, y
20782 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20783 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20784 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20786 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20787 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20788 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20789 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20790 // If the RHS is a constant we have to reverse the const
20791 // canonicalization.
20792 // x > C-1 ? x+-C : 0 --> subus x, C
20793 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20794 CondRHSConst->getAPIntValue() ==
20795 (-OpRHSConst->getAPIntValue() - 1))
20796 return DAG.getNode(
20797 X86ISD::SUBUS, DL, VT, OpLHS,
20798 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20800 // Another special case: If C was a sign bit, the sub has been
20801 // canonicalized into a xor.
20802 // FIXME: Would it be better to use computeKnownBits to determine
20803 // whether it's safe to decanonicalize the xor?
20804 // x s< 0 ? x^C : 0 --> subus x, C
20805 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20806 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20807 OpRHSConst->getAPIntValue().isSignBit())
20808 // Note that we have to rebuild the RHS constant here to ensure we
20809 // don't rely on particular values of undef lanes.
20810 return DAG.getNode(
20811 X86ISD::SUBUS, DL, VT, OpLHS,
20812 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20817 // Try to match a min/max vector operation.
20818 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20819 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20820 unsigned Opc = ret.first;
20821 bool NeedSplit = ret.second;
20823 if (Opc && NeedSplit) {
20824 unsigned NumElems = VT.getVectorNumElements();
20825 // Extract the LHS vectors
20826 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20827 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20829 // Extract the RHS vectors
20830 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20831 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20833 // Create min/max for each subvector
20834 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20835 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20837 // Merge the result
20838 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20840 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20843 // Simplify vector selection if condition value type matches vselect
20845 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20846 assert(Cond.getValueType().isVector() &&
20847 "vector select expects a vector selector!");
20849 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20850 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20852 // Try invert the condition if true value is not all 1s and false value
20854 if (!TValIsAllOnes && !FValIsAllZeros &&
20855 // Check if the selector will be produced by CMPP*/PCMP*
20856 Cond.getOpcode() == ISD::SETCC &&
20857 // Check if SETCC has already been promoted
20858 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20859 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20860 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20862 if (TValIsAllZeros || FValIsAllOnes) {
20863 SDValue CC = Cond.getOperand(2);
20864 ISD::CondCode NewCC =
20865 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20866 Cond.getOperand(0).getValueType().isInteger());
20867 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20868 std::swap(LHS, RHS);
20869 TValIsAllOnes = FValIsAllOnes;
20870 FValIsAllZeros = TValIsAllZeros;
20874 if (TValIsAllOnes || FValIsAllZeros) {
20877 if (TValIsAllOnes && FValIsAllZeros)
20879 else if (TValIsAllOnes)
20880 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20881 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20882 else if (FValIsAllZeros)
20883 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20884 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20886 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20890 // We should generate an X86ISD::BLENDI from a vselect if its argument
20891 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20892 // constants. This specific pattern gets generated when we split a
20893 // selector for a 512 bit vector in a machine without AVX512 (but with
20894 // 256-bit vectors), during legalization:
20896 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20898 // Iff we find this pattern and the build_vectors are built from
20899 // constants, we translate the vselect into a shuffle_vector that we
20900 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20901 if ((N->getOpcode() == ISD::VSELECT ||
20902 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
20903 !DCI.isBeforeLegalize()) {
20904 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20905 if (Shuffle.getNode())
20909 // If this is a *dynamic* select (non-constant condition) and we can match
20910 // this node with one of the variable blend instructions, restructure the
20911 // condition so that the blends can use the high bit of each element and use
20912 // SimplifyDemandedBits to simplify the condition operand.
20913 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20914 !DCI.isBeforeLegalize() &&
20915 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
20916 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20918 // Don't optimize vector selects that map to mask-registers.
20922 // We can only handle the cases where VSELECT is directly legal on the
20923 // subtarget. We custom lower VSELECT nodes with constant conditions and
20924 // this makes it hard to see whether a dynamic VSELECT will correctly
20925 // lower, so we both check the operation's status and explicitly handle the
20926 // cases where a *dynamic* blend will fail even though a constant-condition
20927 // blend could be custom lowered.
20928 // FIXME: We should find a better way to handle this class of problems.
20929 // Potentially, we should combine constant-condition vselect nodes
20930 // pre-legalization into shuffles and not mark as many types as custom
20932 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
20934 // FIXME: We don't support i16-element blends currently. We could and
20935 // should support them by making *all* the bits in the condition be set
20936 // rather than just the high bit and using an i8-element blend.
20937 if (VT.getScalarType() == MVT::i16)
20939 // Dynamic blending was only available from SSE4.1 onward.
20940 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
20942 // Byte blends are only available in AVX2
20943 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
20944 !Subtarget->hasAVX2())
20947 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20948 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20950 APInt KnownZero, KnownOne;
20951 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20952 DCI.isBeforeLegalizeOps());
20953 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20954 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
20956 // If we changed the computation somewhere in the DAG, this change
20957 // will affect all users of Cond.
20958 // Make sure it is fine and update all the nodes so that we do not
20959 // use the generic VSELECT anymore. Otherwise, we may perform
20960 // wrong optimizations as we messed up with the actual expectation
20961 // for the vector boolean values.
20962 if (Cond != TLO.Old) {
20963 // Check all uses of that condition operand to check whether it will be
20964 // consumed by non-BLEND instructions, which may depend on all bits are
20966 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20968 if (I->getOpcode() != ISD::VSELECT)
20969 // TODO: Add other opcodes eventually lowered into BLEND.
20972 // Update all the users of the condition, before committing the change,
20973 // so that the VSELECT optimizations that expect the correct vector
20974 // boolean value will not be triggered.
20975 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20977 DAG.ReplaceAllUsesOfValueWith(
20979 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
20980 Cond, I->getOperand(1), I->getOperand(2)));
20981 DCI.CommitTargetLoweringOpt(TLO);
20984 // At this point, only Cond is changed. Change the condition
20985 // just for N to keep the opportunity to optimize all other
20986 // users their own way.
20987 DAG.ReplaceAllUsesOfValueWith(
20989 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
20990 TLO.New, N->getOperand(1), N->getOperand(2)));
20998 // Check whether a boolean test is testing a boolean value generated by
20999 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21002 // Simplify the following patterns:
21003 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21004 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21005 // to (Op EFLAGS Cond)
21007 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21008 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21009 // to (Op EFLAGS !Cond)
21011 // where Op could be BRCOND or CMOV.
21013 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21014 // Quit if not CMP and SUB with its value result used.
21015 if (Cmp.getOpcode() != X86ISD::CMP &&
21016 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21019 // Quit if not used as a boolean value.
21020 if (CC != X86::COND_E && CC != X86::COND_NE)
21023 // Check CMP operands. One of them should be 0 or 1 and the other should be
21024 // an SetCC or extended from it.
21025 SDValue Op1 = Cmp.getOperand(0);
21026 SDValue Op2 = Cmp.getOperand(1);
21029 const ConstantSDNode* C = nullptr;
21030 bool needOppositeCond = (CC == X86::COND_E);
21031 bool checkAgainstTrue = false; // Is it a comparison against 1?
21033 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21035 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21037 else // Quit if all operands are not constants.
21040 if (C->getZExtValue() == 1) {
21041 needOppositeCond = !needOppositeCond;
21042 checkAgainstTrue = true;
21043 } else if (C->getZExtValue() != 0)
21044 // Quit if the constant is neither 0 or 1.
21047 bool truncatedToBoolWithAnd = false;
21048 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21049 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21050 SetCC.getOpcode() == ISD::TRUNCATE ||
21051 SetCC.getOpcode() == ISD::AND) {
21052 if (SetCC.getOpcode() == ISD::AND) {
21054 ConstantSDNode *CS;
21055 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21056 CS->getZExtValue() == 1)
21058 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21059 CS->getZExtValue() == 1)
21063 SetCC = SetCC.getOperand(OpIdx);
21064 truncatedToBoolWithAnd = true;
21066 SetCC = SetCC.getOperand(0);
21069 switch (SetCC.getOpcode()) {
21070 case X86ISD::SETCC_CARRY:
21071 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21072 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21073 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21074 // truncated to i1 using 'and'.
21075 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21077 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21078 "Invalid use of SETCC_CARRY!");
21080 case X86ISD::SETCC:
21081 // Set the condition code or opposite one if necessary.
21082 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21083 if (needOppositeCond)
21084 CC = X86::GetOppositeBranchCondition(CC);
21085 return SetCC.getOperand(1);
21086 case X86ISD::CMOV: {
21087 // Check whether false/true value has canonical one, i.e. 0 or 1.
21088 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21089 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21090 // Quit if true value is not a constant.
21093 // Quit if false value is not a constant.
21095 SDValue Op = SetCC.getOperand(0);
21096 // Skip 'zext' or 'trunc' node.
21097 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21098 Op.getOpcode() == ISD::TRUNCATE)
21099 Op = Op.getOperand(0);
21100 // A special case for rdrand/rdseed, where 0 is set if false cond is
21102 if ((Op.getOpcode() != X86ISD::RDRAND &&
21103 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21106 // Quit if false value is not the constant 0 or 1.
21107 bool FValIsFalse = true;
21108 if (FVal && FVal->getZExtValue() != 0) {
21109 if (FVal->getZExtValue() != 1)
21111 // If FVal is 1, opposite cond is needed.
21112 needOppositeCond = !needOppositeCond;
21113 FValIsFalse = false;
21115 // Quit if TVal is not the constant opposite of FVal.
21116 if (FValIsFalse && TVal->getZExtValue() != 1)
21118 if (!FValIsFalse && TVal->getZExtValue() != 0)
21120 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21121 if (needOppositeCond)
21122 CC = X86::GetOppositeBranchCondition(CC);
21123 return SetCC.getOperand(3);
21130 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21132 /// (X86or (X86setcc) (X86setcc))
21133 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21134 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21135 X86::CondCode &CC1, SDValue &Flags,
21137 if (Cond->getOpcode() == X86ISD::CMP) {
21138 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21139 if (!CondOp1C || !CondOp1C->isNullValue())
21142 Cond = Cond->getOperand(0);
21147 SDValue SetCC0, SetCC1;
21148 switch (Cond->getOpcode()) {
21149 default: return false;
21156 SetCC0 = Cond->getOperand(0);
21157 SetCC1 = Cond->getOperand(1);
21161 // Make sure we have SETCC nodes, using the same flags value.
21162 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21163 SetCC1.getOpcode() != X86ISD::SETCC ||
21164 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21167 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21168 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21169 Flags = SetCC0->getOperand(1);
21173 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21174 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21175 TargetLowering::DAGCombinerInfo &DCI,
21176 const X86Subtarget *Subtarget) {
21179 // If the flag operand isn't dead, don't touch this CMOV.
21180 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21183 SDValue FalseOp = N->getOperand(0);
21184 SDValue TrueOp = N->getOperand(1);
21185 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21186 SDValue Cond = N->getOperand(3);
21188 if (CC == X86::COND_E || CC == X86::COND_NE) {
21189 switch (Cond.getOpcode()) {
21193 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21194 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21195 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21201 Flags = checkBoolTestSetCCCombine(Cond, CC);
21202 if (Flags.getNode() &&
21203 // Extra check as FCMOV only supports a subset of X86 cond.
21204 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21205 SDValue Ops[] = { FalseOp, TrueOp,
21206 DAG.getConstant(CC, MVT::i8), Flags };
21207 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21210 // If this is a select between two integer constants, try to do some
21211 // optimizations. Note that the operands are ordered the opposite of SELECT
21213 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21214 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21215 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21216 // larger than FalseC (the false value).
21217 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21218 CC = X86::GetOppositeBranchCondition(CC);
21219 std::swap(TrueC, FalseC);
21220 std::swap(TrueOp, FalseOp);
21223 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21224 // This is efficient for any integer data type (including i8/i16) and
21226 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21227 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21228 DAG.getConstant(CC, MVT::i8), Cond);
21230 // Zero extend the condition if needed.
21231 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21233 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21234 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21235 DAG.getConstant(ShAmt, MVT::i8));
21236 if (N->getNumValues() == 2) // Dead flag value?
21237 return DCI.CombineTo(N, Cond, SDValue());
21241 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21242 // for any integer data type, including i8/i16.
21243 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21244 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21245 DAG.getConstant(CC, MVT::i8), Cond);
21247 // Zero extend the condition if needed.
21248 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21249 FalseC->getValueType(0), Cond);
21250 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21251 SDValue(FalseC, 0));
21253 if (N->getNumValues() == 2) // Dead flag value?
21254 return DCI.CombineTo(N, Cond, SDValue());
21258 // Optimize cases that will turn into an LEA instruction. This requires
21259 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21260 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21261 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21262 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21264 bool isFastMultiplier = false;
21266 switch ((unsigned char)Diff) {
21268 case 1: // result = add base, cond
21269 case 2: // result = lea base( , cond*2)
21270 case 3: // result = lea base(cond, cond*2)
21271 case 4: // result = lea base( , cond*4)
21272 case 5: // result = lea base(cond, cond*4)
21273 case 8: // result = lea base( , cond*8)
21274 case 9: // result = lea base(cond, cond*8)
21275 isFastMultiplier = true;
21280 if (isFastMultiplier) {
21281 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21282 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21283 DAG.getConstant(CC, MVT::i8), Cond);
21284 // Zero extend the condition if needed.
21285 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21287 // Scale the condition by the difference.
21289 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21290 DAG.getConstant(Diff, Cond.getValueType()));
21292 // Add the base if non-zero.
21293 if (FalseC->getAPIntValue() != 0)
21294 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21295 SDValue(FalseC, 0));
21296 if (N->getNumValues() == 2) // Dead flag value?
21297 return DCI.CombineTo(N, Cond, SDValue());
21304 // Handle these cases:
21305 // (select (x != c), e, c) -> select (x != c), e, x),
21306 // (select (x == c), c, e) -> select (x == c), x, e)
21307 // where the c is an integer constant, and the "select" is the combination
21308 // of CMOV and CMP.
21310 // The rationale for this change is that the conditional-move from a constant
21311 // needs two instructions, however, conditional-move from a register needs
21312 // only one instruction.
21314 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21315 // some instruction-combining opportunities. This opt needs to be
21316 // postponed as late as possible.
21318 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21319 // the DCI.xxxx conditions are provided to postpone the optimization as
21320 // late as possible.
21322 ConstantSDNode *CmpAgainst = nullptr;
21323 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21324 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21325 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21327 if (CC == X86::COND_NE &&
21328 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21329 CC = X86::GetOppositeBranchCondition(CC);
21330 std::swap(TrueOp, FalseOp);
21333 if (CC == X86::COND_E &&
21334 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21335 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21336 DAG.getConstant(CC, MVT::i8), Cond };
21337 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21342 // Fold and/or of setcc's to double CMOV:
21343 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21344 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21346 // This combine lets us generate:
21347 // cmovcc1 (jcc1 if we don't have CMOV)
21353 // cmovne (jne if we don't have CMOV)
21354 // When we can't use the CMOV instruction, it might increase branch
21356 // When we can use CMOV, or when there is no mispredict, this improves
21357 // throughput and reduces register pressure.
21359 if (CC == X86::COND_NE) {
21361 X86::CondCode CC0, CC1;
21363 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21365 std::swap(FalseOp, TrueOp);
21366 CC0 = X86::GetOppositeBranchCondition(CC0);
21367 CC1 = X86::GetOppositeBranchCondition(CC1);
21370 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21372 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21373 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21374 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21375 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21383 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21384 const X86Subtarget *Subtarget) {
21385 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21387 default: return SDValue();
21388 // SSE/AVX/AVX2 blend intrinsics.
21389 case Intrinsic::x86_avx2_pblendvb:
21390 // Don't try to simplify this intrinsic if we don't have AVX2.
21391 if (!Subtarget->hasAVX2())
21394 case Intrinsic::x86_avx_blendv_pd_256:
21395 case Intrinsic::x86_avx_blendv_ps_256:
21396 // Don't try to simplify this intrinsic if we don't have AVX.
21397 if (!Subtarget->hasAVX())
21400 case Intrinsic::x86_sse41_blendvps:
21401 case Intrinsic::x86_sse41_blendvpd:
21402 case Intrinsic::x86_sse41_pblendvb: {
21403 SDValue Op0 = N->getOperand(1);
21404 SDValue Op1 = N->getOperand(2);
21405 SDValue Mask = N->getOperand(3);
21407 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21408 if (!Subtarget->hasSSE41())
21411 // fold (blend A, A, Mask) -> A
21414 // fold (blend A, B, allZeros) -> A
21415 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21417 // fold (blend A, B, allOnes) -> B
21418 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21421 // Simplify the case where the mask is a constant i32 value.
21422 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21423 if (C->isNullValue())
21425 if (C->isAllOnesValue())
21432 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21433 case Intrinsic::x86_sse2_psrai_w:
21434 case Intrinsic::x86_sse2_psrai_d:
21435 case Intrinsic::x86_avx2_psrai_w:
21436 case Intrinsic::x86_avx2_psrai_d:
21437 case Intrinsic::x86_sse2_psra_w:
21438 case Intrinsic::x86_sse2_psra_d:
21439 case Intrinsic::x86_avx2_psra_w:
21440 case Intrinsic::x86_avx2_psra_d: {
21441 SDValue Op0 = N->getOperand(1);
21442 SDValue Op1 = N->getOperand(2);
21443 EVT VT = Op0.getValueType();
21444 assert(VT.isVector() && "Expected a vector type!");
21446 if (isa<BuildVectorSDNode>(Op1))
21447 Op1 = Op1.getOperand(0);
21449 if (!isa<ConstantSDNode>(Op1))
21452 EVT SVT = VT.getVectorElementType();
21453 unsigned SVTBits = SVT.getSizeInBits();
21455 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21456 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21457 uint64_t ShAmt = C.getZExtValue();
21459 // Don't try to convert this shift into a ISD::SRA if the shift
21460 // count is bigger than or equal to the element size.
21461 if (ShAmt >= SVTBits)
21464 // Trivial case: if the shift count is zero, then fold this
21465 // into the first operand.
21469 // Replace this packed shift intrinsic with a target independent
21471 SDValue Splat = DAG.getConstant(C, VT);
21472 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21477 /// PerformMulCombine - Optimize a single multiply with constant into two
21478 /// in order to implement it with two cheaper instructions, e.g.
21479 /// LEA + SHL, LEA + LEA.
21480 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21481 TargetLowering::DAGCombinerInfo &DCI) {
21482 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21485 EVT VT = N->getValueType(0);
21486 if (VT != MVT::i64 && VT != MVT::i32)
21489 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21492 uint64_t MulAmt = C->getZExtValue();
21493 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21496 uint64_t MulAmt1 = 0;
21497 uint64_t MulAmt2 = 0;
21498 if ((MulAmt % 9) == 0) {
21500 MulAmt2 = MulAmt / 9;
21501 } else if ((MulAmt % 5) == 0) {
21503 MulAmt2 = MulAmt / 5;
21504 } else if ((MulAmt % 3) == 0) {
21506 MulAmt2 = MulAmt / 3;
21509 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21512 if (isPowerOf2_64(MulAmt2) &&
21513 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21514 // If second multiplifer is pow2, issue it first. We want the multiply by
21515 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21517 std::swap(MulAmt1, MulAmt2);
21520 if (isPowerOf2_64(MulAmt1))
21521 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21522 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21524 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21525 DAG.getConstant(MulAmt1, VT));
21527 if (isPowerOf2_64(MulAmt2))
21528 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21529 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21531 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21532 DAG.getConstant(MulAmt2, VT));
21534 // Do not add new nodes to DAG combiner worklist.
21535 DCI.CombineTo(N, NewMul, false);
21540 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21541 SDValue N0 = N->getOperand(0);
21542 SDValue N1 = N->getOperand(1);
21543 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21544 EVT VT = N0.getValueType();
21546 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21547 // since the result of setcc_c is all zero's or all ones.
21548 if (VT.isInteger() && !VT.isVector() &&
21549 N1C && N0.getOpcode() == ISD::AND &&
21550 N0.getOperand(1).getOpcode() == ISD::Constant) {
21551 SDValue N00 = N0.getOperand(0);
21552 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21553 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21554 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21555 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21556 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21557 APInt ShAmt = N1C->getAPIntValue();
21558 Mask = Mask.shl(ShAmt);
21560 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21561 N00, DAG.getConstant(Mask, VT));
21565 // Hardware support for vector shifts is sparse which makes us scalarize the
21566 // vector operations in many cases. Also, on sandybridge ADD is faster than
21568 // (shl V, 1) -> add V,V
21569 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21570 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21571 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21572 // We shift all of the values by one. In many cases we do not have
21573 // hardware support for this operation. This is better expressed as an ADD
21575 if (N1SplatC->getZExtValue() == 1)
21576 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21582 /// \brief Returns a vector of 0s if the node in input is a vector logical
21583 /// shift by a constant amount which is known to be bigger than or equal
21584 /// to the vector element size in bits.
21585 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21586 const X86Subtarget *Subtarget) {
21587 EVT VT = N->getValueType(0);
21589 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21590 (!Subtarget->hasInt256() ||
21591 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21594 SDValue Amt = N->getOperand(1);
21596 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21597 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21598 APInt ShiftAmt = AmtSplat->getAPIntValue();
21599 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21601 // SSE2/AVX2 logical shifts always return a vector of 0s
21602 // if the shift amount is bigger than or equal to
21603 // the element size. The constant shift amount will be
21604 // encoded as a 8-bit immediate.
21605 if (ShiftAmt.trunc(8).uge(MaxAmount))
21606 return getZeroVector(VT, Subtarget, DAG, DL);
21612 /// PerformShiftCombine - Combine shifts.
21613 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21614 TargetLowering::DAGCombinerInfo &DCI,
21615 const X86Subtarget *Subtarget) {
21616 if (N->getOpcode() == ISD::SHL) {
21617 SDValue V = PerformSHLCombine(N, DAG);
21618 if (V.getNode()) return V;
21621 if (N->getOpcode() != ISD::SRA) {
21622 // Try to fold this logical shift into a zero vector.
21623 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21624 if (V.getNode()) return V;
21630 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21631 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21632 // and friends. Likewise for OR -> CMPNEQSS.
21633 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21634 TargetLowering::DAGCombinerInfo &DCI,
21635 const X86Subtarget *Subtarget) {
21638 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21639 // we're requiring SSE2 for both.
21640 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21641 SDValue N0 = N->getOperand(0);
21642 SDValue N1 = N->getOperand(1);
21643 SDValue CMP0 = N0->getOperand(1);
21644 SDValue CMP1 = N1->getOperand(1);
21647 // The SETCCs should both refer to the same CMP.
21648 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21651 SDValue CMP00 = CMP0->getOperand(0);
21652 SDValue CMP01 = CMP0->getOperand(1);
21653 EVT VT = CMP00.getValueType();
21655 if (VT == MVT::f32 || VT == MVT::f64) {
21656 bool ExpectingFlags = false;
21657 // Check for any users that want flags:
21658 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21659 !ExpectingFlags && UI != UE; ++UI)
21660 switch (UI->getOpcode()) {
21665 ExpectingFlags = true;
21667 case ISD::CopyToReg:
21668 case ISD::SIGN_EXTEND:
21669 case ISD::ZERO_EXTEND:
21670 case ISD::ANY_EXTEND:
21674 if (!ExpectingFlags) {
21675 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21676 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21678 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21679 X86::CondCode tmp = cc0;
21684 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21685 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21686 // FIXME: need symbolic constants for these magic numbers.
21687 // See X86ATTInstPrinter.cpp:printSSECC().
21688 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21689 if (Subtarget->hasAVX512()) {
21690 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21691 CMP01, DAG.getConstant(x86cc, MVT::i8));
21692 if (N->getValueType(0) != MVT::i1)
21693 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21697 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21698 CMP00.getValueType(), CMP00, CMP01,
21699 DAG.getConstant(x86cc, MVT::i8));
21701 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21702 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21704 if (is64BitFP && !Subtarget->is64Bit()) {
21705 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21706 // 64-bit integer, since that's not a legal type. Since
21707 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21708 // bits, but can do this little dance to extract the lowest 32 bits
21709 // and work with those going forward.
21710 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21712 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21714 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21715 Vector32, DAG.getIntPtrConstant(0));
21719 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21720 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21721 DAG.getConstant(1, IntVT));
21722 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21723 return OneBitOfTruth;
21731 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21732 /// so it can be folded inside ANDNP.
21733 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21734 EVT VT = N->getValueType(0);
21736 // Match direct AllOnes for 128 and 256-bit vectors
21737 if (ISD::isBuildVectorAllOnes(N))
21740 // Look through a bit convert.
21741 if (N->getOpcode() == ISD::BITCAST)
21742 N = N->getOperand(0).getNode();
21744 // Sometimes the operand may come from a insert_subvector building a 256-bit
21746 if (VT.is256BitVector() &&
21747 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21748 SDValue V1 = N->getOperand(0);
21749 SDValue V2 = N->getOperand(1);
21751 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21752 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21753 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21754 ISD::isBuildVectorAllOnes(V2.getNode()))
21761 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21762 // register. In most cases we actually compare or select YMM-sized registers
21763 // and mixing the two types creates horrible code. This method optimizes
21764 // some of the transition sequences.
21765 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21766 TargetLowering::DAGCombinerInfo &DCI,
21767 const X86Subtarget *Subtarget) {
21768 EVT VT = N->getValueType(0);
21769 if (!VT.is256BitVector())
21772 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21773 N->getOpcode() == ISD::ZERO_EXTEND ||
21774 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21776 SDValue Narrow = N->getOperand(0);
21777 EVT NarrowVT = Narrow->getValueType(0);
21778 if (!NarrowVT.is128BitVector())
21781 if (Narrow->getOpcode() != ISD::XOR &&
21782 Narrow->getOpcode() != ISD::AND &&
21783 Narrow->getOpcode() != ISD::OR)
21786 SDValue N0 = Narrow->getOperand(0);
21787 SDValue N1 = Narrow->getOperand(1);
21790 // The Left side has to be a trunc.
21791 if (N0.getOpcode() != ISD::TRUNCATE)
21794 // The type of the truncated inputs.
21795 EVT WideVT = N0->getOperand(0)->getValueType(0);
21799 // The right side has to be a 'trunc' or a constant vector.
21800 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21801 ConstantSDNode *RHSConstSplat = nullptr;
21802 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21803 RHSConstSplat = RHSBV->getConstantSplatNode();
21804 if (!RHSTrunc && !RHSConstSplat)
21807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21809 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21812 // Set N0 and N1 to hold the inputs to the new wide operation.
21813 N0 = N0->getOperand(0);
21814 if (RHSConstSplat) {
21815 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21816 SDValue(RHSConstSplat, 0));
21817 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21818 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21819 } else if (RHSTrunc) {
21820 N1 = N1->getOperand(0);
21823 // Generate the wide operation.
21824 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21825 unsigned Opcode = N->getOpcode();
21827 case ISD::ANY_EXTEND:
21829 case ISD::ZERO_EXTEND: {
21830 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21831 APInt Mask = APInt::getAllOnesValue(InBits);
21832 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21833 return DAG.getNode(ISD::AND, DL, VT,
21834 Op, DAG.getConstant(Mask, VT));
21836 case ISD::SIGN_EXTEND:
21837 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21838 Op, DAG.getValueType(NarrowVT));
21840 llvm_unreachable("Unexpected opcode");
21844 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21845 TargetLowering::DAGCombinerInfo &DCI,
21846 const X86Subtarget *Subtarget) {
21847 SDValue N0 = N->getOperand(0);
21848 SDValue N1 = N->getOperand(1);
21851 // A vector zext_in_reg may be represented as a shuffle,
21852 // feeding into a bitcast (this represents anyext) feeding into
21853 // an and with a mask.
21854 // We'd like to try to combine that into a shuffle with zero
21855 // plus a bitcast, removing the and.
21856 if (N0.getOpcode() != ISD::BITCAST ||
21857 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21860 // The other side of the AND should be a splat of 2^C, where C
21861 // is the number of bits in the source type.
21862 if (N1.getOpcode() == ISD::BITCAST)
21863 N1 = N1.getOperand(0);
21864 if (N1.getOpcode() != ISD::BUILD_VECTOR)
21866 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21868 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21869 EVT SrcType = Shuffle->getValueType(0);
21871 // We expect a single-source shuffle
21872 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21875 unsigned SrcSize = SrcType.getScalarSizeInBits();
21877 APInt SplatValue, SplatUndef;
21878 unsigned SplatBitSize;
21880 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21881 SplatBitSize, HasAnyUndefs))
21884 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21885 // Make sure the splat matches the mask we expect
21886 if (SplatBitSize > ResSize ||
21887 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21890 // Make sure the input and output size make sense
21891 if (SrcSize >= ResSize || ResSize % SrcSize)
21894 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
21895 // The number of u's between each two values depends on the ratio between
21896 // the source and dest type.
21897 unsigned ZextRatio = ResSize / SrcSize;
21898 bool IsZext = true;
21899 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
21900 if (i % ZextRatio) {
21901 if (Shuffle->getMaskElt(i) > 0) {
21907 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
21908 // Expected element number
21918 // Ok, perform the transformation - replace the shuffle with
21919 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
21920 // (instead of undef) where the k elements come from the zero vector.
21921 SmallVector<int, 8> Mask;
21922 unsigned NumElems = SrcType.getVectorNumElements();
21923 for (unsigned i = 0; i < NumElems; ++i)
21925 Mask.push_back(NumElems);
21927 Mask.push_back(i / ZextRatio);
21929 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
21930 Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
21931 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
21934 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21935 TargetLowering::DAGCombinerInfo &DCI,
21936 const X86Subtarget *Subtarget) {
21937 if (DCI.isBeforeLegalizeOps())
21940 SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget);
21941 if (Zext.getNode())
21944 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21948 EVT VT = N->getValueType(0);
21949 SDValue N0 = N->getOperand(0);
21950 SDValue N1 = N->getOperand(1);
21953 // Create BEXTR instructions
21954 // BEXTR is ((X >> imm) & (2**size-1))
21955 if (VT == MVT::i32 || VT == MVT::i64) {
21956 // Check for BEXTR.
21957 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21958 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21959 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21960 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21961 if (MaskNode && ShiftNode) {
21962 uint64_t Mask = MaskNode->getZExtValue();
21963 uint64_t Shift = ShiftNode->getZExtValue();
21964 if (isMask_64(Mask)) {
21965 uint64_t MaskSize = countPopulation(Mask);
21966 if (Shift + MaskSize <= VT.getSizeInBits())
21967 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21968 DAG.getConstant(Shift | (MaskSize << 8), VT));
21976 // Want to form ANDNP nodes:
21977 // 1) In the hopes of then easily combining them with OR and AND nodes
21978 // to form PBLEND/PSIGN.
21979 // 2) To match ANDN packed intrinsics
21980 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21983 // Check LHS for vnot
21984 if (N0.getOpcode() == ISD::XOR &&
21985 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21986 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21987 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21989 // Check RHS for vnot
21990 if (N1.getOpcode() == ISD::XOR &&
21991 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21992 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21993 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21998 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21999 TargetLowering::DAGCombinerInfo &DCI,
22000 const X86Subtarget *Subtarget) {
22001 if (DCI.isBeforeLegalizeOps())
22004 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22008 SDValue N0 = N->getOperand(0);
22009 SDValue N1 = N->getOperand(1);
22010 EVT VT = N->getValueType(0);
22012 // look for psign/blend
22013 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22014 if (!Subtarget->hasSSSE3() ||
22015 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22018 // Canonicalize pandn to RHS
22019 if (N0.getOpcode() == X86ISD::ANDNP)
22021 // or (and (m, y), (pandn m, x))
22022 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22023 SDValue Mask = N1.getOperand(0);
22024 SDValue X = N1.getOperand(1);
22026 if (N0.getOperand(0) == Mask)
22027 Y = N0.getOperand(1);
22028 if (N0.getOperand(1) == Mask)
22029 Y = N0.getOperand(0);
22031 // Check to see if the mask appeared in both the AND and ANDNP and
22035 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22036 // Look through mask bitcast.
22037 if (Mask.getOpcode() == ISD::BITCAST)
22038 Mask = Mask.getOperand(0);
22039 if (X.getOpcode() == ISD::BITCAST)
22040 X = X.getOperand(0);
22041 if (Y.getOpcode() == ISD::BITCAST)
22042 Y = Y.getOperand(0);
22044 EVT MaskVT = Mask.getValueType();
22046 // Validate that the Mask operand is a vector sra node.
22047 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22048 // there is no psrai.b
22049 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22050 unsigned SraAmt = ~0;
22051 if (Mask.getOpcode() == ISD::SRA) {
22052 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22053 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22054 SraAmt = AmtConst->getZExtValue();
22055 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22056 SDValue SraC = Mask.getOperand(1);
22057 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22059 if ((SraAmt + 1) != EltBits)
22064 // Now we know we at least have a plendvb with the mask val. See if
22065 // we can form a psignb/w/d.
22066 // psign = x.type == y.type == mask.type && y = sub(0, x);
22067 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22068 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22069 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22070 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22071 "Unsupported VT for PSIGN");
22072 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22073 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22075 // PBLENDVB only available on SSE 4.1
22076 if (!Subtarget->hasSSE41())
22079 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22081 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22082 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22083 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22084 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22085 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22089 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22092 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22093 MachineFunction &MF = DAG.getMachineFunction();
22095 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22097 // SHLD/SHRD instructions have lower register pressure, but on some
22098 // platforms they have higher latency than the equivalent
22099 // series of shifts/or that would otherwise be generated.
22100 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22101 // have higher latencies and we are not optimizing for size.
22102 if (!OptForSize && Subtarget->isSHLDSlow())
22105 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22107 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22109 if (!N0.hasOneUse() || !N1.hasOneUse())
22112 SDValue ShAmt0 = N0.getOperand(1);
22113 if (ShAmt0.getValueType() != MVT::i8)
22115 SDValue ShAmt1 = N1.getOperand(1);
22116 if (ShAmt1.getValueType() != MVT::i8)
22118 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22119 ShAmt0 = ShAmt0.getOperand(0);
22120 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22121 ShAmt1 = ShAmt1.getOperand(0);
22124 unsigned Opc = X86ISD::SHLD;
22125 SDValue Op0 = N0.getOperand(0);
22126 SDValue Op1 = N1.getOperand(0);
22127 if (ShAmt0.getOpcode() == ISD::SUB) {
22128 Opc = X86ISD::SHRD;
22129 std::swap(Op0, Op1);
22130 std::swap(ShAmt0, ShAmt1);
22133 unsigned Bits = VT.getSizeInBits();
22134 if (ShAmt1.getOpcode() == ISD::SUB) {
22135 SDValue Sum = ShAmt1.getOperand(0);
22136 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22137 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22138 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22139 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22140 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22141 return DAG.getNode(Opc, DL, VT,
22143 DAG.getNode(ISD::TRUNCATE, DL,
22146 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22147 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22149 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22150 return DAG.getNode(Opc, DL, VT,
22151 N0.getOperand(0), N1.getOperand(0),
22152 DAG.getNode(ISD::TRUNCATE, DL,
22159 // Generate NEG and CMOV for integer abs.
22160 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22161 EVT VT = N->getValueType(0);
22163 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22164 // 8-bit integer abs to NEG and CMOV.
22165 if (VT.isInteger() && VT.getSizeInBits() == 8)
22168 SDValue N0 = N->getOperand(0);
22169 SDValue N1 = N->getOperand(1);
22172 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22173 // and change it to SUB and CMOV.
22174 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22175 N0.getOpcode() == ISD::ADD &&
22176 N0.getOperand(1) == N1 &&
22177 N1.getOpcode() == ISD::SRA &&
22178 N1.getOperand(0) == N0.getOperand(0))
22179 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22180 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22181 // Generate SUB & CMOV.
22182 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22183 DAG.getConstant(0, VT), N0.getOperand(0));
22185 SDValue Ops[] = { N0.getOperand(0), Neg,
22186 DAG.getConstant(X86::COND_GE, MVT::i8),
22187 SDValue(Neg.getNode(), 1) };
22188 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22193 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22194 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22195 TargetLowering::DAGCombinerInfo &DCI,
22196 const X86Subtarget *Subtarget) {
22197 if (DCI.isBeforeLegalizeOps())
22200 if (Subtarget->hasCMov()) {
22201 SDValue RV = performIntegerAbsCombine(N, DAG);
22209 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22210 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22211 TargetLowering::DAGCombinerInfo &DCI,
22212 const X86Subtarget *Subtarget) {
22213 LoadSDNode *Ld = cast<LoadSDNode>(N);
22214 EVT RegVT = Ld->getValueType(0);
22215 EVT MemVT = Ld->getMemoryVT();
22217 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22219 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22220 // into two 16-byte operations.
22221 ISD::LoadExtType Ext = Ld->getExtensionType();
22222 unsigned Alignment = Ld->getAlignment();
22223 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22224 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22225 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22226 unsigned NumElems = RegVT.getVectorNumElements();
22230 SDValue Ptr = Ld->getBasePtr();
22231 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22233 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22235 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22236 Ld->getPointerInfo(), Ld->isVolatile(),
22237 Ld->isNonTemporal(), Ld->isInvariant(),
22239 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22240 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22241 Ld->getPointerInfo(), Ld->isVolatile(),
22242 Ld->isNonTemporal(), Ld->isInvariant(),
22243 std::min(16U, Alignment));
22244 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22246 Load2.getValue(1));
22248 SDValue NewVec = DAG.getUNDEF(RegVT);
22249 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22250 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22251 return DCI.CombineTo(N, NewVec, TF, true);
22257 /// PerformMLOADCombine - Resolve extending loads
22258 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22259 TargetLowering::DAGCombinerInfo &DCI,
22260 const X86Subtarget *Subtarget) {
22261 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22262 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22265 EVT VT = Mld->getValueType(0);
22266 unsigned NumElems = VT.getVectorNumElements();
22267 EVT LdVT = Mld->getMemoryVT();
22270 assert(LdVT != VT && "Cannot extend to the same type");
22271 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22272 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22273 // From, To sizes and ElemCount must be pow of two
22274 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22275 "Unexpected size for extending masked load");
22277 unsigned SizeRatio = ToSz / FromSz;
22278 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22280 // Create a type on which we perform the shuffle
22281 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22282 LdVT.getScalarType(), NumElems*SizeRatio);
22283 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22285 // Convert Src0 value
22286 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22287 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22288 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22289 for (unsigned i = 0; i != NumElems; ++i)
22290 ShuffleVec[i] = i * SizeRatio;
22292 // Can't shuffle using an illegal type.
22293 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22294 && "WideVecVT should be legal");
22295 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22296 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22298 // Prepare the new mask
22300 SDValue Mask = Mld->getMask();
22301 if (Mask.getValueType() == VT) {
22302 // Mask and original value have the same type
22303 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22304 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22305 for (unsigned i = 0; i != NumElems; ++i)
22306 ShuffleVec[i] = i * SizeRatio;
22307 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22308 ShuffleVec[i] = NumElems*SizeRatio;
22309 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22310 DAG.getConstant(0, WideVecVT),
22314 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22315 unsigned WidenNumElts = NumElems*SizeRatio;
22316 unsigned MaskNumElts = VT.getVectorNumElements();
22317 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22320 unsigned NumConcat = WidenNumElts / MaskNumElts;
22321 SmallVector<SDValue, 16> Ops(NumConcat);
22322 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22324 for (unsigned i = 1; i != NumConcat; ++i)
22327 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22330 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22331 Mld->getBasePtr(), NewMask, WideSrc0,
22332 Mld->getMemoryVT(), Mld->getMemOperand(),
22334 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22335 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22338 /// PerformMSTORECombine - Resolve truncating stores
22339 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22340 const X86Subtarget *Subtarget) {
22341 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22342 if (!Mst->isTruncatingStore())
22345 EVT VT = Mst->getValue().getValueType();
22346 unsigned NumElems = VT.getVectorNumElements();
22347 EVT StVT = Mst->getMemoryVT();
22350 assert(StVT != VT && "Cannot truncate to the same type");
22351 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22352 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22354 // From, To sizes and ElemCount must be pow of two
22355 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22356 "Unexpected size for truncating masked store");
22357 // We are going to use the original vector elt for storing.
22358 // Accumulated smaller vector elements must be a multiple of the store size.
22359 assert (((NumElems * FromSz) % ToSz) == 0 &&
22360 "Unexpected ratio for truncating masked store");
22362 unsigned SizeRatio = FromSz / ToSz;
22363 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22365 // Create a type on which we perform the shuffle
22366 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22367 StVT.getScalarType(), NumElems*SizeRatio);
22369 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22371 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22372 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22373 for (unsigned i = 0; i != NumElems; ++i)
22374 ShuffleVec[i] = i * SizeRatio;
22376 // Can't shuffle using an illegal type.
22377 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22378 && "WideVecVT should be legal");
22380 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22381 DAG.getUNDEF(WideVecVT),
22385 SDValue Mask = Mst->getMask();
22386 if (Mask.getValueType() == VT) {
22387 // Mask and original value have the same type
22388 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22389 for (unsigned i = 0; i != NumElems; ++i)
22390 ShuffleVec[i] = i * SizeRatio;
22391 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22392 ShuffleVec[i] = NumElems*SizeRatio;
22393 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22394 DAG.getConstant(0, WideVecVT),
22398 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22399 unsigned WidenNumElts = NumElems*SizeRatio;
22400 unsigned MaskNumElts = VT.getVectorNumElements();
22401 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22404 unsigned NumConcat = WidenNumElts / MaskNumElts;
22405 SmallVector<SDValue, 16> Ops(NumConcat);
22406 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22408 for (unsigned i = 1; i != NumConcat; ++i)
22411 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22414 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22415 NewMask, StVT, Mst->getMemOperand(), false);
22417 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22418 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22419 const X86Subtarget *Subtarget) {
22420 StoreSDNode *St = cast<StoreSDNode>(N);
22421 EVT VT = St->getValue().getValueType();
22422 EVT StVT = St->getMemoryVT();
22424 SDValue StoredVal = St->getOperand(1);
22425 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22427 // If we are saving a concatenation of two XMM registers and 32-byte stores
22428 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22429 unsigned Alignment = St->getAlignment();
22430 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22431 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22432 StVT == VT && !IsAligned) {
22433 unsigned NumElems = VT.getVectorNumElements();
22437 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22438 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22440 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22441 SDValue Ptr0 = St->getBasePtr();
22442 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22444 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22445 St->getPointerInfo(), St->isVolatile(),
22446 St->isNonTemporal(), Alignment);
22447 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22448 St->getPointerInfo(), St->isVolatile(),
22449 St->isNonTemporal(),
22450 std::min(16U, Alignment));
22451 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22454 // Optimize trunc store (of multiple scalars) to shuffle and store.
22455 // First, pack all of the elements in one place. Next, store to memory
22456 // in fewer chunks.
22457 if (St->isTruncatingStore() && VT.isVector()) {
22458 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22459 unsigned NumElems = VT.getVectorNumElements();
22460 assert(StVT != VT && "Cannot truncate to the same type");
22461 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22462 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22464 // From, To sizes and ElemCount must be pow of two
22465 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22466 // We are going to use the original vector elt for storing.
22467 // Accumulated smaller vector elements must be a multiple of the store size.
22468 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22470 unsigned SizeRatio = FromSz / ToSz;
22472 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22474 // Create a type on which we perform the shuffle
22475 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22476 StVT.getScalarType(), NumElems*SizeRatio);
22478 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22480 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22481 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22482 for (unsigned i = 0; i != NumElems; ++i)
22483 ShuffleVec[i] = i * SizeRatio;
22485 // Can't shuffle using an illegal type.
22486 if (!TLI.isTypeLegal(WideVecVT))
22489 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22490 DAG.getUNDEF(WideVecVT),
22492 // At this point all of the data is stored at the bottom of the
22493 // register. We now need to save it to mem.
22495 // Find the largest store unit
22496 MVT StoreType = MVT::i8;
22497 for (MVT Tp : MVT::integer_valuetypes()) {
22498 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22502 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22503 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22504 (64 <= NumElems * ToSz))
22505 StoreType = MVT::f64;
22507 // Bitcast the original vector into a vector of store-size units
22508 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22509 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22510 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22511 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22512 SmallVector<SDValue, 8> Chains;
22513 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22514 TLI.getPointerTy());
22515 SDValue Ptr = St->getBasePtr();
22517 // Perform one or more big stores into memory.
22518 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22519 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22520 StoreType, ShuffWide,
22521 DAG.getIntPtrConstant(i));
22522 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22523 St->getPointerInfo(), St->isVolatile(),
22524 St->isNonTemporal(), St->getAlignment());
22525 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22526 Chains.push_back(Ch);
22529 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22532 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
22533 // the FP state in cases where an emms may be missing.
22534 // A preferable solution to the general problem is to figure out the right
22535 // places to insert EMMS. This qualifies as a quick hack.
22537 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22538 if (VT.getSizeInBits() != 64)
22541 const Function *F = DAG.getMachineFunction().getFunction();
22542 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22543 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22544 && Subtarget->hasSSE2();
22545 if ((VT.isVector() ||
22546 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22547 isa<LoadSDNode>(St->getValue()) &&
22548 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22549 St->getChain().hasOneUse() && !St->isVolatile()) {
22550 SDNode* LdVal = St->getValue().getNode();
22551 LoadSDNode *Ld = nullptr;
22552 int TokenFactorIndex = -1;
22553 SmallVector<SDValue, 8> Ops;
22554 SDNode* ChainVal = St->getChain().getNode();
22555 // Must be a store of a load. We currently handle two cases: the load
22556 // is a direct child, and it's under an intervening TokenFactor. It is
22557 // possible to dig deeper under nested TokenFactors.
22558 if (ChainVal == LdVal)
22559 Ld = cast<LoadSDNode>(St->getChain());
22560 else if (St->getValue().hasOneUse() &&
22561 ChainVal->getOpcode() == ISD::TokenFactor) {
22562 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22563 if (ChainVal->getOperand(i).getNode() == LdVal) {
22564 TokenFactorIndex = i;
22565 Ld = cast<LoadSDNode>(St->getValue());
22567 Ops.push_back(ChainVal->getOperand(i));
22571 if (!Ld || !ISD::isNormalLoad(Ld))
22574 // If this is not the MMX case, i.e. we are just turning i64 load/store
22575 // into f64 load/store, avoid the transformation if there are multiple
22576 // uses of the loaded value.
22577 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22582 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22583 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22585 if (Subtarget->is64Bit() || F64IsLegal) {
22586 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22587 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22588 Ld->getPointerInfo(), Ld->isVolatile(),
22589 Ld->isNonTemporal(), Ld->isInvariant(),
22590 Ld->getAlignment());
22591 SDValue NewChain = NewLd.getValue(1);
22592 if (TokenFactorIndex != -1) {
22593 Ops.push_back(NewChain);
22594 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22596 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22597 St->getPointerInfo(),
22598 St->isVolatile(), St->isNonTemporal(),
22599 St->getAlignment());
22602 // Otherwise, lower to two pairs of 32-bit loads / stores.
22603 SDValue LoAddr = Ld->getBasePtr();
22604 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22605 DAG.getConstant(4, MVT::i32));
22607 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22608 Ld->getPointerInfo(),
22609 Ld->isVolatile(), Ld->isNonTemporal(),
22610 Ld->isInvariant(), Ld->getAlignment());
22611 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22612 Ld->getPointerInfo().getWithOffset(4),
22613 Ld->isVolatile(), Ld->isNonTemporal(),
22615 MinAlign(Ld->getAlignment(), 4));
22617 SDValue NewChain = LoLd.getValue(1);
22618 if (TokenFactorIndex != -1) {
22619 Ops.push_back(LoLd);
22620 Ops.push_back(HiLd);
22621 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22624 LoAddr = St->getBasePtr();
22625 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22626 DAG.getConstant(4, MVT::i32));
22628 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22629 St->getPointerInfo(),
22630 St->isVolatile(), St->isNonTemporal(),
22631 St->getAlignment());
22632 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22633 St->getPointerInfo().getWithOffset(4),
22635 St->isNonTemporal(),
22636 MinAlign(St->getAlignment(), 4));
22637 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22642 /// Return 'true' if this vector operation is "horizontal"
22643 /// and return the operands for the horizontal operation in LHS and RHS. A
22644 /// horizontal operation performs the binary operation on successive elements
22645 /// of its first operand, then on successive elements of its second operand,
22646 /// returning the resulting values in a vector. For example, if
22647 /// A = < float a0, float a1, float a2, float a3 >
22649 /// B = < float b0, float b1, float b2, float b3 >
22650 /// then the result of doing a horizontal operation on A and B is
22651 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22652 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22653 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22654 /// set to A, RHS to B, and the routine returns 'true'.
22655 /// Note that the binary operation should have the property that if one of the
22656 /// operands is UNDEF then the result is UNDEF.
22657 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22658 // Look for the following pattern: if
22659 // A = < float a0, float a1, float a2, float a3 >
22660 // B = < float b0, float b1, float b2, float b3 >
22662 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22663 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22664 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22665 // which is A horizontal-op B.
22667 // At least one of the operands should be a vector shuffle.
22668 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22669 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22672 MVT VT = LHS.getSimpleValueType();
22674 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22675 "Unsupported vector type for horizontal add/sub");
22677 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22678 // operate independently on 128-bit lanes.
22679 unsigned NumElts = VT.getVectorNumElements();
22680 unsigned NumLanes = VT.getSizeInBits()/128;
22681 unsigned NumLaneElts = NumElts / NumLanes;
22682 assert((NumLaneElts % 2 == 0) &&
22683 "Vector type should have an even number of elements in each lane");
22684 unsigned HalfLaneElts = NumLaneElts/2;
22686 // View LHS in the form
22687 // LHS = VECTOR_SHUFFLE A, B, LMask
22688 // If LHS is not a shuffle then pretend it is the shuffle
22689 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22690 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22693 SmallVector<int, 16> LMask(NumElts);
22694 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22695 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22696 A = LHS.getOperand(0);
22697 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22698 B = LHS.getOperand(1);
22699 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22700 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22702 if (LHS.getOpcode() != ISD::UNDEF)
22704 for (unsigned i = 0; i != NumElts; ++i)
22708 // Likewise, view RHS in the form
22709 // RHS = VECTOR_SHUFFLE C, D, RMask
22711 SmallVector<int, 16> RMask(NumElts);
22712 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22713 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22714 C = RHS.getOperand(0);
22715 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22716 D = RHS.getOperand(1);
22717 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22718 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22720 if (RHS.getOpcode() != ISD::UNDEF)
22722 for (unsigned i = 0; i != NumElts; ++i)
22726 // Check that the shuffles are both shuffling the same vectors.
22727 if (!(A == C && B == D) && !(A == D && B == C))
22730 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22731 if (!A.getNode() && !B.getNode())
22734 // If A and B occur in reverse order in RHS, then "swap" them (which means
22735 // rewriting the mask).
22737 CommuteVectorShuffleMask(RMask, NumElts);
22739 // At this point LHS and RHS are equivalent to
22740 // LHS = VECTOR_SHUFFLE A, B, LMask
22741 // RHS = VECTOR_SHUFFLE A, B, RMask
22742 // Check that the masks correspond to performing a horizontal operation.
22743 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22744 for (unsigned i = 0; i != NumLaneElts; ++i) {
22745 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22747 // Ignore any UNDEF components.
22748 if (LIdx < 0 || RIdx < 0 ||
22749 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22750 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22753 // Check that successive elements are being operated on. If not, this is
22754 // not a horizontal operation.
22755 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22756 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22757 if (!(LIdx == Index && RIdx == Index + 1) &&
22758 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22763 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22764 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22768 /// Do target-specific dag combines on floating point adds.
22769 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22770 const X86Subtarget *Subtarget) {
22771 EVT VT = N->getValueType(0);
22772 SDValue LHS = N->getOperand(0);
22773 SDValue RHS = N->getOperand(1);
22775 // Try to synthesize horizontal adds from adds of shuffles.
22776 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22777 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22778 isHorizontalBinOp(LHS, RHS, true))
22779 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22783 /// Do target-specific dag combines on floating point subs.
22784 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22785 const X86Subtarget *Subtarget) {
22786 EVT VT = N->getValueType(0);
22787 SDValue LHS = N->getOperand(0);
22788 SDValue RHS = N->getOperand(1);
22790 // Try to synthesize horizontal subs from subs of shuffles.
22791 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22792 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22793 isHorizontalBinOp(LHS, RHS, false))
22794 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22798 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22799 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22800 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22802 // F[X]OR(0.0, x) -> x
22803 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22804 if (C->getValueAPF().isPosZero())
22805 return N->getOperand(1);
22807 // F[X]OR(x, 0.0) -> x
22808 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22809 if (C->getValueAPF().isPosZero())
22810 return N->getOperand(0);
22814 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22815 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22816 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22818 // Only perform optimizations if UnsafeMath is used.
22819 if (!DAG.getTarget().Options.UnsafeFPMath)
22822 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22823 // into FMINC and FMAXC, which are Commutative operations.
22824 unsigned NewOp = 0;
22825 switch (N->getOpcode()) {
22826 default: llvm_unreachable("unknown opcode");
22827 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22828 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22831 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22832 N->getOperand(0), N->getOperand(1));
22835 /// Do target-specific dag combines on X86ISD::FAND nodes.
22836 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22837 // FAND(0.0, x) -> 0.0
22838 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22839 if (C->getValueAPF().isPosZero())
22840 return N->getOperand(0);
22842 // FAND(x, 0.0) -> 0.0
22843 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22844 if (C->getValueAPF().isPosZero())
22845 return N->getOperand(1);
22850 /// Do target-specific dag combines on X86ISD::FANDN nodes
22851 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22852 // FANDN(0.0, x) -> x
22853 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22854 if (C->getValueAPF().isPosZero())
22855 return N->getOperand(1);
22857 // FANDN(x, 0.0) -> 0.0
22858 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22859 if (C->getValueAPF().isPosZero())
22860 return N->getOperand(1);
22865 static SDValue PerformBTCombine(SDNode *N,
22867 TargetLowering::DAGCombinerInfo &DCI) {
22868 // BT ignores high bits in the bit index operand.
22869 SDValue Op1 = N->getOperand(1);
22870 if (Op1.hasOneUse()) {
22871 unsigned BitWidth = Op1.getValueSizeInBits();
22872 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22873 APInt KnownZero, KnownOne;
22874 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22875 !DCI.isBeforeLegalizeOps());
22876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22877 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22878 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22879 DCI.CommitTargetLoweringOpt(TLO);
22884 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22885 SDValue Op = N->getOperand(0);
22886 if (Op.getOpcode() == ISD::BITCAST)
22887 Op = Op.getOperand(0);
22888 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22889 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22890 VT.getVectorElementType().getSizeInBits() ==
22891 OpVT.getVectorElementType().getSizeInBits()) {
22892 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22897 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22898 const X86Subtarget *Subtarget) {
22899 EVT VT = N->getValueType(0);
22900 if (!VT.isVector())
22903 SDValue N0 = N->getOperand(0);
22904 SDValue N1 = N->getOperand(1);
22905 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22908 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22909 // both SSE and AVX2 since there is no sign-extended shift right
22910 // operation on a vector with 64-bit elements.
22911 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22912 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22913 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22914 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22915 SDValue N00 = N0.getOperand(0);
22917 // EXTLOAD has a better solution on AVX2,
22918 // it may be replaced with X86ISD::VSEXT node.
22919 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22920 if (!ISD::isNormalLoad(N00.getNode()))
22923 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22924 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22926 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22932 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22933 TargetLowering::DAGCombinerInfo &DCI,
22934 const X86Subtarget *Subtarget) {
22935 SDValue N0 = N->getOperand(0);
22936 EVT VT = N->getValueType(0);
22938 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
22939 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
22940 // This exposes the sext to the sdivrem lowering, so that it directly extends
22941 // from AH (which we otherwise need to do contortions to access).
22942 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
22943 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
22945 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22946 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
22947 N0.getOperand(0), N0.getOperand(1));
22948 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22949 return R.getValue(1);
22952 if (!DCI.isBeforeLegalizeOps())
22955 if (!Subtarget->hasFp256())
22958 if (VT.isVector() && VT.getSizeInBits() == 256) {
22959 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22967 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22968 const X86Subtarget* Subtarget) {
22970 EVT VT = N->getValueType(0);
22972 // Let legalize expand this if it isn't a legal type yet.
22973 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22976 EVT ScalarVT = VT.getScalarType();
22977 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22978 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22981 SDValue A = N->getOperand(0);
22982 SDValue B = N->getOperand(1);
22983 SDValue C = N->getOperand(2);
22985 bool NegA = (A.getOpcode() == ISD::FNEG);
22986 bool NegB = (B.getOpcode() == ISD::FNEG);
22987 bool NegC = (C.getOpcode() == ISD::FNEG);
22989 // Negative multiplication when NegA xor NegB
22990 bool NegMul = (NegA != NegB);
22992 A = A.getOperand(0);
22994 B = B.getOperand(0);
22996 C = C.getOperand(0);
23000 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23002 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23004 return DAG.getNode(Opcode, dl, VT, A, B, C);
23007 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23008 TargetLowering::DAGCombinerInfo &DCI,
23009 const X86Subtarget *Subtarget) {
23010 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23011 // (and (i32 x86isd::setcc_carry), 1)
23012 // This eliminates the zext. This transformation is necessary because
23013 // ISD::SETCC is always legalized to i8.
23015 SDValue N0 = N->getOperand(0);
23016 EVT VT = N->getValueType(0);
23018 if (N0.getOpcode() == ISD::AND &&
23020 N0.getOperand(0).hasOneUse()) {
23021 SDValue N00 = N0.getOperand(0);
23022 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23023 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23024 if (!C || C->getZExtValue() != 1)
23026 return DAG.getNode(ISD::AND, dl, VT,
23027 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23028 N00.getOperand(0), N00.getOperand(1)),
23029 DAG.getConstant(1, VT));
23033 if (N0.getOpcode() == ISD::TRUNCATE &&
23035 N0.getOperand(0).hasOneUse()) {
23036 SDValue N00 = N0.getOperand(0);
23037 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23038 return DAG.getNode(ISD::AND, dl, VT,
23039 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23040 N00.getOperand(0), N00.getOperand(1)),
23041 DAG.getConstant(1, VT));
23044 if (VT.is256BitVector()) {
23045 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23050 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23051 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23052 // This exposes the zext to the udivrem lowering, so that it directly extends
23053 // from AH (which we otherwise need to do contortions to access).
23054 if (N0.getOpcode() == ISD::UDIVREM &&
23055 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23056 (VT == MVT::i32 || VT == MVT::i64)) {
23057 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23058 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23059 N0.getOperand(0), N0.getOperand(1));
23060 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23061 return R.getValue(1);
23067 // Optimize x == -y --> x+y == 0
23068 // x != -y --> x+y != 0
23069 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23070 const X86Subtarget* Subtarget) {
23071 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23072 SDValue LHS = N->getOperand(0);
23073 SDValue RHS = N->getOperand(1);
23074 EVT VT = N->getValueType(0);
23077 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23078 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23079 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23080 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23081 LHS.getValueType(), RHS, LHS.getOperand(1));
23082 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23083 addV, DAG.getConstant(0, addV.getValueType()), CC);
23085 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23086 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23087 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23088 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23089 RHS.getValueType(), LHS, RHS.getOperand(1));
23090 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23091 addV, DAG.getConstant(0, addV.getValueType()), CC);
23094 if (VT.getScalarType() == MVT::i1) {
23095 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23096 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23097 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
23098 if (!IsSEXT0 && !IsVZero0)
23100 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
23101 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23102 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23104 if (!IsSEXT1 && !IsVZero1)
23107 if (IsSEXT0 && IsVZero1) {
23108 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
23109 if (CC == ISD::SETEQ)
23110 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23111 return LHS.getOperand(0);
23113 if (IsSEXT1 && IsVZero0) {
23114 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
23115 if (CC == ISD::SETEQ)
23116 return DAG.getNOT(DL, RHS.getOperand(0), VT);
23117 return RHS.getOperand(0);
23124 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23125 SelectionDAG &DAG) {
23127 MVT VT = Load->getSimpleValueType(0);
23128 MVT EVT = VT.getVectorElementType();
23129 SDValue Addr = Load->getOperand(1);
23130 SDValue NewAddr = DAG.getNode(
23131 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23132 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23135 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23136 DAG.getMachineFunction().getMachineMemOperand(
23137 Load->getMemOperand(), 0, EVT.getStoreSize()));
23141 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23142 const X86Subtarget *Subtarget) {
23144 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23145 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23146 "X86insertps is only defined for v4x32");
23148 SDValue Ld = N->getOperand(1);
23149 if (MayFoldLoad(Ld)) {
23150 // Extract the countS bits from the immediate so we can get the proper
23151 // address when narrowing the vector load to a specific element.
23152 // When the second source op is a memory address, insertps doesn't use
23153 // countS and just gets an f32 from that address.
23154 unsigned DestIndex =
23155 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23157 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23159 // Create this as a scalar to vector to match the instruction pattern.
23160 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23161 // countS bits are ignored when loading from memory on insertps, which
23162 // means we don't need to explicitly set them to 0.
23163 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23164 LoadScalarToVector, N->getOperand(2));
23169 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23170 SDValue V0 = N->getOperand(0);
23171 SDValue V1 = N->getOperand(1);
23173 EVT VT = N->getValueType(0);
23175 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23176 // operands and changing the mask to 1. This saves us a bunch of
23177 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23178 // x86InstrInfo knows how to commute this back after instruction selection
23179 // if it would help register allocation.
23181 // TODO: If optimizing for size or a processor that doesn't suffer from
23182 // partial register update stalls, this should be transformed into a MOVSD
23183 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23185 if (VT == MVT::v2f64)
23186 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23187 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23188 SDValue NewMask = DAG.getConstant(1, MVT::i8);
23189 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23195 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23196 // as "sbb reg,reg", since it can be extended without zext and produces
23197 // an all-ones bit which is more useful than 0/1 in some cases.
23198 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23201 return DAG.getNode(ISD::AND, DL, VT,
23202 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23203 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23204 DAG.getConstant(1, VT));
23205 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23206 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23207 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23208 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23211 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23212 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23213 TargetLowering::DAGCombinerInfo &DCI,
23214 const X86Subtarget *Subtarget) {
23216 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23217 SDValue EFLAGS = N->getOperand(1);
23219 if (CC == X86::COND_A) {
23220 // Try to convert COND_A into COND_B in an attempt to facilitate
23221 // materializing "setb reg".
23223 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23224 // cannot take an immediate as its first operand.
23226 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23227 EFLAGS.getValueType().isInteger() &&
23228 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23229 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23230 EFLAGS.getNode()->getVTList(),
23231 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23232 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23233 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23237 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23238 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23240 if (CC == X86::COND_B)
23241 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23245 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23246 if (Flags.getNode()) {
23247 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23248 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23254 // Optimize branch condition evaluation.
23256 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23257 TargetLowering::DAGCombinerInfo &DCI,
23258 const X86Subtarget *Subtarget) {
23260 SDValue Chain = N->getOperand(0);
23261 SDValue Dest = N->getOperand(1);
23262 SDValue EFLAGS = N->getOperand(3);
23263 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23267 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23268 if (Flags.getNode()) {
23269 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23270 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23277 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23278 SelectionDAG &DAG) {
23279 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23280 // optimize away operation when it's from a constant.
23282 // The general transformation is:
23283 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23284 // AND(VECTOR_CMP(x,y), constant2)
23285 // constant2 = UNARYOP(constant)
23287 // Early exit if this isn't a vector operation, the operand of the
23288 // unary operation isn't a bitwise AND, or if the sizes of the operations
23289 // aren't the same.
23290 EVT VT = N->getValueType(0);
23291 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23292 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23293 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23296 // Now check that the other operand of the AND is a constant. We could
23297 // make the transformation for non-constant splats as well, but it's unclear
23298 // that would be a benefit as it would not eliminate any operations, just
23299 // perform one more step in scalar code before moving to the vector unit.
23300 if (BuildVectorSDNode *BV =
23301 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23302 // Bail out if the vector isn't a constant.
23303 if (!BV->isConstant())
23306 // Everything checks out. Build up the new and improved node.
23308 EVT IntVT = BV->getValueType(0);
23309 // Create a new constant of the appropriate type for the transformed
23311 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23312 // The AND node needs bitcasts to/from an integer vector type around it.
23313 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23314 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23315 N->getOperand(0)->getOperand(0), MaskConst);
23316 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23323 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23324 const X86Subtarget *Subtarget) {
23325 // First try to optimize away the conversion entirely when it's
23326 // conditionally from a constant. Vectors only.
23327 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23328 if (Res != SDValue())
23331 // Now move on to more general possibilities.
23332 SDValue Op0 = N->getOperand(0);
23333 EVT InVT = Op0->getValueType(0);
23335 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23336 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23338 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23339 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23340 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23343 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23344 // a 32-bit target where SSE doesn't support i64->FP operations.
23345 if (Op0.getOpcode() == ISD::LOAD) {
23346 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23347 EVT VT = Ld->getValueType(0);
23348 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23349 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23350 !Subtarget->is64Bit() && VT == MVT::i64) {
23351 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23352 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23353 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23360 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23361 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23362 X86TargetLowering::DAGCombinerInfo &DCI) {
23363 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23364 // the result is either zero or one (depending on the input carry bit).
23365 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23366 if (X86::isZeroNode(N->getOperand(0)) &&
23367 X86::isZeroNode(N->getOperand(1)) &&
23368 // We don't have a good way to replace an EFLAGS use, so only do this when
23370 SDValue(N, 1).use_empty()) {
23372 EVT VT = N->getValueType(0);
23373 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23374 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23375 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23376 DAG.getConstant(X86::COND_B,MVT::i8),
23378 DAG.getConstant(1, VT));
23379 return DCI.CombineTo(N, Res1, CarryOut);
23385 // fold (add Y, (sete X, 0)) -> adc 0, Y
23386 // (add Y, (setne X, 0)) -> sbb -1, Y
23387 // (sub (sete X, 0), Y) -> sbb 0, Y
23388 // (sub (setne X, 0), Y) -> adc -1, Y
23389 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23392 // Look through ZExts.
23393 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23394 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23397 SDValue SetCC = Ext.getOperand(0);
23398 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23401 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23402 if (CC != X86::COND_E && CC != X86::COND_NE)
23405 SDValue Cmp = SetCC.getOperand(1);
23406 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23407 !X86::isZeroNode(Cmp.getOperand(1)) ||
23408 !Cmp.getOperand(0).getValueType().isInteger())
23411 SDValue CmpOp0 = Cmp.getOperand(0);
23412 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23413 DAG.getConstant(1, CmpOp0.getValueType()));
23415 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23416 if (CC == X86::COND_NE)
23417 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23418 DL, OtherVal.getValueType(), OtherVal,
23419 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23420 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23421 DL, OtherVal.getValueType(), OtherVal,
23422 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23425 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23426 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23427 const X86Subtarget *Subtarget) {
23428 EVT VT = N->getValueType(0);
23429 SDValue Op0 = N->getOperand(0);
23430 SDValue Op1 = N->getOperand(1);
23432 // Try to synthesize horizontal adds from adds of shuffles.
23433 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23434 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23435 isHorizontalBinOp(Op0, Op1, true))
23436 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23438 return OptimizeConditionalInDecrement(N, DAG);
23441 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23442 const X86Subtarget *Subtarget) {
23443 SDValue Op0 = N->getOperand(0);
23444 SDValue Op1 = N->getOperand(1);
23446 // X86 can't encode an immediate LHS of a sub. See if we can push the
23447 // negation into a preceding instruction.
23448 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23449 // If the RHS of the sub is a XOR with one use and a constant, invert the
23450 // immediate. Then add one to the LHS of the sub so we can turn
23451 // X-Y -> X+~Y+1, saving one register.
23452 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23453 isa<ConstantSDNode>(Op1.getOperand(1))) {
23454 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23455 EVT VT = Op0.getValueType();
23456 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23458 DAG.getConstant(~XorC, VT));
23459 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23460 DAG.getConstant(C->getAPIntValue()+1, VT));
23464 // Try to synthesize horizontal adds from adds of shuffles.
23465 EVT VT = N->getValueType(0);
23466 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23467 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23468 isHorizontalBinOp(Op0, Op1, true))
23469 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23471 return OptimizeConditionalInDecrement(N, DAG);
23474 /// performVZEXTCombine - Performs build vector combines
23475 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23476 TargetLowering::DAGCombinerInfo &DCI,
23477 const X86Subtarget *Subtarget) {
23479 MVT VT = N->getSimpleValueType(0);
23480 SDValue Op = N->getOperand(0);
23481 MVT OpVT = Op.getSimpleValueType();
23482 MVT OpEltVT = OpVT.getVectorElementType();
23483 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23485 // (vzext (bitcast (vzext (x)) -> (vzext x)
23487 while (V.getOpcode() == ISD::BITCAST)
23488 V = V.getOperand(0);
23490 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23491 MVT InnerVT = V.getSimpleValueType();
23492 MVT InnerEltVT = InnerVT.getVectorElementType();
23494 // If the element sizes match exactly, we can just do one larger vzext. This
23495 // is always an exact type match as vzext operates on integer types.
23496 if (OpEltVT == InnerEltVT) {
23497 assert(OpVT == InnerVT && "Types must match for vzext!");
23498 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23501 // The only other way we can combine them is if only a single element of the
23502 // inner vzext is used in the input to the outer vzext.
23503 if (InnerEltVT.getSizeInBits() < InputBits)
23506 // In this case, the inner vzext is completely dead because we're going to
23507 // only look at bits inside of the low element. Just do the outer vzext on
23508 // a bitcast of the input to the inner.
23509 return DAG.getNode(X86ISD::VZEXT, DL, VT,
23510 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23513 // Check if we can bypass extracting and re-inserting an element of an input
23514 // vector. Essentialy:
23515 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23516 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23517 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23518 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23519 SDValue ExtractedV = V.getOperand(0);
23520 SDValue OrigV = ExtractedV.getOperand(0);
23521 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23522 if (ExtractIdx->getZExtValue() == 0) {
23523 MVT OrigVT = OrigV.getSimpleValueType();
23524 // Extract a subvector if necessary...
23525 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23526 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23527 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23528 OrigVT.getVectorNumElements() / Ratio);
23529 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23530 DAG.getIntPtrConstant(0));
23532 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23533 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23540 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23541 DAGCombinerInfo &DCI) const {
23542 SelectionDAG &DAG = DCI.DAG;
23543 switch (N->getOpcode()) {
23545 case ISD::EXTRACT_VECTOR_ELT:
23546 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23549 case X86ISD::SHRUNKBLEND:
23550 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23551 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
23552 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23553 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
23554 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
23555 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
23556 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
23559 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
23560 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
23561 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
23562 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
23563 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
23564 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23565 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
23566 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
23567 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23568 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
23569 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
23571 case X86ISD::FOR: return PerformFORCombine(N, DAG);
23573 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
23574 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
23575 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
23576 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
23577 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
23578 case ISD::ANY_EXTEND:
23579 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
23580 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
23581 case ISD::SIGN_EXTEND_INREG:
23582 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23583 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23584 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
23585 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23586 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23587 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
23588 case X86ISD::SHUFP: // Handle all target specific shuffles
23589 case X86ISD::PALIGNR:
23590 case X86ISD::UNPCKH:
23591 case X86ISD::UNPCKL:
23592 case X86ISD::MOVHLPS:
23593 case X86ISD::MOVLHPS:
23594 case X86ISD::PSHUFB:
23595 case X86ISD::PSHUFD:
23596 case X86ISD::PSHUFHW:
23597 case X86ISD::PSHUFLW:
23598 case X86ISD::MOVSS:
23599 case X86ISD::MOVSD:
23600 case X86ISD::VPERMILPI:
23601 case X86ISD::VPERM2X128:
23602 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23603 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
23604 case ISD::INTRINSIC_WO_CHAIN:
23605 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23606 case X86ISD::INSERTPS: {
23607 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23608 return PerformINSERTPSCombine(N, DAG, Subtarget);
23611 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
23612 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23618 /// isTypeDesirableForOp - Return true if the target has native support for
23619 /// the specified value type and it is 'desirable' to use the type for the
23620 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23621 /// instruction encodings are longer and some i16 instructions are slow.
23622 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23623 if (!isTypeLegal(VT))
23625 if (VT != MVT::i16)
23632 case ISD::SIGN_EXTEND:
23633 case ISD::ZERO_EXTEND:
23634 case ISD::ANY_EXTEND:
23647 /// IsDesirableToPromoteOp - This method query the target whether it is
23648 /// beneficial for dag combiner to promote the specified node. If true, it
23649 /// should return the desired promotion type by reference.
23650 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23651 EVT VT = Op.getValueType();
23652 if (VT != MVT::i16)
23655 bool Promote = false;
23656 bool Commute = false;
23657 switch (Op.getOpcode()) {
23660 LoadSDNode *LD = cast<LoadSDNode>(Op);
23661 // If the non-extending load has a single use and it's not live out, then it
23662 // might be folded.
23663 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23664 Op.hasOneUse()*/) {
23665 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23666 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23667 // The only case where we'd want to promote LOAD (rather then it being
23668 // promoted as an operand is when it's only use is liveout.
23669 if (UI->getOpcode() != ISD::CopyToReg)
23676 case ISD::SIGN_EXTEND:
23677 case ISD::ZERO_EXTEND:
23678 case ISD::ANY_EXTEND:
23683 SDValue N0 = Op.getOperand(0);
23684 // Look out for (store (shl (load), x)).
23685 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23698 SDValue N0 = Op.getOperand(0);
23699 SDValue N1 = Op.getOperand(1);
23700 if (!Commute && MayFoldLoad(N1))
23702 // Avoid disabling potential load folding opportunities.
23703 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23705 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23715 //===----------------------------------------------------------------------===//
23716 // X86 Inline Assembly Support
23717 //===----------------------------------------------------------------------===//
23719 // Helper to match a string separated by whitespace.
23720 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23721 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23723 for (StringRef Piece : Pieces) {
23724 if (!S.startswith(Piece)) // Check if the piece matches.
23727 S = S.substr(Piece.size());
23728 StringRef::size_type Pos = S.find_first_not_of(" \t");
23729 if (Pos == 0) // We matched a prefix.
23738 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23740 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23741 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23742 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23743 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23745 if (AsmPieces.size() == 3)
23747 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23754 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23755 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23757 std::string AsmStr = IA->getAsmString();
23759 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23760 if (!Ty || Ty->getBitWidth() % 16 != 0)
23763 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23764 SmallVector<StringRef, 4> AsmPieces;
23765 SplitString(AsmStr, AsmPieces, ";\n");
23767 switch (AsmPieces.size()) {
23768 default: return false;
23770 // FIXME: this should verify that we are targeting a 486 or better. If not,
23771 // we will turn this bswap into something that will be lowered to logical
23772 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23773 // lower so don't worry about this.
23775 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23776 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23777 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23778 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
23779 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
23780 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
23781 // No need to check constraints, nothing other than the equivalent of
23782 // "=r,0" would be valid here.
23783 return IntrinsicLowering::LowerToByteSwap(CI);
23786 // rorw $$8, ${0:w} --> llvm.bswap.i16
23787 if (CI->getType()->isIntegerTy(16) &&
23788 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23789 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
23790 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
23792 const std::string &ConstraintsStr = IA->getConstraintString();
23793 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23794 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23795 if (clobbersFlagRegisters(AsmPieces))
23796 return IntrinsicLowering::LowerToByteSwap(CI);
23800 if (CI->getType()->isIntegerTy(32) &&
23801 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23802 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
23803 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
23804 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
23806 const std::string &ConstraintsStr = IA->getConstraintString();
23807 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23808 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23809 if (clobbersFlagRegisters(AsmPieces))
23810 return IntrinsicLowering::LowerToByteSwap(CI);
23813 if (CI->getType()->isIntegerTy(64)) {
23814 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23815 if (Constraints.size() >= 2 &&
23816 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23817 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23818 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23819 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
23820 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
23821 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
23822 return IntrinsicLowering::LowerToByteSwap(CI);
23830 /// getConstraintType - Given a constraint letter, return the type of
23831 /// constraint it is for this target.
23832 X86TargetLowering::ConstraintType
23833 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23834 if (Constraint.size() == 1) {
23835 switch (Constraint[0]) {
23846 return C_RegisterClass;
23870 return TargetLowering::getConstraintType(Constraint);
23873 /// Examine constraint type and operand type and determine a weight value.
23874 /// This object must already have been set up with the operand type
23875 /// and the current alternative constraint selected.
23876 TargetLowering::ConstraintWeight
23877 X86TargetLowering::getSingleConstraintMatchWeight(
23878 AsmOperandInfo &info, const char *constraint) const {
23879 ConstraintWeight weight = CW_Invalid;
23880 Value *CallOperandVal = info.CallOperandVal;
23881 // If we don't have a value, we can't do a match,
23882 // but allow it at the lowest weight.
23883 if (!CallOperandVal)
23885 Type *type = CallOperandVal->getType();
23886 // Look at the constraint type.
23887 switch (*constraint) {
23889 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23900 if (CallOperandVal->getType()->isIntegerTy())
23901 weight = CW_SpecificReg;
23906 if (type->isFloatingPointTy())
23907 weight = CW_SpecificReg;
23910 if (type->isX86_MMXTy() && Subtarget->hasMMX())
23911 weight = CW_SpecificReg;
23915 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23916 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23917 weight = CW_Register;
23920 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23921 if (C->getZExtValue() <= 31)
23922 weight = CW_Constant;
23926 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23927 if (C->getZExtValue() <= 63)
23928 weight = CW_Constant;
23932 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23933 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23934 weight = CW_Constant;
23938 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23939 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23940 weight = CW_Constant;
23944 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23945 if (C->getZExtValue() <= 3)
23946 weight = CW_Constant;
23950 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23951 if (C->getZExtValue() <= 0xff)
23952 weight = CW_Constant;
23957 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23958 weight = CW_Constant;
23962 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23963 if ((C->getSExtValue() >= -0x80000000LL) &&
23964 (C->getSExtValue() <= 0x7fffffffLL))
23965 weight = CW_Constant;
23969 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23970 if (C->getZExtValue() <= 0xffffffff)
23971 weight = CW_Constant;
23978 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23979 /// with another that has more specific requirements based on the type of the
23980 /// corresponding operand.
23981 const char *X86TargetLowering::
23982 LowerXConstraint(EVT ConstraintVT) const {
23983 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23984 // 'f' like normal targets.
23985 if (ConstraintVT.isFloatingPoint()) {
23986 if (Subtarget->hasSSE2())
23988 if (Subtarget->hasSSE1())
23992 return TargetLowering::LowerXConstraint(ConstraintVT);
23995 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23996 /// vector. If it is invalid, don't add anything to Ops.
23997 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23998 std::string &Constraint,
23999 std::vector<SDValue>&Ops,
24000 SelectionDAG &DAG) const {
24003 // Only support length 1 constraints for now.
24004 if (Constraint.length() > 1) return;
24006 char ConstraintLetter = Constraint[0];
24007 switch (ConstraintLetter) {
24010 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24011 if (C->getZExtValue() <= 31) {
24012 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24018 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24019 if (C->getZExtValue() <= 63) {
24020 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24026 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24027 if (isInt<8>(C->getSExtValue())) {
24028 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24035 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24036 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24037 Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24043 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24044 if (C->getZExtValue() <= 3) {
24045 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24052 if (C->getZExtValue() <= 255) {
24053 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24060 if (C->getZExtValue() <= 127) {
24061 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24067 // 32-bit signed value
24068 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24069 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24070 C->getSExtValue())) {
24071 // Widen to 64 bits here to get it sign extended.
24072 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24075 // FIXME gcc accepts some relocatable values here too, but only in certain
24076 // memory models; it's complicated.
24081 // 32-bit unsigned value
24082 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24083 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24084 C->getZExtValue())) {
24085 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24089 // FIXME gcc accepts some relocatable values here too, but only in certain
24090 // memory models; it's complicated.
24094 // Literal immediates are always ok.
24095 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24096 // Widen to 64 bits here to get it sign extended.
24097 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24101 // In any sort of PIC mode addresses need to be computed at runtime by
24102 // adding in a register or some sort of table lookup. These can't
24103 // be used as immediates.
24104 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24107 // If we are in non-pic codegen mode, we allow the address of a global (with
24108 // an optional displacement) to be used with 'i'.
24109 GlobalAddressSDNode *GA = nullptr;
24110 int64_t Offset = 0;
24112 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24114 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24115 Offset += GA->getOffset();
24117 } else if (Op.getOpcode() == ISD::ADD) {
24118 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24119 Offset += C->getZExtValue();
24120 Op = Op.getOperand(0);
24123 } else if (Op.getOpcode() == ISD::SUB) {
24124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24125 Offset += -C->getZExtValue();
24126 Op = Op.getOperand(0);
24131 // Otherwise, this isn't something we can handle, reject it.
24135 const GlobalValue *GV = GA->getGlobal();
24136 // If we require an extra load to get this address, as in PIC mode, we
24137 // can't accept it.
24138 if (isGlobalStubReference(
24139 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24142 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24143 GA->getValueType(0), Offset);
24148 if (Result.getNode()) {
24149 Ops.push_back(Result);
24152 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24155 std::pair<unsigned, const TargetRegisterClass *>
24156 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24157 const std::string &Constraint,
24159 // First, see if this is a constraint that directly corresponds to an LLVM
24161 if (Constraint.size() == 1) {
24162 // GCC Constraint Letters
24163 switch (Constraint[0]) {
24165 // TODO: Slight differences here in allocation order and leaving
24166 // RIP in the class. Do they matter any more here than they do
24167 // in the normal allocation?
24168 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24169 if (Subtarget->is64Bit()) {
24170 if (VT == MVT::i32 || VT == MVT::f32)
24171 return std::make_pair(0U, &X86::GR32RegClass);
24172 if (VT == MVT::i16)
24173 return std::make_pair(0U, &X86::GR16RegClass);
24174 if (VT == MVT::i8 || VT == MVT::i1)
24175 return std::make_pair(0U, &X86::GR8RegClass);
24176 if (VT == MVT::i64 || VT == MVT::f64)
24177 return std::make_pair(0U, &X86::GR64RegClass);
24180 // 32-bit fallthrough
24181 case 'Q': // Q_REGS
24182 if (VT == MVT::i32 || VT == MVT::f32)
24183 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24184 if (VT == MVT::i16)
24185 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24186 if (VT == MVT::i8 || VT == MVT::i1)
24187 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24188 if (VT == MVT::i64)
24189 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24191 case 'r': // GENERAL_REGS
24192 case 'l': // INDEX_REGS
24193 if (VT == MVT::i8 || VT == MVT::i1)
24194 return std::make_pair(0U, &X86::GR8RegClass);
24195 if (VT == MVT::i16)
24196 return std::make_pair(0U, &X86::GR16RegClass);
24197 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24198 return std::make_pair(0U, &X86::GR32RegClass);
24199 return std::make_pair(0U, &X86::GR64RegClass);
24200 case 'R': // LEGACY_REGS
24201 if (VT == MVT::i8 || VT == MVT::i1)
24202 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24203 if (VT == MVT::i16)
24204 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24205 if (VT == MVT::i32 || !Subtarget->is64Bit())
24206 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24207 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24208 case 'f': // FP Stack registers.
24209 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24210 // value to the correct fpstack register class.
24211 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24212 return std::make_pair(0U, &X86::RFP32RegClass);
24213 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24214 return std::make_pair(0U, &X86::RFP64RegClass);
24215 return std::make_pair(0U, &X86::RFP80RegClass);
24216 case 'y': // MMX_REGS if MMX allowed.
24217 if (!Subtarget->hasMMX()) break;
24218 return std::make_pair(0U, &X86::VR64RegClass);
24219 case 'Y': // SSE_REGS if SSE2 allowed
24220 if (!Subtarget->hasSSE2()) break;
24222 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24223 if (!Subtarget->hasSSE1()) break;
24225 switch (VT.SimpleTy) {
24227 // Scalar SSE types.
24230 return std::make_pair(0U, &X86::FR32RegClass);
24233 return std::make_pair(0U, &X86::FR64RegClass);
24241 return std::make_pair(0U, &X86::VR128RegClass);
24249 return std::make_pair(0U, &X86::VR256RegClass);
24254 return std::make_pair(0U, &X86::VR512RegClass);
24260 // Use the default implementation in TargetLowering to convert the register
24261 // constraint into a member of a register class.
24262 std::pair<unsigned, const TargetRegisterClass*> Res;
24263 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24265 // Not found as a standard register?
24267 // Map st(0) -> st(7) -> ST0
24268 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24269 tolower(Constraint[1]) == 's' &&
24270 tolower(Constraint[2]) == 't' &&
24271 Constraint[3] == '(' &&
24272 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24273 Constraint[5] == ')' &&
24274 Constraint[6] == '}') {
24276 Res.first = X86::FP0+Constraint[4]-'0';
24277 Res.second = &X86::RFP80RegClass;
24281 // GCC allows "st(0)" to be called just plain "st".
24282 if (StringRef("{st}").equals_lower(Constraint)) {
24283 Res.first = X86::FP0;
24284 Res.second = &X86::RFP80RegClass;
24289 if (StringRef("{flags}").equals_lower(Constraint)) {
24290 Res.first = X86::EFLAGS;
24291 Res.second = &X86::CCRRegClass;
24295 // 'A' means EAX + EDX.
24296 if (Constraint == "A") {
24297 Res.first = X86::EAX;
24298 Res.second = &X86::GR32_ADRegClass;
24304 // Otherwise, check to see if this is a register class of the wrong value
24305 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24306 // turn into {ax},{dx}.
24307 if (Res.second->hasType(VT))
24308 return Res; // Correct type already, nothing to do.
24310 // All of the single-register GCC register classes map their values onto
24311 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
24312 // really want an 8-bit or 32-bit register, map to the appropriate register
24313 // class and return the appropriate register.
24314 if (Res.second == &X86::GR16RegClass) {
24315 if (VT == MVT::i8 || VT == MVT::i1) {
24316 unsigned DestReg = 0;
24317 switch (Res.first) {
24319 case X86::AX: DestReg = X86::AL; break;
24320 case X86::DX: DestReg = X86::DL; break;
24321 case X86::CX: DestReg = X86::CL; break;
24322 case X86::BX: DestReg = X86::BL; break;
24325 Res.first = DestReg;
24326 Res.second = &X86::GR8RegClass;
24328 } else if (VT == MVT::i32 || VT == MVT::f32) {
24329 unsigned DestReg = 0;
24330 switch (Res.first) {
24332 case X86::AX: DestReg = X86::EAX; break;
24333 case X86::DX: DestReg = X86::EDX; break;
24334 case X86::CX: DestReg = X86::ECX; break;
24335 case X86::BX: DestReg = X86::EBX; break;
24336 case X86::SI: DestReg = X86::ESI; break;
24337 case X86::DI: DestReg = X86::EDI; break;
24338 case X86::BP: DestReg = X86::EBP; break;
24339 case X86::SP: DestReg = X86::ESP; break;
24342 Res.first = DestReg;
24343 Res.second = &X86::GR32RegClass;
24345 } else if (VT == MVT::i64 || VT == MVT::f64) {
24346 unsigned DestReg = 0;
24347 switch (Res.first) {
24349 case X86::AX: DestReg = X86::RAX; break;
24350 case X86::DX: DestReg = X86::RDX; break;
24351 case X86::CX: DestReg = X86::RCX; break;
24352 case X86::BX: DestReg = X86::RBX; break;
24353 case X86::SI: DestReg = X86::RSI; break;
24354 case X86::DI: DestReg = X86::RDI; break;
24355 case X86::BP: DestReg = X86::RBP; break;
24356 case X86::SP: DestReg = X86::RSP; break;
24359 Res.first = DestReg;
24360 Res.second = &X86::GR64RegClass;
24363 } else if (Res.second == &X86::FR32RegClass ||
24364 Res.second == &X86::FR64RegClass ||
24365 Res.second == &X86::VR128RegClass ||
24366 Res.second == &X86::VR256RegClass ||
24367 Res.second == &X86::FR32XRegClass ||
24368 Res.second == &X86::FR64XRegClass ||
24369 Res.second == &X86::VR128XRegClass ||
24370 Res.second == &X86::VR256XRegClass ||
24371 Res.second == &X86::VR512RegClass) {
24372 // Handle references to XMM physical registers that got mapped into the
24373 // wrong class. This can happen with constraints like {xmm0} where the
24374 // target independent register mapper will just pick the first match it can
24375 // find, ignoring the required type.
24377 if (VT == MVT::f32 || VT == MVT::i32)
24378 Res.second = &X86::FR32RegClass;
24379 else if (VT == MVT::f64 || VT == MVT::i64)
24380 Res.second = &X86::FR64RegClass;
24381 else if (X86::VR128RegClass.hasType(VT))
24382 Res.second = &X86::VR128RegClass;
24383 else if (X86::VR256RegClass.hasType(VT))
24384 Res.second = &X86::VR256RegClass;
24385 else if (X86::VR512RegClass.hasType(VT))
24386 Res.second = &X86::VR512RegClass;
24392 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24394 // Scaling factors are not free at all.
24395 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24396 // will take 2 allocations in the out of order engine instead of 1
24397 // for plain addressing mode, i.e. inst (reg1).
24399 // vaddps (%rsi,%drx), %ymm0, %ymm1
24400 // Requires two allocations (one for the load, one for the computation)
24402 // vaddps (%rsi), %ymm0, %ymm1
24403 // Requires just 1 allocation, i.e., freeing allocations for other operations
24404 // and having less micro operations to execute.
24406 // For some X86 architectures, this is even worse because for instance for
24407 // stores, the complex addressing mode forces the instruction to use the
24408 // "load" ports instead of the dedicated "store" port.
24409 // E.g., on Haswell:
24410 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24411 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24412 if (isLegalAddressingMode(AM, Ty))
24413 // Scale represents reg2 * scale, thus account for 1
24414 // as soon as we use a second register.
24415 return AM.Scale != 0;
24419 bool X86TargetLowering::isTargetFTOL() const {
24420 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();